ravensight-playtest 0.13.3 → 0.16.0

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.
@@ -1,5 +1,5 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { pngFingerprint, screenDelta, significant } from '../pixels.js';
2
+ import { pngFingerprint, screenDelta, significant, motionBlocks, bracketMask, bracketVerdict, BRACKET_MS, MASK_MAX_SHARE, decodePng, motionMoves, sweepMask, scrollMotionBlocks, scrollShift, steadyScroll, scrollJudge } from '../pixels.js';
3
3
  import { findRegions } from '../regions.js';
4
4
  import { createMarker, isMarkTarget, marksFor, marksText, resolveMark } from '../marks.js';
5
5
  import { gameTime, timeFreezeInit } from '../timeFreeze.js';
@@ -350,6 +350,9 @@ export async function fieldValue(locator) {
350
350
  /** How long `act` waits once for a late change (a navigation still starting) before it says the screen did not change. */
351
351
  export const SETTLE_MS = 300;
352
352
 
353
+ /** What the persona reads when an input's whole change lay inside what moves by itself on the screen. */
354
+ export const SELF_ONLY_NOTE = 'Part of the screen changed, but only what moves on its own.';
355
+
353
356
  /**
354
357
  * Whether an action changed anything: the URL, the document (a navigation or
355
358
  * a reload), the compacted tree (which carries every field's value), or for
@@ -1107,6 +1110,15 @@ export function textOnScreen(nodes, target) {
1107
1110
  /** What a target that is none of a ref, coordinates or visible text is told. */
1108
1111
  export const NOT_A_TARGET_MESSAGE = 'is not a ref, coordinates or text on the current screen; use the ref the snapshot shows, such as e12';
1109
1112
 
1113
+ /**
1114
+ * What a select on a game's canvas is told (the cloud runner says the same): a dropdown a
1115
+ * game engine draws (a Godot OptionButton in a web export) has no options in the page, so it
1116
+ * is opened and chosen with two clicks where the picture shows it. Before, the select clicked
1117
+ * the middle of the game, an input nobody asked for, then waited the full action timeout for
1118
+ * an option the page never holds.
1119
+ */
1120
+ export const CANVAS_SELECT_MESSAGE = 'a dropdown drawn on the game\'s canvas has no options in the page, so select cannot choose from it. Click the dropdown where the picture shows it to open it, then click the option the same way: its grid cell, its mark, or x and y read off the screenshot. This is a limit of the runner, not of the game';
1121
+
1110
1122
  /**
1111
1123
  * How long a click by words on a canvas game looks for those words in the page before it is refused. The words of a game drawn
1112
1124
  * on a canvas are in the picture, not in the page, so there is nothing to wait for: the paid local run of 2026-11-20 waited the
@@ -1225,15 +1237,19 @@ export function tapSdkEvents(request, log) {
1225
1237
  export const CHECK_PLAYTEST_IDENTITY = Object.freeze({ token: 'check', runId: null, jobId: null, persona: 'check' });
1226
1238
 
1227
1239
  /**
1228
- * Chromium's arguments. A recorded run is muted; a live site run can resolve
1229
- * only the names its rules allow (../livesite/resolver.js), because the route
1230
- * never sees a redirect's next hop or a WebSocket.
1240
+ * Chromium's arguments. A recorded run is muted; a headless run gets a fake
1241
+ * audio device (`--disable-audio-output`), so the game's sound is measured
1242
+ * (../anygame/sound.js) and never reaches this machine's speakers, where
1243
+ * nobody is watching; a headed run keeps the real device for the person who
1244
+ * is. A live site run can resolve only the names its rules allow
1245
+ * (../livesite/resolver.js), because the route never sees a redirect's next
1246
+ * hop or a WebSocket.
1231
1247
  *
1232
- * @param {{video: boolean, liveSite: Object|null}} args
1248
+ * @param {{video: boolean, liveSite: Object|null, headless?: boolean}} args
1233
1249
  * @returns {Array<string>}
1234
1250
  */
1235
- export function browserLaunchArgs({ video, liveSite }) {
1236
- const args = video ? ['--mute-audio'] : [];
1251
+ export function browserLaunchArgs({ video, liveSite, headless = false }) {
1252
+ const args = [...(headless ? ['--disable-audio-output'] : []), ...(video ? ['--mute-audio'] : [])];
1237
1253
  if (liveSite) {
1238
1254
  args.push(`--host-resolver-rules=${hostResolverRules({ startHost: liveSite.startHost, local: liveSite.local, addresses: liveSite.addresses || [], ravensightHosts: ravensightHosts(liveSite.ravensightOrigins || []) })}`);
1239
1255
  }
@@ -1444,6 +1460,14 @@ export async function needsFrame(page, text) {
1444
1460
  try { return (await page.evaluate(pageHasLargeCanvas, LARGE_CANVAS_SHARE)) === true; } catch { return false; }
1445
1461
  }
1446
1462
 
1463
+ /** The share of the screen a block mask covers: 1 for no mask at all (nothing could be judged by it). */
1464
+ function maskShare(mask) {
1465
+ if (!mask) return 1;
1466
+ let n = 0;
1467
+ for (let i = 0; i < mask.length; i += 1) n += mask[i];
1468
+ return mask.length ? n / mask.length : 1;
1469
+ }
1470
+
1447
1471
  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, liveSite = null, ingestOrigins = null } = {}) {
1448
1472
  const editModifier = modifier === 'Meta' || modifier === 'Control' ? modifier : platformModifier(platform);
1449
1473
  // What the brief asks the run to stay out of (../avoid.js): an input on such a control is never sent (setAvoid).
@@ -1488,7 +1512,16 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
1488
1512
  // from the first action on: loading before it runs as it always did.
1489
1513
  const clock = gameTime(() => page);
1490
1514
  let clockParked = false;
1515
+ // How long game time last ran between a release and a park (it stands still otherwise): how far what moves by itself
1516
+ // travelled during an input.
1517
+ let clockRanFrom = 0;
1518
+ let lastRanMs = 0;
1491
1519
  let canvasPlay = false;
1520
+ // A canvas game that moves by itself (the cloud runner's docs/playtest/MOVING_SCREENS.md): the frame and page text the
1521
+ // last observation measured, and the last input's after sample, for the next input's bracket.
1522
+ let lastObservedPrint = null;
1523
+ let lastObservedText = null;
1524
+ let motionChain = null;
1492
1525
  /** The compacted lines of the last observation, so a cut can prefer what is new. */
1493
1526
  let lastObservedLines = null;
1494
1527
  /** The kept nodes of the last observation: refs, names and hints, for a target that matches twice. */
@@ -1907,6 +1940,8 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
1907
1940
  async function parkClock(park) {
1908
1941
  if (!freezeTime || clockParked === park) return;
1909
1942
  clockParked = park;
1943
+ if (park) lastRanMs = Date.now() - clockRanFrom;
1944
+ else clockRanFrom = Date.now();
1910
1945
  try {
1911
1946
  await (park ? clock.pause() : clock.resume());
1912
1947
  } catch {
@@ -1931,6 +1966,64 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
1931
1966
  return (await documentToken(current)) === lastNodesDocument;
1932
1967
  }
1933
1968
 
1969
+ /**
1970
+ * After an input on a canvas game whose time is parked between inputs: one more frame BRACKET_MS of game time later
1971
+ * with no input, and what moved between the two masked with the last input's sample (../pixels.js). A shape the
1972
+ * input's game time carried off the edge is swept to it; on a screen that scrolls by itself the samples follow the
1973
+ * scroll, and the input is judged on what is left once the screen's own scroll is taken out. Answers the verdict when
1974
+ * the whole change lay inside what moves by itself, else null. The page text must not have changed: a change of the
1975
+ * words is the game answering. Never fails an input.
1976
+ */
1977
+ async function selfMotionCheck(current, before) {
1978
+ const chain = motionChain && before && !significant(screenDelta(motionChain.print, before)) ? motionChain : null;
1979
+ const ranMs = lastRanMs;
1980
+ motionChain = null;
1981
+ try {
1982
+ const snap = await snapshotText();
1983
+ const sameText = hashText(snap, shownText(snap)) === lastObservedText;
1984
+ const firstPng = await probeFrame(current);
1985
+ const first = pngFingerprint(firstPng);
1986
+ await parkClock(false);
1987
+ await new Promise(resolve => setTimeout(resolve, BRACKET_MS));
1988
+ await parkClock(true);
1989
+ const sampleMs = lastRanMs;
1990
+ const laterPng = await probeFrame(current);
1991
+ const later = pngFingerprint(laterPng);
1992
+ let after = motionBlocks(first, later);
1993
+ let firstImg = null;
1994
+ let laterImg = null;
1995
+ // Too much moved to judge by (a scroll): followed instead once the scroll is taken out.
1996
+ if (later && maskShare(after) > MASK_MAX_SHARE) {
1997
+ firstImg = decodePng(firstPng);
1998
+ laterImg = decodePng(laterPng);
1999
+ after = scrollMotionBlocks(firstImg, laterImg, first, { ms: sampleMs }) || after;
2000
+ }
2001
+ if (after && !after.scroll) after.moves = motionMoves(first, later, { ms: sampleMs });
2002
+ if (after) motionChain = { print: later, mask: after, image: after.scroll ? laterImg : null };
2003
+ const prev = chain ? chain.mask : null;
2004
+ // A chain holds only across samples of one kind: both of a still screen, or both of a scroll.
2005
+ if (!after || !prev || !sameText || Boolean(prev.scroll) !== Boolean(after.scroll)) return null;
2006
+ let seen;
2007
+ if (!after.scroll) {
2008
+ const mask = bracketMask([sweepMask(prev, prev.moves, ranMs, { dir: 1 }), sweepMask(after, after.moves, ranMs, { dir: -1 })]);
2009
+ if (!mask) return null;
2010
+ seen = significant(screenDelta(before, first, undefined, mask));
2011
+ } else {
2012
+ // The scroll during the input is taken out only when it is the screen's own: a camera that follows the player
2013
+ // scrolls because of the input.
2014
+ const shift = scrollShift(chain.image, firstImg);
2015
+ if (!shift || !steadyScroll(shift, ranMs, [prev.scroll, after.scroll])) return null;
2016
+ const judged = scrollJudge(chain.image, firstImg, shift, chain.print, { prev, sample: after });
2017
+ if (!judged) return null;
2018
+ seen = judged.seen;
2019
+ }
2020
+ const verdict = bracketVerdict(true, seen);
2021
+ return verdict.selfOnly ? verdict : null;
2022
+ } catch {
2023
+ return null;
2024
+ }
2025
+ }
2026
+
1934
2027
  /** The hash of the screen as it is now, on observe()'s basis. */
1935
2028
  async function currentHash(current) {
1936
2029
  const snap = await snapshotText();
@@ -2400,6 +2493,7 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
2400
2493
  const after = await resolved.evaluate(readChoiceControl, undefined, { timeout: ACTION_TIMEOUT_MS });
2401
2494
  return `Moved the slider from ${control.value} to ${after.value} with the arrow keys.`;
2402
2495
  }
2496
+ if (control.tag === 'CANVAS') throw new TargetError(CANVAS_SELECT_MESSAGE);
2403
2497
  if (action.option === undefined) throw new TargetError('that control is not a slider: pass option, the text of the option to choose');
2404
2498
  // A dropdown the game draws itself: open it, then press the option.
2405
2499
  await resolved.click({ timeout: ACTION_TIMEOUT_MS });
@@ -2811,12 +2905,15 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
2811
2905
  let token = null;
2812
2906
  lastMarks = null;
2813
2907
  canvasPlay = false;
2908
+ lastObservedPrint = null;
2909
+ lastObservedText = hashText(snap, shown);
2814
2910
  if (await needsFrame(current, text)) {
2815
2911
  canvasPlay = true;
2816
2912
  try {
2817
2913
  const plain = await current.screenshot({ type: OBSERVATION_FRAME.type, quality: OBSERVATION_FRAME.quality, timeout: ACTION_TIMEOUT_MS });
2818
2914
  const measured = frameToken(await probeFrame(current));
2819
2915
  token = measured.token;
2916
+ lastObservedPrint = measured.fingerprint;
2820
2917
  // The persona's copy carries a grid and marks to click by; the page
2821
2918
  // itself is never drawn on.
2822
2919
  const shownFrame = await markedFrame(plain, measured.fingerprint);
@@ -2915,7 +3012,7 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
2915
3012
  try {
2916
3013
  const playwright = await loadPlaywright(importer);
2917
3014
  await mkdir(runDir, { recursive: true });
2918
- const launchArgs = browserLaunchArgs({ video: videoRequested, liveSite });
3015
+ const launchArgs = browserLaunchArgs({ video: videoRequested, liveSite, headless: headless !== false });
2919
3016
  browser = await playwright.chromium.launch({ headless, ...(launchArgs.length ? { args: launchArgs } : {}) });
2920
3017
  const contextBase = { viewport, ...(touch ? { hasTouch: true, isMobile: true, deviceScaleFactor: 1, userAgent: PHONE_USER_AGENT } : {}) };
2921
3018
  // A live site's sign-in happens first, in a context of its own with no recording of any kind; the
@@ -3285,6 +3382,12 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
3285
3382
  if (!outcome.ok && /Timeout \d+ms exceeded/i.test(String(outcome.error || ''))) await assertAlive(current);
3286
3383
  if (canvasPlay) await parkClock(true);
3287
3384
  if (outcome.refused) return outcome;
3385
+ // A change on a canvas game that moves by itself may be the game's own: said, never turned into "nothing changed",
3386
+ // since this runner does not know where the player is (../pixels.js bracketVerdict).
3387
+ if (canvasPlay && freezeTime && outcome.ok && outcome.changed && action.kind !== 'wait') {
3388
+ const verdict = await selfMotionCheck(current, lastObservedPrint);
3389
+ if (verdict) outcome = { ...outcome, selfOnly: true, detail: outcome.detail ? `${outcome.detail}\n${SELF_ONLY_NOTE}` : SELF_ONLY_NOTE };
3390
+ } else motionChain = null;
3288
3391
  // A click, a key, a submit or a script that tried to leave the build:
3289
3392
  // the page stayed (or was brought back), and the persona is told the
3290
3393
  // same as for a refused `navigate`. A step that changed nothing.
@@ -153,6 +153,101 @@ const ODD_VALUE = /^(?:nan|undefined|null|infinity|-infinity)$/i;
153
153
  const memo = new WeakMap();
154
154
  /** The verdicts the gate reached on this run, by claim title: for the report (lib/events.mjs). */
155
155
  export const eventsDecided = run => (run && memo.get(run)) || new Map();
156
+ /** A verdict on one claim, kept for the report. */
157
+ const decide = (run, title) => (verdict, why, list, extra = {}) => {
158
+ const v = { verdict, why: noDashes(why), events: list.slice(0, 4).map(e => ({ step: e.step, name: e.name, props: e.props })), ...extra };
159
+ if (!memo.has(run)) memo.set(run, new Map());
160
+ memo.get(run).set(title, v);
161
+ return v;
162
+ };
163
+
164
+ // ---- Numbers read off the screen ---------------------------------------------------------------------------------------
165
+ //
166
+ // A claim that quotes a number ("score stays at 40", "only 1 life left", "Bois 12") is held to the value the game's own events
167
+ // carried for that same quantity in the steps the claim is about. The quantity is found by the game's own word for it first: the
168
+ // word beside the number is one of the event's own key or name words ("lives" for `{ livesLeft: 1 }`, "bois" for `{ bois: 12 }`),
169
+ // in whatever language the game uses, and only then by the English topic words above. When the events held that quantity there and
170
+ // never at the quoted value:
171
+ // contradicted for a claim about the game itself (the playtester's reading of the state), turned away like any claim the
172
+ // events contradict;
173
+ // disagrees for a claim about what the screen shows (a counter, a bar, a display): the screen may really show a number
174
+ // the game does not hold, which is a fault, so the claim is kept and the finding says what the events held.
175
+ // A number beside a word of comparison ("over 40", "more than 3") or after a slash (a maximum, "2/3") is not a reading, and only
176
+ // a quantity the events sent inside the claim's steps is held against it (a value can change with no event).
177
+ const READ_TOKENS = /(\p{L}[\p{L}\p{N}_']*)|(-?\d+(?:\.\d+)?)|(\/)|([,;.!?()\[\]])/gu;
178
+ const BETWEEN = new Set(['is', 'was', 'are', 'were', 'at', 'of', 'shows', 'showed', 'show', 'reads', 'read', 'says', 'said', 'stays', 'stayed', 'remains', 'stuck', 'frozen', 'to', 'from', 'only', 'still']);
179
+ const COMPARE = new Set(['over', 'under', 'than', 'above', 'below', 'least', 'most', 'max', 'min', 'maximum', 'minimum', 'about', 'around', 'nearly', 'almost', 'approximately', 'roughly', 'per', 'every', 'each', 'step', 'steps', 'turn', 'level', 'room', 'wave', 'round', 'x']);
180
+ // Events can reach the runner a few steps after the input that sent them (lib/events.mjs).
181
+ const LATE_STEPS = 2;
182
+ const singular = w => (w.length > 3 && w.endsWith('s') ? w.slice(0, -1) : w);
183
+
184
+ /** The numbers a claim quotes, each with the words beside it: `[{ value, words }]`. */
185
+ export function quotedNumbers(title) {
186
+ // Punctuation ends a phrase: "after the coin, 2 hearts" puts no word of the first part beside the 2.
187
+ const toks = [...noDashes(String(title || '')).replace(/(\d)\.(?!\d)/g, '$1 .').matchAll(READ_TOKENS)].map(m => (m[1] ? { word: m[1].toLowerCase().replace(/'s$/, '') } : m[2] ? { value: Number(m[2]) } : m[3] ? { slash: true } : { stop: true }));
188
+ const out = [];
189
+ toks.forEach((t, i) => {
190
+ if (t.value === undefined || !Number.isFinite(t.value)) return;
191
+ if (toks[i - 1]?.slash) return;
192
+ // Up to three words before it in its phrase, past the words that only join ("score is 40", "the score counter shows 40",
193
+ // "le bois reste à 9"), and the word just after ("40 points"). Which of them names the quantity is decided by the game's own
194
+ // event keys (keysFor), never by knowing the language.
195
+ const near = [];
196
+ for (let j = i - 1; j >= 0 && toks[j].word && near.length < 3; j--) if (!BETWEEN.has(toks[j].word) || j === i - 1) near.push(toks[j].word);
197
+ if (near.some(w => w && COMPARE.has(w))) return;
198
+ // "2/3 hearts": the word after the maximum.
199
+ const after = (toks[i + 1]?.slash && toks[i + 2]?.value !== undefined ? toks[i + 3]?.word : toks[i + 1]?.word) || null;
200
+ const words = [...near, after].filter(w => w && !BETWEEN.has(w) && !COMPARE.has(w)).map(singular);
201
+ if (words.length) out.push({ value: t.value, words });
202
+ });
203
+ return out;
204
+ }
205
+
206
+ /** The event keys holding a quoted number's quantity, by the game's own words first, then by the English topic words. */
207
+ function keysFor(evs, q, claimOther) {
208
+ const keys = new Set();
209
+ for (const e of evs) {
210
+ const otherInEvent = [...ownTokens(e)].some(w => OTHER_TOKENS.has(w));
211
+ if (otherInEvent !== claimOther) continue;
212
+ for (const [k, v] of Object.entries(e.props)) {
213
+ if (typeof v !== 'number' || !Number.isFinite(v)) continue;
214
+ const own = new Set([...tokensOf(k), ...tokensOf(e.name)].map(singular));
215
+ const byOwn = q.words.some(w => own.has(w) && !NO_ONE.has(w));
216
+ const byTopic = q.words.some(w => TOPICS.some(tp => VALUED.has(tp.id) && tp.words.test(w) && tokensOf(k).some(x => tp.tokens.includes(x) || tp.tokens.includes(singular(x)))));
217
+ if (byOwn || byTopic) keys.add(k);
218
+ }
219
+ }
220
+ return keys;
221
+ }
222
+
223
+ /** What the game's own events say about a number the claim quotes: `contradicted`, `disagrees` or null (see above). */
224
+ function numberVerdict(run, claim) {
225
+ const evs = (run?.gameEvents?.events || []).filter(e => e.phase === 'play' && Number.isSafeInteger(e.step) && e.props && typeof e.props === 'object');
226
+ if (!evs.length || !claim) return null;
227
+ const win = windowOf(claim);
228
+ if (!win) return null;
229
+ const title = String(claim.title || '');
230
+ // A value no game should have, and a reset to zero, are the rules above: they confirm, and a value they do not find says nothing.
231
+ if (IMPOSSIBLE.test(title) || RESET.test(title)) return null;
232
+ const claimOther = OTHER_ACTOR.test(title);
233
+ for (const q of quotedNumbers(title)) {
234
+ for (const k of keysFor(evs, q, claimOther)) {
235
+ const keyed = evs.filter(e => typeof e.props[k] === 'number' && [...ownTokens(e)].some(w => OTHER_TOKENS.has(w)) === claimOther);
236
+ // The value entering the claim's steps, and every value inside them (with the few steps an event may come late).
237
+ const prior = keyed.filter(e => e.step < win.from).at(-1);
238
+ const inside = keyed.filter(e => e.step >= win.from && earliest(e) <= win.to + LATE_STEPS);
239
+ // Only a quantity the game sent inside those steps speaks to them: a value can change with no event.
240
+ if (!inside.length) continue;
241
+ const held = [...(prior ? [prior] : []), ...inside];
242
+ if (held.some(e => e.props[k] === q.value)) return null;
243
+ const values = [...new Set(held.map(e => e.props[k]))];
244
+ const why = `it reads ${k} as ${q.value}, and the game's own events held ${k} at ${values.slice(0, 4).join(', ')} in the steps it is about (${show(held.at(-1))}${atStep(held.at(-1))})`;
245
+ // A claim about what the screen shows may be the screen's own fault: it is labelled, not turned away.
246
+ return decide(run, title)(NOT_STATE.test(title) ? 'disagrees' : 'contradicted', why, held);
247
+ }
248
+ }
249
+ return null;
250
+ }
156
251
 
157
252
  /**
158
253
  * What the game's own events say about a claim (`{ title, step, inputs }`): `{ verdict: 'contradicted' | 'confirmed', why,
@@ -160,18 +255,19 @@ export const eventsDecided = run => (run && memo.get(run)) || new Map();
160
255
  * empty), so such a run's gate is exactly what it was. See the top of this file for the rules.
161
256
  */
162
257
  export function eventsVerdict(run, claim) {
258
+ const v = topicVerdict(run, claim);
259
+ if (v) return v;
260
+ return numberVerdict(run, claim);
261
+ }
262
+
263
+ function topicVerdict(run, claim) {
163
264
  const evs = run?.gameEvents?.events;
164
265
  if (!Array.isArray(evs) || !evs.length || !claim) return null;
165
266
  const win = windowOf(claim);
166
267
  if (!win) return null;
167
268
  const title = String(claim.title || '');
168
269
  const inWin = evs.filter(e => e.phase === 'play' && Number.isSafeInteger(e.step) && earliest(e) >= win.from && e.step <= win.to);
169
- const done = (verdict, why, list, extra = {}) => {
170
- const v = { verdict, why: noDashes(why), events: list.slice(0, 4).map(e => ({ step: e.step, name: e.name, props: e.props })), ...extra };
171
- if (!memo.has(run)) memo.set(run, new Map());
172
- memo.get(run).set(title, v);
173
- return v;
174
- };
270
+ const done = decide(run, title);
175
271
 
176
272
  // An error the game itself reported, in the steps the claim is about: a fault in itself.
177
273
  if (ERROR_CLAIM.test(title) && !NEG_AT.test(title) && !/\bno\b/i.test(title)) {
package/src/run/events.js CHANGED
@@ -80,14 +80,15 @@ function cleanValue(v) {
80
80
  return undefined;
81
81
  }
82
82
 
83
- /** An event's top-level properties, bounded. The SDKs' own tags (rs_*, pt_*) are left out except the error kind. */
83
+ /** An event's top-level properties, bounded. The SDKs' own tags (rs_*, pt_*) are left out except the typed kind and its status. */
84
84
  export function cleanProps(data) {
85
85
  const out = {};
86
86
  if (!data || typeof data !== 'object' || Array.isArray(data)) return out;
87
87
  let n = 0;
88
88
  for (const [k0, v0] of Object.entries(data)) {
89
89
  if (n >= EVENT_LIMITS.props) break;
90
- if (/^(?:rs|pt)_/i.test(k0) && k0 !== 'rs_kind') continue;
90
+ // Normalised first (width, case, spaces and separators), so " RS_secret", "Rs-token" or a full-width "rs_x" is filtered too.
91
+ if (k0 !== 'rs_kind' && k0 !== 'rs_status' && /^(?:rs|pt)_/.test(String(k0).normalize('NFKC').trim().toLowerCase().replace(/[\s.\-]+/g, '_'))) continue;
91
92
  const k = cleanKey(k0), v = cleanValue(v0);
92
93
  if (!k || v === undefined) continue;
93
94
  out[k] = v;
@@ -230,6 +231,15 @@ export function createGameEvents({ now = Date.now, limits = EVENT_LIMITS } = {})
230
231
  return { lines: planLines(fresh.map(e => ({ ...e, ...place(e) })), limits), upTo: events.length };
231
232
  }
232
233
  function planned(upTo) { if (Number.isSafeInteger(upTo) && upTo > shownUpTo) shownUpTo = Math.min(upTo, events.length); }
234
+ /**
235
+ * The game's events kept after the first `from`, as it sent them (`{ name, props }`, the SDK's own left out), and the
236
+ * cursor for the next call. For the run's notebook (anygame/memory observe), which keeps a cursor of its own, so the
237
+ * planner's (`pendingForPlan`, `planned`) is untouched.
238
+ */
239
+ function since(from = 0) {
240
+ const start = Number.isSafeInteger(from) && from > 0 ? from : 0;
241
+ return { events: events.slice(start).filter(e => !systemEvent(e.name)).map(e => ({ name: e.name, props: e.props })), upTo: events.length };
242
+ }
233
243
 
234
244
  /**
235
245
  * Ask the game's SDK to send what it still holds, as it does when a tab is
@@ -270,7 +280,7 @@ export function createGameEvents({ now = Date.now, limits = EVENT_LIMITS } = {})
270
280
  return { total, kept: events.length, dropped, duplicates, untimed, coarse: events.filter(e => e.coarse).length, bodies, clock: by.arrival ? (by.clock ? 'mixed' : 'arrival') : 'clock', names, marks: marks.length, events: placed };
271
281
  }
272
282
 
273
- return { tap, mark, markPage, flush, pendingForPlan, planned, record, get size() { return events.length; } };
283
+ return { tap, mark, markPage, flush, pendingForPlan, planned, since, record, get size() { return events.length; } };
274
284
  }
275
285
 
276
286
  /** Where an event was placed, in words: a step, or the steps a whole-second timestamp spans. */
@@ -319,6 +329,44 @@ export function planLines(placed, limits = EVENT_LIMITS) {
319
329
  return lines;
320
330
  }
321
331
 
332
+ // ---- Outcomes ---------------------------------------------------------------------------------------------------------
333
+
334
+ // What a game's own event says about how play went: a level cleared, the game won, or the game lost (over). A win a game draws
335
+ // only on its canvas (a Unity web build's "LEVEL COMPLETE") is otherwise one reading of the picture; an event the game sent is
336
+ // measured, so it is preferred, and a game that sends events of an outcome's kind and sent none there contradicts a reading.
337
+ // Kept narrow on purpose: a death is not a game over, a level start or a level up is not a level cleared.
338
+ const PLACE_WORDS = new Set(['level', 'stage', 'round', 'wave', 'chapter', 'mission', 'puzzle', 'room', 'floor', 'world', 'act', 'quest']);
339
+ const DONE_WORDS = new Set(['complete', 'completed', 'clear', 'cleared', 'done', 'finished', 'finish', 'passed', 'beaten', 'won', 'win', 'success', 'succeeded']);
340
+ const FAIL_WORDS = new Set(['failed', 'fail', 'lost', 'lose']);
341
+ // A word that undoes a done word or names something else done: "level_not_complete", "retry_level_done", "level_cache_done".
342
+ const NOT_WORDS = new Set(['not', 'no', 'non', 'never', 'fail', 'failed', 'failure', 'cancel', 'cancelled', 'canceled', 'retry', 'retried', 'abort', 'aborted', 'skip', 'skipped', 'cache', 'cached', 'undo', 'reset', 'incomplete', 'uncleared', 'unfinished']);
343
+ const WON_NAMES = new Set(['won', 'win', 'victory', 'you_win', 'you_won', 'game_won', 'game_win', 'game_complete', 'game_completed', 'game_finished', 'game_beaten', 'player_won', 'player_win']);
344
+ const LOST_NAMES = new Set(['game_over', 'gameover', 'game_lost', 'defeat', 'defeated', 'you_lose', 'you_lost', 'player_lost']);
345
+ const nameWords = name => String(name || '').normalize('NFKC').replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
346
+
347
+ /**
348
+ * The outcome an event of the game's own records: 'level_complete', 'won', 'lost', or null for anything else. Whole names only:
349
+ * one of the names above, or a place word followed by a done (or fail) word and nothing else (a level number may sit between).
350
+ */
351
+ export function outcomeOfEvent(e) {
352
+ const props = e?.props && typeof e.props === 'object' ? e.props : {};
353
+ if (props.rs_kind === 'level_complete') return 'level_complete';
354
+ if (props.rs_kind === 'progression') return props.rs_status === 'complete' ? 'level_complete' : props.rs_status === 'fail' ? 'lost' : null;
355
+ const words = nameWords(e?.name);
356
+ if (!words.length) return null;
357
+ const joined = words.join('_');
358
+ if (WON_NAMES.has(joined)) return 'won';
359
+ if (LOST_NAMES.has(joined)) return 'lost';
360
+ const core = words.filter(w => !/^\d+$/.test(w));
361
+ if (core.length !== 2 || !PLACE_WORDS.has(core[0])) return null;
362
+ if (FAIL_WORDS.has(core[1])) return 'lost';
363
+ if (NOT_WORDS.has(core[1])) return null;
364
+ return DONE_WORDS.has(core[1]) ? 'level_complete' : null;
365
+ }
366
+
367
+ /** The outcome events of a run's event record (`run.gameEvents`) placed in play, each with its `outcome`. */
368
+ export const outcomeEvents = record => (Array.isArray(record?.events) ? record.events : []).filter(e => e && e.phase === 'play' && Number.isSafeInteger(e.step) && !systemEvent(e.name)).map(e => ({ ...e, outcome: outcomeOfEvent(e) })).filter(e => e.outcome);
369
+
322
370
  /** The plan request's fixed line about the events (before its untrusted-data line), or ''. */
323
371
  export const EVENTS_RULE = 'Below the line are events the game itself sent through its own Ravensight analytics since your last plan, each at the step it happened (they can arrive a few steps late). They are measured, not read off the picture: use them to tell whether an input landed, whether you took damage or died, and what the score is, and never report that something did not happen when an event shows it did.';
324
372
  /** The events part of a plan request, after its untrusted-data line, or ''. */
@@ -328,17 +376,25 @@ export const eventsBlock = lines => (Array.isArray(lines) && lines.length ? `Gam
328
376
 
329
377
  // ---- The report ------------------------------------------------------------------------------------------------------
330
378
 
331
- /** The findings the game's own events confirmed, each with one more sentence saying so. Returns the same list. */
379
+ /**
380
+ * The findings the game's own events confirmed, each with one more sentence saying so, and those that quote a number off the
381
+ * screen the events never held (lib/eventclaims.mjs `disagrees`), labelled with what the events held. Returns the same list.
382
+ */
332
383
  export function withEventEvidence(findings, run) {
333
384
  const decided = eventsDecided(run);
334
385
  for (const f of findings || []) {
335
386
  const v = decided.get(f.title);
336
- if (v?.verdict === 'confirmed' && typeof f.description === 'string' && !f.description.includes('Measured from the game\'s own events')) {
387
+ if (typeof f.description !== 'string') continue;
388
+ if (v?.verdict === 'confirmed' && !f.description.includes('Measured from the game\'s own events')) {
337
389
  f.description = `${f.description} Measured from the game's own events: ${v.why}.`.slice(0, 2000);
338
390
  }
391
+ if (v?.verdict === 'disagrees' && !f.description.includes(DISAGREES)) {
392
+ f.description = `${f.description} ${DISAGREES}: ${v.why}. The screen may show a number the game does not hold, or the playtester misread it.`.slice(0, 2000);
393
+ }
339
394
  }
340
395
  return findings;
341
396
  }
397
+ const DISAGREES = 'The number it reads off the screen disagrees with the game\'s own events';
342
398
 
343
399
  /** Whether a finding was confirmed by the game's own events (usage.json `finding_basis` says 'events'). */
344
400
  export const eventBacked = (run, f) => eventsDecided(run).get(f?.title)?.verdict === 'confirmed';
@@ -360,7 +416,9 @@ export function eventsReportLines(run, { findings = [], turnedAway = [] } = {})
360
416
  const contradicted = (turnedAway || []).filter(t => decided.get(t.title)?.verdict === 'contradicted');
361
417
  for (const f of confirmed) md.push(`- Confirmed by the game's own events: "${cleanText(f.title, 120)}". ${decided.get(f.title).why}.`);
362
418
  for (const t of contradicted) md.push(`- Contradicted by the game's own events, so not reported as a finding: "${cleanText(t.title, 120)}". ${decided.get(t.title).why}.`);
363
- if (!confirmed.length && !contradicted.length) md.push('- No claim of the playtester\'s was about something these events measure, so they confirmed and contradicted nothing.');
419
+ const disagrees = (findings || []).filter(f => decided.get(f.title)?.verdict === 'disagrees');
420
+ for (const f of disagrees) md.push(`- Reported, with a number that disagrees with the game's own events: "${cleanText(f.title, 120)}". ${decided.get(f.title).why}.`);
421
+ if (!confirmed.length && !contradicted.length && !disagrees.length) md.push('- No claim of the playtester\'s was about something these events measure, so they confirmed and contradicted nothing.');
364
422
  md.push('');
365
423
  const shown = g.events.filter(e => !systemEvent(e.name)).slice(0, EVENT_LIMITS.reportLines);
366
424
  if (shown.length) {
@@ -25,13 +25,13 @@ import path from 'node:path';
25
25
  import { promisify } from 'node:util';
26
26
  import {
27
27
  MEMORY_SCHEMA, note, startRoute, controlNotes, progressNote, measuredStuckNotes, deathTexts, ruleTexts, messageNotes, designedNotes,
28
- collectNotes, earlierNotesBlock, withoutSteps
28
+ collectNotes, earlierNotesBlock, withoutSteps, recordNumbers
29
29
  } from './anygame/gamenotes.js';
30
30
 
31
31
  const execFileAsync = promisify(execFile);
32
32
 
33
33
  // The words a claim is about (the server's own test, playtestMemoryService sameClaim): four letters or more, plain endings off.
34
- const words = t => new Set(String(t || '').toLowerCase().replace(/[^a-z0-9\s]/g, ' ').split(/\s+/).filter(w => w.length >= 4).map(w => w.replace(/(ly|ing|ed|s)$/, '')));
34
+ const words = t => new Set(String(t || '').toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, ' ').split(/\s+/).filter(w => w.length >= 4).map(w => w.replace(/(ly|ing|ed|s)$/, '')));
35
35
  /** Whether two notes or claims say the same thing: most of the shorter one's words are in the other, and at least two. */
36
36
  export function sameClaim(a, b) {
37
37
  const x = words(a);
@@ -119,8 +119,15 @@ export const memoryBlock = memory => earlierNotesBlock({ memory: memory || null
119
119
  * measured controls, the same shapes a cloud run keeps); `turnedAway` the claims the
120
120
  * judge turned away (those found to be as designed become notes). The playtester's own
121
121
  * words about where it lost are kept only when no claim turned away says the same thing.
122
+ * `gameEvents` is the run's usage record of the game's own events (./events.js eventsUsage).
123
+ *
124
+ * Held to the record by the hosted runner's own rule (gamenotes holdToRecord): a note of
125
+ * the playtester's that states a number is handed on only when the record holds it, a
126
+ * number the game itself said (a tutorial's words) or a value its own events sent under a
127
+ * word the note uses. A local run has no frames to count losses or wins from, so the
128
+ * progress note names no count, and the notebook's own tally is never handed on.
122
129
  */
123
- export function extractLocalNotes({ digest = null, turnedAway = [] } = {}) {
130
+ export function extractLocalNotes({ digest = null, turnedAway = [], gameEvents = null } = {}) {
124
131
  const memory = digest && digest.memory ? digest.memory : null;
125
132
  const measured = digest && digest.controls && Array.isArray(digest.controls.measured) ? digest.controls.measured : [];
126
133
  const away = (Array.isArray(turnedAway) ? turnedAway : []).filter(entry => entry && entry.title);
@@ -130,13 +137,15 @@ export function extractLocalNotes({ digest = null, turnedAway = [] } = {}) {
130
137
  const start = startRoute(memory);
131
138
  if (start) all.push(note('start', start, 'measured', { subject: 'start' }));
132
139
  all.push(...controlNotes(measured));
133
- all.push(progressNote(null, memory));
140
+ all.push(progressNote(null, memory, null));
134
141
  all.push(...measuredStuckNotes({ memory }));
135
142
  for (const t of notShownFalse(deathTexts(memory)).slice(0, 2)) all.push(note('stuck', withoutSteps(t), 'playtester'));
136
143
  all.push(...messageNotes(null, memory));
137
144
  all.push(...notShownFalse(ruleTexts(memory)).map(t => note('rule', t, 'playtester')).filter(Boolean));
138
145
  all.push(...designedNotes(away.map(entry => ({ outcome: entry.outcome, title: entry.title, reason: entry.reason })), sameClaim));
139
- return collectNotes(all, sameClaim);
146
+ const texts = (memory && Array.isArray(memory.learned) ? memory.learned : []).filter(f => f && f.kind === 'tutorial').map(f => f.text);
147
+ const record = recordNumbers({ counts: null, texts, events: gameEvents && Array.isArray(gameEvents.events) ? gameEvents.events : [] });
148
+ return collectNotes(all, sameClaim, record);
140
149
  }
141
150
 
142
151
  /** The `game_memory` a local run's `complete` carries, or null when the game's memory did not ask for notes. */
@@ -515,8 +515,37 @@ export const EVIDENCE_HEADING = '## Where to look (added by the runner)';
515
515
  * @param {Map<string, Object>} [context.anchors] the runner's own findings, by id
516
516
  * @returns {{report: Object, index: Array<{id: string, action: number|null, screenshot: string|null, video: string|null}>}}
517
517
  */
518
+ /**
519
+ * Every finding with its own id. A report that repeats an id (the model wrote
520
+ * two F001s) keeps the first and gives each repeat the next free id after the
521
+ * report's highest (`F007`, in the schema's F and three digits form), so every
522
+ * consumer that looks a finding up by id, first match or last, reaches the
523
+ * same one. Run once, as soon as the report is settled; running it again
524
+ * changes nothing.
525
+ */
526
+ export function uniqueFindingIds(report) {
527
+ if (!report || !Array.isArray(report.findings)) return report;
528
+ const taken = new Set(report.findings.map(finding => finding && typeof finding === 'object' ? finding.id : undefined).filter(id => id !== undefined && id !== null && id !== ''));
529
+ const seen = new Set();
530
+ let changed = false;
531
+ const findings = report.findings.map(finding => {
532
+ if (!finding || typeof finding !== 'object' || finding.id === undefined || finding.id === null || finding.id === '') return finding;
533
+ if (!seen.has(finding.id)) { seen.add(finding.id); return finding; }
534
+ let n = Math.max(0, ...[...taken].map(id => Number((String(id).match(/^F(\d+)$/) || [])[1]) || 0)) + 1;
535
+ while (taken.has(`F${String(n).padStart(3, '0')}`)) n += 1;
536
+ const id = `F${String(n).padStart(3, '0')}`;
537
+ taken.add(id);
538
+ seen.add(id);
539
+ changed = true;
540
+ return { ...finding, id };
541
+ });
542
+ return changed ? { ...report, findings } : report;
543
+ }
544
+
518
545
  export function attachWhereToLook(report, { observations = [], notes = [], screenshots = [], video = null, anchors = new Map(), bindings = new Map() } = {}) {
519
546
  if (!report || !Array.isArray(report.findings)) return { report, index: [] };
547
+ // One finding per id, so the index has one entry per id and a binding one owner.
548
+ report = uniqueFindingIds(report);
520
549
  const byIndex = new Map(observations.map(entry => [entry.index, entry]));
521
550
  const every = (screenshots || []).filter(shot => shot && typeof shot.relativePath === 'string' && shot.relativePath);
522
551
  const shotByPath = new Map(every.map(shot => [String(shot.relativePath).replace(/\\/g, '/'), shot]));
@@ -525,11 +554,29 @@ export function attachWhereToLook(report, { observations = [], notes = [], scree
525
554
  // it, never for something the persona saw.
526
555
  const shots = every.filter(shot => !shot.edge && !shot.derived);
527
556
  const index = [];
557
+ const unbound = new Map(bindings);
528
558
  const findings = report.findings.map(finding => {
529
559
  if (!finding || typeof finding !== 'object') return finding;
530
560
  // Later report formatting may append evidence; it cannot redefine the
531
561
  // provenance of the picture already sent to the claim check.
532
- if (bindings.has(finding.id)) { index.push(bindings.get(finding.id)); return finding; }
562
+ // The step and the video time it was placed at still land in its evidence,
563
+ // said once; a time the finding cites itself stands.
564
+ // Each binding is used once: a later finding that repeats an id is placed
565
+ // on its own evidence and inherits nothing from the first.
566
+ if (unbound.has(finding.id)) {
567
+ const bound = unbound.get(finding.id);
568
+ unbound.delete(finding.id);
569
+ index.push(bound);
570
+ const original = Array.isArray(finding.evidence) ? finding.evidence : null;
571
+ const kept = original ? [...original] : [];
572
+ const has = (type, test) => kept.some(item => item && item.type === type && test(String(item.ref)));
573
+ if (Number.isInteger(bound.action) && !has('transcript_step', ref => new RegExp(`^\\s*action\\s*#?\\s*${bound.action}\\s*$`, 'i').test(ref))) {
574
+ kept.push({ type: 'transcript_step', ref: `action ${bound.action}` });
575
+ }
576
+ if (typeof bound.video === 'string' && bound.video && !has('video_ts', () => true)) kept.push({ type: 'video_ts', ref: bound.video });
577
+ // Evidence that was not a list is always replaced by the list.
578
+ return original && kept.length === original.length ? finding : { ...finding, evidence: kept };
579
+ }
533
580
  const evidence = Array.isArray(finding.evidence) ? [...finding.evidence] : [];
534
581
  let at = null;
535
582
  let action = null;
@@ -704,5 +751,5 @@ export function playOnText(actions, maxActions) {
704
751
 
705
752
  export default {
706
753
  createCapabilityLedger, capabilityLines, writeCapabilitySection, capabilityPrompt, flatShare, isBlankScreen, createBlankWatch,
707
- describeInput, stepsBefore, runnerFinding, addRunnerFindings, runnerFindingsMarkdown, dialogNote, videoTime, attachWhereToLook, whereToLookMarkdown, playOnText
754
+ describeInput, stepsBefore, runnerFinding, addRunnerFindings, runnerFindingsMarkdown, dialogNote, videoTime, attachWhereToLook, uniqueFindingIds, whereToLookMarkdown, playOnText
708
755
  };