ravensight-playtest 0.10.2 → 0.10.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ravensight-playtest",
3
- "version": "0.10.2",
3
+ "version": "0.10.4",
4
4
  "description": "Local AI playtests and seeded game simulations with reports in Ravensight.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://ravensight.io/docs/#playtest",
@@ -0,0 +1,58 @@
1
+ /**
2
+ * What the studio asked a run to stay out of (`--avoid`, the brief's
3
+ * `this_run_focus.stay_out_of`), for every input a local run sends: the
4
+ * persona's own (refused in the web driver before it reaches the page), the
5
+ * tester probes and the edge behaviour checks. One matcher, the any-game
6
+ * layer's (./anygame/language.js avoidedIn, every language), shared with the
7
+ * cloud runner (direct-runner/lib/avoid.mjs). On a paid 0.10.1 web run the
8
+ * probes pressed "Pull the red lever" the brief said to avoid, and the page
9
+ * never answered again.
10
+ */
11
+ import { avoidedIn } from './anygame/language.js';
12
+
13
+ const clip = s => String(s ?? '').replace(/\s+/g, ' ').trim().slice(0, 80);
14
+
15
+ /**
16
+ * The avoid lines a brief carries for this run, or [].
17
+ *
18
+ * @param {Object|null} brief
19
+ * @returns {string[]}
20
+ */
21
+ export function avoidLinesOf(brief) {
22
+ const block = brief && typeof brief === 'object' ? (brief.fields && brief.fields.this_run_focus) || brief.this_run_focus : null;
23
+ const lines = block && Array.isArray(block.stay_out_of) ? block.stay_out_of : [];
24
+ return lines.map(line => String(line || '').trim()).filter(Boolean).slice(0, 10);
25
+ }
26
+
27
+ /**
28
+ * `{ lines, skip(name), list(), line() }`: `skip` answers whether a control by
29
+ * that name is one to stay out of and keeps its name for the report.
30
+ *
31
+ * @param {string[]} avoid
32
+ */
33
+ export function createAvoidGuard(avoid = []) {
34
+ const lines = (Array.isArray(avoid) ? avoid : []).map(line => String(line || '').trim()).filter(Boolean).slice(0, 10);
35
+ const skipped = new Set();
36
+ const named = name => lines.length > 0 && Boolean(clip(name)) && avoidedIn(String(name), lines);
37
+ return {
38
+ lines,
39
+ named,
40
+ skip(name) { if (!named(name)) return false; skipped.add(clip(name)); return true; },
41
+ note(name) { if (clip(name)) skipped.add(clip(name)); },
42
+ list: () => [...skipped],
43
+ line: () => (skipped.size ? `Not pressed, because the brief asks to stay out of it: ${[...skipped].map(n => `"${n.replace(/"/g, "'")}"`).join(', ')}.` : null)
44
+ };
45
+ }
46
+
47
+ /* c8 ignore start */
48
+ /** Runs in the page: the name of the clickable control at a point, by its label or text, or ''. */
49
+ export function controlNameAt([x, y]) {
50
+ let el = document.elementFromPoint(x, y);
51
+ const control = el && el.closest('button, [role=button], a, input, select, textarea, label, summary, [onclick]');
52
+ el = control || el;
53
+ if (!el) return '';
54
+ return String(el.getAttribute('aria-label') || el.innerText || el.value || el.getAttribute('title') || '').replace(/\s+/g, ' ').trim().slice(0, 120);
55
+ }
56
+ /* c8 ignore stop */
57
+
58
+ export default { avoidLinesOf, createAvoidGuard, controlNameAt };
@@ -13,6 +13,7 @@ import { mkdir, rename, stat, readdir, rm, chmod } from 'node:fs/promises';
13
13
  import { recordingLimits, recordingViewport, recordingDirectory, recordingMetadata, saveRecording, probeVideo, videoInfo } from './recording.js';
14
14
  import path from 'node:path';
15
15
  import { gameRefusal, runnerGone } from '../gameRefusal.js';
16
+ import { createAvoidGuard } from '../avoid.js';
16
17
  import {
17
18
  DEFAULT_DRAG_MS, DOUBLE_CLICK_GAP_MS, KEY_REPEAT_DELAY_MS, KEY_REPEAT_INTERVAL_MS, MAX_DRAG_MS, MAX_HOLD_MS,
18
19
  dragPath, mouseButton, sequenceEvents, webKeyName, wheelNotches
@@ -1390,6 +1391,8 @@ export async function needsFrame(page, text) {
1390
1391
 
1391
1392
  export function createWebDriver({ importer, headless = true, playtest = null, platform = process.platform, modifier = null, recording = {}, now = () => Date.now(), inspectVideo = probeVideo, freezeTime = true, touch = false, frameStrip = true } = {}) {
1392
1393
  const editModifier = modifier === 'Meta' || modifier === 'Control' ? modifier : platformModifier(platform);
1394
+ // What the brief asks the run to stay out of (../avoid.js): an input on such a control is never sent (setAvoid).
1395
+ let avoidGuard = createAvoidGuard([]);
1393
1396
  let browser = null;
1394
1397
  let context = null;
1395
1398
  let page = null;
@@ -1947,6 +1950,42 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
1947
1950
  return { x: Math.round(box.x + box.width / 2), y: Math.round(box.y + box.height / 2) };
1948
1951
  }
1949
1952
 
1953
+ /** The name of the control at a point on the page: the clickable thing under it, by its label or text. */
1954
+ const nameAtPoint = (current, point) => current.evaluate(({ x, y }) => {
1955
+ let el = document.elementFromPoint(x, y);
1956
+ const control = el && el.closest('button, [role=button], a, input, select, textarea, label, summary, [onclick]');
1957
+ el = control || el;
1958
+ if (!el) return '';
1959
+ return String(el.getAttribute('aria-label') || el.innerText || el.value || el.getAttribute('title') || '').replace(/\s+/g, ' ').trim().slice(0, 120);
1960
+ }, point).catch(() => '');
1961
+
1962
+ /** The name of the control an action spec lands on, or '' when it cannot be told without acting. */
1963
+ async function controlNameOf(current, spec) {
1964
+ try {
1965
+ if (!spec.ref && spec.target && typeof spec.target === 'object') return await nameAtPoint(current, { x: Number(spec.target.x), y: Number(spec.target.y) });
1966
+ if (!spec.ref && lastMarks && isMarkTarget(spec.target)) { const point = resolveMark(spec.target, lastMarks); return point ? await nameAtPoint(current, point) : ''; }
1967
+ const resolved = await targetFor(current, spec);
1968
+ if (resolved && resolved.point) return await nameAtPoint(current, resolved.point);
1969
+ return await resolved.evaluate(el => String(el.getAttribute('aria-label') || el.innerText || el.value || el.getAttribute('title') || '').replace(/\s+/g, ' ').trim().slice(0, 120), null, { timeout: 2000 });
1970
+ } catch {
1971
+ return '';
1972
+ }
1973
+ }
1974
+
1975
+ /** The control an action would press that the brief asks to stay out of, by name, or null. */
1976
+ async function avoidedTargetOf(current, action) {
1977
+ if (!avoidGuard.lines.length || !action) return null;
1978
+ const specs = ['click', 'hover', 'type', 'select'].includes(action.kind) ? [action] : ['drag', 'swipe'].includes(action.kind) ? [endSpec(action.from), endSpec(action.to)] : [];
1979
+ for (const spec of specs) {
1980
+ const text = typeof spec.target === 'string' ? spec.target : '';
1981
+ if (text && avoidGuard.named(text)) return text.replace(/^[a-z]+\s+"(.*)"$/, '$1');
1982
+ if (!spec.ref && !spec.target) continue;
1983
+ const name = await controlNameOf(current, spec);
1984
+ if (name && avoidGuard.named(name)) return name;
1985
+ }
1986
+ return null;
1987
+ }
1988
+
1950
1989
  /** One end of a drag as pointFor takes it: a ref, a name or a point. */
1951
1990
  function endSpec(end) {
1952
1991
  if (end && typeof end === 'object') return { target: end };
@@ -3045,6 +3084,12 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
3045
3084
  if (pendingDialog) return answerDialog(current, action);
3046
3085
  await assertAlive(current);
3047
3086
  await settled();
3087
+ // A control the brief asks the run to stay out of is never pressed, whoever chose the input: refused, and kept for the report.
3088
+ const avoidedName = await avoidedTargetOf(current, action);
3089
+ if (avoidedName) {
3090
+ avoidGuard.note(avoidedName);
3091
+ return { ok: false, changed: false, refused: 'avoided', name: avoidedName, error: `the brief asks to stay out of "${avoidedName}", so the runner did not send that input` };
3092
+ }
3048
3093
  const attemptsBefore = offSiteCount;
3049
3094
  // The game runs while an action plays and stands still while the
3050
3095
  // persona thinks, on a game drawn in a canvas.
@@ -3077,6 +3122,12 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
3077
3122
  return outcome;
3078
3123
  },
3079
3124
 
3125
+ /** The brief's avoid lines for this run (../avoid.js): an input on a control they name is refused before the page. */
3126
+ setAvoid(lines) { avoidGuard = createAvoidGuard(lines); },
3127
+
3128
+ /** The controls an input was refused on because the brief asks to stay out of them, by name. */
3129
+ avoidedControls() { return avoidGuard.list(); },
3130
+
3080
3131
  /**
3081
3132
  * Every attempt to leave the build since the last call, claimed by an
3082
3133
  * action or not (a timer redirect between actions has no action), for the
@@ -10,6 +10,7 @@
10
10
  // defect by itself) or not_checked (with the reason, which is a limit of the
11
11
  // runner). A check never guesses: a problem is only what was measured.
12
12
  import { pngFingerprint, screenDelta, significant } from './pixels.js';
13
+ import { createAvoidGuard, controlNameAt } from './avoid.js';
13
14
  import { flatShare, BLANK_SHARE, runnerFinding, stepsBefore } from './honesty.js';
14
15
 
15
16
  /** The heading the checks are written under in report.md. */
@@ -345,7 +346,9 @@ export function blankCapabilityNote(checks = []) {
345
346
  return { input: 'blank screen check', reason: `the blank screen part of ${held.map(check => check.title).join(', ')} could not be made: ${why}` };
346
347
  }
347
348
 
348
- export async function runEdgePass({ driver, actionRecords = [], screenshots = [], observation = null, signal = null, log = () => {}, sleep = ms => new Promise(resolve => setTimeout(resolve, ms)), timing = EDGE_TIMING, sizes = EDGE_SIZES }) {
349
+ export async function runEdgePass({ driver, actionRecords = [], screenshots = [], observation = null, signal = null, log = () => {}, sleep = ms => new Promise(resolve => setTimeout(resolve, ms)), timing = EDGE_TIMING, sizes = EDGE_SIZES, avoid = [] }) {
350
+ // What the brief asks the run to stay out of (./avoid.js): no check clicks a control it names.
351
+ const guard = createAvoidGuard(avoid);
349
352
  const session = driver.edgeSession();
350
353
  const { context } = session;
351
354
  // Reads of the page are bounded: one that never answers reads as nothing.
@@ -599,7 +602,9 @@ export async function runEdgePass({ driver, actionRecords = [], screenshots = []
599
602
  if (!stopped()) {
600
603
  const title = 'rapid input';
601
604
  const keys = usedKeysOf(actionRecords);
602
- const point = lastClickPoint(actionRecords);
605
+ const lastPoint = lastClickPoint(actionRecords);
606
+ // The point play last clicked is not clicked again when the control there is one the brief says to stay out of.
607
+ const point = lastPoint && guard.lines.length && guard.skip(await page.evaluate(controlNameAt, [lastPoint.x, lastPoint.y]).catch(() => '')) ? null : lastPoint;
603
608
  let sent = 0;
604
609
  for (let i = 0; i < timing.burstKeys && !stopped(); i += 1) {
605
610
  if (session.dialogOpen && session.dialogOpen()) break;
@@ -680,7 +685,7 @@ export async function runEdgePass({ driver, actionRecords = [], screenshots = []
680
685
  if (session.dismissDialogs) session.dismissDialogs(false);
681
686
  await session.parkClock().catch(() => {});
682
687
  }
683
- return { checks, restored, elapsedMs: Date.now() - started };
688
+ return { checks, restored, elapsedMs: Date.now() - started, avoided: guard.list() };
684
689
  }
685
690
 
686
691
  /**
@@ -724,6 +729,7 @@ export function edgeMarkdown(edge) {
724
729
  return [
725
730
  ...edge.checks.map(check => `- **${check.title}**: ${STATUS_WORD[check.status] || check.status}. ${String(check.detail || '').replace(/\.?$/, '.')}${check.screenshot ? ` (${check.screenshot})` : ''}`),
726
731
  '',
732
+ ...(Array.isArray(edge.avoided) && edge.avoided.length ? [`Not pressed, because the brief asks to stay out of it: ${edge.avoided.map(name => `"${String(name).replace(/"/g, "'")}"`).join(', ')}.`, ''] : []),
727
733
  'These checks are scripted. A problem here was measured, not judged; a check that could not tell says so.'
728
734
  ].join('\n');
729
735
  }
@@ -22,6 +22,7 @@ import { runEdgePass, edgeFindings, edgeMarkdown, EDGE_HEADING, blankCapabilityN
22
22
  // Tester techniques (./testerLedger.js): a coverage map, the game's own numbers and placeholder text, kept by the runner.
23
23
  import { createTesterLedger, testerFindings, testedMarkdown, TESTED_HEADING } from './testerLedger.js';
24
24
  import { runTesterProbes, probeFindings, probesMarkdown, probeObserver, PROBES_HEADING } from './testerProbes.js';
25
+ import { avoidLinesOf } from './avoid.js';
25
26
  import { runGodotTesterProbes, godotProbesMarkdown } from './godotTesterProbes.js';
26
27
  import { runGodotEdgePass } from './godotEdgePass.js';
27
28
  import { recordingMetadata, saveRecording } from './drivers/recording.js';
@@ -356,6 +357,8 @@ export async function runPersona(args) {
356
357
  // that rather than still holding `queued`.
357
358
  await advance('launching');
358
359
  if ('traceSecrets' in driver) driver.traceSecrets = secretsOf(localBrief);
360
+ // What the brief asks the run to stay out of: the driver refuses an input on it, whoever chose the input (./avoid.js).
361
+ if (typeof driver.setAvoid === 'function') driver.setAvoid(avoidLinesOf(brief));
359
362
  await driver.launch({ target, runDir: runDirectory, recordVideo, viewport, signal: args.signal });
360
363
  // A web run keeps its inputs, in this process only, so its findings can be replayed after the report.
361
364
  if (driverName === 'playwright_web' && typeof args.replayDriver === 'function' && args.replayFindings !== false) traceWebInputs(driver, { fingerprint: pngFingerprint });
@@ -1550,18 +1553,23 @@ async function playLoop({
1550
1553
  const probing = edgePass && !gameEnded && !canceled && !budgetExceeded && typeof driver.edgeSession === 'function' && driverName === 'playwright_web' && !(argsSignal && argsSignal.aborted);
1551
1554
  if (probing) {
1552
1555
  try {
1553
- honesty.probes = await runTesterProbes({ driver, actionRecords, screenshots, observation: observations.length, signal: argsSignal, log });
1556
+ honesty.probes = await runTesterProbes({ driver, actionRecords, screenshots, observation: observations.length, signal: argsSignal, log, avoid: avoidLinesOf(brief) });
1554
1557
  transcript.write({ kind: 'tester_probes', elapsed_ms: honesty.probes.elapsedMs, checks: honesty.probes.checks.map(check => ({ name: check.name, status: check.status, detail: check.detail })) });
1555
1558
  } catch (error) {
1556
1559
  transcript.write({ kind: 'tester_probes_failed', message: String(error && error.message) });
1557
1560
  log(`the tester probes did not finish: ${String(error && error.message)}`);
1558
1561
  }
1559
1562
  }
1563
+ // A page the probes left unable to answer (an input it never took: a click handler that never returns), or a browser that
1564
+ // closed under them, has nothing more to check: the edge checks and the probe on a loading page are skipped, said in the
1565
+ // record, and the run goes on to its report and upload (0.10.1 waited 2 h 52 min on one such click).
1566
+ const probesStopped = honesty.probes && honesty.probes.stopped ? honesty.probes.stopped : null;
1567
+ if (probesStopped) transcript.write({ kind: 'edge_pass_skipped', reason: `the tester probes stopped: ${probesStopped}` });
1560
1568
  // The edge behaviour pass: scripted, no model call, after the last screen
1561
1569
  // has been saved. A canceled run and a game that already ended skip it.
1562
- if (edgePass && !gameEnded && !canceled && !budgetExceeded && typeof driver.edgeSession === 'function' && !(argsSignal && argsSignal.aborted)) {
1570
+ if (edgePass && !probesStopped && !gameEnded && !canceled && !budgetExceeded && typeof driver.edgeSession === 'function' && !(argsSignal && argsSignal.aborted)) {
1563
1571
  try {
1564
- honesty.edge = await runEdgePass({ driver, actionRecords, screenshots, observation: observations.length, signal: argsSignal, log });
1572
+ honesty.edge = await runEdgePass({ driver, actionRecords, screenshots, observation: observations.length, signal: argsSignal, log, avoid: avoidLinesOf(brief) });
1565
1573
  transcript.write({ kind: 'edge_pass', restored: honesty.edge.restored, elapsed_ms: honesty.edge.elapsedMs, checks: honesty.edge.checks.map(check => ({ name: check.name, status: check.status, detail: check.detail })) });
1566
1574
  for (const finding of edgeFindings(honesty.edge, { actionRecords, action: actions })) honesty.findings.push(finding);
1567
1575
  // A check whose blank screen part could not be told from the start is a limit of the runner, never a finding.
@@ -1577,15 +1585,20 @@ async function playLoop({
1577
1585
  }
1578
1586
  // [tester hook] Input while the page loads: a reload, so it comes after the edge checks have asked their own reload what survived.
1579
1587
  if (probing && honesty.probes) {
1580
- try {
1581
- const loaded = await runTesterProbes({ driver, actionRecords, screenshots, observation: observations.length, signal: argsSignal, log, loading: true });
1588
+ if (!probesStopped) try {
1589
+ const loaded = await runTesterProbes({ driver, actionRecords, screenshots, observation: observations.length, signal: argsSignal, log, loading: true, avoid: avoidLinesOf(brief) });
1582
1590
  honesty.probes.checks.push(...loaded.checks);
1583
1591
  honesty.probes.suspects.push(...loaded.suspects);
1592
+ honesty.probes.avoided = [...new Set([...(honesty.probes.avoided || []), ...(loaded.avoided || [])])];
1584
1593
  } catch (error) {
1585
1594
  transcript.write({ kind: 'tester_probes_failed', message: String(error && error.message) });
1586
1595
  }
1587
1596
  for (const finding of probeFindings(honesty.probes, { actionRecords, action: actions })) { if (honesty.findings.some(known => known.title === finding.title)) continue; honesty.findings.push(finding); transcript.write({ kind: 'runner_finding', key: finding.runner.key, title: finding.title }); }
1588
1597
  }
1598
+ // What the brief asks the run to stay out of, and what was left alone for it: the persona's own inputs the driver refused,
1599
+ // and the controls the probes and the edge checks did not press (./avoid.js). In the step log and in report.md.
1600
+ honesty.leftAlone = [...new Set([...(typeof driver.avoidedControls === 'function' ? driver.avoidedControls() : []), ...(honesty.probes?.avoided || []), ...(honesty.edge?.avoided || [])])];
1601
+ if (honesty.leftAlone.length) transcript.write({ kind: 'avoided', controls: honesty.leftAlone });
1589
1602
  // [tester hook] The tester probes a keyboard can make on a Godot game (./godotTesterProbes.js), before its edge checks start it a second time.
1590
1603
  if (edgePass && !gameEnded && !canceled && !budgetExceeded && driver.edgeKind === 'godot' && typeof driver.runFor === 'function' && !(argsSignal && argsSignal.aborted)) {
1591
1604
  try {
@@ -2079,12 +2092,21 @@ export function writeHonesty({ report: given, markdown, honesty, driverName, not
2079
2092
  }
2080
2093
  // [tester hook] What was and was not tested, from the runner's own ledger.
2081
2094
  if (honesty.probes) text = replaceSection(text, PROBES_HEADING, honesty.probes.godot ? godotProbesMarkdown(honesty.probes) : probesMarkdown(honesty.probes));
2095
+ if (Array.isArray(honesty.leftAlone) && honesty.leftAlone.length) text = replaceSection(text, AVOID_HEADING, avoidMarkdown(honesty.leftAlone));
2082
2096
  if (honesty.tester) text = replaceSection(text, TESTED_HEADING, testedMarkdown(honesty.tester, { edge: honesty.edge, probes: honesty.probes || null }));
2083
2097
  text = writeCapabilitySection(text, driverName, honesty.capability.list());
2084
2098
  if (located.index.length > 0) text = replaceSection(text, EVIDENCE_HEADING, whereToLookMarkdown(located.index, honesty.video));
2085
2099
  return { report: located.report, markdown: text, added, index: located.index };
2086
2100
  }
2087
2101
 
2102
+ /** The heading what the run left alone is written under in report.md. */
2103
+ export const AVOID_HEADING = '## Left alone, as the brief asks (written by the runner)';
2104
+
2105
+ /** What the run left alone because the brief asks to stay out of it, as that section's body. */
2106
+ export function avoidMarkdown(names) {
2107
+ return `No part of this run pressed what the brief asks to stay out of: the persona's own inputs on it were refused before they reached the game, and the scripted checks after play left it alone. Left alone: ${names.map(name => `"${String(name).replace(/"/g, "'")}"`).join(', ')}.`;
2108
+ }
2109
+
2088
2110
  /**
2089
2111
  * The most findings whose picture is checked against the claim: every issue
2090
2112
  * of a run, the most severe first, up to this many (about a third of a cent
@@ -374,7 +374,7 @@ export function traceWebInputs(driver, { fingerprint }) {
374
374
  const result = await act(action);
375
375
  let print = null;
376
376
  try { print = fingerprint(await driver.screenProbe()); } catch { print = null; }
377
- trace.push({ action, ok: Boolean(result) && result.ok !== false && !result.refused, changed: result ? result.changed : null, print });
377
+ trace.push({ action, ok: Boolean(result) && result.ok !== false && !result.refused, changed: result ? result.changed : null, print, ...(result && result.refused === 'avoided' ? { avoided: true } : {}) });
378
378
  return result;
379
379
  };
380
380
  driver.webTrace = trace;
@@ -437,7 +437,8 @@ export async function replayWebFindings({ report, index = [], traceSteps = new M
437
437
  for (let n = 0; n < last; n++) {
438
438
  if (now() > deadline) break;
439
439
  const entry = trace[n];
440
- await driver.act(entry.action);
440
+ // An input the run refused because the brief asks to stay out of it is never sent by the replay either.
441
+ if (!entry.avoided) await driver.act(entry.action);
441
442
  let after = null;
442
443
  try { after = fingerprint(await driver.screenProbe()); } catch { after = null; }
443
444
  for (const hit of targets.filter(candidate => candidate.trace_steps === n + 1)) {
@@ -25,6 +25,7 @@
25
25
  import { pngFingerprint, screenDelta, significant } from './pixels.js';
26
26
  import { flatShare, BLANK_SHARE, runnerFinding, stepsBefore } from './honesty.js';
27
27
  import { readings, NEVER_NEGATIVE, BOUNDED, NEVER_FALLS } from './testerLedger.js';
28
+ import { createAvoidGuard, controlNameAt } from './avoid.js';
28
29
 
29
30
  /** The heading the probes are written under in report.md. */
30
31
  export const PROBES_HEADING = '## Tester probes (run by the runner after play, no model call)';
@@ -32,6 +33,11 @@ export const PROBES_HEADING = '## Tester probes (run by the runner after play, n
32
33
  export const PROBE_TIMING = Object.freeze({ settleMs: 300, rapidClicks: 15, rapidGapMs: 12, holdMs: 700, edgeHoldMs: 400, edgeMaxMs: 4000, longText: 5000, maxSweep: 6, retries: 2, loadInputMs: 1200, budgetMs: 60000 });
33
34
 
34
35
  /** The probes, in the order they run, with the words the report uses. */
36
+ // One input to the page waits this long at most. A page whose main thread is stuck (a click handler that never
37
+ // returns) never answers one, and the paid 0.10.1 run pt_job_e8c2ea4d636362e50109 waited on such a click for 2 h 52 min.
38
+ export const INPUT_MS = 5000;
39
+ // Past its own budget the pass waits this long for a probe still in flight, then ends with what it has.
40
+ export const PASS_GRACE_MS = 10000;
35
41
  export const PROBES = Object.freeze([
36
42
  ['overflow', 'text that overflows or is cut off'],
37
43
  ['rapid', 'rapid repeated input on one control'],
@@ -171,42 +177,61 @@ const q = value => `"${String(value || '').replace(/"/g, "'").slice(0, 60)}"`;
171
177
  * @param {Object} args
172
178
  * @returns {Promise<{checks: Array<Object>, elapsedMs: number, canaries: Array<string>}>}
173
179
  */
174
- export async function runTesterProbes({ driver, actionRecords = [], screenshots = [], observation = null, signal = null, log = () => {}, sleep = ms => new Promise(resolve => setTimeout(resolve, ms)), timing = PROBE_TIMING, only = null, loading = false, retries = timing.retries, save = true }) {
180
+ export async function runTesterProbes({ driver, actionRecords = [], screenshots = [], observation = null, signal = null, log = () => {}, sleep = ms => new Promise(resolve => setTimeout(resolve, ms)), timing = PROBE_TIMING, only = null, loading = false, retries = timing.retries, save = true, avoid = [] }) {
181
+ // What the brief asks the run to stay out of (./avoid.js): no probe sees a control it names, so none presses it.
182
+ const guard = createAvoidGuard(avoid);
175
183
  const session = driver.edgeSession();
176
184
  const page = session.page;
177
185
  const started = Date.now();
178
186
  const left = () => timing.budgetMs - (Date.now() - started);
179
187
  const checks = [];
180
- const stopped = () => Boolean(signal && signal.aborted) || Boolean(session.gameEnded && session.gameEnded());
181
- const evaluate = (fn, arg) => { let timer; return Promise.race([Promise.resolve().then(() => page.evaluate(fn, arg)), new Promise((resolve, reject) => { timer = setTimeout(() => reject(new Error('the page did not answer')), 8000); })]).finally(() => clearTimeout(timer)); };
182
- const controls = () => evaluate(pageControls).catch(() => ({ buttons: [], fields: [], text: '', canvas: null }));
183
- const print = async () => { try { return pngFingerprint(await page.screenshot({ type: 'png', timeout: 10000 })); } catch { return null; } };
188
+ // Why the page or its browser can take no more input: then every probe after it is not checked, and the pass ends.
189
+ let hung = null;
190
+ const browserGone = () => { try { const browser = page.context().browser(); return page.isClosed() || Boolean(browser && !browser.isConnected()); } catch { return true; } };
191
+ const stopped = () => Boolean(signal && signal.aborted) || Boolean(session.gameEnded && session.gameEnded()) || Boolean(hung) || browserGone();
192
+ const stopWhy = () => (hung || (browserGone() ? 'the browser closed' : 'the page had ended'));
193
+ /** One input to the page, bounded: true when it was taken, false when it failed; one the page never answers stops the pass. */
194
+ const input = async (work, ms = INPUT_MS) => {
195
+ if (hung || browserGone()) return false;
196
+ let timer;
197
+ const took = await Promise.race([Promise.resolve().then(work).then(() => true, () => false), new Promise(resolve => { timer = setTimeout(() => resolve(null), ms); })]).finally(() => clearTimeout(timer));
198
+ if (took === null) hung = hung || 'the page stopped answering input';
199
+ return took === true;
200
+ };
201
+ const mouse = { click: (x, y, options) => input(() => page.mouse.click(x, y, options)), move: (x, y) => input(() => page.mouse.move(x, y)) };
202
+ const keys = { down: key => input(() => page.keyboard.down(key)), up: key => input(() => page.keyboard.up(key)), press: key => input(() => page.keyboard.press(key)) };
203
+ const evaluate = (fn, arg) => { if (hung) return Promise.reject(new Error(hung)); let timer; return Promise.race([Promise.resolve().then(() => page.evaluate(fn, arg)), new Promise((resolve, reject) => { timer = setTimeout(() => reject(new Error('the page did not answer')), 8000); })]).finally(() => clearTimeout(timer)); };
204
+ // A page that stopped answering is not asked again: each ask would wait out its own timeout.
205
+ const leaveAlone = c => ({ ...c, buttons: (c.buttons || []).filter(b => !guard.skip(b.name)), fields: (c.fields || []).filter(f => !guard.skip(f.name)) });
206
+ const controls = () => (hung ? Promise.resolve({ buttons: [], fields: [], text: '', canvas: null }) : evaluate(pageControls).then(leaveAlone).catch(() => ({ buttons: [], fields: [], text: '', canvas: null })));
207
+ const print = async () => { if (hung) return null; try { return pngFingerprint(await page.screenshot({ type: 'png', timeout: 10000 })); } catch { return null; } };
184
208
  const look = async () => { const c = await controls(); return { ...c, print: await print(), sig: `${c.text}\n${c.buttons.map(b => `${b.name}|${b.disabled ? 1 : 0}`).join('\n')}` }; };
185
209
  const differs = (a, b) => a.sig !== b.sig || (a.print && b.print ? significant(screenDelta(a.print, b.print)) : false);
186
210
  const errors = () => (session.drainErrors ? session.drainErrors() : []).filter(entry => entry && (entry.type === 'pageerror' || (entry.type === 'console' && !/favicon|Failed to load resource/i.test(String(entry.text))))).map(entry => ({ thrown: entry.type === 'pageerror', text: String(entry.text || '').slice(0, 200) }));
187
211
  const alive = async () => { let timer; try { return await Promise.race([Promise.resolve().then(() => page.evaluate(() => 1)).then(() => true, () => true), new Promise(resolve => { timer = setTimeout(() => resolve(false), 5000); })]); } finally { clearTimeout(timer); } };
188
212
  const shot = async (name, reason) => {
189
- if (!save) return null;
213
+ if (!save || hung) return null;
190
214
  try {
191
- const saved = await driver.screenshot(name);
215
+ let timer;
216
+ const saved = await Promise.race([Promise.resolve().then(() => driver.screenshot(name)), new Promise(resolve => { timer = setTimeout(() => resolve(null), 10000); })]).finally(() => clearTimeout(timer));
192
217
  if (saved && saved.relativePath) { screenshots.push({ ...saved, edge: true, reason: `tester probe: ${reason} (saved by the runner)`, ...(Number.isInteger(observation) ? { observation } : {}), at: Date.now(), order: Number.MAX_SAFE_INTEGER - 200 + screenshots.length }); return saved.relativePath; }
193
218
  } catch { /* no picture is still a check */ }
194
219
  return null;
195
220
  };
196
- const park = async () => { await page.mouse.move(1, 1).catch(() => {}); await evaluate(pageRings, true).catch(() => {}); };
221
+ const park = async () => { await mouse.move(1, 1).catch(() => {}); await evaluate(pageRings, true).catch(() => {}); };
197
222
  /** Click a button by its name as it is on the page now. `{ ok, changed }`. */
198
223
  const click = async name => {
199
224
  await park();
200
225
  const before = await look();
201
226
  const button = before.buttons.find(b => b.name === name);
202
227
  if (!button) return { ok: false, changed: false, before };
203
- await page.mouse.click(button.x, button.y).catch(() => {});
204
- await page.mouse.move(1, 1).catch(() => {});
228
+ await mouse.click(button.x, button.y).catch(() => {});
229
+ await mouse.move(1, 1).catch(() => {});
205
230
  await sleep(timing.settleMs);
206
231
  const after = await look();
207
232
  return { ok: true, disabled: button.disabled, changed: differs(before, after), before, after };
208
233
  };
209
- const press = async (key, ms = 120) => { await park(); const before = await look(); await page.keyboard.down(key).catch(() => {}); await sleep(ms); await page.keyboard.up(key).catch(() => {}); await sleep(timing.settleMs); const after = await look(); return { changed: differs(before, after), before, after }; };
234
+ const press = async (key, ms = 120) => { await park(); const before = await look(); await keys.down(key).catch(() => {}); await sleep(ms); await keys.up(key).catch(() => {}); await sleep(timing.settleMs); const after = await look(); return { changed: differs(before, after), before, after }; };
210
235
  const pressable = list => list.filter(b => !b.disabled && !RISKY.test(b.name));
211
236
  const answered = new Set();
212
237
  const names = l => l.buttons.map(b => b.name).join('|');
@@ -237,7 +262,7 @@ export async function runTesterProbes({ driver, actionRecords = [], screenshots
237
262
  const judge = async (what, { before = null, softLock = true } = {}) => {
238
263
  const hits = [];
239
264
  if (session.gameEnded && session.gameEnded()) { hits.push({ oracle: 'crash', severity: 'blocker', category: 'bug', title: `The page ended after ${what}`, description: `The page running the game ended after ${what}. It had run through play.` }); return hits; }
240
- if (!(await alive())) { hits.push({ oracle: 'frozen', severity: 'major', category: 'bug', title: `The page stopped answering after ${what}`, description: `After ${what} the page did not answer for five seconds: its main thread is busy or stuck.` }); return hits; }
265
+ if (hung || !(await alive())) { hits.push({ oracle: 'frozen', severity: 'major', category: 'bug', title: `The page stopped answering after ${what}`, description: `After ${what} the page did not answer for five seconds: its main thread is busy or stuck.` }); return hits; }
241
266
  for (const e of errors()) hits.push({ oracle: 'error', key: e.text.replace(/\d+/g, '#'), ...(e.thrown ? { thrown: true } : {}), severity: e.thrown ? 'major' : 'minor', category: 'bug', title: e.thrown ? `A script error was raised when ${what}` : `The game logged an error when ${what}`, description: `${e.thrown ? 'The game threw an error that nothing caught' : 'The game wrote an error to the console'} when ${what}: ${q(e.text)}.` });
242
267
  const now = await look();
243
268
  const share = flatShare(now.print);
@@ -263,7 +288,7 @@ export async function runTesterProbes({ driver, actionRecords = [], screenshots
263
288
  if ((id === 'loading') !== Boolean(loading)) return;
264
289
  const title = PROBES.find(p => p[0] === id)[1];
265
290
  const add = check => { checks.push({ name: id, title, ...check }); log(`tester probe, ${title}: ${check.status}${check.detail ? ` (${check.detail})` : ''}`); };
266
- if (stopped()) return add({ status: 'not_checked', detail: 'the page had ended' });
291
+ if (stopped()) return add({ status: 'not_checked', detail: stopWhy() });
267
292
  const stuck = suspects.find(s => ['soft_lock', 'frozen', 'crash', 'blank'].includes(s.oracle));
268
293
  if (stuck) return add({ status: 'not_checked', detail: `the game had stopped answering after ${stuck.what}` });
269
294
  if (left() < 5000) return add({ status: 'not_checked', detail: 'no time was left for it' });
@@ -278,246 +303,263 @@ export async function runTesterProbes({ driver, actionRecords = [], screenshots
278
303
  }
279
304
  };
280
305
 
281
- await session.releaseClock();
282
- if (session.dismissDialogs) session.dismissDialogs(true);
283
- // The element play left focused gets the focus back afterwards: the edge
284
- // checks that follow press the session's keys where play left them, not on
285
- // the last button a probe clicked.
286
- const focusMark = loading ? false : await evaluate(() => { const el = document.activeElement; if (!el || el === document.body) return false; el.setAttribute('data-ravensight-play-focus', '1'); return true; }).catch(() => false);
287
- try {
288
- errors();
289
- await evaluate(pageRings, true).catch(() => {});
290
- const start = await look();
291
- const keyboard = Boolean(start.canvas) || actionRecords.some(r => r && r.kind === 'action' && r.tool === 'key' && r.ok);
292
- if (!only || !loading) for (const name of workedButtons(actionRecords)) { const a = await click(name); const b = a.ok && a.changed ? await click(name) : null; if (b && b.ok && b.changed) canaries.push(name); }
293
-
294
- await run('overflow', async () => {
295
- const r = await evaluate(pageOverflow, 6).catch(() => null);
296
- if (!r) return { skip: 'the page could not be measured' };
297
- if (!r.texts) return { skip: r.canvas ? 'the game draws its text on a canvas, which the runner cannot measure' : 'the page shows no text to measure' };
298
- const what = 'the page was measured';
299
- const hits = r.found.length ? [{ oracle: 'overflow', key: r.found[0].text, severity: 'minor', category: 'ux', title: `Text is cut off: ${q(r.found[0].text)}`, description: `${r.found.slice(0, 4).map(f => `${q(f.text)} is ${f.px} pixels ${f.how}`).join('; ')}.` }] : [];
300
- return { hits, what, again: async () => { const n = await evaluate(pageOverflow, 6).catch(() => null); return Boolean(n && n.found.some(f => f.text === r.found[0].text)); } };
301
- });
302
-
303
- await run('rapid', async () => {
304
- const now = await look();
305
- const name = canaries[0] || (pressable(now.buttons)[0] || {}).name;
306
- if (!name) return { skip: 'no button was known to do anything on this screen' };
307
- const what = `${q(name)} was clicked ${timing.rapidClicks} times as fast as possible`;
308
- const once = async () => {
309
- const before = await look();
310
- const button = before.buttons.find(b => b.name === name);
311
- if (!button) return [];
312
- errors();
313
- for (let i = 0; i < timing.rapidClicks; i += 1) { await page.mouse.click(button.x, button.y).catch(() => {}); await sleep(timing.rapidGapMs); }
314
- await sleep(timing.settleMs);
315
- return judge(what, { before });
316
- };
317
- const hits = await once();
318
- if (names(await look()) !== names(now)) { answered.add(name); await comeBack(now); }
319
- return { hits, what, again: async hit => {
320
- // A control the game has since disabled or taken away cannot be pressed again: that try was never made.
321
- const button = (await look()).buttons.find(b => b.name === name);
322
- if (!button || button.disabled) return { untried: `${q(name)} was ${button ? 'disabled' : 'gone'} by then, so it could only be tried again from a fresh start` };
323
- return (await once()).some(h => h.oracle === hit.oracle && h.key === hit.key);
324
- } };
325
- });
326
-
327
- await run('untried', async () => {
328
- const now = await look();
329
- const played = namedInPlay(actionRecords);
330
- const list = pressable(now.buttons).filter(b => !played.has(b.name.toLowerCase()) && ![...played].some(p => p.includes(`"${b.name.toLowerCase()}"`))).slice(0, timing.maxSweep);
331
- if (pressable(now.buttons).length === 0) return { skip: 'the page play ended on lists no buttons' };
332
- if (list.length === 0) return { detail: 'play had already named every button on this page' };
333
- const beside = b => now.fields.some(f => Math.abs(f.y - b.y) <= 40);
334
- const hits = [];
335
- let dead = null;
336
- for (const b of list) {
337
- if (left() < 5000 || stopped()) break;
338
- errors();
339
- const first = await click(b.name);
340
- if (!first.ok) continue;
341
- if (first.changed) answered.add(b.name);
342
- if (!first.changed && !UNSEEN_EFFECT.test(b.name) && !answered.has(b.name) && !beside(b)) {
343
- await press('Escape');
344
- const second = await click(b.name);
345
- if (second.ok && second.changed) await comeBack(now);
346
- if (second.ok && !second.changed && !dead) { dead = b.name; hits.push({ oracle: 'dead_control', key: b.name, severity: 'minor', category: 'ux', title: `${q(b.name)} does nothing when clicked`, description: `The button ${q(b.name)} was clicked twice, with Escape pressed in between in case something was open over it. The page was answering, and its picture, its text and its buttons were the same before and after. Play had never named it.` }); }
347
- }
348
- hits.push(...await judge(`${q(b.name)} was clicked`, { before: first.before, softLock: false }));
349
- if (first.changed && !(await comeBack(now))) break;
350
- }
351
- return { hits, what: dead ? `${q(dead)} was clicked` : 'the buttons play never named were clicked', again: async hit => { if (hit.oracle !== 'dead_control') return false; const r = await click(hit.key); return r.ok && !r.changed; }, detail: `${list.length} pressed` };
352
- });
353
-
354
- await run('text', async () => {
355
- const now = await look();
356
- if (now.fields.length === 0) return { skip: now.canvas ? 'no text field is on the page (one drawn on a canvas cannot be filled by this probe)' : 'the page play ended on has no text field' };
357
- const field = now.fields[0];
358
- const hits = [];
359
- const tryText = async (label, text) => {
360
- const at = (await look()).fields.find(f => f.name === field.name);
361
- if (!at) return [];
362
- errors();
363
- const before = await look();
364
- const filled = await evaluate(pageFill, [at.x, at.y, text]).catch(() => null);
365
- if (!filled) return [];
366
- await page.keyboard.press('Enter').catch(() => {});
367
- await sleep(timing.settleMs);
368
- const what = `${label} was entered in ${q(field.name)} and Enter was pressed`;
369
- const found = await judge(what, { before, softLock: false });
370
- if (text === ODD_TEXT && await evaluate(pageMarkup, MARKUP_ID).catch(() => false)) found.push({ oracle: 'markup', severity: 'major', category: 'bug', title: 'Text the player types is inserted into the page as markup', description: `Text typed into ${q(field.name)} that contained a markup tag was put into the page as markup, not shown as the characters typed. A player's name or message can change the page it is shown on.` });
371
- if (text.length >= 1000) { const over = await evaluate(pageOverflow, 3).catch(() => null); const long = over ? over.found.find(o => /A{20}/.test(o.text)) : null; if (long) found.push({ oracle: 'overflow_input', severity: 'minor', category: 'ux', title: 'Very long typed text runs out of its box', description: `After ${label} was entered in ${q(field.name)}, the game showed it ${long.px} pixels ${long.how}. The field takes ${filled.max ? `up to ${filled.max}` : 'any number of'} characters.` }); }
372
- return found.map(h => ({ ...h, text, label }));
373
- };
374
- for (const [label, text] of [['nothing', ''], [`${timing.longText} characters`, 'A'.repeat(timing.longText)], ['unusual text (markup, quotes, other scripts, an emoji)', ODD_TEXT]]) hits.push(...await tryText(label, text));
375
- const back = (await look()).fields.find(f => f.name === field.name);
376
- if (back) await evaluate(pageFill, [back.x, back.y, '']).catch(() => {});
306
+ // The pass keeps to its time whatever a probe waits on: past its budget and a grace it ends with what it has.
307
+ let deadlineTimer, failure = null;
308
+ const work = (async () => {
309
+ await session.releaseClock();
310
+ if (session.dismissDialogs) session.dismissDialogs(true);
311
+ // The element play left focused gets the focus back afterwards: the edge
312
+ // checks that follow press the session's keys where play left them, not on
313
+ // the last button a probe clicked.
314
+ const focusMark = loading ? false : await evaluate(() => { const el = document.activeElement; if (!el || el === document.body) return false; el.setAttribute('data-ravensight-play-focus', '1'); return true; }).catch(() => false);
315
+ try {
316
+ errors();
377
317
  await evaluate(pageRings, true).catch(() => {});
378
- return { hits, what: `text was entered in ${q(field.name)}`, again: async hit => (await tryText(hit.label, hit.text)).some(h => h.oracle === hit.oracle && h.key === hit.key) };
379
- });
380
-
381
- await run('menu', async () => {
382
- const now = await look();
383
- const opener = pressable(now.buttons).find(b => MENU.test(b.name));
384
- if (!opener) return { skip: 'no menu, shop, settings or help button was found on the page play ended on' };
385
- const numbers = text => new Map(readings(text).map(r => [r.label, r.value]));
386
- const what = `${q(opener.name)} was opened and closed twice, the second time at once`;
387
- let opened = true;
388
- const once = async () => {
389
- // Something is done first: a menu that undoes what was just done shows only when there is something to undo.
390
- for (const name of canaries) await click(name);
391
- errors();
392
- const before = await look();
393
- const n0 = numbers(before.text);
394
- const first = await click(opener.name);
395
- if (!first.ok || !first.changed) { opened = false; return []; }
396
- await comeBack(before);
397
- const again = (await look()).buttons.find(b => b.name === opener.name);
398
- if (again) { await page.mouse.click(again.x, again.y).catch(() => {}); await page.keyboard.press('Escape').catch(() => {}); await sleep(timing.settleMs); }
399
- await comeBack(before);
400
- const n1 = numbers((await look()).text);
401
- const found = await judge(what, { before });
402
- for (const [label, was] of n0) { if (!n1.has(label) || n1.get(label) === was || CLOCK.test(label)) continue; found.push({ oracle: 'menu_state', key: label, severity: 'major', category: 'bug', title: `Opening and closing ${q(opener.name)} changes "${label}"`, description: `"${label}" was ${was} before ${q(opener.name)} was opened and ${n1.get(label)} after it was closed again. Nothing was done in between but opening and leaving it.` }); break; }
403
- return found;
404
- };
405
- const hits = await once();
406
- if (!opened) return { skip: `clicking ${q(opener.name)} did not open anything` };
407
- return { hits, what, again: async hit => (await once()).some(h => h.oracle === hit.oracle && h.key === hit.key) };
408
- });
409
-
410
- await run('pause', async () => {
411
- const now = await look();
412
- const control = now.buttons.find(b => !b.disabled && PAUSE.test(b.name));
413
- if (!control) return { skip: 'no pause button was found on the page play ended on' };
414
- const what = `the game was paused with ${q(control.name)} and resumed`;
415
- const frames = () => evaluate(() => new Promise(resolve => { let n = 0; const tick = () => { n += 1; requestAnimationFrame(tick); }; requestAnimationFrame(tick); setTimeout(() => resolve(n), 400); })).catch(() => null);
416
- const moving = async () => { const a = await print(); await sleep(400); const b = await print(); return Boolean(a && b && significant(screenDelta(a, b))); };
417
- const once = async () => {
418
- errors();
419
- const before = await look();
420
- const movedBefore = await moving();
421
- const paused = await click(control.name);
422
- if (!paused.ok) return [];
423
- const resume = pressable((await look()).buttons).find(b => RESUME.test(b.name) || PAUSE.test(b.name));
424
- if (resume) await click(resume.name);
425
- const found = await judge(what, { before });
426
- // The page still draws frames; a game that moved before the pause and stands still after the resume did not come back.
427
- if (movedBefore && found.length === 0 && (await frames()) !== null && !(await moving())) found.push({ oracle: 'pause_stuck', severity: 'major', category: 'bug', title: `The game does not come back after a pause with ${q(control.name)}`, description: `Before the pause the screen moved on its own. After pausing with ${q(control.name)} and resuming, it stood still: the game stayed paused, or its loop did not start again.` });
428
- return found;
429
- };
430
- return { hits: await once(), what, again: async hit => (await once()).some(h => h.oracle === hit.oracle && h.key === hit.key) };
431
- });
432
-
433
- await run('opposite', async () => {
434
- if (!keyboard) return { skip: 'the game has no canvas and play pressed no key, so it does not seem to be played by keys' };
435
- const what = `opposite keys were held together (${OPPOSITES.map(p => p.join(' with ')).join(', ')})`;
436
- const once = async () => {
437
- errors();
438
- const before = await look();
439
- for (const [a, b] of OPPOSITES) { await page.keyboard.down(a).catch(() => {}); await page.keyboard.down(b).catch(() => {}); await sleep(timing.holdMs); await page.keyboard.up(a).catch(() => {}); await page.keyboard.up(b).catch(() => {}); await sleep(100); }
440
- await sleep(timing.settleMs);
441
- return judge(what, { before });
442
- };
443
- return { hits: await once(), what, again: async hit => (await once()).some(h => h.oracle === hit.oracle && h.key === hit.key) };
444
- });
445
-
446
- await run('edges', async () => {
447
- if (!keyboard) return { skip: 'the game has no canvas and play pressed no key, so there is no player to push to an edge' };
448
- const what = 'the player was pushed to the edges of the play area';
449
- const once = async () => {
450
- errors();
451
- const before = await look();
452
- for (const key of ['ArrowLeft', 'ArrowUp', 'ArrowRight', 'ArrowDown']) {
453
- if (left() < 4000 || stopped()) break;
454
- const from = Date.now();
455
- await page.keyboard.down(key).catch(() => {});
456
- let last = await print();
457
- while (Date.now() - from < timing.edgeMaxMs) { await sleep(timing.edgeHoldMs); const now = await print(); const moved = last && now && significant(screenDelta(last, now)); last = now; if (!moved) break; }
458
- await page.keyboard.up(key).catch(() => {});
459
- await sleep(80);
318
+ const start = await look();
319
+ const keyboard = Boolean(start.canvas) || actionRecords.some(r => r && r.kind === 'action' && r.tool === 'key' && r.ok);
320
+ if (!only || !loading) for (const name of workedButtons(actionRecords)) { const a = await click(name); const b = a.ok && a.changed ? await click(name) : null; if (b && b.ok && b.changed) canaries.push(name); }
321
+
322
+ await run('overflow', async () => {
323
+ const r = await evaluate(pageOverflow, 6).catch(() => null);
324
+ if (!r) return { skip: 'the page could not be measured' };
325
+ if (!r.texts) return { skip: r.canvas ? 'the game draws its text on a canvas, which the runner cannot measure' : 'the page shows no text to measure' };
326
+ const what = 'the page was measured';
327
+ const hits = r.found.length ? [{ oracle: 'overflow', key: r.found[0].text, severity: 'minor', category: 'ux', title: `Text is cut off: ${q(r.found[0].text)}`, description: `${r.found.slice(0, 4).map(f => `${q(f.text)} is ${f.px} pixels ${f.how}`).join('; ')}.` }] : [];
328
+ return { hits, what, again: async () => { const n = await evaluate(pageOverflow, 6).catch(() => null); return Boolean(n && n.found.some(f => f.text === r.found[0].text)); } };
329
+ });
330
+
331
+ await run('rapid', async () => {
332
+ const now = await look();
333
+ const name = canaries[0] || (pressable(now.buttons)[0] || {}).name;
334
+ if (!name) return { skip: 'no button was known to do anything on this screen' };
335
+ const what = `${q(name)} was clicked ${timing.rapidClicks} times as fast as possible`;
336
+ const once = async () => {
337
+ const before = await look();
338
+ const button = before.buttons.find(b => b.name === name);
339
+ if (!button) return [];
340
+ errors();
341
+ for (let i = 0; i < timing.rapidClicks; i += 1) { await mouse.click(button.x, button.y).catch(() => {}); await sleep(timing.rapidGapMs); }
342
+ await sleep(timing.settleMs);
343
+ return judge(what, { before });
344
+ };
345
+ const hits = await once();
346
+ if (names(await look()) !== names(now)) { answered.add(name); await comeBack(now); }
347
+ return { hits, what, again: async hit => {
348
+ // A control the game has since disabled or taken away cannot be pressed again: that try was never made.
349
+ const button = (await look()).buttons.find(b => b.name === name);
350
+ if (!button || button.disabled) return { untried: `${q(name)} was ${button ? 'disabled' : 'gone'} by then, so it could only be tried again from a fresh start` };
351
+ return (await once()).some(h => h.oracle === hit.oracle && h.key === hit.key);
352
+ } };
353
+ });
354
+
355
+ await run('untried', async () => {
356
+ const now = await look();
357
+ const played = namedInPlay(actionRecords);
358
+ const list = pressable(now.buttons).filter(b => !played.has(b.name.toLowerCase()) && ![...played].some(p => p.includes(`"${b.name.toLowerCase()}"`))).slice(0, timing.maxSweep);
359
+ if (pressable(now.buttons).length === 0) return { skip: 'the page play ended on lists no buttons' };
360
+ if (list.length === 0) return { detail: 'play had already named every button on this page' };
361
+ const beside = b => now.fields.some(f => Math.abs(f.y - b.y) <= 40);
362
+ const hits = [];
363
+ let dead = null;
364
+ for (const b of list) {
365
+ if (left() < 5000 || stopped()) break;
366
+ errors();
367
+ const first = await click(b.name);
368
+ if (!first.ok) continue;
369
+ if (first.changed) answered.add(b.name);
370
+ if (!first.changed && !UNSEEN_EFFECT.test(b.name) && !answered.has(b.name) && !beside(b)) {
371
+ await press('Escape');
372
+ const second = await click(b.name);
373
+ if (second.ok && second.changed) await comeBack(now);
374
+ if (second.ok && !second.changed && !dead) { dead = b.name; hits.push({ oracle: 'dead_control', key: b.name, severity: 'minor', category: 'ux', title: `${q(b.name)} does nothing when clicked`, description: `The button ${q(b.name)} was clicked twice, with Escape pressed in between in case something was open over it. The page was answering, and its picture, its text and its buttons were the same before and after. Play had never named it.` }); }
375
+ }
376
+ hits.push(...await judge(`${q(b.name)} was clicked`, { before: first.before, softLock: false }));
377
+ if (first.changed && !(await comeBack(now))) break;
460
378
  }
461
- await sleep(timing.settleMs);
462
- return judge(what, { before });
463
- };
464
- return { hits: await once(), what, again: async hit => (await once()).some(h => h.oracle === hit.oracle && h.key === hit.key) };
465
- });
466
-
467
- await run('order', async () => {
468
- const now = await look();
469
- const list = pressable(now.buttons).filter(b => !UNSEEN_EFFECT.test(b.name)).slice(0, timing.maxSweep).reverse();
470
- if (list.length < 2) return { skip: 'the page lists fewer than two buttons to press out of order' };
471
- const what = 'the buttons were pressed in reverse order with no pause';
472
- const once = async () => {
473
- errors();
474
- const before = await look();
475
- for (const b of list) { const at = (await controls()).buttons.find(x => x.name === b.name && !x.disabled); if (at) { await page.mouse.click(at.x, at.y).catch(() => {}); await sleep(60); } }
476
- await sleep(timing.settleMs);
477
- return judge(what, { before });
478
- };
479
- return { hits: await once(), what, again: async hit => (await once()).some(h => h.oracle === hit.oracle && h.key === hit.key) };
480
- });
481
-
482
- await run('loading', async () => {
483
- const what = 'clicks and keys were sent while the page was still loading';
484
- const size = page.viewportSize() || { width: 1280, height: 720 };
485
- const once = async () => {
486
- errors();
487
- const going = page.reload({ waitUntil: 'load', timeout: 15000 }).then(() => true, () => false);
488
- const until = Date.now() + timing.loadInputMs;
489
- while (Date.now() < until) { await page.mouse.click(Math.round(size.width / 2), Math.round(size.height / 2)).catch(() => {}); await page.keyboard.press('Enter').catch(() => {}); await page.keyboard.press(' ').catch(() => {}); await sleep(40); }
490
- const loaded = await going;
491
- await sleep(timing.settleMs + 400);
492
- if (!loaded) return [{ oracle: 'no_load', severity: 'major', category: 'bug', title: 'The game does not load when input arrives while it is loading', description: 'With clicks and keys sent while the page was loading, it did not finish loading. It had loaded when left alone.' }];
493
- return judge(what, { softLock: false });
494
- };
495
- return { hits: await once(), what, again: async hit => (await once()).some(h => h.oracle === hit.oracle && h.key === hit.key) };
496
- });
497
-
498
- // Try each suspect again where it stands; a game left stuck waits for the replay.
499
- for (const s of suspects) {
500
- s.tries = 0; s.hits = 0; s.why = null; s.uncounted = false;
501
- if (['soft_lock', 'frozen', 'crash', 'blank', 'pause_stuck', 'no_load'].includes(s.oracle) && s.probe !== 'loading') { s.why = 'the game was left stuck, so it can only be tried again from a fresh start'; continue; }
502
- for (let i = 0; i < retries && left() > 3000 && !stopped() && typeof s.again === 'function'; i += 1) {
503
- const r = await Promise.resolve().then(() => s.again(s)).catch(() => false);
504
- // A try the game could not take is not a try: it is never counted as "not reproduced" (the replay tries it from a fresh start).
505
- if (r && typeof r === 'object' && r.untried) { if (!s.tries) s.why = r.untried; break; }
506
- // An error nothing caught can leave the game unable to raise it again where it stands (a game loop it
507
- // stopped): a second try that sees nothing is not counted, and the replay tries it from a fresh start.
508
- if (!r && s.thrown) { if (!s.tries) { s.why = 'an error nothing caught can leave the game unable to raise it again where it stands, so the run\'s replay tries it from a fresh start'; s.uncounted = true; } break; }
509
- s.tries += 1;
510
- if (r) s.hits += 1;
379
+ return { hits, what: dead ? `${q(dead)} was clicked` : 'the buttons play never named were clicked', again: async hit => { if (hit.oracle !== 'dead_control') return false; const r = await click(hit.key); return r.ok && !r.changed; }, detail: `${list.length} pressed` };
380
+ });
381
+
382
+ await run('text', async () => {
383
+ const now = await look();
384
+ if (now.fields.length === 0) return { skip: now.canvas ? 'no text field is on the page (one drawn on a canvas cannot be filled by this probe)' : 'the page play ended on has no text field' };
385
+ const field = now.fields[0];
386
+ const hits = [];
387
+ const tryText = async (label, text) => {
388
+ const at = (await look()).fields.find(f => f.name === field.name);
389
+ if (!at) return [];
390
+ errors();
391
+ const before = await look();
392
+ const filled = await evaluate(pageFill, [at.x, at.y, text]).catch(() => null);
393
+ if (!filled) return [];
394
+ await keys.press('Enter').catch(() => {});
395
+ await sleep(timing.settleMs);
396
+ const what = `${label} was entered in ${q(field.name)} and Enter was pressed`;
397
+ const found = await judge(what, { before, softLock: false });
398
+ if (text === ODD_TEXT && await evaluate(pageMarkup, MARKUP_ID).catch(() => false)) found.push({ oracle: 'markup', severity: 'major', category: 'bug', title: 'Text the player types is inserted into the page as markup', description: `Text typed into ${q(field.name)} that contained a markup tag was put into the page as markup, not shown as the characters typed. A player's name or message can change the page it is shown on.` });
399
+ if (text.length >= 1000) { const over = await evaluate(pageOverflow, 3).catch(() => null); const long = over ? over.found.find(o => /A{20}/.test(o.text)) : null; if (long) found.push({ oracle: 'overflow_input', severity: 'minor', category: 'ux', title: 'Very long typed text runs out of its box', description: `After ${label} was entered in ${q(field.name)}, the game showed it ${long.px} pixels ${long.how}. The field takes ${filled.max ? `up to ${filled.max}` : 'any number of'} characters.` }); }
400
+ return found.map(h => ({ ...h, text, label }));
401
+ };
402
+ for (const [label, text] of [['nothing', ''], [`${timing.longText} characters`, 'A'.repeat(timing.longText)], ['unusual text (markup, quotes, other scripts, an emoji)', ODD_TEXT]]) hits.push(...await tryText(label, text));
403
+ const back = (await look()).fields.find(f => f.name === field.name);
404
+ if (back) await evaluate(pageFill, [back.x, back.y, '']).catch(() => {});
405
+ await evaluate(pageRings, true).catch(() => {});
406
+ return { hits, what: `text was entered in ${q(field.name)}`, again: async hit => (await tryText(hit.label, hit.text)).some(h => h.oracle === hit.oracle && h.key === hit.key) };
407
+ });
408
+
409
+ await run('menu', async () => {
410
+ const now = await look();
411
+ const opener = pressable(now.buttons).find(b => MENU.test(b.name));
412
+ if (!opener) return { skip: 'no menu, shop, settings or help button was found on the page play ended on' };
413
+ const numbers = text => new Map(readings(text).map(r => [r.label, r.value]));
414
+ const what = `${q(opener.name)} was opened and closed twice, the second time at once`;
415
+ let opened = true;
416
+ const once = async () => {
417
+ // Something is done first: a menu that undoes what was just done shows only when there is something to undo.
418
+ for (const name of canaries) await click(name);
419
+ errors();
420
+ const before = await look();
421
+ const n0 = numbers(before.text);
422
+ const first = await click(opener.name);
423
+ if (!first.ok || !first.changed) { opened = false; return []; }
424
+ await comeBack(before);
425
+ const again = (await look()).buttons.find(b => b.name === opener.name);
426
+ if (again) { await mouse.click(again.x, again.y).catch(() => {}); await keys.press('Escape').catch(() => {}); await sleep(timing.settleMs); }
427
+ await comeBack(before);
428
+ const n1 = numbers((await look()).text);
429
+ const found = await judge(what, { before });
430
+ for (const [label, was] of n0) { if (!n1.has(label) || n1.get(label) === was || CLOCK.test(label)) continue; found.push({ oracle: 'menu_state', key: label, severity: 'major', category: 'bug', title: `Opening and closing ${q(opener.name)} changes "${label}"`, description: `"${label}" was ${was} before ${q(opener.name)} was opened and ${n1.get(label)} after it was closed again. Nothing was done in between but opening and leaving it.` }); break; }
431
+ return found;
432
+ };
433
+ const hits = await once();
434
+ if (!opened) return { skip: `clicking ${q(opener.name)} did not open anything` };
435
+ return { hits, what, again: async hit => (await once()).some(h => h.oracle === hit.oracle && h.key === hit.key) };
436
+ });
437
+
438
+ await run('pause', async () => {
439
+ const now = await look();
440
+ const control = now.buttons.find(b => !b.disabled && PAUSE.test(b.name));
441
+ if (!control) return { skip: 'no pause button was found on the page play ended on' };
442
+ const what = `the game was paused with ${q(control.name)} and resumed`;
443
+ const frames = () => evaluate(() => new Promise(resolve => { let n = 0; const tick = () => { n += 1; requestAnimationFrame(tick); }; requestAnimationFrame(tick); setTimeout(() => resolve(n), 400); })).catch(() => null);
444
+ const moving = async () => { const a = await print(); await sleep(400); const b = await print(); return Boolean(a && b && significant(screenDelta(a, b))); };
445
+ const once = async () => {
446
+ errors();
447
+ const before = await look();
448
+ const movedBefore = await moving();
449
+ const paused = await click(control.name);
450
+ if (!paused.ok) return [];
451
+ const resume = pressable((await look()).buttons).find(b => RESUME.test(b.name) || PAUSE.test(b.name));
452
+ if (resume) await click(resume.name);
453
+ const found = await judge(what, { before });
454
+ // The page still draws frames; a game that moved before the pause and stands still after the resume did not come back.
455
+ if (movedBefore && found.length === 0 && (await frames()) !== null && !(await moving())) found.push({ oracle: 'pause_stuck', severity: 'major', category: 'bug', title: `The game does not come back after a pause with ${q(control.name)}`, description: `Before the pause the screen moved on its own. After pausing with ${q(control.name)} and resuming, it stood still: the game stayed paused, or its loop did not start again.` });
456
+ return found;
457
+ };
458
+ return { hits: await once(), what, again: async hit => (await once()).some(h => h.oracle === hit.oracle && h.key === hit.key) };
459
+ });
460
+
461
+ await run('opposite', async () => {
462
+ if (!keyboard) return { skip: 'the game has no canvas and play pressed no key, so it does not seem to be played by keys' };
463
+ const what = `opposite keys were held together (${OPPOSITES.map(p => p.join(' with ')).join(', ')})`;
464
+ const once = async () => {
465
+ errors();
466
+ const before = await look();
467
+ for (const [a, b] of OPPOSITES) { await keys.down(a).catch(() => {}); await keys.down(b).catch(() => {}); await sleep(timing.holdMs); await keys.up(a).catch(() => {}); await keys.up(b).catch(() => {}); await sleep(100); }
468
+ await sleep(timing.settleMs);
469
+ return judge(what, { before });
470
+ };
471
+ return { hits: await once(), what, again: async hit => (await once()).some(h => h.oracle === hit.oracle && h.key === hit.key) };
472
+ });
473
+
474
+ await run('edges', async () => {
475
+ if (!keyboard) return { skip: 'the game has no canvas and play pressed no key, so there is no player to push to an edge' };
476
+ const what = 'the player was pushed to the edges of the play area';
477
+ const once = async () => {
478
+ errors();
479
+ const before = await look();
480
+ for (const key of ['ArrowLeft', 'ArrowUp', 'ArrowRight', 'ArrowDown']) {
481
+ if (left() < 4000 || stopped()) break;
482
+ const from = Date.now();
483
+ await keys.down(key).catch(() => {});
484
+ let last = await print();
485
+ while (Date.now() - from < timing.edgeMaxMs) { await sleep(timing.edgeHoldMs); const now = await print(); const moved = last && now && significant(screenDelta(last, now)); last = now; if (!moved) break; }
486
+ await keys.up(key).catch(() => {});
487
+ await sleep(80);
488
+ }
489
+ await sleep(timing.settleMs);
490
+ return judge(what, { before });
491
+ };
492
+ return { hits: await once(), what, again: async hit => (await once()).some(h => h.oracle === hit.oracle && h.key === hit.key) };
493
+ });
494
+
495
+ await run('order', async () => {
496
+ const now = await look();
497
+ const list = pressable(now.buttons).filter(b => !UNSEEN_EFFECT.test(b.name)).slice(0, timing.maxSweep).reverse();
498
+ if (list.length < 2) return { skip: 'the page lists fewer than two buttons to press out of order' };
499
+ const what = 'the buttons were pressed in reverse order with no pause';
500
+ const once = async () => {
501
+ errors();
502
+ const before = await look();
503
+ for (const b of list) { const at = (await controls()).buttons.find(x => x.name === b.name && !x.disabled); if (at) { await mouse.click(at.x, at.y).catch(() => {}); await sleep(60); } }
504
+ await sleep(timing.settleMs);
505
+ return judge(what, { before });
506
+ };
507
+ return { hits: await once(), what, again: async hit => (await once()).some(h => h.oracle === hit.oracle && h.key === hit.key) };
508
+ });
509
+
510
+ await run('loading', async () => {
511
+ const what = 'clicks and keys were sent while the page was still loading';
512
+ const size = page.viewportSize() || { width: 1280, height: 720 };
513
+ // The centre is not clicked when a control the brief says to stay out of sits there.
514
+ const centre = [Math.round(size.width / 2), Math.round(size.height / 2)];
515
+ const centreClick = !guard.lines.length || !guard.skip(await evaluate(controlNameAt, centre).catch(() => ''));
516
+ const once = async () => {
517
+ errors();
518
+ const going = page.reload({ waitUntil: 'load', timeout: 15000 }).then(() => true, () => false);
519
+ const until = Date.now() + timing.loadInputMs;
520
+ while (Date.now() < until) { if (centreClick) await mouse.click(centre[0], centre[1]).catch(() => {}); await keys.press('Enter').catch(() => {}); await keys.press(' ').catch(() => {}); await sleep(40); }
521
+ const loaded = await going;
522
+ await sleep(timing.settleMs + 400);
523
+ if (!loaded) return [{ oracle: 'no_load', severity: 'major', category: 'bug', title: 'The game does not load when input arrives while it is loading', description: 'With clicks and keys sent while the page was loading, it did not finish loading. It had loaded when left alone.' }];
524
+ return judge(what, { softLock: false });
525
+ };
526
+ return { hits: await once(), what, again: async hit => (await once()).some(h => h.oracle === hit.oracle && h.key === hit.key) };
527
+ });
528
+
529
+ // Try each suspect again where it stands; a game left stuck waits for the replay.
530
+ for (const s of suspects) {
531
+ s.tries = 0; s.hits = 0; s.why = null; s.uncounted = false;
532
+ if (['soft_lock', 'frozen', 'crash', 'blank', 'pause_stuck', 'no_load'].includes(s.oracle) && s.probe !== 'loading') { s.why = 'the game was left stuck, so it can only be tried again from a fresh start'; continue; }
533
+ for (let i = 0; i < retries && left() > 3000 && !stopped() && typeof s.again === 'function'; i += 1) {
534
+ const r = await Promise.resolve().then(() => s.again(s)).catch(() => false);
535
+ // A try the game could not take is not a try: it is never counted as "not reproduced" (the replay tries it from a fresh start).
536
+ if (r && typeof r === 'object' && r.untried) { if (!s.tries) s.why = r.untried; break; }
537
+ // An error nothing caught can leave the game unable to raise it again where it stands (a game loop it
538
+ // stopped): a second try that sees nothing is not counted, and the replay tries it from a fresh start.
539
+ if (!r && s.thrown) { if (!s.tries) { s.why = 'an error nothing caught can leave the game unable to raise it again where it stands, so the run\'s replay tries it from a fresh start'; s.uncounted = true; } break; }
540
+ s.tries += 1;
541
+ if (r) s.hits += 1;
542
+ }
543
+ if (!s.tries && retries > 0 && !s.why) s.why = 'no time was left';
544
+ }
545
+ } finally {
546
+ // A page that stopped answering has nothing to put back, and every ask would wait out its timeout.
547
+ if (!hung) {
548
+ if (focusMark) await evaluate(() => { const el = document.querySelector('[data-ravensight-play-focus]'); if (el) { el.removeAttribute('data-ravensight-play-focus'); el.focus(); } }).catch(() => {});
549
+ await evaluate(pageRings, false).catch(() => {});
550
+ if (session.dismissDialogs) session.dismissDialogs(false);
551
+ await Promise.resolve().then(() => session.parkClock()).catch(() => {});
511
552
  }
512
- if (!s.tries && retries > 0 && !s.why) s.why = 'no time was left';
513
553
  }
514
- } finally {
515
- if (focusMark) await evaluate(() => { const el = document.querySelector('[data-ravensight-play-focus]'); if (el) { el.removeAttribute('data-ravensight-play-focus'); el.focus(); } }).catch(() => {});
516
- await evaluate(pageRings, false).catch(() => {});
517
- if (session.dismissDialogs) session.dismissDialogs(false);
518
- await Promise.resolve().then(() => session.parkClock()).catch(() => {});
554
+ })().catch(error => { failure = error; });
555
+ const late = await Promise.race([work.then(() => false), new Promise(resolve => { deadlineTimer = setTimeout(() => resolve(true), Math.max(0, timing.budgetMs) + PASS_GRACE_MS); })]);
556
+ clearTimeout(deadlineTimer);
557
+ if (late) {
558
+ hung = hung || 'the probes ran out of time';
559
+ for (const [id, title] of PROBES) if (!checks.some(c => c.name === id) && (id === 'loading') === Boolean(loading) && (!only || only.includes(id))) { checks.push({ name: id, title, status: 'not_checked', detail: hung }); log(`tester probe, ${title}: not_checked (${hung})`); }
519
560
  }
520
- return { checks, suspects: suspects.map(({ again: _again, ...rest }) => rest), canaries, elapsedMs: Date.now() - started };
561
+ if (failure && !late) throw failure;
562
+ return { checks: [...checks], suspects: suspects.map(({ again: _again, ...rest }) => rest), canaries: [...canaries], elapsedMs: Date.now() - started, ...(hung ? { stopped: hung } : {}), avoided: guard.list() };
521
563
  }
522
564
 
523
565
  /**
@@ -577,6 +619,7 @@ export function probesMarkdown(pass) {
577
619
  if (!check) return `- **${title}**: not tested. The probes ended before it.`;
578
620
  return `- **${title}**: ${STATUS[check.status] || check.status}. ${String(check.detail || '').replace(/\.?$/, '.')}`;
579
621
  });
622
+ if (Array.isArray(pass.avoided) && pass.avoided.length) lines.push('', `Not pressed, because the brief asks to stay out of it: ${pass.avoided.map(name => `"${String(name).replace(/"/g, "'")}"`).join(', ')}.`);
580
623
  lines.push('', `A soft lock was ${pass.canaries && pass.canaries.length ? `watched for after each probe, with ${pass.canaries.length === 1 ? 'a button' : `${pass.canaries.length} buttons`} that changed the screen twice running` : 'not watched for: no button play pressed changed the screen twice running, so there was nothing to compare against'}. These probes are scripted. Not tested never means it works.`);
581
624
  return lines.join('\n').replace(/[\u2013\u2014]/g, ',');
582
625
  }
package/src/run/tools.js CHANGED
@@ -732,6 +732,17 @@ export async function executeTool({ driver, toolUse, onNote, onScreenshot, stale
732
732
  // The runner refused to leave the build. The persona is told so in plain
733
733
  // text and plays on: it is a step that changed nothing, never an error and
734
734
  // never a run failure. No observation either, because nothing moved.
735
+ // An input on a control the brief asks the run to stay out of: not sent. The persona is told plainly and plays on.
736
+ if (outcome.refused === 'avoided') {
737
+ return {
738
+ result: toolResult(toolUse.id, `Not sent: the brief asks to stay out of "${outcome.name}". Leave it alone and choose another input.`),
739
+ observation: null,
740
+ spentAction: false,
741
+ changed: false,
742
+ error: null,
743
+ refused: 'avoided'
744
+ };
745
+ }
735
746
  if (outcome.refused === 'off_site') {
736
747
  return {
737
748
  result: toolResult(toolUse.id, offSiteRefusalText(outcome.host)),