ravensight-playtest 0.13.3 → 0.17.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.
Files changed (41) hide show
  1. package/README.md +82 -1
  2. package/addons/ravensight_driver/driver.gd +472 -28
  3. package/docs/godot-driver.md +66 -2
  4. package/package.json +4 -4
  5. package/src/api/README.md +8 -1
  6. package/src/api/client.js +24 -1
  7. package/src/cli.js +19 -0
  8. package/src/commands/check.js +5 -2
  9. package/src/commands/run.js +40 -5
  10. package/src/commands/setup.js +176 -0
  11. package/src/packs/index.js +37 -5
  12. package/src/packs/keys.json +11 -0
  13. package/src/packs/pack-signing-hashes.json +7 -0
  14. package/src/packs/pack-signing-vectors.json +119 -0
  15. package/src/packs/signature.js +186 -0
  16. package/src/run/anygame/gamenotes.js +74 -12
  17. package/src/run/anygame/index.js +97 -34
  18. package/src/run/anygame/language.js +100 -10
  19. package/src/run/anygame/memory.js +70 -13
  20. package/src/run/anygame/shared-hashes.json +9 -8
  21. package/src/run/anygame/shared.js +6 -5
  22. package/src/run/anygame/sound.js +59 -16
  23. package/src/run/args.js +5 -0
  24. package/src/run/claimwords.js +43 -7
  25. package/src/run/drivers/godot-cursor.js +96 -0
  26. package/src/run/drivers/godot-observation.js +29 -5
  27. package/src/run/drivers/godot.js +60 -5
  28. package/src/run/drivers/web.js +181 -10
  29. package/src/run/egress.js +282 -0
  30. package/src/run/eventclaims.js +102 -6
  31. package/src/run/events.js +64 -6
  32. package/src/run/gameMemory.js +14 -5
  33. package/src/run/honesty.js +49 -2
  34. package/src/run/judge.js +22 -10
  35. package/src/run/liveFeed.js +254 -0
  36. package/src/run/networkRun.js +54 -0
  37. package/src/run/personaLoop.js +70 -20
  38. package/src/run/pixels.js +491 -2
  39. package/src/run/replay.js +11 -0
  40. package/src/run/resume.js +3 -1
  41. package/src/run/tools.js +2 -2
@@ -0,0 +1,254 @@
1
+ /**
2
+ * The job's live view in the dashboard, fed while a local persona run plays.
3
+ *
4
+ * The play loop hands each played input here; this posts the newest steps to
5
+ * `POST .../runs/:runId/live` every few seconds and, only while the server
6
+ * says someone is watching, one small JPEG of the latest changed screen. It is
7
+ * the same body the cloud runner sends, read by the same live view.
8
+ *
9
+ * Nothing here can slow or fail the run: `step()` returns at once and never
10
+ * throws, one post is in flight at a time, a post is never retried and has an
11
+ * 8 second limit, a failed post is dropped, and the feed gives up quietly for
12
+ * the rest of the run after a refusal that will not change (401, 403, 404,
13
+ * 409) or five failures in a row. It writes nothing in the run folder: a frame
14
+ * is made in a temporary folder of its own. The run's upload stays the record.
15
+ * Live posts are free; nothing here touches money.
16
+ */
17
+ import { execFile } from 'node:child_process';
18
+ import { mkdtemp, readFile, rm, writeFile, access } from 'node:fs/promises';
19
+ import os from 'node:os';
20
+ import path from 'node:path';
21
+ import { redactText } from './redaction.js';
22
+ import { scanForSecrets } from './secretScan.js';
23
+
24
+ export const LIVE_INTERVAL_MS = 5000;
25
+ export const LIVE_MIN_INTERVAL_MS = 2000;
26
+ export const LIVE_MAX_INTERVAL_MS = 30000;
27
+ export const LIVE_MAX_STEPS = 10;
28
+ export const LIVE_MAX_FRAME_BYTES = 64 * 1024;
29
+ export const LIVE_MAX_SIDE = 640;
30
+ export const LIVE_WIDTH = 480;
31
+ export const LIVE_TIMEOUT_MS = 8000;
32
+ export const LIVE_MAX_FAILURES = 5;
33
+ // Shared by every run this process plays at once, so the live view never takes
34
+ // the request budget the runs' own heartbeats and uploads need.
35
+ export const LIVE_BUDGET = Object.freeze({ posts: 120, windowMs: 15 * 60 * 1000 });
36
+ const FINAL = new Set([401, 403, 404, 409]);
37
+ const TEXT = { label: 100, intent: 240, screen: 60 };
38
+
39
+ /**
40
+ * Whether this run feeds the live view: on when the run uploads, off with
41
+ * --no-live, --dry-upload, or a step log kept on this machine (the live steps
42
+ * are the step log's own content).
43
+ * @returns {{on: boolean, reason: 'flag'|'dry_upload'|'step_log'|null}}
44
+ */
45
+ export function liveDecision(options = {}) {
46
+ if (options.noLive === true) return { on: false, reason: 'flag' };
47
+ if (options.dryUpload === true) return { on: false, reason: 'dry_upload' };
48
+ if (options.uploadTranscript === false || options.noUploadStepLog === true) return { on: false, reason: 'step_log' };
49
+ return { on: true, reason: null };
50
+ }
51
+
52
+ /** The one line a run prints about the live view. */
53
+ export function liveLine(decision) {
54
+ if (decision.on) return 'While it plays, the job\'s page shows the recent steps, and a small picture of the screen while someone watches (Watch live). It costs nothing; --no-live turns it off.';
55
+ const why = { flag: '--no-live', dry_upload: '--dry-upload', step_log: 'the step log is kept local' }[decision.reason] || 'it is off';
56
+ return `The job's page will not show this run live (${why}).`;
57
+ }
58
+
59
+ /** A sliding window of posts, shared by the feeds of one process. */
60
+ export function createPostBudget({ posts = LIVE_BUDGET.posts, windowMs = LIVE_BUDGET.windowMs, now = Date.now } = {}) {
61
+ let sent = [];
62
+ return {
63
+ take() {
64
+ const at = now();
65
+ sent = sent.filter(t => at - t < windowMs);
66
+ if (sent.length >= posts) return false;
67
+ sent.push(at);
68
+ return true;
69
+ }
70
+ };
71
+ }
72
+ const processBudget = createPostBudget();
73
+
74
+ function clip(value, max) {
75
+ if (typeof value !== 'string') return '';
76
+ const cut = redactText(value).replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, max);
77
+ return cut && scanForSecrets(cut).length ? '' : cut;
78
+ }
79
+
80
+ /** The few fields of a played step the studio sees, trimmed and redacted. */
81
+ export function liveStep(step = {}, startedAt = null, at = Date.now()) {
82
+ const n = Number.isSafeInteger(step.n) && step.n >= 0 ? step.n : 0;
83
+ return {
84
+ n,
85
+ label: clip(step.label, TEXT.label),
86
+ intent: clip(step.intent, TEXT.intent),
87
+ changed: typeof step.changed === 'boolean' ? step.changed : null,
88
+ screen: clip(step.screen, TEXT.screen),
89
+ atMs: Number.isFinite(startedAt) ? Math.max(0, Math.round(at - startedAt)) : null
90
+ };
91
+ }
92
+
93
+ /** Width and height of a baseline or progressive JPEG, or null. */
94
+ export function jpegSize(buf) {
95
+ if (!Buffer.isBuffer(buf) || buf.length < 4 || buf[0] !== 0xff || buf[1] !== 0xd8) return null;
96
+ let off = 2;
97
+ while (off + 9 < buf.length) {
98
+ if (buf[off] !== 0xff) return null;
99
+ const marker = buf[off + 1];
100
+ const len = buf.readUInt16BE(off + 2);
101
+ if ([0xc0, 0xc1, 0xc2].includes(marker)) return { height: buf.readUInt16BE(off + 5), width: buf.readUInt16BE(off + 7) };
102
+ off += 2 + len;
103
+ }
104
+ return null;
105
+ }
106
+
107
+ const fits = bytes => {
108
+ const size = jpegSize(bytes);
109
+ return size && bytes.length <= LIVE_MAX_FRAME_BYTES && size.width >= 1 && size.height >= 1 && size.width <= LIVE_MAX_SIDE && size.height <= LIVE_MAX_SIDE ? size : null;
110
+ };
111
+
112
+ function run(file, args, timeoutMs) {
113
+ return new Promise(resolve => {
114
+ execFile(file, args, { timeout: timeoutMs, windowsHide: true, env: { PATH: process.env.PATH || '' } }, error => resolve(error ? (error.code === 'ENOENT' ? 'missing' : 'failed') : 'ok'));
115
+ });
116
+ }
117
+
118
+ let noFfmpeg = false;
119
+ /**
120
+ * Scale an image to a small JPEG with ffmpeg at the lowest CPU priority, so a
121
+ * viewer never takes time from the game. Answers the bytes, or null (no
122
+ * ffmpeg on this machine, a failed scale).
123
+ */
124
+ export async function scaleFrame({ input, dir, ffmpeg = 'ffmpeg', exec = run, nice = process.platform === 'win32' ? null : '/usr/bin/nice' }) {
125
+ if (noFfmpeg) return null;
126
+ const source = path.join(dir, 'screen.img');
127
+ const out = path.join(dir, 'frame.jpg');
128
+ await writeFile(source, input);
129
+ await rm(out, { force: true });
130
+ const args = ['-hide_banner', '-loglevel', 'error', '-nostdin', '-y', '-threads', '1', '-i', source, '-frames:v', '1',
131
+ '-vf', `scale=w=${LIVE_WIDTH}:h=${LIVE_MAX_SIDE}:force_original_aspect_ratio=decrease,scale=trunc(iw/2)*2:trunc(ih/2)*2`, '-q:v', '9', '-f', 'image2', out];
132
+ const niced = nice && await access(nice).then(() => true, () => false);
133
+ const result = niced ? await exec(nice, ['-n', '19', ffmpeg, ...args], 5000) : await exec(ffmpeg, args, 5000);
134
+ if (result === 'missing') { noFfmpeg = true; return null; }
135
+ if (result !== 'ok') return null;
136
+ return readFile(out).catch(() => null);
137
+ }
138
+
139
+ /** For tests: forget that ffmpeg was missing. */
140
+ export function _resetFfmpeg() { noFfmpeg = false; }
141
+
142
+ /**
143
+ * One feed per run. Start it only after the run's `playing` transition was
144
+ * accepted; nothing is sent before a step arrives.
145
+ */
146
+ export function createLiveFeed({
147
+ api, gameId, jobId, runId,
148
+ startedAt = Date.now(),
149
+ now = Date.now,
150
+ budget = processBudget,
151
+ scale = scaleFrame,
152
+ makeDir = () => mkdtemp(path.join(os.tmpdir(), 'ravensight-live-')),
153
+ setTimer = setTimeout,
154
+ clearTimer = clearTimeout
155
+ }) {
156
+ let seq = 0, pending = [], shot = null, sentStep = -1, watching = false, inFlight = false, stopped = false;
157
+ let nextAt = 0, interval = LIVE_INTERVAL_MS, timer = null, failures = 0, dir = null;
158
+ const stats = { posts: 0, frames: 0, dropped: 0, failures: 0, reason: null };
159
+
160
+ const stop = reason => {
161
+ if (stopped) return;
162
+ stopped = true;
163
+ stats.reason = reason;
164
+ if (timer) clearTimer(timer);
165
+ timer = null;
166
+ pending = [];
167
+ shot = null;
168
+ if (dir) { const gone = dir; dir = null; rm(gone, { recursive: true, force: true }).catch(() => {}); }
169
+ };
170
+
171
+ async function frame() {
172
+ if (!watching || !shot || shot.step === sentStep) return null;
173
+ const want = shot;
174
+ try {
175
+ // Every frame is made fresh by the scaler, never forwarded as the driver gave it: the
176
+ // header of an image this process did not encode is not trusted. No scaler, no frame.
177
+ const input = Buffer.from(want.data, 'base64');
178
+ if (!dir) dir = await makeDir();
179
+ const bytes = await scale({ input, dir });
180
+ const size = bytes && fits(bytes);
181
+ if (!size) return null;
182
+ return { step: want.step, body: { type: 'image/jpeg', data: bytes.toString('base64'), width: size.width, height: size.height, step: want.step } };
183
+ } catch {
184
+ return null;
185
+ }
186
+ }
187
+
188
+ async function flush() {
189
+ timer = null;
190
+ if (stopped || inFlight) return;
191
+ if (!budget.take()) { nextAt = now() + LIVE_MAX_INTERVAL_MS; schedule(); return; }
192
+ inFlight = true;
193
+ const steps = pending.slice(-LIVE_MAX_STEPS);
194
+ stats.dropped += pending.length - steps.length;
195
+ pending = [];
196
+ try {
197
+ const f = await frame();
198
+ if (stopped) return;
199
+ seq += 1;
200
+ const answer = await api.runs.live(gameId, jobId, runId, { seq, steps, ...(f ? { frame: f.body } : {}) }, { timeoutMs: LIVE_TIMEOUT_MS });
201
+ stats.posts += 1;
202
+ failures = 0;
203
+ watching = answer?.watching === true;
204
+ if (f && answer?.accepted) { sentStep = f.step; stats.frames += 1; }
205
+ if (Number.isFinite(answer?.intervalMs)) interval = Math.min(LIVE_MAX_INTERVAL_MS, Math.max(LIVE_MIN_INTERVAL_MS, answer.intervalMs));
206
+ } catch (error) {
207
+ stats.failures += 1;
208
+ stats.dropped += steps.length;
209
+ const status = error && error.status;
210
+ if (FINAL.has(status)) return stop(`http_${status}`);
211
+ failures += 1;
212
+ if (failures >= LIVE_MAX_FAILURES) return stop('failures');
213
+ const waitMs = Number.isFinite(error?.body?.retryAfterMs) ? error.body.retryAfterMs : Number.isFinite(error?.retryAfter) ? error.retryAfter * 1000 : null;
214
+ if (status === 429 && waitMs !== null) nextAt = now() + Math.min(LIVE_MAX_INTERVAL_MS, Math.max(LIVE_MIN_INTERVAL_MS, waitMs));
215
+ } finally {
216
+ inFlight = false;
217
+ if (!stopped) {
218
+ nextAt = Math.max(nextAt, now() + interval);
219
+ if (pending.length || (watching && shot && shot.step !== sentStep)) schedule();
220
+ }
221
+ }
222
+ return undefined;
223
+ }
224
+
225
+ function schedule() {
226
+ if (stopped || timer || inFlight) return;
227
+ timer = setTimer(() => { flush().catch(() => {}); }, Math.max(0, nextAt - now()));
228
+ if (timer && typeof timer.unref === 'function') timer.unref();
229
+ }
230
+
231
+ return {
232
+ /**
233
+ * A step was played. `image` is the screen after it, `{ data: base64 }`
234
+ * (a PNG or a JPEG), when the screen changed and the driver has one.
235
+ */
236
+ step(step, { image = null } = {}) {
237
+ if (stopped) return;
238
+ try {
239
+ const s = liveStep(step, startedAt, now());
240
+ pending.push(s);
241
+ if (pending.length > LIVE_MAX_STEPS * 3) { stats.dropped += pending.length - LIVE_MAX_STEPS; pending = pending.slice(-LIVE_MAX_STEPS); }
242
+ if (image && typeof image.data === 'string' && image.data && step.changed !== false) shot = { data: image.data, step: s.n };
243
+ schedule();
244
+ } catch {
245
+ // Never into play.
246
+ }
247
+ },
248
+ close() { stop(stats.reason || 'closed'); },
249
+ stats: () => ({ ...stats, seq, watching, stopped })
250
+ };
251
+ }
252
+
253
+ /** A feed that sends nothing, for a run with the live view off. */
254
+ export const NO_LIVE_FEED = Object.freeze({ step() {}, close() {}, stats: () => ({ posts: 0, frames: 0, dropped: 0, failures: 0, reason: 'off', seq: 0, watching: false, stopped: true }) });
@@ -0,0 +1,54 @@
1
+ import { readFile, writeFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { RUN_FILES } from './paths.js';
4
+ import { networkLines } from './egress.js';
5
+
6
+ /**
7
+ * A local run's network access (`--allow-network`; the platform's docs/playtest-network/CONTRACT.md section 6).
8
+ *
9
+ * A browser build's run reaches the hosts the game lists for it, and nothing else outside the build: the run's route
10
+ * and its proxy (./egress.js) hold every request and connection to that list. A Godot, desktop, Unity, Unreal,
11
+ * native mobile or custom bridge run is the game's own program on this machine, which the playtester cannot limit,
12
+ * so the flag is refused for them rather than accepted with a promise it cannot keep.
13
+ */
14
+
15
+ /** Said when the server answered no hosts for a run that asked (an older server): the run plays as before. */
16
+ export const NETWORK_NOT_GRANTED = 'This server did not record network access for the job, so the run plays as it always has, with nothing limited by the list.';
17
+
18
+ /**
19
+ * Why --allow-network cannot be used on this run, or null.
20
+ * @param {{allowNetwork?: boolean, liveSite?: Object|null}} options
21
+ * @param {string} driverName
22
+ * @returns {string|null}
23
+ */
24
+ export function networkRefusal(options, driverName) {
25
+ if (!options || !options.allowNetwork) return null;
26
+ if (options.liveSite) return '--allow-network is for an uploaded or local build. A --url run already reaches its own site\'s hosts and nothing else. Nothing was registered or charged.';
27
+ if (driverName !== 'playwright_web') {
28
+ return `--allow-network holds a browser build to the hosts your game lists. A ${driverName} run is your game's own program on this machine, and the playtester cannot limit what it reaches, so it reaches what it always has. Run without --allow-network. Nothing was registered or charged.`;
29
+ }
30
+ return null;
31
+ }
32
+
33
+ /**
34
+ * After a run with access, before it is delivered: the "Network" section of report.md (and of the outcome's markdown
35
+ * the server is sent) and usage.json `network`. A run without access is left exactly as it was.
36
+ * @param {{directory: string, driver: Object|null, outcome: Object|null}} args
37
+ * @returns {Promise<Object|null>} the summary, or null
38
+ */
39
+ export async function finishNetworkRun({ directory, driver, outcome }) {
40
+ const summary = driver && typeof driver.networkSummary === 'function' ? driver.networkSummary() : null;
41
+ if (!summary) return null;
42
+ const notes = summary.hosts.some(h => h.startsWith('*.')) ? ['A wildcard entry covers the names one level under it on this machine; a cloud run opens exact names only.'] : [];
43
+ const section = ['', '## Network', '', ...networkLines(summary, { notes }).flatMap((line, i) => (i ? ['', line] : [line]))].join('\n');
44
+ const markdownPath = path.join(directory, RUN_FILES.reportMd);
45
+ const markdown = await readFile(markdownPath, 'utf8').catch(() => null);
46
+ if (markdown !== null && !markdown.includes('\n## Network\n')) await writeFile(markdownPath, `${markdown.replace(/\s*$/, '')}\n${section}\n`, 'utf8');
47
+ if (outcome && typeof outcome.reportMarkdown === 'string' && !outcome.reportMarkdown.includes('\n## Network\n')) outcome.reportMarkdown = `${outcome.reportMarkdown.replace(/\s*$/, '')}\n${section}\n`;
48
+ const usagePath = path.join(directory, RUN_FILES.usageJson);
49
+ const usage = await readFile(usagePath, 'utf8').then(JSON.parse).catch(() => null);
50
+ if (usage) await writeFile(usagePath, `${JSON.stringify({ ...usage, network: { ...summary, notes } }, null, 2)}\n`, 'utf8');
51
+ return summary;
52
+ }
53
+
54
+ export default { finishNetworkRun, networkRefusal, NETWORK_NOT_GRANTED };
@@ -19,7 +19,7 @@ import { redactText } from './redaction.js';
19
19
  import { ACTION_TOOLS, NEW_TOOL_NAMES, REPORT_TOOLS, executeTool, expectationOf, modelFrameOf, toolResult, toolsFor, NEWEST_TOOL_NAMES } from './tools.js';
20
20
  import {
21
21
  CAPABILITY_HEADING, DIALOGS_HEADING, EVIDENCE_HEADING, MAX_WIN_CONTINUES, RUNNER_FINDINGS_HEADING, WIN_TEXT,
22
- addRunnerFindings, attachWhereToLook, blankFinding, capabilityPrompt, createBlankWatch, createCapabilityLedger, describeInput, dialogNote, gameEndedFinding, gameEndedOf, mergeRunnerDuplicates,
22
+ addRunnerFindings, attachWhereToLook, uniqueFindingIds, blankFinding, capabilityPrompt, createBlankWatch, createCapabilityLedger, describeInput, dialogNote, gameEndedFinding, gameEndedOf, mergeRunnerDuplicates,
23
23
  playOnText, replaceSection, runnerFinding, runnerFindingsMarkdown, stepsBefore, videoTime, whereToLookMarkdown, writeCapabilitySection
24
24
  } from './honesty.js';
25
25
  import { runEdgePass, edgeFindings, edgeMarkdown, EDGE_HEADING, blankCapabilityNote } from './edgePass.js';
@@ -41,7 +41,7 @@ import { annotateActionLog, createIntentWatch, goalsOf, holdInCharacter, intentR
41
41
  import { claimShape, judgeIssue, legacyIssue, impressionOf } from './judge.js';
42
42
  import { EVENTS_RULE, eventsBlock, eventsReportLines, eventsUsage, withEventEvidence } from './events.js';
43
43
  import { memoryBlock, extractLocalNotes, gameMemoryBody } from './gameMemory.js';
44
- import { CLAIM_SYSTEM, CLAIM_WIRE, checkSaid, claimText, claimRead, claimMessage } from './claimwords.js';
44
+ import { CLAIM_SYSTEM, CLAIM_WIRE, checkSaid, claimText, claimRead, claimMessage, readsEnglish } from './claimwords.js';
45
45
  import { CLAIM_FAULT_SYSTEM, claimCheckSystem, claimReply, claimFormatRepair, MAX_CLAIM_REPLY_TEXT } from './claimProtocol.js';
46
46
  import { captureNotes, createCaptureWatch, rewriteStaleEvidence, staleSentence } from './captureCheck.js';
47
47
  import { gameRefusal } from './gameRefusal.js';
@@ -55,6 +55,7 @@ import os from 'node:os';
55
55
  import { MIN_PASSWORD_CHARS } from '../briefLocal.js';
56
56
  // any-game hook: the run's notebook, control learning, language, kind of game and sound (./anygame/index.js).
57
57
  import { createLocalAnyGame } from './anygame/index.js';
58
+ import { TOOL_TEXT_OTHER, NO_SOUND_OTHER } from './anygame/language.js';
58
59
  import { staleObservationCount } from './context.js';
59
60
 
60
61
  /**
@@ -405,6 +406,8 @@ export async function runPersona(args) {
405
406
  imageBudget = next;
406
407
  }
407
408
  });
409
+ // Play is over: the live view ends with it (the server ends the stream when the run leaves `playing`).
410
+ if (args.live) args.live.close();
408
411
  imageBudget = play.imageBudget;
409
412
  outcome = { ...outcome, ...play };
410
413
  // The intent check's record for usage.json (./intent.js); what the run played is added once the report has it.
@@ -529,7 +532,7 @@ export async function runPersona(args) {
529
532
  if (honesty.sdkSession) outcome.gameEvents = { ...(outcome.gameEvents || { total: 0 }), sessionRefused: { status: honesty.sdkSession.status, error: honesty.sdkSession.error, key: honesty.sdkSession.key, tagged: honesty.sdkSession.tagged } };
530
533
  // The notes this run hands on to the next playtest of the game, when the game's memory asked for them (./gameMemory.js).
531
534
  if (memory && memory.save === true) {
532
- const handed = gameMemoryBody(memory, extractLocalNotes({ digest: honesty.anygame ? honesty.anygame.digest() : null, turnedAway: written.turnedAway || [] }));
535
+ const handed = gameMemoryBody(memory, extractLocalNotes({ digest: honesty.anygame ? honesty.anygame.digest() : null, turnedAway: written.turnedAway || [], gameEvents: outcome.gameEvents }));
533
536
  if (handed) {
534
537
  outcome.gameMemory = handed;
535
538
  transcript.write({ kind: 'game_memory', notes: handed.notes.length, kinds: Object.fromEntries([...new Set(handed.notes.map(n => n.kind))].map(kind => [kind, handed.notes.filter(n => n.kind === kind).length])) });
@@ -810,7 +813,17 @@ export const RUNNER_LIMIT_TEXT = new RegExp([
810
813
  * @returns {boolean} true when the finding's own words are about the runner
811
814
  */
812
815
  export function aboutRunnerLimit(finding) {
813
- return RUNNER_LIMIT_TEXT.test(`${(finding && finding.title) || ''}\n${(finding && finding.description) || ''}`);
816
+ const text = `${(finding && finding.title) || ''}\n${(finding && finding.description) || ''}`;
817
+ // The same rules in the report's language when it is not English (./anygame/language.js, shared with the hosted runner).
818
+ return RUNNER_LIMIT_TEXT.test(text) || TOOL_TEXT_OTHER.test(text) || NO_SOUND_OTHER.test(text);
819
+ }
820
+
821
+ /** A line added to a tool result the persona is about to read (a string or a list of blocks). Changes it in place. */
822
+ export function withResultLine(result, line) {
823
+ if (!result || typeof line !== 'string' || !line) return result;
824
+ if (Array.isArray(result.content)) result.content.push({ type: 'text', text: line });
825
+ else if (typeof result.content === 'string') result.content = `${result.content}\n${line}`;
826
+ return result;
814
827
  }
815
828
 
816
829
  /* ------------------------------------- a game timer the playtester's own thinking ran out (./tooFast.js) */
@@ -889,6 +902,8 @@ async function playLoop({
889
902
  imageBudget,
890
903
  keepObservations,
891
904
  heartbeat,
905
+ // The job's live view (./liveFeed.js): handed each played input; never awaited, never throws.
906
+ live = null,
892
907
  onProgress = () => {},
893
908
  onBudgetWarning = null,
894
909
  // The run's model budget in USD, from register (`limits.model_usd`). With it
@@ -915,7 +930,7 @@ async function playLoop({
915
930
  const noisePatterns = (localBrief && Array.isArray(localBrief.expected_noise)) ? localBrief.expected_noise : [];
916
931
  // any-game hook: one notebook a run, on the honesty record so the report step reads the same one.
917
932
  const briefFields = brief && brief.fields && typeof brief.fields === 'object' ? brief.fields : brief || {};
918
- const anyGame = honesty.anygame || (honesty.anygame = createLocalAnyGame({ briefText: briefForPrompt(brief), controls: briefFields.build_notes && typeof briefFields.build_notes.controls === 'string' ? briefFields.build_notes.controls : null, touch: Boolean(driver && driver.touch), continuousTime: driver?.inputProfile === 'native-mobile' && driver.frozenBetweenActions === false, driverName: typeof driver.soundSelfTest === 'function' ? '' : driverName }));
933
+ const anyGame = honesty.anygame || (honesty.anygame = createLocalAnyGame({ briefText: briefForPrompt(brief), controls: briefFields.build_notes && typeof briefFields.build_notes.controls === 'string' ? briefFields.build_notes.controls : null, touch: Boolean(driver && driver.touch), reportLanguageHint: briefFields.play && typeof briefFields.play.report_language === 'string' ? briefFields.play.report_language : null, continuousTime: driver?.inputProfile === 'native-mobile' && driver.frozenBetweenActions === false, driverName: typeof driver.soundSelfTest === 'function' ? '' : driverName }));
919
934
  system.push({ type: 'text', text: anyGame.systemText() });
920
935
  // The intent check (./intent.js): one watch a run, on the honesty record so the report step reads the same one. Every answer,
921
936
  // miss and refused repeat is a line of the step log.
@@ -1574,7 +1589,15 @@ async function playLoop({
1574
1589
  if (ACTION_TOOLS.includes(toolUse.name)) {
1575
1590
  // any-game hook: the input is tallied by kind and the page's sound is read for it.
1576
1591
  anyGame.afterAction({ tool: toolUse.name, input: toolUse.input, changed: Boolean(executed.changed), place: executed.observation.title || '', label: inputLabel(redactToolInput(toolUse, secrets), toolUse.name), action: actions, text: executed.observation.text, driverError: Boolean(executed.driverError) });
1577
- if (typeof driver.soundRead === 'function') anyGame.afterSound(actions, await Promise.resolve().then(() => driver.soundRead()).catch(() => null), { changed: Boolean(executed.changed) });
1592
+ if (typeof driver.soundRead === 'function') {
1593
+ // Each action's sound is a line of the step log, and, once the game has made a sound, a line of the tool result:
1594
+ // evidence about feedback ("no feedback when pressing jump"), never a finding of its own. No audio is kept or sent.
1595
+ const heard = anyGame.afterSound(actions, await Promise.resolve().then(() => driver.soundRead()).catch(() => null), { changed: Boolean(executed.changed) });
1596
+ if (heard) {
1597
+ transcript.write({ kind: 'sound', action: actions, sound: heard.state });
1598
+ if (heard.say) withResultLine(executed.result, heard.say);
1599
+ }
1600
+ }
1578
1601
  // A hover that shows nothing is a look, not a stuck game.
1579
1602
  // An input the runner could not send (a target it could not resolve, a stale ref, a hold this driver
1580
1603
  // lacks) never reached the game: it says nothing about the game being stuck and is not an input that
@@ -1596,6 +1619,17 @@ async function playLoop({
1596
1619
  }
1597
1620
  }
1598
1621
  }
1622
+ // The live view: the step just played and, when the screen changed, the picture the driver has of it.
1623
+ if (live && ACTION_TOOLS.includes(toolUse.name)) {
1624
+ const seen = executed.observation;
1625
+ live.step({
1626
+ n: actions,
1627
+ label: describeInput({ tool: toolUse.name, input: redactToolInput(toolUse, secrets) }),
1628
+ intent: actionLine.expect || actionLine.thought || '',
1629
+ changed: typeof executed.changed === 'boolean' ? executed.changed : null,
1630
+ screen: screenNow || ''
1631
+ }, { image: executed.changed && seen && typeof seen.screenshotBase64 === 'string' ? { data: seen.screenshotBase64 } : null });
1632
+ }
1599
1633
  // A screen that showed the game, went one flat colour and stayed so
1600
1634
  // through the next inputs is a blank screen, found by the runner.
1601
1635
  if (executed.observation && !executed.observation.dialog && (ACTION_TOOLS.includes(toolUse.name) || toolUse.name === 'wait') && typeof driver.screenProbe === 'function') {
@@ -1718,7 +1752,9 @@ async function playLoop({
1718
1752
  // The intent check: a miss the runner or the record found, and a part of the game to leave, said once (./intent.js).
1719
1753
  for (const notice of intentWatch.notices()) asides.push(notice);
1720
1754
 
1721
- // any-game hook: the play style once, and the notebook when screens have dropped out of context.
1755
+ // any-game hook: the game's own events into the notebook's record (a numbered note is carried only once the record holds it),
1756
+ // then the play style once, and the notebook when screens have dropped out of context.
1757
+ anyGame.seeEvents(driver && driver.gameEvents, actions);
1722
1758
  const anyAside = anyGame.aside({ actions, dropped: staleObservationCount(observations.length, keepObservations) });
1723
1759
  if (anyAside) { asides.push(anyAside); transcript.write({ kind: 'any_game_aside', chars: anyAside.length }); }
1724
1760
  // The game's own analytics events since the last turn, measured and not read off the picture (./events.js): only when there are new ones.
@@ -1811,12 +1847,7 @@ async function playLoop({
1811
1847
  honesty.findings.push(finding);
1812
1848
  transcript.write({ kind: 'runner_finding', key: 'blank_screen', title: finding.title, since_action: stillBlank.sinceAction });
1813
1849
  }
1814
- // any-game hook: what the sound record supports is the runner's own finding; what it could not check is a capability note.
1815
- for (const f of anyGame.soundFindings()) {
1816
- const finding = runnerFinding({ severity: f.severity, category: f.category, key: `sound:${f.title}`, title: f.title, description: f.description, steps: stepsBefore(actionRecords.filter(record => record && record.kind === 'action')), screenshot: final ? final.relativePath : null, action: Number.isInteger(f.action) ? f.action : actions });
1817
- honesty.findings.push(finding);
1818
- transcript.write({ kind: 'runner_finding', key: 'sound', title: finding.title });
1819
- }
1850
+ // any-game hook: sound is evidence, never a finding of its own; what it could not check is a capability note.
1820
1851
  for (const note of anyGame.capabilityNotes()) if (honesty.capability.add(note)) transcript.write({ kind: 'capability_note', input: note.input, reason: note.reason });
1821
1852
  transcript.write({ kind: 'any_game', record: anyGame.digest() });
1822
1853
  // What the game asked for that the runner could not give.
@@ -2184,11 +2215,16 @@ async function reportPhase({
2184
2215
  }
2185
2216
  droppedByRunner = runnerDrop.dropped;
2186
2217
  const contradicted = runnerDrop.report ? downgradeContradictedFindings(runnerDrop.report, play.actionLog) : { report: null, downgraded: [] };
2187
- const candidate = contradicted.report;
2218
+ let candidate = contradicted.report;
2188
2219
  for (const entry of contradicted.downgraded) {
2189
2220
  transcript.write({ kind: 'finding_downgraded', id: entry.id, from: entry.from, to: entry.to, control: entry.control, action: entry.action });
2190
2221
  }
2191
2222
  downgradedByRunner = contradicted.downgraded;
2223
+ // any-game hook: a finding about missing feedback says whether a sound played at the action it cites (evidence, never a finding).
2224
+ if (candidate && honesty && honesty.anygame) {
2225
+ const heard = honesty.anygame.soundEvidence(candidate);
2226
+ if (heard.changed.length) { candidate = heard.report; transcript.write({ kind: 'finding_sound_noted', attempt, ids: heard.changed }); }
2227
+ }
2192
2228
  if (contradicted.downgraded.length > 0) {
2193
2229
  log(`downgraded ${contradicted.downgraded.length} finding(s) the action log contradicts: ${contradicted.downgraded.map(entry => `${entry.id} (${entry.from} to ${entry.to}, ${entry.control} clicked at step ${entry.action})`).join(', ')}`);
2194
2230
  }
@@ -2296,6 +2332,16 @@ async function reportPhase({
2296
2332
  // after the report is settled, so a refusal can cost the check and never
2297
2333
  // the report.
2298
2334
  report = scrubSecrets(report, secrets);
2335
+ // Every finding gets its own id before anything is placed, judged or cut by id (./honesty.js uniqueFindingIds).
2336
+ {
2337
+ const before = (report.findings || []).map(finding => finding && finding.id);
2338
+ report = uniqueFindingIds(report);
2339
+ const renamed = (report.findings || []).map((finding, i) => [before[i], finding && finding.id]).filter(([from, to]) => from !== to);
2340
+ if (renamed.length > 0) {
2341
+ transcript.write({ kind: 'finding_ids_renamed', renamed: renamed.map(([from, to]) => ({ from, to })) });
2342
+ log(`the report repeated a finding id; renamed ${renamed.map(([from, to]) => `${from} to ${to}`).join(', ')}`);
2343
+ }
2344
+ }
2299
2345
  const submittedSchemaValid = validator.validate(report).ok;
2300
2346
  // Preserve the submitted account before attribution or judgement changes it.
2301
2347
  // Bounded and scrubbed; a truncated audit is explicitly not a full draft.
@@ -2327,7 +2373,7 @@ async function reportPhase({
2327
2373
  let impressions = [];
2328
2374
  if (!shrunk && !play.budgetExceeded) {
2329
2375
  const impressionsAllowed = Boolean(reportSchema && reportSchema.properties && reportSchema.properties.impressions);
2330
- const checked = await checkClaimsAgainstScreenshots({ client, jobId, runId, report, screenshots, runDirectory, ledger, transcript, log, frames, measured: new Set(mergedAnchors(honesty).keys()), observations, notes, index: where, run: eventRun, impressionsAllowed: impressionsAllowed && claimGate !== 'legacy', gate: claimGate, secrets, stillReplay });
2376
+ const checked = await checkClaimsAgainstScreenshots({ client, jobId, runId, report, screenshots, runDirectory, ledger, transcript, log, frames, measured: new Set(mergedAnchors(honesty).keys()), observations, notes, index: where, run: eventRun, impressionsAllowed: impressionsAllowed && claimGate !== 'legacy', gate: claimGate, secrets, stillReplay, reportLanguage: honesty && honesty.anygame ? honesty.anygame.report?.code || null : null });
2331
2377
  report = checked.report;
2332
2378
  turnedAway = checked.turnedAway;
2333
2379
  impressions = checked.impressions;
@@ -2643,7 +2689,8 @@ const WIDEST_CLAIM = Object.freeze({ severity: 'blocker', title: 'x'.repeat(160)
2643
2689
  * @returns {Object} a request body
2644
2690
  */
2645
2691
  export function claimCheckSizingRequest(frame) {
2646
- const questions = [{ cls: 'absence', fault: true }, { cls: 'other', fault: true }, { cls: 'layout', fault: false }, { cls: 'other', fault: false }].map(moment => claimText(WIDEST_CLAIM, moment));
2692
+ // A claim in another language is asked the same questions with one more paragraph (./claimwords.js UNSORTED): the reserve covers it.
2693
+ const questions = [{ cls: 'absence', fault: true }, { cls: 'other', fault: true }, { cls: 'layout', fault: false }, { cls: 'other', fault: false }, { cls: 'other', fault: true, english: false }, { cls: 'other', fault: false, english: false }].map(moment => claimText(WIDEST_CLAIM, moment));
2647
2694
  const question = questions.reduce((longest, text) => (text.length > longest.length ? text : longest), '');
2648
2695
  const system = [CLAIM_SYSTEM, CLAIM_FAULT_SYSTEM].reduce((longest, text) => (text.length > longest.length ? text : longest), '');
2649
2696
  return {
@@ -2721,12 +2768,15 @@ export function citedAfterScreenshot(finding, screenshots) {
2721
2768
  *
2722
2769
  * @returns {Promise<{report: Object, turnedAway: Array<Object>, impressions: Array<Object>}>}
2723
2770
  */
2724
- export async function checkClaimsAgainstScreenshots({ client, jobId, runId, report, screenshots, runDirectory, ledger, transcript, log = () => {}, frames = new Map(), measured = new Set(), observations = [], notes = [], index = null, run = null, impressionsAllowed = true, gate = 'judge', secrets = [], stillReplay = null }) {
2771
+ export async function checkClaimsAgainstScreenshots({ client, jobId, runId, report, screenshots, runDirectory, ledger, transcript, log = () => {}, frames = new Map(), measured = new Set(), observations = [], notes = [], index = null, run = null, impressionsAllowed = true, gate = 'judge', secrets = [], stillReplay = null, reportLanguage = null }) {
2725
2772
  if (!report || !Array.isArray(report.findings)) return { report, turnedAway: [], impressions: [] };
2726
2773
  const placedIndex = Array.isArray(index) ? index : attachWhereToLook(report, { observations, notes, screenshots }).index;
2727
2774
  const where = new Map(placedIndex.map(entry => [entry.id, entry]));
2728
2775
  const judged = report.findings.filter(finding => finding && (CLAIM_SEVERITIES.includes(finding.severity) || finding.severity === 'praise') && !measured.has(finding.id));
2729
- const shapes = new Map(judged.map(finding => [finding, claimShape(finding, { marked: Boolean(where.get(finding.id)?.marked) })]));
2776
+ // The report's language (./anygame/language.js reportLanguage): the playtester's claims are written in it, and English words are read only in English.
2777
+ // The legacy gate decides money elsewhere and keeps exactly the rules it had (./judge.js legacyIssue), in every language.
2778
+ const english = gate === 'legacy' || readsEnglish(reportLanguage);
2779
+ const shapes = new Map(judged.map(finding => [finding, claimShape(finding, { marked: Boolean(where.get(finding.id)?.marked), english })]));
2730
2780
  // Every issue a question is asked about, the most severe first; praise and a judgement of its own play are not asked.
2731
2781
  const issues = judged.filter(finding => shapes.get(finding).question !== null || (gate === 'legacy' && shapes.get(finding).cls === 'difficulty'))
2732
2782
  .sort((a, b) => CLAIM_SEVERITIES.indexOf(a.severity) - CLAIM_SEVERITIES.indexOf(b.severity));
@@ -2765,7 +2815,7 @@ export async function checkClaimsAgainstScreenshots({ client, jobId, runId, repo
2765
2815
  .reverse().find(entry => entry.relativePath !== shot.relativePath);
2766
2816
  if (before) pictures.push(before.relativePath);
2767
2817
  }
2768
- const question = claimText(finding, { cls: shape.cls === 'difficulty' ? 'other' : shape.cls, fault: shape.question !== null && shape.question !== 'plain' && shape.question !== 'layout' });
2818
+ const question = claimText(finding, { cls: shape.cls === 'difficulty' ? 'other' : shape.cls, fault: shape.question !== null && shape.question !== 'plain' && shape.question !== 'layout', ...(english ? {} : { english: false }) });
2769
2819
  const answers = [];
2770
2820
  let formatRepairUsed = false;
2771
2821
  for (const picture of pictures) {
@@ -2864,7 +2914,7 @@ export async function checkClaimsAgainstScreenshots({ client, jobId, runId, repo
2864
2914
  // A run whose findings decide money elsewhere (a fix's verify, a Labs scenario) keeps the gate it had: see ./judge.js legacyIssue.
2865
2915
  const outcome = gate === 'legacy'
2866
2916
  ? legacyIssue(finding, { check: checks.get(finding) || null, marked: Boolean(placed.marked) })
2867
- : judgeIssue(finding, { check: checks.get(finding) || null, run, step, marked: Boolean(placed.marked), still: still.get(finding) || null });
2917
+ : judgeIssue(finding, { check: checks.get(finding) || null, run, step, marked: Boolean(placed.marked), still: still.get(finding) || null, english });
2868
2918
  transcript.write({ kind: 'claim_judged', id: finding.id, route: outcome.route, outcome: outcome.outcome, cls: outcome.cls, ...(outcome.basis ? { basis: outcome.basis } : {}), ...(outcome.impression ? { impression: outcome.impression.kind } : {}), ...(outcome.evidence ? { evidence: outcome.evidence } : {}) });
2869
2919
  if (outcome.route === 'finding') { findings.push(finding); continue; }
2870
2920
  if (outcome.route === 'impression') {