File size: 22,735 Bytes
ef987bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
const fs = require('fs');
const path = require('path');
const { chromium } = require('playwright');

const DEFAULT_TIMEOUT_MS = 12000;

function walk(dir) {
  let out = [];
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
    if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue;
    const p = path.join(dir, entry.name);
    if (entry.isDirectory()) out = out.concat(walk(p));
    else out.push(p);
  }
  return out;
}

function stripNoisyComments(text) {
  return text
    .replace(/<!--([\s\S]*?)-->/g, ' ')
    .replace(/\/\*([\s\S]*?)\*\//g, ' ')
    .replace(/(^|[^:])\/\/.*$/gm, '$1 ')
    .toLowerCase();
}

function readSourceText(taskDir) {
  const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']);
  const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase()));
  if (files.length === 0) {
    throw new Error('no source files found for semantic validation');
  }
  return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n');
}

function hasAnyIn(text, list) {
  return list.some((t) => text.includes(String(t).toLowerCase()));
}

function hasAll(text, list) {
  return list.every((t) => text.includes(String(t).toLowerCase()));
}

function escapedRegExp(token) {
  return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

function readContract(taskDir) {
  const contractPath = path.join(taskDir, 'task_contract.json');
  if (!fs.existsSync(contractPath)) {
    throw new Error(`missing task_contract.json: ${contractPath}`);
  }
  return JSON.parse(fs.readFileSync(contractPath, 'utf8'));
}

function checkSemantics(contract, taskDir) {
  const text = stripNoisyComments(readSourceText(taskDir));
  const rules = contract.semantics || {};
  const errors = [];
  const warnings = [];

  if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) {
    errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`);
  }
  if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) {
    errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`);
  }
  if (Array.isArray(rules.all_groups)) {
    for (const group of rules.all_groups) {
      if (!hasAnyIn(text, group)) {
        errors.push(`missing required semantic group: ${group.join(' | ')}`);
      }
    }
  }
  if (rules.min_tokens && typeof rules.min_tokens === 'object') {
    for (const [token, minCount] of Object.entries(rules.min_tokens)) {
      const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length;
      if (count < minCount) {
        errors.push(`token "${token}" count ${count} < ${minCount}`);
      }
    }
  }
  if (contract.compat && contract.compat.minSourceBytes) {
    // reserve compatibility pass for extremely small outputs
    const files = walk(taskDir);
    let total = 0;
    for (const f of files) {
      const stat = fs.statSync(f);
      if (stat.isFile()) total += stat.size;
    }
    if (total < Number(contract.compat.minSourceBytes)) {
      warnings.push(`source footprint small: ${total} bytes`);
    }
  }

  return { strictOk: errors.length === 0, warnings, errors };
}

function pick(selectorList) {
  return selectorList.filter(Boolean).join(', ');
}

async function gatherEntry(taskDir) {
  const files = walk(taskDir);
  const html = files.find((f) => f.toLowerCase().endsWith('.html'));
  if (!html) throw new Error('no html entrypoint found');
  return html;
}

async function startBrowser(taskDir) {
  const entry = await gatherEntry(taskDir);
  const browser = await chromium.launch({
    headless: true,
    args: [
      '--no-sandbox',
      '--disable-dev-shm-usage',
      '--disable-gpu'
    ]
  });
  const page = await browser.newPage({ viewport: { width: 1100, height: 760 } });
  const errors = [];
  page.on('pageerror', (err) => errors.push(err.message || String(err)));
  page.on('console', (msg) => {
    if (msg.type() === 'error') errors.push(msg.text());
  });
  await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' });
  await page.waitForTimeout(250);
  if (errors.length) {
    await browser.close();
    throw new Error('browser load errors: ' + errors.join(' | '));
  }
  return { browser, page, errors };
}

function pathToFileUrl(filePath) {
  const abs = path.resolve(filePath);
  return new URL('file://' + abs.replace(/\\/g, '/')).href;
}

function assertStateDiff(before, after, message) {
  if (before === after) {
    throw new Error(message);
  }
}

function toNumberText(v) {
  return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0;
}

async function checkGomoku(taskDir, config) {
  const sel = config.selectors || {};
  const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']);
  const statusSel = sel.status;
  const resetSel = sel.reset;

  const task = async () => {
    const { browser, page } = await startBrowser(taskDir);
    try {
      const count = await page.locator(cellsSel).count();
      if (count < 40) {
        throw new Error('board-like grid should have at least 40 cells');
      }
      const before = await page.evaluate(({ cellsSel, statusSel }) => {
        const cells = Array.from(document.querySelectorAll(cellsSel));
        const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : '';
        const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length;
        const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||');
        return { occupied, marker, status, count };
      }, { cellsSel, statusSel });
      const first = page.locator(cellsSel).nth(0);
      const second = page.locator(cellsSel).nth(1);
      await first.click({ force: true });
      await page.waitForTimeout(120);
      await second.click({ force: true });
      await page.waitForTimeout(200);
      const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => {
        const cells = Array.from(document.querySelectorAll(cellsSel));
        const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : '';
        const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length;
        const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||');
        return { occupied, marker, status, count: cells.length };
      }, { cellsSel, statusSel });
      if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) {
        throw new Error('clicking board cells does not alter board state');
      }
      if (resetSel) {
        const resetCount = await page.locator(resetSel).count();
        if (resetCount === 0) {
          throw new Error('reset control not found');
        }
        await page.locator(resetSel).first().click({ force: true });
        await page.waitForTimeout(250);
        const afterReset = await page.evaluate(({ cellsSel, statusSel }) => {
          const cells = Array.from(document.querySelectorAll(cellsSel));
          const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : '';
          const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length;
          const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||');
          return { occupied, marker, status, count: cells.length };
        }, { cellsSel, statusSel });
        if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) {
          throw new Error('reset does not restore board state');
        }
      }
      await browser.close();
    } catch (err) {
      await browser.close();
      throw err;
    }
  };
  return task();
}

async function checkMemoryMatch(taskDir, config) {
  const sel = config.selectors || {};
  const cardSel = pick([sel.card, '.card', '[data-card]']);
  const task = async () => {
    const { browser, page } = await startBrowser(taskDir);
    try {
      const count = await page.locator(cardSel).count();
      if (count < 8) {
        throw new Error('not enough cards rendered');
      }
      const before = await page.evaluate((cardSel) => {
        const cards = Array.from(document.querySelectorAll(cardSel));
        return {
          flipCount: cards.filter((c) => c.classList.contains('flip')).length,
          matchedCount: cards.filter((c) => c.classList.contains('matched')).length,
          moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText,
        };
      }, cardSel);

      // Read each card's symbol so we can drive a guaranteed-equal and a
      // guaranteed-different pair instead of relying on the (shuffled) order.
      const symbolAttr = sel.symbolAttr || 'data-symbol';
      const symbols = await page.evaluate(({ cardSel, symbolAttr }) => {
        return Array.from(document.querySelectorAll(cardSel)).map((c) => c.getAttribute(symbolAttr));
      }, { cardSel, symbolAttr });

      if (symbols.every((s) => s != null && s !== '')) {
        // find a matching pair (same symbol) and a mismatching pair (different symbols)
        let matchPair = null;
        for (let i = 0; i < symbols.length && !matchPair; i++) {
          for (let j = i + 1; j < symbols.length; j++) {
            if (symbols[i] === symbols[j]) { matchPair = [i, j]; break; }
          }
        }
        let diffPair = null;
        for (let i = 0; i < symbols.length && !diffPair; i++) {
          for (let j = i + 1; j < symbols.length; j++) {
            if (symbols[i] !== symbols[j]) { diffPair = [i, j]; break; }
          }
        }
        if (matchPair) {
          await page.locator(cardSel).nth(matchPair[0]).click({ force: true });
          await page.waitForTimeout(120);
          await page.locator(cardSel).nth(matchPair[1]).click({ force: true });
          await page.waitForTimeout(900);
          const matchedOk = await page.evaluate(({ cardSel, pair }) => {
            const cards = Array.from(document.querySelectorAll(cardSel));
            return cards[pair[0]].classList.contains('matched') && cards[pair[1]].classList.contains('matched');
          }, { cardSel, pair: matchPair });
          if (!matchedOk) {
            throw new Error('two equal-symbol cards should both gain the matched class');
          }
        }
        // Fresh game for the mismatch trial: reload the page so card state is
        // clean regardless of whether (or how) a reset control is implemented
        // (the instruction never mandates a reset button or its id). If a reset
        // control happens to exist, click it too as a best-effort re-init.
        const resetSel = pick([
          sel.reset,
          '#reset',
          '#restart',
          '[data-testid="reset"]',
          '[data-testid="restart"]',
        ]);
        if (await page.locator(resetSel).count()) {
          await page.locator(resetSel).first().click({ force: true }).catch(() => {});
          await page.waitForTimeout(150);
        }
        await page.reload({ waitUntil: 'domcontentloaded' });
        await page.waitForTimeout(350);
        const symbols2 = await page.evaluate(({ cardSel, symbolAttr }) => {
          return Array.from(document.querySelectorAll(cardSel)).map((c) => c.getAttribute(symbolAttr));
        }, { cardSel, symbolAttr });
        let diffPair2 = null;
        for (let i = 0; i < symbols2.length && !diffPair2; i++) {
          for (let j = i + 1; j < symbols2.length; j++) {
            if (symbols2[i] !== symbols2[j]) { diffPair2 = [i, j]; break; }
          }
        }
        const usePair = diffPair2 || diffPair;
        if (usePair) {
          await page.locator(cardSel).nth(usePair[0]).click({ force: true });
          await page.waitForTimeout(120);
          await page.locator(cardSel).nth(usePair[1]).click({ force: true });
          await page.waitForTimeout(1100); // wait past the mismatch unflip delay
          const mismatchOk = await page.evaluate(({ cardSel, pair }) => {
            const cards = Array.from(document.querySelectorAll(cardSel));
            return !cards[pair[0]].classList.contains('matched') && !cards[pair[1]].classList.contains('matched');
          }, { cardSel, pair: usePair });
          if (!mismatchOk) {
            throw new Error('two different-symbol cards should not retain the matched class');
          }
        }
        await browser.close();
        return;
      }

      // Fallback (no per-card symbol attr): generic "interaction changes state".
      const first = page.locator(cardSel).nth(0);
      const second = page.locator(cardSel).nth(1);
      await first.click({ force: true });
      await page.waitForTimeout(120);
      await second.click({ force: true });
      await page.waitForTimeout(700);
      const after = await page.evaluate((cardSel) => {
        const cards = Array.from(document.querySelectorAll(cardSel));
        return {
          flipCount: cards.filter((c) => c.classList.contains('flip')).length,
          matchedCount: cards.filter((c) => c.classList.contains('matched')).length,
          moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText,
        };
      }, cardSel);
      if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) {
        throw new Error('card interaction is not reflected in UI state');
      }
      await browser.close();
    } catch (err) {
      await browser.close();
      throw err;
    }
  };
  return task();
}

async function checkTowerDefense(taskDir, config) {
  const sel = config.selectors || {};
  const canvasSel = pick([sel.canvas, 'canvas', '#game']);
  const spawnSel = pick([sel.spawn, '#spawn']);
  const resetSel = pick([sel.reset, '#reset']);
  const task = async () => {
    const { browser, page } = await startBrowser(taskDir);
    try {
      const before = await page.evaluate((canvasSel) => {
        const canvas = document.querySelector(canvasSel);
        if (!canvas) return null;
        let canvasSample = '';
        try {
          canvasSample = canvas.toDataURL().slice(0, 120);
        } catch {
          canvasSample = '';
        }
        return {
          canvasSample,
          hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '',
        };
      }, canvasSel);
      if (!before) throw new Error('canvas not found');
      const spawnCount = await page.locator(spawnSel).count();
      if (spawnCount === 0) throw new Error('spawn control not found');
      await page.locator(spawnSel).first().click({ force: true });
      await page.waitForTimeout(900);
      const afterSpawn = await page.evaluate((canvasSel) => {
        const canvas = document.querySelector(canvasSel);
        let canvasSample = '';
        try {
          canvasSample = canvas?.toDataURL().slice(0, 120) || '';
        } catch {
          canvasSample = '';
        }
        return {
          canvasSample,
          hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '',
        };
      }, canvasSel);
      if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) {
        throw new Error('spawn action has no observable effect');
      }

      const canvas = page.locator(canvasSel);
      const box = await canvas.boundingBox();
      if (box) {
        await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
        await page.waitForTimeout(500);
      }
      const afterPlace = await page.evaluate((canvasSel) => {
        const canvas = document.querySelector(canvasSel);
        let canvasSample = '';
        try {
          canvasSample = canvas?.toDataURL().slice(0, 120) || '';
        } catch {
          canvasSample = '';
        }
        return {
          canvasSample,
          hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '',
        };
      }, canvasSel);
      if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) {
        throw new Error('placing tower on canvas has no observable effect');
      }

      if (resetSel) {
        const resetCount = await page.locator(resetSel).count();
        if (resetCount > 0) {
          await page.locator(resetSel).first().click({ force: true });
          await page.waitForTimeout(250);
        }
      }
      await browser.close();
    } catch (err) {
      await browser.close();
      throw err;
    }
  };
  return task();
}

async function checkLudo(taskDir, config) {
  const sel = config.selectors || {};
  const rollSel = pick([sel.roll, '#roll, button']);
  const statusSel = sel.status || '#status';
  const diceSel = sel.dice || '#dice';
  const task = async () => {
    const { browser, page } = await startBrowser(taskDir);
    try {
      const before = await page.evaluate(({ statusSel, diceSel }) => {
        return {
          status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '',
          dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '',
          boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '',
        };
      }, { statusSel, diceSel });

      const rollCount = await page.locator(rollSel).count();
      if (rollCount === 0) throw new Error('roll control not found');
      for (let i = 0; i < 4; i++) {
        await page.locator(rollSel).first().click({ force: true });
        await page.waitForTimeout(220);
      }
      const after = await page.evaluate(({ statusSel, diceSel }) => {
        return {
          status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '',
          dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '',
          boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '',
        };
      }, { statusSel, diceSel });
      if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) {
        throw new Error('turn + dice workflow has no state change');
      }
      await browser.close();
    } catch (err) {
      await browser.close();
      throw err;
    }
  };
  return task();
}

async function checkSpaceShooter(taskDir, config) {
  const sel = config.selectors || {};
  const canvasSel = pick([sel.canvas, 'canvas', '#space']);
  const restartSel = pick([sel.restart, '#restart']);
  const scoreSel = sel.score || '#score';
  const hpSel = sel.hp || '#hp';
  const task = async () => {
    const { browser, page } = await startBrowser(taskDir);
    try {
      const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => {
        const canvas = document.querySelector(canvasSel);
        if (!canvas) return null;
        let canvasSample = '';
        try {
          canvasSample = canvas.toDataURL().slice(0, 140);
        } catch {
          canvasSample = '';
        }
        const scoreEl = document.querySelector(scoreSel);
        const hpEl = document.querySelector(hpSel);
        return {
          canvasSample,
          scoreText: scoreEl ? scoreEl.innerText : '',
          hpText: hpEl ? hpEl.innerText : '',
        };
      }, { canvasSel, scoreSel, hpSel });
      if (!before) throw new Error('canvas not found');
      const canvas = page.locator(canvasSel).first();
      await canvas.click({ force: true });
      await page.keyboard.press('Space');
      await page.keyboard.press('Space');
      await page.keyboard.press('Space');
      await page.waitForTimeout(500);
      const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => {
        const canvas = document.querySelector(canvasSel);
        let canvasSample = '';
        try {
          canvasSample = canvas?.toDataURL().slice(0, 140) || '';
        } catch {
          canvasSample = '';
        }
        const scoreEl = document.querySelector(scoreSel);
        const hpEl = document.querySelector(hpSel);
        return {
          canvasSample,
          scoreText: scoreEl ? scoreEl.innerText : '',
          hpText: hpEl ? hpEl.innerText : '',
        };
      }, { canvasSel, scoreSel, hpSel });
      if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) {
        throw new Error('shooting key interaction has no observable effect');
      }
      if (restartSel) {
        const restartCount = await page.locator(restartSel).count();
        if (restartCount > 0) {
          await page.locator(restartSel).first().click({ force: true });
          await page.waitForTimeout(250);
        }
      }
      await browser.close();
    } catch (err) {
      await browser.close();
      throw err;
    }
  };
  return task();
}

const behaviorRunners = {
  gomoku: checkGomoku,
  memory_match: checkMemoryMatch,
  tower_defense: checkTowerDefense,
  ludo: checkLudo,
  space_shooter: checkSpaceShooter,
};

async function runContractChecks({ taskDir, mode, contractDir }) {
  const contract = readContract(contractDir || taskDir);
  if (mode === 'semantics' || mode === 'full') {
    const semantic = checkSemantics(contract, taskDir);
    if (semantic.warnings.length) {
      console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings }));
    }
    if (!semantic.strictOk) {
      throw new Error('semantic checks failed: ' + semantic.errors.join(' | '));
    }
  }

  if (mode === 'browser' || mode === 'full') {
    const browserType = (contract.browser || {}).type;
    const runner = behaviorRunners[browserType];
    if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`);
    await runner(taskDir, contract.browser || {});
  }

  console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true }));
}

if (require.main === module) {
  (async () => {
    const args = Object.fromEntries(
      process.argv.slice(2).map((arg, idx, all) => {
        if (!arg.startsWith('--')) return null;
        const key = arg.slice(2);
        const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true';
        return [key, value];
      }).filter(Boolean)
    );
    const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd();
    const mode = args.mode || 'full';
    await runContractChecks({ taskDir, mode });
  })().catch((err) => {
    console.error(err && err.stack ? err.stack : String(err));
    process.exit(1);
  });
}

module.exports = { runContractChecks };