ravensight-playtest 0.8.3 → 0.10.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 (66) hide show
  1. package/README.md +280 -66
  2. package/addons/ravensight_driver/driver.gd +666 -21
  3. package/docs/ADAPTERS.md +11 -7
  4. package/docs/NATIVE_RUNNER.md +3 -1
  5. package/docs/godot-driver.md +127 -13
  6. package/package.json +8 -6
  7. package/src/api/client.js +4 -3
  8. package/src/cli.js +84 -25
  9. package/src/commands/check.js +30 -4
  10. package/src/commands/fakeCore.js +1 -0
  11. package/src/commands/hosted.js +41 -12
  12. package/src/commands/init.js +17 -1
  13. package/src/commands/run.js +209 -14
  14. package/src/commands/upload.js +6 -2
  15. package/src/commands/validate.js +1 -1
  16. package/src/commands/validateHosted.js +50 -5
  17. package/src/config.js +33 -2
  18. package/src/hosted/archivePreflight.js +7 -7
  19. package/src/hosted/buildUpload.js +89 -8
  20. package/src/hosted/recordedRun.js +141 -26
  21. package/src/hosted/status.js +19 -10
  22. package/src/run/actionSelector.js +14 -3
  23. package/src/run/aggregate.js +57 -3
  24. package/src/run/anygame/controlbook.js +179 -0
  25. package/src/run/anygame/genre.js +179 -0
  26. package/src/run/anygame/index.js +258 -0
  27. package/src/run/anygame/language.js +336 -0
  28. package/src/run/anygame/memory.js +330 -0
  29. package/src/run/anygame/shared-hashes.json +10 -0
  30. package/src/run/anygame/shared.js +24 -0
  31. package/src/run/anygame/sound.js +342 -0
  32. package/src/run/args.js +75 -8
  33. package/src/run/choiceCheck.js +312 -0
  34. package/src/run/context.js +254 -13
  35. package/src/run/drivers/godot-observation.js +93 -6
  36. package/src/run/drivers/godot.js +769 -46
  37. package/src/run/drivers/recording.js +24 -4
  38. package/src/run/drivers/web.js +1242 -77
  39. package/src/run/edgePass.js +731 -0
  40. package/src/run/fixLoop.js +5 -4
  41. package/src/run/focus.js +65 -0
  42. package/src/run/gamepad.js +108 -0
  43. package/src/run/godotEdgePass.js +235 -0
  44. package/src/run/godotTesterProbes.js +192 -0
  45. package/src/run/headings.js +21 -0
  46. package/src/run/honesty.js +544 -0
  47. package/src/run/inputs.js +256 -0
  48. package/src/run/marks.js +142 -0
  49. package/src/run/personaLoop.js +1000 -79
  50. package/src/run/phone.js +7 -0
  51. package/src/run/pixels.js +215 -0
  52. package/src/run/playClock.js +162 -0
  53. package/src/run/readiness.js +585 -0
  54. package/src/run/refusal.js +67 -0
  55. package/src/run/regions.js +119 -0
  56. package/src/run/report.js +14 -2
  57. package/src/run/reportChecks.js +472 -0
  58. package/src/run/resume.js +3 -2
  59. package/src/run/screenshots.js +161 -0
  60. package/src/run/strip.js +114 -0
  61. package/src/run/testerLedger.js +312 -0
  62. package/src/run/testerProbes.js +584 -0
  63. package/src/run/thinRun.js +102 -0
  64. package/src/run/timeFreeze.js +79 -0
  65. package/src/run/tools.js +454 -29
  66. package/src/runDefaults.js +24 -2
@@ -2,20 +2,42 @@ import { rewriteMarkdown } from './dropped.js';
2
2
  import { selectAction, JEV_CONTROLLER_PROMPT } from './actionSelector.js';
3
3
  import { mkdir, readFile, writeFile } from 'node:fs/promises';
4
4
  import path from 'node:path';
5
- import { prepareMessages, repairLastTurn, MAX_IMAGES_IN_CONTEXT, KEEP_OBSERVATIONS, shrinkImages } from './context.js';
6
- import { withRollingCacheBreakpoint } from './fixLoop.js';
5
+ import { prepareMessages, repairLastTurn, frozenEnds, frozenEnd, createCacheLayout, MAX_IMAGES_IN_CONTEXT, KEEP_OBSERVATIONS, shrinkImages } from './context.js';
7
6
  import { callStepWithRetry, ProxyError, STEPS } from './model.js';
8
7
  import { RUN_FILES } from './paths.js';
9
8
  import { reserveDecision } from './budgetReserve.js';
9
+ import { createScreenshotKeeper } from './screenshots.js';
10
+ import { checkBriefChoice, screensForCheck, writeChoiceIntoMarkdown, CHOICE_CHECK_FILE } from './choiceCheck.js';
11
+ import { declinedAnswer, declinedPrompt, declinedStopDetail, NEUTRAL_RESTATEMENT } from './refusal.js';
12
+ import { createPlayClock, clockStopDetail, timeLeftAside } from './playClock.js';
10
13
  import { appendNormalisedMarkdown, checkEvidence, createReportValidator, lintMarkdownSections, normaliseEnums, normaliseEvidence, repairInstruction, REQUIRED_MARKDOWN_SECTIONS, stampReport, stripTrailingToolMarkup, writeReportFiles } from './report.js';
11
14
  import { assertNoSecrets, scanForSecrets } from './secretScan.js';
12
- import { ACTION_TOOLS, PLAY_TOOLS, SWIPE_TOOL, REPORT_TOOLS, executeTool } from './tools.js';
15
+ import { ACTION_TOOLS, NEW_TOOL_NAMES, REPORT_TOOLS, executeTool, expectationOf, modelFrameOf, toolResult, toolsFor, NEWEST_TOOL_NAMES } from './tools.js';
16
+ import {
17
+ CAPABILITY_HEADING, DIALOGS_HEADING, EVIDENCE_HEADING, MAX_WIN_CONTINUES, RUNNER_FINDINGS_HEADING, WIN_TEXT,
18
+ addRunnerFindings, attachWhereToLook, blankFinding, capabilityPrompt, createBlankWatch, createCapabilityLedger, describeInput, dialogNote, gameEndedFinding, gameEndedOf,
19
+ playOnText, replaceSection, runnerFinding, runnerFindingsMarkdown, stepsBefore, whereToLookMarkdown, writeCapabilitySection
20
+ } from './honesty.js';
21
+ import { runEdgePass, edgeFindings, edgeMarkdown, EDGE_HEADING, blankCapabilityNote } from './edgePass.js';
22
+ // Tester techniques (./testerLedger.js): a coverage map, the game's own numbers and placeholder text, kept by the runner.
23
+ import { createTesterLedger, testerFindings, testedMarkdown, TESTED_HEADING } from './testerLedger.js';
24
+ import { runTesterProbes, probeFindings, probesMarkdown, probeObserver, PROBES_HEADING } from './testerProbes.js';
25
+ import { runGodotTesterProbes, godotProbesMarkdown } from './godotTesterProbes.js';
26
+ import { runGodotEdgePass } from './godotEdgePass.js';
27
+ import { recordingMetadata, saveRecording } from './drivers/recording.js';
13
28
  import { createTranscript } from './transcript.js';
14
29
  import { createUsageLedger, writeUsageFile } from './usage.js';
15
30
  import { fillPlaceholders, fillReportPlaceholders } from './placeholders.js';
16
31
  import { gameRefusal } from './gameRefusal.js';
17
32
  import { BUILT_IN_NOISE, expectedNoiseForPrompt, isExpectedNoise } from './noise.js';
33
+ import { cutFindingFrames, moodOf, replayCapabilityNote, replayFindings, replayWebFindings, screenOf, traceWebInputs } from './reportChecks.js';
34
+ import { pngFingerprint, screenDelta, significant } from './pixels.js';
35
+ import { mkdtemp } from 'node:fs/promises';
36
+ import os from 'node:os';
18
37
  import { MIN_PASSWORD_CHARS } from '../briefLocal.js';
38
+ // any-game hook: the run's notebook, control learning, language, kind of game and sound (./anygame/index.js).
39
+ import { createLocalAnyGame } from './anygame/index.js';
40
+ import { staleObservationCount } from './context.js';
19
41
 
20
42
  /**
21
43
  * One persona's playthrough: PLAYING then REPORTING (spec 03).
@@ -90,6 +112,12 @@ const OFF_SITE_VIA = Object.freeze({
90
112
  * @param {{host?: string, via?: string}} attempt
91
113
  * @returns {string}
92
114
  */
115
+ /** The screen an observation shows, as the field its step log line carries; nothing when it cannot be told from the text. */
116
+ export function screenLine(text, url) {
117
+ const screen = screenOf(text, url);
118
+ return screen ? { screen } : {};
119
+ }
120
+
93
121
  export function offSiteNoteText(attempt) {
94
122
  const via = OFF_SITE_VIA[attempt && attempt.via] || 'the page';
95
123
  return `off-site: ${via} tried to leave the build for ${(attempt && attempt.host) || 'another site'}; the runner kept the page on the build.`;
@@ -103,19 +131,75 @@ export const NOTE_CATEGORY = Object.freeze({ bug: 'bug', confusing: 'ux', sugges
103
131
  /** Stop injecting the "nothing changed" hint after this many identical screens. */
104
132
  export const STUCK_HINT_AFTER = 5;
105
133
 
134
+ /**
135
+ * The first hint comes sooner: after this many inputs in a row that changed
136
+ * nothing, the persona is told which inputs failed on this screen and what
137
+ * else there is to try. The cloud runner hands a stuck screen back after two.
138
+ */
139
+ export const FIRST_STUCK_HINT_AFTER = 2;
140
+
141
+ /** The most failed inputs a stuck hint lists. */
142
+ export const MAX_FAILED_INPUTS_LISTED = 8;
143
+
106
144
  /** Give up entirely after this many identical screens: the persona is wedged. */
107
145
  export const STUCK_LIMIT = 12;
108
146
 
109
147
  /**
110
- * Act turns allowed after a budget warning: none. The proxy reserves each
111
- * call's pessimistic projection (the whole request at the full input rate,
112
- * plus the output ceiling) before it sends it, so every act turn after the
113
- * warning ate into the 20 percent the report step needs, and in the Texas run
114
- * three of them left too little for the report's own reservation: the report
115
- * call was refused with 402 and the run ended at cost_cap with no report.
116
- * The warned turn's own actions are still played; then the report is written.
148
+ * Act turns allowed after a budget warning: one, and only when the reserve
149
+ * check (./budgetReserve.js) says the report still fits after it. With no
150
+ * figures to check against (an older server), none.
151
+ *
152
+ * It was three once, unchecked: the proxy reserves each call's pessimistic
153
+ * projection before it sends it, so every act turn after the warning ate into
154
+ * the 20 percent the report step needs, and in the Texas run three of them
155
+ * left too little for the report's own reservation (402, cost_cap, no
156
+ * report). Then it was none, which ended a run on whatever screen the warning
157
+ * found it, mid-thought, with nothing said about what it had been about to do.
158
+ * One checked turn lets the persona take a last look and write down what it
159
+ * has not yet noted. The warned turn's own actions are still played.
160
+ */
161
+ export const WRAP_UP_TURNS = 1;
162
+
163
+ /**
164
+ * A session shorter than this is not what a run is sold as: the proof bar a
165
+ * run is held to is fifteen actions.
166
+ */
167
+ export const MIN_SESSION_ACTIONS = 15;
168
+
169
+ /**
170
+ * Below this many actions a persona that stops on its own, with budget left,
171
+ * is asked once whether it is really done: at least the proof bar, and at
172
+ * least half of what it may take. Only for a run allowed a whole session.
173
+ *
174
+ * @param {number} maxActions
175
+ * @returns {number} 0 when the run is too short to ask
176
+ */
177
+ export function keepGoingBelow(maxActions) {
178
+ const max = Number(maxActions) || 0;
179
+ return max >= MIN_SESSION_ACTIONS ? Math.max(MIN_SESSION_ACTIONS, Math.ceil(max / 2)) : 0;
180
+ }
181
+
182
+ /** What a persona that stopped early is asked, once. */
183
+ export function keepGoingText(actions, maxActions) {
184
+ return `You stopped after ${actions} of ${maxActions} actions, and the run's budget has room for more. Having done what the brief's success criteria describe is not by itself a reason to stop: the developer paid for a full session, and learns most from what lies past the first goal. Keep playing in scope: try the systems you have not touched and go further into the ones you have. If one of your persona's own stop conditions fired, or there is truly nothing left to do, say which in one line with no tool call, and the session ends there.`;
185
+ }
186
+
187
+ /** What the persona is told on the turn before its last. */
188
+ export const WRAP_UP_ASIDE = 'The model budget for play is nearly spent: your next turn is the last one. Use it for the one thing that matters most now: a final action you were about to take, a screenshot of where you ended, and a note for anything you saw and have not written down. Then the report is written from your notes.';
189
+
190
+ /**
191
+ * Runner notes for the act step, after the skill and the brief. They are
192
+ * about how this runner works and what it costs, never about the game.
117
193
  */
118
- export const WRAP_UP_TURNS = 0;
194
+ export const PLAY_NOTES = [
195
+ 'How this runner works (none of this is ever a finding about the game):',
196
+ '- Every action answers with the screen that followed, so do not call snapshot after an action; call it only to look again after a wait.',
197
+ '- Each turn spends the run\'s model budget, and the budget, not the action count, usually ends a run. Do not spend turns looking twice. When the next two or three inputs are plain (close a dialog, then press Start; end three turns in a row), send them as separate tool calls in ONE turn.',
198
+ '- Say what you expect an action to do (expect). When the brief tells you to pick an option (a faction, a character, a class, a mode, a difficulty), read the options on the screen first, make exactly that choice, and check on the next screen that it is the one in effect. If it is not, say so in a note at once.',
199
+ '- Doing what the brief\'s success criteria describe is not a reason to stop. The developer paid for a full session and learns most from what lies past the first goal: keep playing in scope, try the systems you have not touched and go further into the ones you have, until your actions or the budget run out or one of your persona\'s own stop conditions fires.',
200
+ '- When you do stop, stop with one short sentence and no tool call. Never write the report here: a separate step writes it from your notes.',
201
+ '- The screen text or the scene outline can be cut short, and a picture is only sent when the text is not enough. When you need to see the screen, call screenshot: its result shows you the picture. What this runner could not show you, could not click or does not offer is a limit of the runner: mention it in a note of kind reaction if you must, never as a bug, a confusing or a suggestion note.'
202
+ ].join('\n');
119
203
 
120
204
  /** Token ceiling asked for per act turn. The proxy clamps it to the step's own. */
121
205
  export const ACT_MAX_TOKENS = 1024;
@@ -213,6 +297,11 @@ export async function runPersona(args) {
213
297
  // What the persona did, kept out here so a report can still say so when the
214
298
  // play loop dies part way through.
215
299
  const actionRecords = [];
300
+ // What the runner itself knows of this run (./honesty.js): inputs it could
301
+ // not send, findings it watched happen, dialogs and their answers, and the
302
+ // edge behaviour checks. Kept out here so a report written from the step
303
+ // log after a failure still carries them.
304
+ const honesty = { capability: createCapabilityLedger(), findings: [], dialogs: [], edge: null, video: null, traceSteps: new Map(), tester: createTesterLedger() };
216
305
  let imageBudget = maxImages;
217
306
 
218
307
  await mkdir(path.join(runDirectory, 'screenshots'), { recursive: true });
@@ -241,6 +330,7 @@ export async function runPersona(args) {
241
330
  reportLint: [],
242
331
  videoPath: null,
243
332
  usage: null,
333
+ runDirectory,
244
334
  // The last state the SERVER accepted, which is not the same thing as the
245
335
  // outcome: the caller has to know whether this run ever reached
246
336
  // `reporting`, because the server's table only allows `uploading` from
@@ -265,6 +355,8 @@ export async function runPersona(args) {
265
355
  await advance('launching');
266
356
  if ('traceSecrets' in driver) driver.traceSecrets = secretsOf(localBrief);
267
357
  await driver.launch({ target, runDir: runDirectory, recordVideo, viewport, signal: args.signal });
358
+ // A web run keeps its inputs, in this process only, so its findings can be replayed after the report.
359
+ if (driverName === 'playwright_web' && typeof args.replayDriver === 'function' && args.replayFindings !== false) traceWebInputs(driver, { fingerprint: pngFingerprint });
268
360
  await advance('playing');
269
361
 
270
362
  const play = await playLoop({
@@ -275,6 +367,7 @@ export async function runPersona(args) {
275
367
  screenshots,
276
368
  observations,
277
369
  actionRecords,
370
+ honesty,
278
371
  imageBudget,
279
372
  keepObservations,
280
373
  onImageBudget: next => {
@@ -285,7 +378,13 @@ export async function runPersona(args) {
285
378
  outcome = { ...outcome, ...play };
286
379
 
287
380
  const endedAt = new Date().toISOString();
288
- await driverStop(driver, outcome, log, play.canceled ? 'canceled' : 'completed');
381
+ // When the recording began, read before the driver is stopped: a finding's
382
+ // video time is measured from it.
383
+ const recordingStartedAt = typeof driver.recordingStartedAt === 'function' ? driver.recordingStartedAt() : null;
384
+ await driverStop(driver, outcome, log, play.canceled ? 'canceled' : play.gameEnded ? 'game_crashed' : 'completed');
385
+ if (outcome.videoPath && Number.isFinite(recordingStartedAt)) {
386
+ honesty.video = { startedAt: recordingStartedAt, file: path.basename(outcome.videoPath), ...(outcome.recording && Number.isFinite(outcome.recording.durationMs) ? { durationMs: outcome.recording.durationMs } : {}) };
387
+ }
289
388
  if (typeof driver.playMetrics === 'function') outcome.playMetrics = driver.playMetrics();
290
389
 
291
390
  if (args.signal?.aborted || heartbeat?.canceled) play.canceled = true;
@@ -301,7 +400,7 @@ export async function runPersona(args) {
301
400
  outcome.quitReason = 'cost_cap';
302
401
  // No positive remaining budget was established by the refusal.
303
402
  // Preserve the notes without authorizing another model call.
304
- await writeSomeReport({ outcome, runDirectory, persona, driverName, target, notes, screenshots, actionRecords, play, skill, ledger, runId, jobId, startedAt, endedAt, log });
403
+ await writeSomeReport({ outcome, runDirectory, persona, driverName, target, notes, screenshots, actionRecords, play, skill, ledger, runId, jobId, startedAt, endedAt, log, honesty, observations });
305
404
  return finish(outcome, ledger, runDirectory, transcript, heartbeat);
306
405
  }
307
406
 
@@ -328,13 +427,38 @@ export async function runPersona(args) {
328
427
  notes,
329
428
  screenshots,
330
429
  observations,
430
+ honesty,
331
431
  play,
332
432
  startedAt,
333
433
  endedAt,
334
434
  log
335
435
  });
336
436
 
437
+ // The findings' recorded inputs played again with no model, on this
438
+ // project, to see whether the same state comes back (a Godot lockstep
439
+ // run; any other says it cannot be replayed). The result is a line of
440
+ // the step log per finding. It never changes the report or fails the run.
441
+ if (args.replayFindings !== false) {
442
+ const replayed = Array.isArray(driver.webTrace)
443
+ ? replayWebFindings({ report: written.report, index: written.index || [], traceSteps: honesty.traceSteps, trace: driver.webTrace, makeDriver: args.replayDriver, target, viewport, playMs: Date.parse(endedAt) - Date.parse(startedAt), transcript, signal: args.signal,
444
+ fingerprint: pngFingerprint, differs: (a, b) => { const delta = screenDelta(a, b); return delta === null || significant(delta); }, tempDir: () => mkdtemp(path.join(os.tmpdir(), 'rs-replay-')),
445
+ // [tester hook] The probes that found something are run once more at the end of this one replay (./testerProbes.js probeObserver).
446
+ observer: probeObserver({ probes: honesty.probes, report: written.report, actionRecords, signal: args.signal }) })
447
+ : replayFindings({ report: written.report, index: written.index || [], traceSteps: honesty.traceSteps, runDirectory, driver, playMs: Date.parse(endedAt) - Date.parse(startedAt), transcript, signal: args.signal });
448
+ await replayed
449
+ .then(pass => {
450
+ // A game that started differently on replay is a limit of the runner: a capability note, never a finding.
451
+ const note = replayCapabilityNote(pass);
452
+ if (note && honesty.capability.add(note)) transcript.write({ kind: 'capability_note', input: note.input, reason: note.reason });
453
+ if (pass.ran) log(`replayed ${pass.results.filter(result => result.of > 0).length} finding(s) with no model: ${pass.results.filter(result => result.of > 0).map(result => `${result.id} ${result.state.replace('_', ' ')} (${result.runs} of ${result.of})`).join(', ')}`); })
454
+ .catch(error => transcript.write({ kind: 'replay_pass', ran: false, runs: 0, skipped: `the replay could not start (${String(error && error.message ? error.message : error).slice(0, 80)})` }));
455
+ } else {
456
+ transcript.write({ kind: 'replay_pass', ran: false, runs: 0, skipped: 'the replay was turned off for this run (--no-replay)' });
457
+ }
458
+
337
459
  outcome.report = written.report;
460
+ // What the runner met and could not do, for the complete call (./thinRun.js capabilityNotesBody).
461
+ outcome.capabilityNotes = honesty.capability.list();
338
462
  outcome.reportMarkdown = written.markdown;
339
463
  outcome.reportLint = written.lint;
340
464
  outcome.state = play.budgetExceeded ? 'budget_exceeded' : 'succeeded';
@@ -349,18 +473,20 @@ export async function runPersona(args) {
349
473
  // The money ran out in the report step itself: the notes are still
350
474
  // worth keeping, by the same rule as a 402 during play.
351
475
  const play = { actionsTaken: outcome.actionsTaken, quitReason: 'cost_cap', quitDetail: String(error.message || '') };
352
- await writeSomeReport({ outcome, runDirectory, persona, driverName, target, notes, screenshots, actionRecords, play, skill, ledger, runId, jobId, startedAt, endedAt: new Date().toISOString(), log, preservedMarkdown: error.completedReportMarkdown });
476
+ await writeSomeReport({ outcome, runDirectory, persona, driverName, target, notes, screenshots, actionRecords, play, skill, ledger, runId, jobId, startedAt, endedAt: new Date().toISOString(), log, honesty, observations, preservedMarkdown: error.completedReportMarkdown });
353
477
  } else if (error && error.reportIncomplete && !args.signal?.aborted) {
354
478
  // The run played; only the report step could not finish. Its notes are
355
479
  // the report, by the same rule as a 402 in the report step. Under budget
356
- // pressure that is a budget stop; otherwise the run is marked failed, so
357
- // the unit is refunded, and the report still carries what it saw.
480
+ // pressure that is a budget stop; otherwise the run is marked failed, and
481
+ // the report still carries what it saw. What is charged or refunded is the
482
+ // server's decision: a failed run with AI time and a report is billed at
483
+ // cost unless the server recorded a failure of its own on the run.
358
484
  outcome.state = error.budgetPressure ? 'budget_exceeded' : 'failed';
359
485
  outcome.quitReason = error.budgetPressure ? 'cost_cap' : 'error';
360
486
  const actionsTaken = Math.max(outcome.actionsTaken || 0, actionLogFrom(actionRecords).length);
361
487
  const play = { actionsTaken, quitReason: outcome.quitReason, quitDetail: safeErrorDetail(error, localBrief) };
362
488
  await writeSomeReport({ outcome, runDirectory, persona, driverName, target, notes, screenshots, actionRecords, play, skill, ledger, runId, jobId, startedAt,
363
- endedAt: new Date().toISOString(), log, quitReason: outcome.quitReason, reason: REPORT_INCOMPLETE_REASON, bareReason: REPORT_INCOMPLETE_REASON,
489
+ endedAt: new Date().toISOString(), log, honesty, observations, quitReason: outcome.quitReason, reason: REPORT_INCOMPLETE_REASON, bareReason: REPORT_INCOMPLETE_REASON,
364
490
  preservedMarkdown: error.completedReportMarkdown });
365
491
  } else if (error instanceof ProxyError && error.isClosed) {
366
492
  outcome.state = 'canceled';
@@ -369,8 +495,10 @@ export async function runPersona(args) {
369
495
  outcome.state = 'failed';
370
496
  outcome.quitReason = 'error';
371
497
  // A run that broke still reports what it saw and why it stopped. The
372
- // state is still `failed`, so the unit is still refunded; the report
373
- // costs no model call. An abort is the person stopping it, not a failure.
498
+ // state is still `failed`, and the server decides what it is charged
499
+ // (whole refund only for a failure of its own, otherwise at cost when AI
500
+ // time was used and a report was accepted). The report costs no model
501
+ // call. An abort is the person stopping it, not a failure.
374
502
  if (!args.signal?.aborted) {
375
503
  const detail = safeErrorDetail(error, localBrief);
376
504
  // The play loop's count only reaches `outcome` when it returns, and this
@@ -378,7 +506,7 @@ export async function runPersona(args) {
378
506
  const actionsTaken = Math.max(outcome.actionsTaken || 0, actionLogFrom(actionRecords).length);
379
507
  const play = { actionsTaken, quitReason: 'error', quitDetail: detail };
380
508
  await writeSomeReport({
381
- outcome, runDirectory, persona, driverName, target, notes, screenshots, actionRecords, play, skill, ledger, runId, jobId, startedAt, endedAt: new Date().toISOString(), log,
509
+ outcome, runDirectory, persona, driverName, target, notes, screenshots, actionRecords, play, skill, ledger, runId, jobId, startedAt, endedAt: new Date().toISOString(), log, honesty, observations,
382
510
  quitReason: 'error',
383
511
  // The notes stay in report.md and out of report.json. Nothing reviewed
384
512
  // them, they may be symptoms of the crash, and what report.json holds
@@ -402,6 +530,213 @@ export async function runPersona(args) {
402
530
  *
403
531
  * @returns {Promise<Object>}
404
532
  */
533
+ /**
534
+ * Take the pictures out of a turn's tool results: the results as text only,
535
+ * and the newest picture on its own.
536
+ *
537
+ * Why. The act step keeps one picture in the whole conversation, so the
538
+ * picture a turn sends is rewritten into a one line placeholder on the next
539
+ * turn. While it sat inside the turn's last tool result, that was the block
540
+ * the prompt cache had been written at, so every turn on a screen played from
541
+ * a picture found nothing to read back and wrote the whole conversation again
542
+ * at the write premium. With the picture as a separate block after the
543
+ * breakpoint, what was written is what the next turn sends.
544
+ *
545
+ * @param {Array<Object>} results tool_result blocks
546
+ * @returns {{results: Array<Object>, image: Object|null}}
547
+ */
548
+ export function hoistImages(results) {
549
+ let image = null;
550
+ const out = (Array.isArray(results) ? results : []).map(block => {
551
+ if (!block || block.type !== 'tool_result' || !Array.isArray(block.content) || !block.content.some(child => child && child.type === 'image')) return block;
552
+ for (const child of block.content) if (child && child.type === 'image') image = child;
553
+ const content = block.content.filter(child => !(child && child.type === 'image'));
554
+ return { ...block, content: content.length > 0 ? content : [{ type: 'text', text: '(a picture)' }] };
555
+ });
556
+ return { results: out, image };
557
+ }
558
+
559
+ /** The marker the proxy passes through unchanged. */
560
+ const PLAY_CACHE_BREAKPOINT = Object.freeze({ type: 'ephemeral' });
561
+
562
+ /**
563
+ * The cache breakpoints of an act request, on a copy: one moving breakpoint
564
+ * on the newest block that is not a picture, and one fixed breakpoint where
565
+ * the stubbed part of the conversation ends (./context.js `frozenEnd`).
566
+ *
567
+ * See {@link hoistImages} for why the picture is left after the moving one;
568
+ * see ./fixLoop.js `withRollingCacheBreakpoint` for why it moves and is never
569
+ * left behind.
570
+ *
571
+ * Why the fixed one, and why only one. A cache entry exists only where a
572
+ * breakpoint was. With the moving breakpoint alone, the turn that stubbed a
573
+ * block of old observations changed bytes ahead of every entry the cache
574
+ * held, so the whole conversation was written again at the write premium. A
575
+ * breakpoint on the end of the stubbed part is an entry that turn can read.
576
+ * There were two of these (the end, and the end before it), and the third
577
+ * stubbed block of a paid run still read back only to the first: the marker
578
+ * itself is compared, so the turn that took the oldest marker away changed
579
+ * that block and lost everything after it. One fixed breakpoint, moved only
580
+ * as far as the cache looks back, is read on every block after the first:
581
+ * the old end is found by the look back and needs no marker of its own.
582
+ *
583
+ * @param {Array<Object>} messages a prepared conversation
584
+ * @param {Object|null} [layout] the run's cache layout (./context.js)
585
+ * @returns {Array<Object>}
586
+ */
587
+ export function withPlayCacheBreakpoint(messages, layout = null) {
588
+ const last = messages.at(-1);
589
+ if (!last || !Array.isArray(last.content) || last.content.length === 0) return messages;
590
+ let index = last.content.length - 1;
591
+ while (index >= 0 && last.content[index] && last.content[index].type === 'image') index -= 1;
592
+ if (index < 0 || !last.content[index] || typeof last.content[index] !== 'object') return messages;
593
+ const out = [...messages];
594
+ const mark = (i, j) => {
595
+ const message = out[i];
596
+ const content = [...message.content];
597
+ content[j] = { ...content[j], cache_control: PLAY_CACHE_BREAKPOINT };
598
+ out[i] = { ...message, content };
599
+ };
600
+ const end = layout ? frozenEnd(messages, layout) : frozenEnds(messages).current;
601
+ if (end && !(end[0] === messages.length - 1 && end[1] === index)) mark(end[0], end[1]);
602
+ mark(messages.length - 1, index);
603
+ return out;
604
+ }
605
+
606
+ /**
607
+ * One call's token counts as a transcript line, so what a turn cost can be
608
+ * read back per turn (usage.json holds only the run's totals).
609
+ *
610
+ * @param {Object} usage
611
+ * @returns {Object}
612
+ */
613
+ export function usageLine(usage = {}) {
614
+ return {
615
+ input_tokens: Number(usage.input_tokens || 0),
616
+ cache_write_tokens: Number(usage.cache_creation_input_tokens || 0),
617
+ cache_read_tokens: Number(usage.cache_read_input_tokens || 0),
618
+ output_tokens: Number(usage.output_tokens || 0)
619
+ };
620
+ }
621
+
622
+ /**
623
+ * An input as a few words, for the list of inputs that changed nothing.
624
+ *
625
+ * @param {Object} input the tool call's input, secrets already redacted
626
+ * @param {string} tool
627
+ * @returns {string}
628
+ */
629
+ export function inputLabel(input = {}, tool = '') {
630
+ if (tool === 'key') return `key ${String(input.key || '')}${input.hold_ms ? ` held ${input.hold_ms} ms` : ''}`;
631
+ if (tool === 'type') return 'typing';
632
+ if (tool === 'navigate') return `navigate ${String(input.url || '').slice(0, 60)}`;
633
+ if (tool === 'swipe') return `swipe from (${input.x},${input.y})`;
634
+ if (typeof input.ref === 'string' && input.ref.trim()) return `click ${input.ref.trim()}`;
635
+ if (typeof input.target === 'string' && input.target.trim()) return `click ${input.target.trim().slice(0, 60)}`;
636
+ if (Number.isFinite(Number(input.x)) && Number.isFinite(Number(input.y))) return `click at (${Math.round(Number(input.x))},${Math.round(Number(input.y))})`;
637
+ return tool || 'an input';
638
+ }
639
+
640
+ /** Remember that `label` changed nothing on the screen whose text is `screen`. */
641
+ export function rememberFailedInput(failed, screen, label) {
642
+ const key = String(screen == null ? '' : screen);
643
+ if (!failed.has(key)) failed.set(key, new Set());
644
+ failed.get(key).add(label);
645
+ }
646
+
647
+ /** The inputs that changed nothing on this screen, oldest first. */
648
+ export function failedInputsOn(failed, screen) {
649
+ return [...(failed.get(String(screen == null ? '' : screen)) || [])];
650
+ }
651
+
652
+ /**
653
+ * What a persona is told when its inputs stopped changing the screen: how
654
+ * long, which inputs failed here, and what else there is to try. The cloud
655
+ * runner tries other inputs by itself at this point; here the persona chooses
656
+ * every input, so it is handed the same list to choose from.
657
+ *
658
+ * @param {number} unchanged
659
+ * @param {Array<string>} failedHere
660
+ * @returns {string}
661
+ */
662
+ export function stuckHint(unchanged, failedHere = []) {
663
+ const failed = failedHere.slice(-MAX_FAILED_INPUTS_LISTED);
664
+ return [
665
+ `The screen has not changed for ${unchanged} actions. Your persona would notice that.`,
666
+ failed.length > 0 ? `Inputs that changed nothing on this screen, so do not send them again: ${failed.join('; ')}.` : '',
667
+ 'Try something you have not tried here: another control from the screen, by its exact name or the centre it prints; Enter, Space or Escape; a wait of a second or two in case the game is busy; or a screenshot to see the screen as it is drawn. If a target could not be found, that is the runner not finding it, not the game refusing you. Or stop.'
668
+ ].filter(Boolean).join(' ');
669
+ }
670
+
671
+ /**
672
+ * The report step's instruction for a choice the brief names. The runner
673
+ * makes its own check afterwards (./choiceCheck.js) and writes the result
674
+ * into the report; this is so the persona's own account agrees with it.
675
+ */
676
+ export const CHOICE_CHECK_INSTRUCTION = 'When the brief tells the player to pick one option out of several the game offers (play as a faction, choose a character or a class, select a mode or a difficulty), check it before you write: find the action that made the choice in the list above, read the observation that followed it, and say in the success criteria line of "What worked" which option the screens show is in effect, quoting their text. Clicking an option is not proof that it took. If the screens show a different option, or never show which one is in effect, say exactly that, and say in "What this run didn\'t cover" that the session was not played as the brief asked. A success criterion, a goal, a level to reach or how far the session got is never such a choice: a session that tried for a goal and fell short was played as the brief asked, and you say how far it got. The runner checks the same thing against the screens and writes its own line into the report when the brief names a choice.';
677
+
678
+ /**
679
+ * What the report step is told the runner's choice check found, so the
680
+ * persona's account does not say the opposite of the line the runner writes.
681
+ *
682
+ * @param {{choice: string, result: string, shown: string}} check
683
+ * @returns {string}
684
+ */
685
+ export function choiceCheckLine(check) {
686
+ const verdict = check.result === 'confirmed'
687
+ ? 'the screens show it in effect'
688
+ : check.result === 'contradicted' ? 'the screens show a DIFFERENT choice in effect' : 'no screen shows which choice is in effect';
689
+ return `The runner has already checked this against the session's screens: the brief names ${check.choice}, and ${verdict}${check.shown ? ` (${check.shown.replace(/[.\s]+$/, '')})` : ''}. Say the same in your success criteria line and in "What this run didn't cover"; never write the opposite.`;
690
+ }
691
+
692
+ /**
693
+ * The visible text of the screens that followed a stated expectation, and of
694
+ * the last screen, for the report prompt.
695
+ *
696
+ * @param {Array<Object>} records the transcript's observation and action lines
697
+ * @returns {string}
698
+ */
699
+ export function screenTextLines(records) {
700
+ const screens = screensForCheck(records || []);
701
+ return screens.length > 0 ? screens.map(screen => `- ${screen.label}: ${screen.text}`).join('\n') : '(none)';
702
+ }
703
+
704
+ /** The report step's instruction for the runner's own limits. */
705
+ export const CAPABILITY_NOTES_INSTRUCTION = 'Limits of this runner are capability notes, never findings of any severity or category: what the screen text or the scene outline did not show or cut short, a picture you were not shown, a target the runner could not find or click, a tool you did not have, anything about snapshots, screenshots, node paths, refs or drivers. Write them in "What this run didn\'t cover". A finding about how the game looks (text that cannot be read, a label that is missing or cut off) must be true of a screenshot you cite; if you never saw the picture, it is a capability note. The runner drops a finding that is about its own tools.';
706
+
707
+ /**
708
+ * A finding that is about the runner's tools and not the game. Phrases, not
709
+ * single words: "driver", "outline" and "snapshot" are ordinary words in a
710
+ * racing game, a drawing game and a photo mode.
711
+ */
712
+ export const RUNNER_LIMIT_TEXT = new RegExp([
713
+ '\\b(?:snapshot|screenshot|observation) tool\\b',
714
+ '\\bscene tree\\b',
715
+ '\\bnode paths?\\b',
716
+ '\\baccessibility (?:tree|snapshot)\\b',
717
+ '\\b(?:tree|outline|snapshot|observation)s? (?:is|was|were|are|keeps?|kept|got|gets) (?:cut|truncat\\w+)',
718
+ '\\btruncat\\w+ (?:scene tree|tree|outline|snapshot|observation)\\b',
719
+ '\\[\\+\\d+ more\\]',
720
+ '\\b(?:the|this) (?:runner|test harness|harness|playtest tool|automation)\\b[^.]{0,60}\\b(?:cannot|can not|could not|couldn\'t|can\'t|does not|doesn\'t|did not|didn\'t|unable|limit)',
721
+ '\\bclickable node not found\\b',
722
+ '\\b(?:could|can) ?not (?:see|view) the (?:screenshot|picture|image)\\b',
723
+ '\\bwithout (?:seeing|being shown) the (?:screenshot|picture|image)\\b',
724
+ // What the runner cannot sense or send: it hears nothing and holds no
725
+ // controller, so "there is no sound" and "the gamepad does nothing" are
726
+ // about the runner.
727
+ '\\b(?:no|missing|lacks?|without|absence of)(?: any| a)? (?:sound|audio|music|sound effects?)\\b',
728
+ '\\b(?:game|it) (?:is|was|plays?|played) (?:completely |entirely |totally )?(?:silent|mute|muted)\\b',
729
+ '\\b(?:gamepad|controller|touch(?: ?screen)?|pointer lock|microphone)\\b[^.]{0,80}\\b(?:could not be|cannot be|can not be|was not|were not|not) (?:tested|sent|used|tried)'
730
+ ].join('|'), 'i');
731
+
732
+ /**
733
+ * @param {Object} finding
734
+ * @returns {boolean} true when the finding's own words are about the runner
735
+ */
736
+ export function aboutRunnerLimit(finding) {
737
+ return RUNNER_LIMIT_TEXT.test(`${(finding && finding.title) || ''}\n${(finding && finding.description) || ''}`);
738
+ }
739
+
405
740
  async function playLoop({
406
741
  // The observation and action lines of the transcript, kept for the report
407
742
  // step's "Actions you took" list and for a partial report.
@@ -436,17 +771,39 @@ async function playLoop({
436
771
  // older server) only the server's 80 percent warning does.
437
772
  modelBudgetUsd = null,
438
773
  reportSkill = null,
774
+ honesty = { capability: createCapabilityLedger(), findings: [], dialogs: [], edge: null, video: null, tester: createTesterLedger() },
775
+ // The scripted edge behaviour checks after play (./edgePass.js): on unless
776
+ // the run turned them off.
777
+ edgePass = true,
778
+ // The run's clock, for a run sold by the minute (./playClock.js): seconds of
779
+ // play, and the wall clock the server stops serving the run at.
780
+ playClock: clockLimits = null,
439
781
  log = () => {}
440
782
  }) {
441
783
  const system = buildSystem({ skill, persona, brief, localBrief, intentNotes, driverName, target, maxActions, runId });
442
784
  const identity = runIdentity({ persona, runId });
443
785
  const secrets = secretsOf(localBrief);
444
786
  const noisePatterns = (localBrief && Array.isArray(localBrief.expected_noise)) ? localBrief.expected_noise : [];
787
+ // any-game hook: one notebook a run, on the honesty record so the report step reads the same one.
788
+ const briefFields = brief && brief.fields && typeof brief.fields === 'object' ? brief.fields : brief || {};
789
+ 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), driverName: typeof driver.soundSelfTest === 'function' ? '' : driverName }));
790
+ system.push({ type: 'text', text: anyGame.systemText() });
791
+ system.push({ type: 'text', text: PLAY_NOTES });
792
+ if (typeof driver.soundSelfTest === 'function') anyGame.soundAvailable(await Promise.resolve().then(() => driver.soundSelfTest()).catch(() => null));
445
793
  if (['jev', 'rune'].includes(controller)) system.push({ type: 'text', text: JEV_CONTROLLER_PROMPT });
446
- const availableTools = driver.supportedActions
447
- ? [...PLAY_TOOLS, ...(driver.supportedActions.includes('swipe') ? [SWIPE_TOOL] : [])].filter(tool => !ACTION_TOOLS.includes(tool.name) || driver.supportedActions.includes(tool.name))
448
- : PLAY_TOOLS;
449
- const playTools = ['jev', 'rune'].includes(controller) ? availableTools.map(tool => ({
794
+ // The tools this driver can do. The newest names (drag, hover, scroll,
795
+ // select) are on the server's list from the release that added them; an
796
+ // older server refuses a request that carries one, and the run goes on with
797
+ // the names it has always allowed (the drag is then sent as `swipe`).
798
+ let newTools = true;
799
+ // pinch and gamepad are newer still: a server may allow the pointer tools
800
+ // and not yet these two, so they are given up first, on their own.
801
+ let newestTools = true;
802
+ const toolsNow = () => controllerTools(toolsFor(driver, { newTools, newestTools }));
803
+ // The tools a driver offers can grow during play (the gamepad, once the
804
+ // page has looked for one): the names it offers now, to notice when.
805
+ const offeredNow = () => (Array.isArray(driver && driver.pointerTools) ? driver.pointerTools.join(',') : '');
806
+ const controllerTools = availableTools => (['jev', 'rune'].includes(controller) ? availableTools.map(tool => ({
450
807
  ...tool,
451
808
  input_schema: {
452
809
  ...tool.input_schema,
@@ -457,7 +814,14 @@ async function playLoop({
457
814
  ...(tool.name === 'click' ? { target: { type: 'string', description: 'Label of the visible control. For canvas also supply x and y; the driver uses those coordinates.' } } : {})
458
815
  }
459
816
  }
460
- })) : availableTools;
817
+ })) : availableTools);
818
+ let playTools = toolsNow();
819
+ let offered = offeredNow();
820
+ // What a driver has to say about how this run is played (touch on a phone screen).
821
+ if (driver && typeof driver.playNote === 'string' && driver.playNote) system.push({ type: 'text', text: driver.playNote });
822
+ const blankWatch = createBlankWatch();
823
+ let gameEnded = null;
824
+ let winContinues = 0;
461
825
  const recentActions = [];
462
826
  let latestObservation = '';
463
827
  let visualObservation = false;
@@ -472,6 +836,35 @@ async function playLoop({
472
836
  let reserveStopped = false;
473
837
  let canceled = false;
474
838
  let unchanged = 0;
839
+ // Inputs in a row the runner itself could not send.
840
+ let toolFailures = 0;
841
+ // The screen the last observation showed: an observation that says only "unchanged" is still on it.
842
+ let screenNow = null;
843
+ const seenScreen = (text, url, same) => {
844
+ const line = screenLine(text, url);
845
+ if (line.screen) screenNow = line.screen;
846
+ else if (!same) screenNow = null;
847
+ return screenNow ? { screen: screenNow } : {};
848
+ };
849
+ let wrapUpTurnsLeft = WRAP_UP_TURNS;
850
+ let wrappingUp = false;
851
+ let keepGoingAsked = false;
852
+ // Answers that were not the persona's (./refusal.js): how many, and whether
853
+ // the turn just before this one was one.
854
+ let declined = 0;
855
+ let declinedLastTurn = false;
856
+ let declinedEnded = false;
857
+ // The clock a run sold by the minute stops on; never stops a run with no limit.
858
+ const clock = createPlayClock({ ...(clockLimits || {}) });
859
+ let clockStopped = false;
860
+ let timeLeftSaid = false;
861
+ // Inputs that changed nothing, by the screen they were tried on, so a stuck
862
+ // hint can say which ones not to repeat (the cloud runner's failed list).
863
+ const failedInputs = new Map();
864
+ const keeper = createScreenshotKeeper();
865
+ // Which old observations are sent as stubs and where the fixed cache
866
+ // breakpoint sits, decided once and kept for the run (./context.js).
867
+ const cacheLayout = createCacheLayout();
475
868
  const maxTurns = maxActions * 3 + 20;
476
869
  // What the last few act turns really cost, in weighted units.
477
870
  const recentActUnits = [];
@@ -484,11 +877,11 @@ async function playLoop({
484
877
  const reserveCheck = () => {
485
878
  const spend = modelBudgetUsd ? ledger.spendEstimate() : null;
486
879
  if (!spend) return { stop: false, known: false, figures: {} };
487
- const prepared = withRollingCacheBreakpoint(prepareMessages(messages, { maxImages: imageBudget, keepObservations }));
880
+ const prepared = withPlayCacheBreakpoint(prepareMessages(messages, { maxImages: imageBudget, keepObservations, layout: cacheLayout }), cacheLayout);
488
881
  const actChars = JSON.stringify({ messages: prepared, max_tokens: ACT_MAX_TOKENS, stream: true, system, tools: playTools }).length;
489
882
  const reportRequest = buildReportRequest({
490
883
  skill: reportSkill || skill, persona, brief, localBrief, intentNotes, driverName, target, runId, jobId,
491
- play: { actionsTaken: actions, quitReason: 'budget_exhausted', quitDetail: RESERVE_STOP_DETAIL, actionLog: actionLogFrom(actionRecords) },
884
+ play: { actionsTaken: actions, quitReason: 'budget_exhausted', quitDetail: RESERVE_STOP_DETAIL, actionLog: actionLogFrom(actionRecords), records: actionRecords },
492
885
  notes, observations, screenshots
493
886
  });
494
887
  const reportChars = JSON.stringify({ messages: reportRequest.messages, max_tokens: REPORT_MAX_TOKENS, stream: true, system: reportRequest.system, tools: REPORT_TOOLS }).length;
@@ -509,7 +902,13 @@ async function playLoop({
509
902
  let awaitingAfter = [];
510
903
  const observed = observation => {
511
904
  const entry = observationEntry(observation, observations.length + 1);
905
+ // When it was seen and after how many actions: what ties a finding to a
906
+ // step and to a time in the video.
907
+ entry.at = Date.now();
908
+ entry.actions = actions;
512
909
  observations.push(entry);
910
+ // [tester hook] The screen goes on the coverage map and its text is checked.
911
+ if (honesty.tester) honesty.tester.observe({ index: observations.length, text: observation && observation.text, title: entry.title, actions });
513
912
  for (const note of awaitingAfter) note.after = { url: entry.url, title: entry.title };
514
913
  awaitingAfter = [];
515
914
  return entry;
@@ -517,19 +916,23 @@ async function playLoop({
517
916
  const noted = note => {
518
917
  // A note never carries the test account password, in the transcript, a
519
918
  // partial report or the report prompt.
520
- const entry = { ...scrubSecrets(note, secrets), at_action: actions, observation: observations.length, order: nextOrder() };
919
+ const entry = { ...scrubSecrets(note, secrets), at_action: actions, observation: observations.length, order: nextOrder(), at: Date.now() };
521
920
  notes.push(entry);
522
921
  awaitingAfter.push(entry);
922
+ anyGame.afterNote(entry, actions); // any-game hook: a marked note is kept in the notebook
523
923
  return entry;
524
924
  };
525
925
 
526
926
  const first = await driver.observe();
527
927
  observed(first);
928
+ anyGame.seeScreen(first.text);
528
929
  latestObservation = first.text;
529
930
  visualObservation = Boolean(first.screenshotBase64);
530
- transcript.write({ kind: 'observation', step: first.step, text: first.text, url: first.url });
931
+ transcript.write({ kind: 'observation', step: first.step, text: first.text, url: first.url, ...seenScreen(first.text, first.url, false) });
531
932
  actionRecords.push({ kind: 'observation', text: first.text });
532
- const landing = await safeScreenshot(driver, 'landing', screenshots, transcript, observations.length);
933
+ const landing = await safeScreenshot(driver, 'landing', screenshots, transcript, observations.length, keeper);
934
+ // The landing is the first scene; its picture is already saved.
935
+ await keeper.scene(driver, 'landing', { save: false, text: first.text }).catch(() => null);
533
936
  messages.push({
534
937
  role: 'user',
535
938
  content: [
@@ -547,6 +950,15 @@ async function playLoop({
547
950
  quitDetail = 'the job was cancelled';
548
951
  break;
549
952
  }
953
+ const due = clock.due();
954
+ if (due) {
955
+ clockStopped = true;
956
+ quitReason = 'timeout';
957
+ quitDetail = clockStopDetail(due, clock.read());
958
+ transcript.write({ kind: 'clock_stop', which: due, ...clock.read() });
959
+ log(`stopping play after ${actions} action(s): ${quitDetail}.`);
960
+ break;
961
+ }
550
962
  if (turns > 0) {
551
963
  const reserve = reserveCheck();
552
964
  if (reserve.stop) {
@@ -559,6 +971,15 @@ async function playLoop({
559
971
  }
560
972
  }
561
973
  turns += 1;
974
+ if (offeredNow() !== offered) {
975
+ // One request writes the conversation to the cache again (the tools are
976
+ // ahead of everything); it happens once, when the game first looks for a gamepad.
977
+ const added = offeredNow().split(',').filter(name => name && !offered.split(',').includes(name));
978
+ offered = offeredNow();
979
+ playTools = toolsNow();
980
+ transcript.write({ kind: 'tools_offered', added });
981
+ if (added.length > 0) log(`the game asked for ${added.join(', ')}; the persona is offered ${added.length === 1 ? 'that tool' : 'those tools'} from this turn on.`);
982
+ }
562
983
  let answer;
563
984
  const askedAt = Date.now();
564
985
  const askAct = () => callWithImageRetry({
@@ -573,6 +994,7 @@ async function playLoop({
573
994
  escalate: shouldEscalate(persona),
574
995
  imageBudget,
575
996
  keepObservations,
997
+ layout: cacheLayout,
576
998
  onImageBudget: next => {
577
999
  imageBudget = next;
578
1000
  }
@@ -587,12 +1009,47 @@ async function playLoop({
587
1009
  // once more. A second refusal ends play, and the run still reports
588
1010
  // from its step log (runPersona's error path), because a run that
589
1011
  // played never comes back empty.
1012
+ const offersNewest = playTools.some(tool => NEWEST_TOOL_NAMES.includes(tool.name));
1013
+ if (error instanceof ProxyError && error.code === 'tool_not_allowed' && newTools && newestTools && offersNewest) {
1014
+ // A server from before pinch and the gamepad: play on without those
1015
+ // two, and say so. If it refuses the pointer tools as well, the next
1016
+ // refusal drops them the same way.
1017
+ newestTools = false;
1018
+ playTools = toolsNow();
1019
+ const dropped = NEWEST_TOOL_NAMES.filter(name => Array.isArray(driver.pointerTools) && driver.pointerTools.includes(name));
1020
+ for (const name of dropped) honesty.capability.add({ input: name === 'pinch' ? 'pinch (two fingers)' : name, reason: `the Ravensight server this run used does not yet allow the ${name} tool, so the persona was not offered it` });
1021
+ transcript.write({ kind: 'tools_fallback', dropped, message: String(error.message || '') });
1022
+ log(`the server does not allow ${dropped.join(' or ')} yet (${error.message}); playing on without ${dropped.length === 1 ? 'it' : 'them'}.`);
1023
+ try {
1024
+ answer = await askAct();
1025
+ } catch (again) {
1026
+ if (!(again instanceof ProxyError) || again.code !== 'tool_not_allowed') throw again;
1027
+ newTools = false;
1028
+ playTools = toolsNow();
1029
+ const older = NEW_TOOL_NAMES.filter(name => name !== 'drag' && Array.isArray(driver.pointerTools) && driver.pointerTools.includes(name));
1030
+ for (const name of older) honesty.capability.add({ input: name, reason: `the Ravensight server this run used does not yet allow the ${name} tool, so the persona was not offered it` });
1031
+ transcript.write({ kind: 'tools_fallback', dropped: older, message: String(again.message || '') });
1032
+ log(`the server does not allow the pointer tools either (${again.message}); playing on without ${older.join(', ') || 'them'}, with drag sent as swipe.`);
1033
+ answer = await askAct();
1034
+ }
1035
+ } else if (error instanceof ProxyError && error.code === 'tool_not_allowed' && newTools) {
1036
+ // A server from before the pointer tools: play on with the names it
1037
+ // allows, and say what could not be offered.
1038
+ newTools = false;
1039
+ playTools = toolsNow();
1040
+ const dropped = NEW_TOOL_NAMES.filter(name => name !== 'drag' && Array.isArray(driver.pointerTools) && driver.pointerTools.includes(name));
1041
+ for (const name of dropped) honesty.capability.add({ input: name, reason: `the Ravensight server this run used does not yet allow the ${name} tool, so the persona was not offered it` });
1042
+ transcript.write({ kind: 'tools_fallback', dropped, message: String(error.message || '') });
1043
+ log(`the server does not allow the newest input tools yet (${error.message}); playing on without ${dropped.join(', ') || 'them'}, with drag sent as swipe.`);
1044
+ answer = await askAct();
1045
+ } else {
590
1046
  if (!(error instanceof ProxyError) || error.code !== 'upstream_rejected') throw error;
591
1047
  log(`the model provider rejected this turn (${error.message}); retrying once with the last turn as plain text.`);
592
1048
  transcript.write({ kind: 'provider_rejected', retry: true, code: error.code, provider_type: error.figures.provider_type || null, provider_message: error.figures.provider_message || null });
593
1049
  const repaired = repairLastTurn(messages);
594
1050
  messages.splice(0, messages.length, ...repaired);
595
1051
  answer = await askAct();
1052
+ }
596
1053
  }
597
1054
  } catch (error) {
598
1055
  if (error instanceof ProxyError && error.isBudget) {
@@ -611,6 +1068,9 @@ async function playLoop({
611
1068
  }
612
1069
 
613
1070
  ledger.record({ model: answer.model, usage: answer.usage, ms: Date.now() - askedAt });
1071
+ transcript.write({ kind: 'usage', step: 'act', turn: turns, ...usageLine(answer.usage) });
1072
+ // The time the model took is play time only when the game ran through it.
1073
+ clock.thought(Date.now() - askedAt, Boolean(driver && driver.frozenBetweenActions));
614
1074
  recentActUnits.push(ledger.lastCallUnits || 0);
615
1075
  if (recentActUnits.length > 3) recentActUnits.shift();
616
1076
  // The warn turn is a turn the developer paid for, so its tool calls are
@@ -625,16 +1085,62 @@ async function playLoop({
625
1085
  // moment where telling them costs nothing and saying nothing costs a
626
1086
  // report. Recorded before anything else can fail, so the journal and
627
1087
  // the transcript both say the run was warned.
628
- log('budget warning: this run has used at least 80 percent of its model budget. Playing this turn\'s actions, then stopping so the rest of the budget goes to the report.');
1088
+ log('budget warning: this run has used at least 80 percent of its model budget. Playing this turn\'s actions, then one wrap-up turn if the report still fits after it, so the rest of the budget goes to the report.');
629
1089
  transcript.write({ kind: 'budget_warning', wrap_up_turns: WRAP_UP_TURNS });
630
1090
  if (typeof onBudgetWarning === 'function') await onBudgetWarning();
631
1091
  }
632
1092
 
633
1093
  if (argsSignal?.aborted || heartbeat?.canceled) { canceled = true; quitReason = 'error'; quitDetail = 'the job was cancelled'; break; }
1094
+ // An answer that is not the persona's (a refusal, or nothing usable) is
1095
+ // counted and asked once more. It is never the persona quitting, never a
1096
+ // finding, and one of them never ends the session.
1097
+ const how = declinedAnswer(answer);
1098
+ if (how && !wrappingUp) {
1099
+ declined += 1;
1100
+ const again = !declinedLastTurn;
1101
+ transcript.write({ kind: 'model_declined', how, stop_reason: answer.stopReason || null, action: actions, asked_again: again, text: String(answer.text || '').slice(0, 400) });
1102
+ if (again) {
1103
+ declinedLastTurn = true;
1104
+ log(`the model ${how === 'refusal' ? 'declined to answer' : 'gave no usable answer'} after ${actions} action(s); asking once more with a plain restatement. This is not the persona stopping.`);
1105
+ // The restatement joins the newest user message, ahead of its picture:
1106
+ // roles still alternate, and nothing of the unusable answer is kept.
1107
+ const last = messages[messages.length - 1];
1108
+ const content = Array.isArray(last.content) ? last.content : [{ type: 'text', text: String(last.content || '') }];
1109
+ const picture = content.filter(block => block && block.type === 'image');
1110
+ messages[messages.length - 1] = { ...last, content: [...content.filter(block => !(block && block.type === 'image')), { type: 'text', text: NEUTRAL_RESTATEMENT }, ...picture] };
1111
+ continue;
1112
+ }
1113
+ declinedEnded = true;
1114
+ quitReason = 'error';
1115
+ quitDetail = declinedStopDetail(actions, how);
1116
+ log(`${quitDetail}.`);
1117
+ break;
1118
+ }
1119
+ declinedLastTurn = false;
1120
+ if (answer.toolUses.length === 0 && !budgetWarned && !wrappingUp && actions < maxActions && winContinues < MAX_WIN_CONTINUES && WIN_TEXT.test(String(answer.text || ''))) {
1121
+ // A win or a finished level never ends the session early: it is noted,
1122
+ // and play goes on to the limits.
1123
+ winContinues += 1;
1124
+ transcript.write({ kind: 'play_on_after_win', actions, max_actions: maxActions, text: String(answer.text || '').slice(0, 400) });
1125
+ log(`the persona stopped on a win after ${actions} of ${maxActions} actions; a win does not end the session, so it is sent back in.`);
1126
+ messages.push({ role: 'assistant', content: [{ type: 'text', text: answer.text && answer.text.trim() ? answer.text : '(stopped)' }] });
1127
+ messages.push({ role: 'user', content: [{ type: 'text', text: playOnText(actions, maxActions) }] });
1128
+ continue;
1129
+ }
1130
+ if (answer.toolUses.length === 0 && !keepGoingAsked && !budgetWarned && actions < keepGoingBelow(maxActions)) {
1131
+ // An early stop with budget left is asked about once. The persona may
1132
+ // still stop: its own stop conditions are its own.
1133
+ keepGoingAsked = true;
1134
+ transcript.write({ kind: 'keep_going', actions, max_actions: maxActions, text: String(answer.text || '').slice(0, 400) });
1135
+ log(`the persona stopped after ${actions} of ${maxActions} actions with budget left; asking once whether the session is really over.`);
1136
+ messages.push({ role: 'assistant', content: [{ type: 'text', text: answer.text && answer.text.trim() ? answer.text : '(stopped)' }] });
1137
+ messages.push({ role: 'user', content: [{ type: 'text', text: keepGoingText(actions, maxActions) }] });
1138
+ continue;
1139
+ }
634
1140
  if (answer.toolUses.length === 0) {
635
1141
  // No tool call is how a persona stops: there is no quit tool in the
636
1142
  // step's allowlist, and adding one would be refused by the proxy.
637
- quitReason = warnedNow ? 'budget_exhausted' : 'persona_quit';
1143
+ quitReason = warnedNow || wrappingUp ? 'budget_exhausted' : 'persona_quit';
638
1144
  // The whole closing message is in the transcript. The detail is one
639
1145
  // short line: it becomes report.json's quit_detail, and a closing turn
640
1146
  // is often the persona starting on its report ("Now writing the final
@@ -656,6 +1162,8 @@ async function playLoop({
656
1162
  }
657
1163
  if (argsSignal?.aborted || heartbeat?.canceled) { canceled = true; quitReason = 'error'; quitDetail = 'the job was cancelled'; break; }
658
1164
  transcript.write({ kind: 'action_selection', source: selection.source || 'jev', status: selection.status, confidence: selection.confidence, selected_tool_id: selection.toolId, reason: selection.reason });
1165
+ // The selector was unsure or could not be reached: play went on with its candidate or the persona's own first proposal.
1166
+ if (selection.source === 'candidate' || selection.source === 'persona') log(`the selecting playtester did not choose (${String(selection.reason).replace(/_/g, ' ')}); playing ${selection.source === 'candidate' ? 'its most likely candidate' : 'the first action proposed for this screen'}.`);
659
1167
  if (selection.status !== 'selected') { quitReason = 'persona_quit'; quitDetail = 'Ravensight Playtester stopped for review: ' + selection.reason; break; }
660
1168
  if (selection.budget === 'warn' && !budgetWarned) {
661
1169
  budgetWarned = true;
@@ -680,25 +1188,66 @@ async function playLoop({
680
1188
  transcript.write({ kind: 'action_not_played', tool: toolUse.name, reason: 'action_budget' });
681
1189
  continue;
682
1190
  }
1191
+ // A tool the server refused for this run is not played, even when the
1192
+ // model sends it anyway: the server's list of allowed tools is the
1193
+ // server's to keep. Said as a limit of the runner.
1194
+ const refusedByServer = (NEWEST_TOOL_NAMES.includes(toolUse.name) && !(newTools && newestTools)) || (NEW_TOOL_NAMES.includes(toolUse.name) && toolUse.name !== 'drag' && !newTools);
1195
+ if (refusedByServer && !toolUse.malformed) {
1196
+ results.push(toolResult(toolUse.id, `The Ravensight server this run used does not allow the ${toolUse.name} tool, so it was not played. This is a limit of the runner, not of the game: note it as something this run could not test, and go on with the tools you were given.`, true));
1197
+ transcript.write({ kind: 'action_not_played', tool: toolUse.name, reason: 'tool_not_allowed_by_server' });
1198
+ continue;
1199
+ }
683
1200
  const notesBefore = notes.length;
684
- const executed = await executeTool({
1201
+ const screenBefore = latestObservation;
1202
+ // A note about something wrong is about the screen as it is now, before
1203
+ // this call changes it: that screen is saved, so the finding it becomes
1204
+ // can cite the moment and not the next screenshot that happened along.
1205
+ const notedKind = toolUse.input && toolUse.input.note && toolUse.input.note.kind;
1206
+ const notedShot = (notedKind === 'bug' || notedKind === 'confusing') && !toolUse.malformed
1207
+ ? await safeScreenshot(driver, 'noted', screenshots, transcript, observations.length, keeper)
1208
+ : null;
1209
+ let executed;
1210
+ const ranAt = Date.now();
1211
+ try {
1212
+ executed = await executeTool({
685
1213
  driver,
686
1214
  toolUse,
687
1215
  staleRefs: screenChangedThisTurn,
688
1216
  identity,
1217
+ keeper,
689
1218
  onNote: note => {
690
1219
  // The note is nested rather than spread: its own `kind`
691
1220
  // (bug, confusing, good, suggestion, reaction) would otherwise
692
1221
  // overwrite the transcript line's `kind`, and every note would
693
1222
  // read as a different sort of line.
694
- noted(note);
1223
+ noted(notedShot && notedShot.relativePath ? { ...note, screenshot: notedShot.relativePath } : note);
695
1224
  transcript.write({ kind: 'note', tool: toolUse.name, note: scrubSecrets(note, secrets) });
696
1225
  },
697
1226
  onScreenshot: shot => {
698
- screenshots.push({ ...shot, observation: observations.length, order: nextOrder() });
1227
+ if (shot.duplicate) {
1228
+ stillTheScreen(screenshots, shot.relativePath, observations.length);
1229
+ transcript.write({ kind: 'screenshot_duplicate', path: shot.relativePath, reason: shot.reason });
1230
+ return;
1231
+ }
1232
+ screenshots.push({ ...shot, observation: observations.length, order: nextOrder(), at: Date.now() });
699
1233
  transcript.write({ kind: 'screenshot', path: shot.relativePath, reason: shot.reason });
700
1234
  }
701
1235
  });
1236
+ } catch (error) {
1237
+ // The game ended under this input: a crash or a freeze. That is the
1238
+ // most valuable thing a tester finds, so it is a finding with the
1239
+ // steps that led to it, and the run reports instead of failing.
1240
+ const ended = await gameEndedOf(driver, error);
1241
+ if (!ended) throw error;
1242
+ const line = { kind: 'action', tool: toolUse.name, input: redactToolInput(toolUse, secrets), thought: null, ok: false, error: ended.message, changed: false, actions: actions + (ACTION_TOOLS.includes(toolUse.name) ? 1 : 0) };
1243
+ transcript.write(line);
1244
+ actionRecords.push(line);
1245
+ if (ACTION_TOOLS.includes(toolUse.name)) actions += 1;
1246
+ gameEnded = ended;
1247
+ break;
1248
+ }
1249
+ // The game ran for as long as an input or a wait took; a look did not run it.
1250
+ if (ACTION_TOOLS.includes(toolUse.name) || toolUse.name === 'wait') clock.ran(Date.now() - ranAt);
702
1251
  results.push(executed.result);
703
1252
  if (executed.spentAction) actions += 1;
704
1253
  if (executed.changed && ACTION_TOOLS.includes(toolUse.name)) screenChangedThisTurn = true;
@@ -711,10 +1260,21 @@ async function playLoop({
711
1260
  error: executed.error,
712
1261
  changed: executed.changed,
713
1262
  ...(executed.refused ? { refused: executed.refused } : {}),
1263
+ ...(expectationOf(toolUse.input) ? { expect: scrubSecrets(expectationOf(toolUse.input), secrets) } : {}),
1264
+ // The persona's mood at this action, and how many steps of the input trace it had written by the end of it (a replay plays that many).
1265
+ ...(moodOf(toolUse.input) ? { mood: moodOf(toolUse.input) } : {}),
1266
+ ...(driver.trace && Number.isInteger(driver.trace.steps) ? { trace_steps: driver.trace.steps } : Array.isArray(driver.webTrace) ? { trace_steps: driver.webTrace.length } : {}),
1267
+ ...(executed.strip ? { strip: { ...executed.strip, shown: Boolean(executed.stripShown), ...(executed.stripShown ? { image_tokens: executed.stripShown.tokens, extra_image_tokens: executed.stripShown.extraTokens } : {}) } } : {}),
714
1268
  actions
715
1269
  };
716
1270
  transcript.write(actionLine);
717
1271
  actionRecords.push(actionLine);
1272
+ if (honesty.traceSteps && Number.isInteger(actionLine.trace_steps)) honesty.traceSteps.set(actions, actionLine.trace_steps);
1273
+ if (honesty.tester) honesty.tester.acted(actionLine); // [tester hook]
1274
+ if (executed.unsupported && honesty.capability.add(executed.unsupported)) {
1275
+ transcript.write({ kind: 'capability_note', input: executed.unsupported.input, reason: executed.unsupported.reason });
1276
+ }
1277
+ if (executed.dialog) transcript.write({ kind: 'dialog_opened', type: executed.dialog.type, message: executed.dialog.message });
718
1278
  if (executed.driverError) {
719
1279
  // The driver failed, not the game: a target that matched twice,
720
1280
  // locator code, a ref not on screen, a timeout on an unchanged page.
@@ -731,13 +1291,49 @@ async function playLoop({
731
1291
  visualObservation = Boolean(executed.observation.screenshotBase64);
732
1292
  recentActions.push(`${toolUse.name}: ${executed.changed ? 'screen changed' : 'no observed change'}`);
733
1293
  if (recentActions.length > 10) recentActions.shift();
734
- transcript.write({ kind: 'observation', step: executed.observation.step, text: executed.observation.text, url: executed.observation.url });
1294
+ transcript.write({ kind: 'observation', step: executed.observation.step, text: executed.observation.text, url: executed.observation.url, ...seenScreen(executed.observation.text, executed.observation.url, Boolean(executed.observation.unchanged)) });
735
1295
  actionRecords.push({ kind: 'observation', text: executed.observation.text });
736
1296
  // Only an input to the game can tell us anything about being stuck. A
737
1297
  // `snapshot` or a `screenshot` never changes the screen by design, so
738
1298
  // counting those would have a persona that looks twice before acting
739
1299
  // declared wedged for doing the right thing.
740
- if (ACTION_TOOLS.includes(toolUse.name)) unchanged = executed.changed ? 0 : unchanged + 1;
1300
+ if (ACTION_TOOLS.includes(toolUse.name)) {
1301
+ // any-game hook: the input is tallied by kind and the page's sound is read for it.
1302
+ 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) });
1303
+ if (typeof driver.soundRead === 'function') anyGame.afterSound(actions, await Promise.resolve().then(() => driver.soundRead()).catch(() => null), { changed: Boolean(executed.changed) });
1304
+ // A hover that shows nothing is a look, not a stuck game.
1305
+ // An input the runner could not send (a target it could not resolve, a stale ref, a hold this driver
1306
+ // lacks) never reached the game: it says nothing about the game being stuck and is not an input that
1307
+ // "changed nothing". A long run of them ends play as the runner's own limit, said so.
1308
+ if (executed.driverError) toolFailures += 1;
1309
+ else {
1310
+ toolFailures = 0;
1311
+ unchanged = executed.changed ? 0 : unchanged + (toolUse.name === 'hover' ? 0 : 1);
1312
+ if (!executed.changed) rememberFailedInput(failedInputs, screenBefore, inputLabel(redactToolInput(toolUse, secrets), toolUse.name));
1313
+ }
1314
+ // A scene not seen before is saved as evidence, whether or not the
1315
+ // persona thought to photograph it. Never a reason to fail a step.
1316
+ if (executed.changed) {
1317
+ const scene = await keeper.scene(driver, 'new-screen', { text: executed.observation.unchanged ? latestObservation : executed.observation.text }).catch(() => null);
1318
+ if (scene) {
1319
+ screenshots.push({ at: Date.now(), ...scene, reason: `a screen not seen before, after action ${actions} (saved by the runner)`, observation: observations.length, order: nextOrder() });
1320
+ transcript.write({ kind: 'screenshot', path: scene.relativePath, reason: 'new_screen', auto: true });
1321
+ }
1322
+ }
1323
+ }
1324
+ }
1325
+ // A screen that showed the game, went one flat colour and stayed so
1326
+ // through the next inputs is a blank screen, found by the runner.
1327
+ if (executed.observation && !executed.observation.dialog && (ACTION_TOOLS.includes(toolUse.name) || toolUse.name === 'wait') && typeof driver.screenProbe === 'function') {
1328
+ const probe = await Promise.resolve().then(() => driver.screenProbe()).catch(() => null);
1329
+ const label = describeInput({ tool: toolUse.name, input: redactToolInput(toolUse, secrets) });
1330
+ if (blankWatch.check(probe, { action: actions, label }) === 'confirmed') {
1331
+ const shot = await safeScreenshot(driver, 'blank-screen', screenshots, transcript, observations.length, keeper);
1332
+ const finding = blankFinding(blankWatch.confirmed(), { actionRecords, screenshot: shot ? shot.relativePath : null, action: actions });
1333
+ honesty.findings.push(finding);
1334
+ transcript.write({ kind: 'runner_finding', key: 'blank_screen', title: finding.title, since_action: blankWatch.confirmed().sinceAction });
1335
+ log(`the screen went blank after action ${blankWatch.confirmed().sinceAction} and stayed blank; recorded as a finding.`);
1336
+ }
741
1337
  }
742
1338
  if (executed.refused) {
743
1339
  // A refused off-site navigation is a step that changed nothing: it
@@ -749,6 +1345,33 @@ async function playLoop({
749
1345
  onProgress({ phase: 'playing', persona: persona.slug, actions, maxActions, tool: toolUse.name });
750
1346
  }
751
1347
 
1348
+ if (gameEnded) {
1349
+ const errors = typeof driver.consoleErrors === 'function' ? await Promise.resolve().then(() => driver.consoleErrors()).catch(() => []) : [];
1350
+ // A frozen page can often still be photographed; a crashed one cannot.
1351
+ const shot = gameEnded.kind === 'frozen' ? await safeScreenshot(driver, 'frozen', screenshots, transcript, observations.length, keeper) : null;
1352
+ const last = [...screenshots].reverse().find(entry => entry && entry.relativePath);
1353
+ if (gameEnded.kind !== 'exited') {
1354
+ const finding = gameEndedFinding(gameEnded, { actionRecords, screenshot: shot ? shot.relativePath : last ? last.relativePath : null, action: actions, errors });
1355
+ honesty.findings.push(finding);
1356
+ transcript.write({ kind: 'runner_finding', key: `game_${gameEnded.kind}`, title: finding.title, action: actions });
1357
+ }
1358
+ transcript.write({ kind: 'game_ended', how: gameEnded.kind, message: gameEnded.message, action: actions });
1359
+ log(`the game ${gameEnded.kind === 'crashed' ? 'crashed' : gameEnded.kind === 'frozen' ? 'stopped responding' : 'closed itself'} on action ${actions}: ${gameEnded.message}. Play ends here and the report says what led to it.`);
1360
+ quitReason = gameEnded.kind === 'exited' ? 'persona_quit' : 'blocker';
1361
+ quitDetail = gameEnded.kind === 'crashed' ? `the game crashed on action ${actions}` : gameEnded.kind === 'frozen' ? `the game stopped responding on action ${actions}` : `the game closed itself on action ${actions}`;
1362
+ break;
1363
+ }
1364
+
1365
+ // Browser dialogs answered this turn: what the game asked and the answer
1366
+ // given, kept for the report. Context, never a finding by itself.
1367
+ const answered = typeof driver.dialogEvents === 'function' ? driver.dialogEvents() : [];
1368
+ for (const event of answered) {
1369
+ honesty.dialogs.push({ ...event, action: actions });
1370
+ const note = dialogNote(event);
1371
+ noted(note);
1372
+ transcript.write({ kind: 'note', note: scrubSecrets(note, secrets) });
1373
+ }
1374
+
752
1375
  // Everything the runner wants to tell the model about this turn goes into
753
1376
  // the SAME user message as the tool results: console errors, the budget
754
1377
  // wrap-up, the stuck hint. Two reasons it is not a second message. The
@@ -766,7 +1389,7 @@ async function playLoop({
766
1389
  // with the persona's view of the screen in front of it. A 4xx on a
767
1390
  // resource is a `network` note, which the report step reads as context
768
1391
  // rather than as a bug (a missing favicon is not a broken game).
769
- const shot = await safeScreenshot(driver, 'console-error', screenshots, transcript, observations.length);
1392
+ const shot = await safeScreenshot(driver, 'console-error', screenshots, transcript, observations.length, keeper);
770
1393
  for (const entry of consoleErrors) {
771
1394
  const kind = RESOURCE_4XX.test(String(entry.text)) ? 'network' : 'bug';
772
1395
  const note = {
@@ -805,19 +1428,40 @@ async function playLoop({
805
1428
  transcript.write({ kind: 'note', note: scrubSecrets(note, secrets) });
806
1429
  }
807
1430
 
1431
+ if (!timeLeftSaid && clock.nearlyDue()) {
1432
+ timeLeftSaid = true;
1433
+ asides.push(timeLeftAside(clock.read()));
1434
+ transcript.write({ kind: 'clock_warning', ...clock.read() });
1435
+ }
1436
+
808
1437
  const wedged = unchanged >= STUCK_LIMIT;
809
- if (!wedged && unchanged > 0 && unchanged % STUCK_HINT_AFTER === 0) {
1438
+ if (!wedged && unchanged > 0 && (unchanged === FIRST_STUCK_HINT_AFTER || unchanged % STUCK_HINT_AFTER === 0)) {
810
1439
  transcript.write({ kind: 'stuck', unchanged, fatal: false });
811
- asides.push(`The screen has not changed for ${unchanged} actions. Your persona would notice that. Try something different, or stop.`);
1440
+ asides.push(stuckHint(unchanged, failedInputsOn(failedInputs, latestObservation)));
812
1441
  }
813
1442
 
1443
+ // any-game hook: the play style once, and the notebook when screens have dropped out of context.
1444
+ const anyAside = anyGame.aside({ actions, dropped: staleObservationCount(observations.length, keepObservations) });
1445
+ if (anyAside) { asides.push(anyAside); transcript.write({ kind: 'any_game_aside', chars: anyAside.length }); }
1446
+
1447
+ // The picture goes last, outside the tool results, so the cache
1448
+ // breakpoint can sit before it (withPlayCacheBreakpoint).
1449
+ const hoisted = hoistImages(results);
814
1450
  messages.push({
815
1451
  role: 'user',
816
- content: asides.length > 0
817
- ? [...results, { type: 'text', text: asides.join('\n\n') }]
818
- : results
1452
+ content: [
1453
+ ...hoisted.results,
1454
+ ...(asides.length > 0 ? [{ type: 'text', text: asides.join('\n\n') }] : []),
1455
+ ...(hoisted.image ? [hoisted.image] : [])
1456
+ ]
819
1457
  });
820
1458
 
1459
+ if (toolFailures >= STUCK_LIMIT) {
1460
+ quitReason = 'error';
1461
+ quitDetail = `the runner could not send ${toolFailures} inputs in a row (targets it could not resolve); none of them reached the game`;
1462
+ transcript.write({ kind: 'tool_failures', count: toolFailures, fatal: true });
1463
+ break;
1464
+ }
821
1465
  if (wedged) {
822
1466
  quitReason = 'blocker';
823
1467
  quitDetail = `the screen did not change for ${unchanged} actions`;
@@ -828,8 +1472,23 @@ async function playLoop({
828
1472
  if (heartbeat) await heartbeat.beat({ actionsTaken: actions, checkpointStep: turns });
829
1473
 
830
1474
  if (budgetWarned) {
1475
+ // One wrap-up turn, when the report still fits after it. The check
1476
+ // sizes the turn about to be sent, the message above included.
1477
+ const reserve = !wrappingUp && wrapUpTurnsLeft > 0 ? reserveCheck() : null;
1478
+ if (reserve && reserve.known && !reserve.stop) {
1479
+ wrapUpTurnsLeft -= 1;
1480
+ wrappingUp = true;
1481
+ const last = messages[messages.length - 1];
1482
+ const picture = last.content.filter(block => block && block.type === 'image');
1483
+ last.content = [...last.content.filter(block => !(block && block.type === 'image')), { type: 'text', text: WRAP_UP_ASIDE }, ...picture];
1484
+ transcript.write({ kind: 'wrap_up_turn', ...reserve.figures });
1485
+ log('one wrap-up turn: the reserve check says the report still fits after it.');
1486
+ continue;
1487
+ }
831
1488
  quitReason = 'budget_exhausted';
832
- quitDetail = 'stopped at the 80 percent budget warning so the report could be written';
1489
+ quitDetail = wrappingUp
1490
+ ? 'stopped after one wrap-up turn that followed the 80 percent budget warning, so the report could be written'
1491
+ : 'stopped at the 80 percent budget warning so the report could be written';
833
1492
  break;
834
1493
  }
835
1494
  }
@@ -837,12 +1496,115 @@ async function playLoop({
837
1496
  if (actions >= maxActions && quitReason === 'budget_exhausted') {
838
1497
  quitReason = 'budget_exhausted';
839
1498
  quitDetail = `the action budget of ${maxActions} ran out`;
1499
+ } else if (turns >= maxTurns && quitReason === 'budget_exhausted' && !quitDetail) {
1500
+ // The loop ran out of turns, not actions: most turns looked at the screen without sending an input.
1501
+ quitDetail = `the turn limit of ${maxTurns} ran out after ${actions} of ${maxActions} actions, because most turns looked at the screen without acting`;
840
1502
  }
841
1503
 
842
- const final = await safeScreenshot(driver, 'final', screenshots, transcript, observations.length);
1504
+ const final = gameEnded ? null : await safeScreenshot(driver, 'final', screenshots, transcript, observations.length, keeper);
1505
+ transcript.write({ kind: 'play_summary', actions, turns, observations: observations.length, screenshots: screenshots.length, distinct_screens: keeper.distinctScreens, scenes: keeper.scenes, model_declined: declined, clock: clock.read() });
1506
+ // The last screen as the model is shown it, for the brief choice check.
1507
+ const finalFrame = brief && !gameEnded ? await modelFrameOf(driver) : null;
1508
+
1509
+ // A blank screen play ended on, with inputs already tried against it.
1510
+ const stillBlank = blankWatch.pending();
1511
+ if (stillBlank && !gameEnded) {
1512
+ const finding = blankFinding(stillBlank, { actionRecords, screenshot: final ? final.relativePath : null, action: actions });
1513
+ honesty.findings.push(finding);
1514
+ transcript.write({ kind: 'runner_finding', key: 'blank_screen', title: finding.title, since_action: stillBlank.sinceAction });
1515
+ }
1516
+ // any-game hook: what the sound record supports is the runner's own finding; what it could not check is a capability note.
1517
+ for (const f of anyGame.soundFindings()) {
1518
+ 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 });
1519
+ honesty.findings.push(finding);
1520
+ transcript.write({ kind: 'runner_finding', key: 'sound', title: finding.title });
1521
+ }
1522
+ for (const note of anyGame.capabilityNotes()) if (honesty.capability.add(note)) transcript.write({ kind: 'capability_note', input: note.input, reason: note.reason });
1523
+ transcript.write({ kind: 'any_game', record: anyGame.digest() });
1524
+ // What the game asked for that the runner could not give.
1525
+ if (typeof driver.capabilityNotes === 'function') {
1526
+ const met = await Promise.resolve().then(() => driver.capabilityNotes()).catch(() => []);
1527
+ for (const note of met || []) if (honesty.capability.add(note)) transcript.write({ kind: 'capability_note', input: note.input, reason: note.reason });
1528
+ }
1529
+ // [tester hook] The tester probes (./testerProbes.js): scripted, no model call, on the page play ended on, before the edge
1530
+ // behaviour checks reload it. On the same switch as those checks.
1531
+ const probing = edgePass && !gameEnded && !canceled && !budgetExceeded && typeof driver.edgeSession === 'function' && driverName === 'playwright_web' && !(argsSignal && argsSignal.aborted);
1532
+ if (probing) {
1533
+ try {
1534
+ honesty.probes = await runTesterProbes({ driver, actionRecords, screenshots, observation: observations.length, signal: argsSignal, log });
1535
+ 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 })) });
1536
+ } catch (error) {
1537
+ transcript.write({ kind: 'tester_probes_failed', message: String(error && error.message) });
1538
+ log(`the tester probes did not finish: ${String(error && error.message)}`);
1539
+ }
1540
+ }
1541
+ // The edge behaviour pass: scripted, no model call, after the last screen
1542
+ // has been saved. A canceled run and a game that already ended skip it.
1543
+ if (edgePass && !gameEnded && !canceled && !budgetExceeded && typeof driver.edgeSession === 'function' && !(argsSignal && argsSignal.aborted)) {
1544
+ try {
1545
+ honesty.edge = await runEdgePass({ driver, actionRecords, screenshots, observation: observations.length, signal: argsSignal, log });
1546
+ 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 })) });
1547
+ for (const finding of edgeFindings(honesty.edge, { actionRecords, action: actions })) honesty.findings.push(finding);
1548
+ // A check whose blank screen part could not be told from the start is a limit of the runner, never a finding.
1549
+ // Said whatever the check's own status: a problem or a note found by other means still could not test the blank screen.
1550
+ const blankNote = blankCapabilityNote(honesty.edge.checks);
1551
+ if (blankNote && honesty.capability.add(blankNote)) transcript.write({ kind: 'capability_note', input: blankNote.input, reason: blankNote.reason });
1552
+ // Dialogs the checks raised (a leave prompt on reload) are in the record too.
1553
+ for (const event of (typeof driver.dialogEvents === 'function' ? driver.dialogEvents() : [])) honesty.dialogs.push({ ...event, action: actions, during: 'edge checks' });
1554
+ } catch (error) {
1555
+ transcript.write({ kind: 'edge_pass_failed', message: String(error && error.message) });
1556
+ log(`the edge behaviour checks did not finish: ${String(error && error.message)}`);
1557
+ }
1558
+ }
1559
+ // [tester hook] Input while the page loads: a reload, so it comes after the edge checks have asked their own reload what survived.
1560
+ if (probing && honesty.probes) {
1561
+ try {
1562
+ const loaded = await runTesterProbes({ driver, actionRecords, screenshots, observation: observations.length, signal: argsSignal, log, loading: true });
1563
+ honesty.probes.checks.push(...loaded.checks);
1564
+ honesty.probes.suspects.push(...loaded.suspects);
1565
+ } catch (error) {
1566
+ transcript.write({ kind: 'tester_probes_failed', message: String(error && error.message) });
1567
+ }
1568
+ 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 }); }
1569
+ }
1570
+ // [tester hook] The tester probes a keyboard can make on a Godot game (./godotTesterProbes.js), before its edge checks start it a second time.
1571
+ if (edgePass && !gameEnded && !canceled && !budgetExceeded && driver.edgeKind === 'godot' && typeof driver.runFor === 'function' && !(argsSignal && argsSignal.aborted)) {
1572
+ try {
1573
+ honesty.probes = { ...(await runGodotTesterProbes({ driver, actionRecords, screenshots, observation: observations.length, signal: argsSignal, log })), godot: true };
1574
+ 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 })) });
1575
+ 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 }); }
1576
+ } catch (error) {
1577
+ transcript.write({ kind: 'tester_probes_failed', message: String(error && error.message) });
1578
+ log(`the tester probes did not finish: ${String(error && error.message)}`);
1579
+ }
1580
+ }
1581
+ // The same checks on a Godot game, through the driver addon (./godotEdgePass.js).
1582
+ if (edgePass && !gameEnded && !canceled && !budgetExceeded && driver.edgeKind === 'godot' && typeof driver.runFor === 'function' && !driver.headless && !(argsSignal && argsSignal.aborted)) {
1583
+ try {
1584
+ honesty.edge = await runGodotEdgePass({ driver, actionRecords, screenshots, observation: observations.length, signal: argsSignal, log });
1585
+ 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 })) });
1586
+ for (const finding of edgeFindings(honesty.edge, { actionRecords, action: actions })) honesty.findings.push(finding);
1587
+ } catch (error) {
1588
+ const ended = await gameEndedOf(driver, error).catch(() => null);
1589
+ transcript.write({ kind: 'edge_pass_failed', message: String(error && error.message), ...(ended ? { game_ended: ended.kind } : {}) });
1590
+ log(`the edge behaviour checks did not finish: ${String(error && error.message)}`);
1591
+ }
1592
+ }
1593
+ // [tester hook] What the runner's own ledger saw break a rule during play.
1594
+ for (const finding of testerFindings(honesty.tester, { actionRecords })) { 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 }); }
843
1595
  return {
844
1596
  actionsTaken: actions,
845
1597
  turns,
1598
+ distinctScreens: keeper.distinctScreens,
1599
+ wrapUpTurn: wrappingUp,
1600
+ gameEnded,
1601
+ newTools,
1602
+ declined,
1603
+ declinedEnded,
1604
+ clockStopped,
1605
+ clock: clock.read(),
1606
+ finalFrame,
1607
+ records: actionRecords,
846
1608
  quitReason,
847
1609
  quitDetail,
848
1610
  budgetWarned,
@@ -879,6 +1641,7 @@ async function reportPhase({
879
1641
  notes,
880
1642
  screenshots,
881
1643
  observations = [],
1644
+ honesty = null,
882
1645
  play,
883
1646
  startedAt,
884
1647
  endedAt,
@@ -887,7 +1650,30 @@ async function reportPhase({
887
1650
  // The report step never sees the test account: it has nothing to sign in
888
1651
  // to, and the password crosses the model proxy during play only.
889
1652
  const secrets = secretsOf(localBrief);
890
- const { system, messages } = buildReportRequest({ skill, persona, brief, localBrief, intentNotes, driverName, target, runId, jobId, play, notes, observations, screenshots });
1653
+
1654
+ // One bounded question before the report is written: was the choice the
1655
+ // brief names (a faction, a character, a mode) the one in effect? The
1656
+ // answer goes to the report step, so the persona's own account and the
1657
+ // runner's line say the same thing, and into report.md in a fixed shape
1658
+ // afterwards. A refusal for budget costs the check and never the report.
1659
+ let choiceCheck = null;
1660
+ if (brief && !play.budgetExceeded) {
1661
+ choiceCheck = await checkBriefChoice({
1662
+ client,
1663
+ jobId,
1664
+ runId,
1665
+ briefText: scrubSecrets(`${briefForPrompt(brief)}\n${intentNotesForPrompt(brief, intentNotes)}`, secrets),
1666
+ actionText: scrubSecrets(actionLogLines(play.actionLog), secrets),
1667
+ records: play.records || [],
1668
+ frame: play.finalFrame || null,
1669
+ ledger,
1670
+ transcript,
1671
+ log
1672
+ });
1673
+ if (choiceCheck) log(`brief choice check: ${choiceCheck.choice}: ${choiceCheck.result}${choiceCheck.shown ? ` (${choiceCheck.shown})` : ''}`);
1674
+ }
1675
+
1676
+ const { system, messages } = buildReportRequest({ skill, persona, brief, localBrief, intentNotes, driverName, target, runId, jobId, play, notes, observations, screenshots, choiceCheck, honesty });
891
1677
 
892
1678
  let report = null;
893
1679
  let markdown = null;
@@ -1017,7 +1803,10 @@ async function reportPhase({
1017
1803
  usage: ledger.toReportUsage(),
1018
1804
  promptVersion: promptVersionOf(skill),
1019
1805
  quitReason: play.quitReason,
1020
- quitDetail: play.quitDetail
1806
+ quitDetail: play.quitDetail,
1807
+ // Whether this server's report schema has the goal check to write into.
1808
+ goalCheck: Boolean(reportSchema && reportSchema.properties && reportSchema.properties.data_points
1809
+ && reportSchema.properties.data_points.properties && reportSchema.properties.data_points.properties.goal_reached)
1021
1810
  };
1022
1811
  // An evidence path under the wrong key is moved to `ref` before anything
1023
1812
  // judges the report; see normaliseEvidence.
@@ -1141,8 +1930,17 @@ async function reportPhase({
1141
1930
  // after the report is settled, so a refusal can cost the check and never
1142
1931
  // the report.
1143
1932
  report = scrubSecrets(report, secrets);
1933
+ // A frame for each finding, cut from the session video at the finding's own
1934
+ // moment: it is what the claim check looks at, and what the report in the
1935
+ // dashboard shows. No model call; a finding the run cannot place in the
1936
+ // video keeps the screenshot it cites.
1937
+ let frames = new Map();
1938
+ if (honesty && honesty.video) {
1939
+ const where = attachWhereToLook(report, { observations, notes, screenshots, video: honesty.video }).index;
1940
+ frames = await cutFindingFrames({ runDirectory, index: where, video: honesty.video, transcript, viewport: honesty.viewport || null }).catch(() => new Map());
1941
+ }
1144
1942
  if (!shrunk && !play.budgetExceeded) {
1145
- const checked = await checkClaimsAgainstScreenshots({ client, jobId, runId, report, screenshots, runDirectory, ledger, transcript, log });
1943
+ const checked = await checkClaimsAgainstScreenshots({ client, jobId, runId, report, screenshots, runDirectory, ledger, transcript, log, frames });
1146
1944
  if (checked.downgraded.length > 0) {
1147
1945
  report = checked.report;
1148
1946
  downgradedByRunner = [...downgradedByRunner, ...checked.downgraded];
@@ -1161,6 +1959,10 @@ async function reportPhase({
1161
1959
  }
1162
1960
  // The uploaded pair agree: report.md says the severity report.json does.
1163
1961
  if (downgradedByRunner.length > 0) markdown = rewriteDowngradedMarkdown(markdown, downgradedByRunner);
1962
+ if (choiceCheck) {
1963
+ markdown = writeChoiceIntoMarkdown(markdown, choiceCheck);
1964
+ await writeFile(path.join(runDirectory, CHOICE_CHECK_FILE), `${JSON.stringify(choiceCheck, null, 2)}\n`, 'utf8');
1965
+ }
1164
1966
  if (normalisedByRunner.length > 0) {
1165
1967
  markdown = appendNormalisedMarkdown(markdown, normalisedByRunner);
1166
1968
  log(`normalised ${normalisedByRunner.length} value(s) the report schema does not allow: ${normalisedByRunner.map(change => `${change.id ? `${change.id} ` : ''}${change.field} ${JSON.stringify(change.from)} to ${JSON.stringify(change.to)}`).join(', ')}`);
@@ -1179,22 +1981,67 @@ async function reportPhase({
1179
1981
  await writeFile(path.join(runDirectory, RUN_FILES.runnerEvidence), `${JSON.stringify({ attached: withShots.attached }, null, 2)}\n`, 'utf8');
1180
1982
  log(`attached a screenshot as evidence to ${withShots.attached.length} finding(s) that cited none: ${withShots.attached.map(entry => `${entry.id} (${entry.ref})`).join(', ')}`);
1181
1983
  }
1984
+ // What the runner itself knows goes in last, in fixed sections: its own
1985
+ // findings, where to look for every finding, the inputs it could not send,
1986
+ // the dialogs and the edge checks.
1987
+ const honest = writeHonesty({ report, markdown, honesty, driverName, notes, screenshots, observations });
1988
+ report = honest.report;
1989
+ markdown = honest.markdown;
1990
+ if (honest.added.length > 0) log(`the runner added ${honest.added.length} finding(s) of its own: ${honest.added.map(finding => `${finding.id} (${finding.title})`).join(', ')}`);
1991
+ if (honest.index.length > 0) transcript.write({ kind: 'where_to_look', findings: honest.index });
1992
+ // The runner's own findings were added just now: each gets its frame too.
1993
+ if (honesty && honesty.video) await cutFindingFrames({ runDirectory, index: honest.index.filter(entry => !frames.has(entry.id)), video: honesty.video, transcript, viewport: honesty.viewport || null }).catch(() => null);
1182
1994
  // Whatever the model wrote, the password does not leave in a report.
1183
1995
  markdown = scrubSecrets(markdown, secrets);
1184
1996
  report = scrubSecrets(report, secrets);
1185
1997
 
1186
1998
  await writeReportFiles({ runDirectory, markdown, report });
1187
- return { report, markdown, lint };
1999
+ return { report, markdown, lint, index: honest.index };
1188
2000
  }
1189
2001
 
1190
- /** The most blocker or major findings whose screenshot is checked against the claim. */
1191
- export const MAX_CLAIM_CHECKS = 3;
2002
+ /**
2003
+ * Write what the runner itself knows into a finished report: its own findings
2004
+ * (after the report's), for every finding the step, a screenshot and a video
2005
+ * time, and the fixed sections of report.md that say so.
2006
+ *
2007
+ * @param {Object} args
2008
+ * @returns {{report: Object, markdown: string, added: Array<Object>, index: Array<Object>}}
2009
+ */
2010
+ export function writeHonesty({ report, markdown, honesty, driverName, notes = [], screenshots = [], observations = [] }) {
2011
+ if (!honesty || !report) return { report, markdown, added: [], index: [] };
2012
+ const merged = addRunnerFindings(report, honesty.findings);
2013
+ const located = attachWhereToLook(merged.report, { observations, notes, screenshots, video: honesty.video, anchors: merged.anchors });
2014
+ let text = markdown;
2015
+ // The findings as they now stand, with the evidence the pass attached.
2016
+ const added = merged.added.map(finding => located.report.findings.find(entry => entry.id === finding.id) || finding);
2017
+ if (added.length > 0) text = replaceSection(text, RUNNER_FINDINGS_HEADING, runnerFindingsMarkdown(added));
2018
+ if (honesty.edge) text = replaceSection(text, EDGE_HEADING, edgeMarkdown(honesty.edge));
2019
+ if (honesty.dialogs.length > 0) {
2020
+ text = replaceSection(text, DIALOGS_HEADING, honesty.dialogs.map(event => `- ${event.type}: ${JSON.stringify(String(event.message || '').slice(0, 300))} was answered ${event.answer === 'accepted' ? 'OK' : 'Cancel'}${event.text !== undefined ? ` with ${JSON.stringify(String(event.text))}` : ''}${event.automatic ? ' by the runner' : ' by the persona'}${Number.isInteger(event.action) ? ` (around action ${event.action}${event.during ? `, during the ${event.during}` : ''})` : ''}.`).join('\n'));
2021
+ }
2022
+ // [tester hook] What was and was not tested, from the runner's own ledger.
2023
+ if (honesty.probes) text = replaceSection(text, PROBES_HEADING, honesty.probes.godot ? godotProbesMarkdown(honesty.probes) : probesMarkdown(honesty.probes));
2024
+ if (honesty.tester) text = replaceSection(text, TESTED_HEADING, testedMarkdown(honesty.tester, { edge: honesty.edge, probes: honesty.probes || null }));
2025
+ text = writeCapabilitySection(text, driverName, honesty.capability.list());
2026
+ if (located.index.length > 0) text = replaceSection(text, EVIDENCE_HEADING, whereToLookMarkdown(located.index, honesty.video));
2027
+ return { report: located.report, markdown: text, added, index: located.index };
2028
+ }
2029
+
2030
+ /**
2031
+ * The most findings whose picture is checked against the claim: every issue
2032
+ * of a run, the most severe first, up to this many (about a third of a cent
2033
+ * each at the act step's rate). One past it says it was not checked.
2034
+ */
2035
+ export const MAX_CLAIM_CHECKS = 8;
2036
+
2037
+ /** The severities a claim check is made on: every issue, never praise. */
2038
+ export const CLAIM_SEVERITIES = Object.freeze(['blocker', 'major', 'minor', 'cosmetic']);
1192
2039
 
1193
2040
  /** Output ceiling for one claim check: the answer is one word. */
1194
2041
  export const CLAIM_CHECK_MAX_TOKENS = 32;
1195
2042
 
1196
2043
  /** The instruction for a claim check. */
1197
- export const CLAIM_CHECK_SYSTEM = 'You check playtest findings against their evidence. You are shown one screenshot and one claim about it. Answer with exactly one word: yes if the image contradicts the claim, no if it does not, unclear if the image cannot settle it.';
2044
+ export const CLAIM_CHECK_SYSTEM = 'You check playtest findings against their evidence. You are shown one picture of the game at the moment of a claim (a frame of the session video, or a screenshot) and one claim about it. Answer with exactly one word: yes if the image contradicts the claim, no if it does not, unclear if the image cannot settle it.';
1198
2045
 
1199
2046
  /**
1200
2047
  * The screenshot a finding's claim is checked against: of those it cites, the
@@ -1220,7 +2067,7 @@ export function citedAfterScreenshot(finding, screenshots) {
1220
2067
  // it, and of two taken on the same observation the later one.
1221
2068
  const order = new Map((screenshots || []).map((shot, index) => [shot, index]));
1222
2069
  const after = cited
1223
- .filter(shot => Number.isInteger(shot.observation) && shot.observation >= latest)
2070
+ .filter(shot => Number.isInteger(shot.observation) && (shot.observationUntil ?? shot.observation) >= latest)
1224
2071
  .sort((a, b) => a.observation - b.observation || order.get(b) - order.get(a))[0];
1225
2072
  if (after) return after;
1226
2073
  }
@@ -1254,22 +2101,29 @@ export function claimCheckAnswer(text) {
1254
2101
  *
1255
2102
  * @returns {Promise<{report: Object, downgraded: Array<Object>}>}
1256
2103
  */
1257
- export async function checkClaimsAgainstScreenshots({ client, jobId, runId, report, screenshots, runDirectory, ledger, transcript, log = () => {} }) {
2104
+ export async function checkClaimsAgainstScreenshots({ client, jobId, runId, report, screenshots, runDirectory, ledger, transcript, log = () => {}, frames = new Map() }) {
1258
2105
  if (!report || !Array.isArray(report.findings)) return { report, downgraded: [] };
1259
- const targets = report.findings.filter(finding => finding && ABOVE_MINOR.includes(finding.severity)).slice(0, MAX_CLAIM_CHECKS);
2106
+ // Every issue, the most severe first; what worked is not checked.
2107
+ const issues = report.findings.filter(finding => finding && CLAIM_SEVERITIES.includes(finding.severity))
2108
+ .sort((a, b) => CLAIM_SEVERITIES.indexOf(a.severity) - CLAIM_SEVERITIES.indexOf(b.severity));
2109
+ const targets = issues.slice(0, MAX_CLAIM_CHECKS);
2110
+ for (const finding of issues.slice(MAX_CLAIM_CHECKS)) transcript.write({ kind: 'claim_check', id: finding.id, screenshot: null, answer: 'skipped', reason: `the run checks at most ${MAX_CLAIM_CHECKS} findings` });
1260
2111
  const downgraded = [];
1261
2112
  const verdicts = new Map();
1262
2113
  for (const finding of targets) {
1263
- const shot = citedAfterScreenshot(finding, screenshots);
2114
+ // The frame cut from the video at the finding's moment, else the screenshot it cites.
2115
+ const frame = frames.get(finding.id) || null;
2116
+ const shot = frame ? { relativePath: frame.path } : citedAfterScreenshot(finding, screenshots);
2117
+ const on = frame ? { frame: frame.path } : {};
1264
2118
  if (!shot) {
1265
- transcript.write({ kind: 'claim_check', id: finding.id, screenshot: null, answer: 'skipped', reason: 'no cited screenshot' });
2119
+ transcript.write({ kind: 'claim_check', id: finding.id, screenshot: null, answer: 'skipped', reason: 'no frame of its moment and no cited screenshot' });
1266
2120
  continue;
1267
2121
  }
1268
2122
  let data;
1269
2123
  try {
1270
2124
  data = (await readFile(path.join(runDirectory, shot.relativePath))).toString('base64');
1271
2125
  } catch {
1272
- transcript.write({ kind: 'claim_check', id: finding.id, screenshot: shot.relativePath, answer: 'skipped', reason: 'the screenshot could not be read' });
2126
+ transcript.write({ kind: 'claim_check', id: finding.id, screenshot: shot.relativePath, ...on, answer: 'skipped', reason: 'the picture could not be read' });
1273
2127
  continue;
1274
2128
  }
1275
2129
  let answer;
@@ -1284,7 +2138,7 @@ export async function checkClaimsAgainstScreenshots({ client, jobId, runId, repo
1284
2138
  messages: [{
1285
2139
  role: 'user',
1286
2140
  content: [
1287
- { type: 'image', source: { type: 'base64', media_type: 'image/png', data } },
2141
+ { type: 'image', source: { type: 'base64', media_type: /\.jpe?g$/i.test(shot.relativePath) ? 'image/jpeg' : 'image/png', data } },
1288
2142
  { type: 'text', text: `Claim (${finding.severity}): ${finding.title || ''}\n${String(finding.description || '').slice(0, 1200)}\n\nDoes this image contradict the claim: yes, no, unclear?` }
1289
2143
  ]
1290
2144
  }],
@@ -1294,13 +2148,15 @@ export async function checkClaimsAgainstScreenshots({ client, jobId, runId, repo
1294
2148
  });
1295
2149
  } catch (error) {
1296
2150
  const reason = error instanceof ProxyError && error.isBudget ? 'the run budget is spent' : String(error && error.message ? error.message : error);
1297
- transcript.write({ kind: 'claim_check', id: finding.id, screenshot: shot.relativePath, answer: 'skipped', reason });
2151
+ transcript.write({ kind: 'claim_check', id: finding.id, screenshot: shot.relativePath, ...on, answer: 'skipped', reason });
2152
+ // A refusal ends the checks, and every finding not reached says so; nothing is asked again.
2153
+ for (const rest of targets.slice(targets.indexOf(finding) + 1)) transcript.write({ kind: 'claim_check', id: rest.id, screenshot: null, answer: 'skipped', reason });
1298
2154
  log(`the screenshot check stopped (${reason}); the report is kept as written.`);
1299
2155
  break;
1300
2156
  }
1301
2157
  if (ledger) ledger.record({ model: answer.model, usage: answer.usage, ms: Date.now() - askedAt });
1302
2158
  const verdict = claimCheckAnswer(answer.text);
1303
- transcript.write({ kind: 'claim_check', id: finding.id, screenshot: shot.relativePath, answer: verdict });
2159
+ transcript.write({ kind: 'claim_check', id: finding.id, screenshot: shot.relativePath, ...on, answer: verdict });
1304
2160
  if (verdict === 'yes' && DOWNGRADE[finding.severity]) verdicts.set(finding, shot.relativePath);
1305
2161
  }
1306
2162
  if (verdicts.size === 0) return { report, downgraded };
@@ -1323,7 +2179,7 @@ export async function checkClaimsAgainstScreenshots({ client, jobId, runId, repo
1323
2179
  *
1324
2180
  * @returns {{system: Array, messages: Array}}
1325
2181
  */
1326
- export function buildReportRequest({ skill, persona, brief, localBrief = {}, intentNotes, driverName, target, runId, jobId, play, notes, observations = [], screenshots }) {
2182
+ export function buildReportRequest({ skill, persona, brief, localBrief = {}, intentNotes, driverName, target, runId, jobId, play, notes, observations = [], screenshots, choiceCheck = null, honesty = null }) {
1327
2183
  const secrets = secretsOf(localBrief);
1328
2184
  const reportLocal = localBrief && Array.isArray(localBrief.expected_noise) ? { expected_noise: localBrief.expected_noise } : {};
1329
2185
  const system = buildSystem({ skill, persona, brief, localBrief: reportLocal, intentNotes, driverName, target, maxActions: play.actionsTaken, runId });
@@ -1348,11 +2204,27 @@ export function buildReportRequest({ skill, persona, brief, localBrief = {}, int
1348
2204
  '',
1349
2205
  'A claim in report.md or report.json that something was never done, never worked, did nothing or could not be done must agree with this list. If the list shows you clicked a control and the screen changed, do not write that you never clicked it or that it did nothing; describe what the screen showed after it instead. The runner downgrades a finding that says otherwise.',
1350
2206
  '',
2207
+ 'What the screens read after the actions you stated an expectation for, and at the end (their visible text, which the observation list above leaves out):',
2208
+ screenTextLines(play.records),
2209
+ '',
2210
+ CHOICE_CHECK_INSTRUCTION,
2211
+ ...(choiceCheck ? [choiceCheckLine(choiceCheck)] : []),
2212
+ ...(play.declined ? ['', declinedPrompt(play.declined, Boolean(play.declinedEnded))] : []),
2213
+ ...(play.clockStopped ? ['', 'Play stopped on the clock: the time this run was sold ran out. That is how the session was meant to end; say how far it got and never report it as a problem.'] : []),
2214
+ '',
2215
+ // any-game hook: what the runner measured and kept, and the language to write in.
2216
+ ...(honesty && honesty.anygame ? [...honesty.anygame.reportLines(), ''] : []),
2217
+ CAPABILITY_NOTES_INSTRUCTION,
2218
+ ...(capabilityPrompt(driverName, honesty ? honesty.capability.list() : []) ? ['', capabilityPrompt(driverName, honesty ? honesty.capability.list() : [])] : []),
2219
+ ...(honesty && honesty.findings.length > 0 ? ['', `The runner itself saw these happen and adds them to the report as its own findings, with their steps and evidence. Do not write a finding of your own for the same thing; you may refer to them in "Top issues" by their title:\n${honesty.findings.map(finding => `- [${finding.severity}] ${finding.title}: ${finding.description}`).join('\n')}`] : []),
2220
+ 'Notes of kind dialog record a browser dialog the game opened and how it was answered. They are context: a finding only when what the game did after the answer was wrong.',
2221
+ 'Reaching a win, a finished level or the brief\'s goal did not end this session, by design: say in "What worked" how far the session got, and never report the continued play as a problem.',
2222
+ '',
1351
2223
  'Network notes (failed requests the runner recorded, with the URL and the status; list them under a "Network notes" heading in report.md when there are any):',
1352
2224
  networkNoteLines(notes),
1353
2225
  '',
1354
2226
  'Each note carries "after": the URL and title of the observation that followed it. A blocker or major finding must cite the observation index where the failure is visible, as evidence {"type": "transcript_step", "ref": "observation N"}, and must not be contradicted by its note\'s "after" state or by a later persona note: if the next screen or a later note shows the game working, it is not a blocker or a major. Cite a note as {"type": "transcript_step", "ref": "note N"}.',
1355
- 'A blocker or major finding must also cite the screenshot taken at or after that observation (the list below says which observation each one followed), and that screenshot must not contradict it: if it shows the thing the finding says is missing or broken, such as the field or the button, it is not a blocker or a major. A text observation can be cut short on a long page; the screenshot is what the player saw. After you write the report, the runner shows each blocker or major (at most three) its cited screenshot and downgrades one step any finding the image contradicts.',
2227
+ 'A blocker or major finding must also cite the screenshot taken at or after that observation (the list below says which observation each one followed), and that screenshot must not contradict it: if it shows the thing the finding says is missing or broken, such as the field or the button, it is not a blocker or a major. A text observation can be cut short on a long page; the screenshot is what the player saw. After you write the report, the runner shows each blocker or major (at most three), and each minor that cites a screenshot (at most three), its cited screenshot and downgrades one step any finding the image contradicts. So a finding about how the game looks (text that cannot be read, a missing label, something cut off) has to be true of the screenshot it cites.',
1356
2228
  '',
1357
2229
  'Every evidence entry is an object with exactly two keys, "type" and "ref", and nothing else. A screenshot is {"type": "screenshot", "ref": "screenshots/04-example.png"}, never "path" or "file".',
1358
2230
  '',
@@ -1482,13 +2354,13 @@ export function reportTokensThatFit(error, current, bodyChars = 0) {
1482
2354
  * fewer images than we sent, so halve and send again instead of losing the
1483
2355
  * run over a policy number the CLI is not allowed to read.
1484
2356
  */
1485
- async function callWithImageRetry({ imageBudget, keepObservations, messages, onImageBudget, ...rest }) {
2357
+ async function callWithImageRetry({ imageBudget, keepObservations, messages, onImageBudget, layout = null, ...rest }) {
1486
2358
  let budget = imageBudget;
1487
2359
  for (let attempt = 0; attempt < 3; attempt += 1) {
1488
2360
  // One moving cache breakpoint on the newest block, as the fix loop does:
1489
2361
  // the prefix up to it is what the next turn re-sends, so the next turn
1490
2362
  // reads it from the cache instead of paying for it again.
1491
- const prepared = withRollingCacheBreakpoint(prepareMessages(messages, { maxImages: budget, keepObservations }));
2363
+ const prepared = withPlayCacheBreakpoint(prepareMessages(messages, { maxImages: budget, keepObservations, layout }), layout);
1492
2364
  try {
1493
2365
  return await callStepWithRetry({ ...rest, messages: prepared });
1494
2366
  } catch (error) {
@@ -1720,9 +2592,31 @@ export function redactToolInput(toolUse, secrets = []) {
1720
2592
  return scrubSecrets(rest, secrets);
1721
2593
  }
1722
2594
 
1723
- export async function safeScreenshot(driver, name, screenshots, transcript, observation = null) {
2595
+ /**
2596
+ * A screenshot entry showed the same screen again at a later observation: it
2597
+ * stands for that moment too, which is what a finding's "screenshot taken at
2598
+ * or after that observation" is checked against.
2599
+ *
2600
+ * @param {Array<Object>} screenshots
2601
+ * @param {string} relativePath
2602
+ * @param {number} observation
2603
+ */
2604
+ export function stillTheScreen(screenshots, relativePath, observation) {
2605
+ const entry = [...screenshots].reverse().find(shot => shot && shot.relativePath === relativePath);
2606
+ if (entry && Number.isInteger(observation) && observation > (entry.observationUntil ?? entry.observation ?? -1)) entry.observationUntil = observation;
2607
+ }
2608
+
2609
+ export async function safeScreenshot(driver, name, screenshots, transcript, observation = null, keeper = null) {
1724
2610
  try {
1725
- const shot = await driver.screenshot(name);
2611
+ const taken = keeper ? await keeper.take(driver, name) : { shot: await driver.screenshot(name), duplicate: false };
2612
+ const { shot } = taken;
2613
+ // The same screen as the last saved screenshot: the earlier file stands
2614
+ // for this moment as well, and nothing new is listed.
2615
+ if (taken.duplicate && shot && shot.relativePath) {
2616
+ stillTheScreen(screenshots, shot.relativePath, observation);
2617
+ transcript.write({ kind: 'screenshot_duplicate', path: shot.relativePath, reason: name });
2618
+ return shot;
2619
+ }
1726
2620
  // A driver that cannot screenshot here (headless Godot answers
1727
2621
  // `{ path: null, skipped }`) saved nothing. Listing it anyway is how a
1728
2622
  // report came to cite "screenshots/undefined" and "- undefined".
@@ -1730,7 +2624,7 @@ export async function safeScreenshot(driver, name, screenshots, transcript, obse
1730
2624
  transcript.write({ kind: 'screenshot_skipped', name, reason: (shot && shot.skipped) || 'no file' });
1731
2625
  return null;
1732
2626
  }
1733
- screenshots.push({ ...shot, reason: name, ...(Number.isInteger(observation) ? { observation } : {}), order: nextOrder() });
2627
+ screenshots.push({ ...shot, reason: name, ...(Number.isInteger(observation) ? { observation } : {}), order: nextOrder(), at: Date.now() });
1734
2628
  transcript.write({ kind: 'screenshot', path: shot.relativePath, reason: name });
1735
2629
  return shot;
1736
2630
  } catch (error) {
@@ -1746,6 +2640,15 @@ async function driverStop(driver, outcome, log, reason) {
1746
2640
  const stopped = await driver.stop({ reason });
1747
2641
  if (stopped?.recording) outcome.recording = stopped.recording;
1748
2642
  if (stopped && stopped.videoPath) outcome.videoPath = stopped.videoPath;
2643
+ // A default recording that could not be made here is said once, with why.
2644
+ if (stopped && stopped.recordingSkipped && !stopped.videoPath) {
2645
+ outcome.recordingSkipped = String(stopped.recordingSkipped);
2646
+ log(`no video was recorded: ${outcome.recordingSkipped}.`);
2647
+ if (outcome.runDirectory && !stopped.recording) {
2648
+ const now = Date.now();
2649
+ await saveRecording(outcome.runDirectory, recordingMetadata({ driver: driver && driver.name, startedAt: now, endedAt: now, reason: 'not_recorded', status: 'unsupported', detail: outcome.recordingSkipped })).catch(() => {});
2650
+ }
2651
+ }
1749
2652
  // The Godot driver captures frames rather than video, and stitching them
1750
2653
  // needs ffmpeg, which is optional. No video is a normal outcome: say
1751
2654
  // where the frames are and move on.
@@ -1996,7 +2899,7 @@ export function notesToFindings(notes, screenshots) {
1996
2899
  * and no persona verdict was recorded; `partial` is what tells a reader not
1997
2900
  * to read them as one.
1998
2901
  */
1999
- async function writePartialReport({ outcome, runDirectory, persona, driverName, target, notes, screenshots, actionRecords = [], play, skill, ledger, runId, jobId, startedAt, endedAt, quitReason = 'cost_cap', reason = BUDGET_PARTIAL_REASON, findings = null, preservedMarkdown = null }) {
2902
+ async function writePartialReport({ outcome, runDirectory, persona, driverName, target, notes, screenshots, actionRecords = [], play, skill, ledger, runId, jobId, startedAt, endedAt, quitReason = 'cost_cap', reason = BUDGET_PARTIAL_REASON, findings = null, preservedMarkdown = null, honesty = null, observations = [] }) {
2000
2903
  // The sentiment is read off the persona's own notes (moodFromNotes), and
2001
2904
  // is the scale's midpoint when it wrote none. `partial` still tells a reader
2002
2905
  // that no report step judged it.
@@ -2037,9 +2940,12 @@ async function writePartialReport({ outcome, runDirectory, persona, driverName,
2037
2940
  'The run reached its model budget before this draft could be completed and checked. It is preserved below for review.',
2038
2941
  '', preservedMarkdown, '', '---', '', fallbackMarkdown].join('\n')
2039
2942
  : fallbackMarkdown;
2040
- const stamped = stampGeneratedAt(markdown, new Date().toISOString(), reportFacts({ persona, driverName, target, play }));
2041
- await writeReportFiles({ runDirectory, markdown: stamped, report });
2042
- outcome.report = report;
2943
+ // What the runner saw happen is kept even in a report nobody reviewed: a
2944
+ // crash it watched is true whatever became of the report step.
2945
+ const honest = writeHonesty({ report, markdown, honesty, driverName, notes, screenshots, observations });
2946
+ const stamped = stampGeneratedAt(honest.markdown, new Date().toISOString(), reportFacts({ persona, driverName, target, play }));
2947
+ await writeReportFiles({ runDirectory, markdown: stamped, report: honest.report });
2948
+ outcome.report = honest.report;
2043
2949
  outcome.reportMarkdown = stamped;
2044
2950
  }
2045
2951
 
@@ -2128,7 +3034,9 @@ export const CONTINUE_WITH_JSON = 'report.md is saved. Now write report.json wit
2128
3034
  */
2129
3035
  export function screenshotLine(shot) {
2130
3036
  const tags = [
2131
- Number.isInteger(shot.observation) && shot.observation > 0 ? `after observation ${shot.observation}` : null,
3037
+ Number.isInteger(shot.observation) && shot.observation > 0
3038
+ ? `after observation ${shot.observation}${Number.isInteger(shot.observationUntil) && shot.observationUntil > shot.observation ? `, and the screen was the same again after observation ${shot.observationUntil}` : ''}`
3039
+ : null,
2132
3040
  shot.reason ? String(shot.reason) : null
2133
3041
  ].filter(Boolean);
2134
3042
  return `- ${shot.relativePath}${tags.length > 0 ? ` (${tags.join('; ')})` : ''}`;
@@ -2200,7 +3108,9 @@ export function observationLines(observations) {
2200
3108
  * @returns {{report: Object, attached: Array<{id: string, ref: string}>}}
2201
3109
  */
2202
3110
  export function attachScreenshotEvidence(report, { screenshots = [], notes = [] } = {}) {
2203
- const usable = (screenshots || []).filter(shot => shot && typeof shot.relativePath === 'string' && shot.relativePath);
3111
+ // Never a picture the edge checks took after play: it shows another window
3112
+ // size or the game after a reload, not what the persona saw.
3113
+ const usable = (screenshots || []).filter(shot => shot && typeof shot.relativePath === 'string' && shot.relativePath && !shot.edge);
2204
3114
  if (!report || !Array.isArray(report.findings) || usable.length === 0) return { report, attached: [] };
2205
3115
  const known = new Set(usable.map(shot => shot.relativePath));
2206
3116
  const attached = [];
@@ -2208,6 +3118,15 @@ export function attachScreenshotEvidence(report, { screenshots = [], notes = []
2208
3118
  const evidence = Array.isArray(finding && finding.evidence) ? finding.evidence : [];
2209
3119
  if (evidence.some(item => item && item.type === 'screenshot' && known.has(item.ref))) return finding;
2210
3120
  let latest = null;
3121
+ // The picture saved when a cited note was written is the one that shows it.
3122
+ const noted = evidence
3123
+ .map(item => (item && item.type === 'transcript_step' ? String(item.ref || '').match(/^note\s+(\d+)$/i) : null))
3124
+ .map(match => (match && notes[Number(match[1]) - 1] ? notes[Number(match[1]) - 1].screenshot : null))
3125
+ .find(ref => ref && known.has(ref));
3126
+ if (noted) {
3127
+ attached.push({ id: finding.id, ref: noted });
3128
+ return { ...finding, evidence: [...evidence, { type: 'screenshot', ref: noted }] };
3129
+ }
2211
3130
  for (const item of evidence) {
2212
3131
  if (!item || item.type !== 'transcript_step') continue;
2213
3132
  const ref = String(item.ref || '');
@@ -2256,8 +3175,8 @@ export function observationTitle(observation) {
2256
3175
  */
2257
3176
  /** How report.md lists what the runner dropped. */
2258
3177
  export const RUNNER_DROPPED_SECTION = Object.freeze({
2259
- heading: '## Dropped by the runner (driver errors, waiting notes or expected noise only)',
2260
- explanation: 'The runner removes a blocker or major whose only cited observations are driver errors (the runner could not carry out an action; the game did nothing wrong), and any finding cited only by waiting notes or by console noise the brief says to expect. They are not sent to the server. They are kept here so you can judge them yourself.',
3178
+ heading: '## Dropped by the runner (driver errors, runner limits, waiting notes or expected noise only)',
3179
+ explanation: 'The runner removes a blocker or major whose only cited observations are driver errors (the runner could not carry out an action; the game did nothing wrong), a finding that is about a limit of the runner itself (what its screen text did not show, a target it could not find), and any finding cited only by waiting notes or by console noise the brief says to expect. They are not sent to the server. They are kept here so you can judge them yourself.',
2261
3180
  emptyNote: '- Nothing here that the runner kept. See the dropped findings below.'
2262
3181
  });
2263
3182
 
@@ -2323,7 +3242,9 @@ export function dropRunnerRejectedFindings(report, { notes = [], observations =
2323
3242
  const dropped = [];
2324
3243
  const findings = [];
2325
3244
  for (const finding of report.findings) {
2326
- const reason = finding ? verdict(finding) : null;
3245
+ // Praise is never about a limit; anything else that talks about the
3246
+ // runner's own tools is a capability note the persona filed as a finding.
3247
+ const reason = finding ? (finding.severity !== 'praise' && aboutRunnerLimit(finding) ? 'about a limit of the runner, not the game' : verdict(finding)) : null;
2327
3248
  if (reason) dropped.push({ finding, reason });
2328
3249
  else findings.push(finding);
2329
3250
  }
@@ -2409,7 +3330,7 @@ export function actionLogFrom(records) {
2409
3330
  target = where;
2410
3331
  }
2411
3332
  }
2412
- const entry = { action: Number(record.actions) || log.length + 1, kind: record.tool, target, name, ref, changed: Boolean(record.changed), observationBefore: observation, observationAfter: null, introducedError: false };
3333
+ const entry = { action: Number(record.actions) || log.length + 1, kind: record.tool, target, name, ref, changed: Boolean(record.changed), observationBefore: observation, observationAfter: null, introducedError: false, ...(typeof record.expect === 'string' && record.expect ? { expect: record.expect } : {}) };
2413
3334
  log.push(entry);
2414
3335
  pending = entry;
2415
3336
  }
@@ -2443,7 +3364,7 @@ export function introducesError(before, after) {
2443
3364
  export function actionLogLines(log) {
2444
3365
  if (!Array.isArray(log) || log.length === 0) return '(none)';
2445
3366
  const shown = log.slice(-MAX_ACTIONS_IN_REPORT);
2446
- const lines = shown.map(entry => `${entry.action}. ${entry.kind} ${entry.target}: ${entry.changed ? 'screen changed' : 'no change'}`);
3367
+ const lines = shown.map(entry => `${entry.action}. ${entry.kind} ${entry.target}: ${entry.changed ? 'screen changed' : 'no change'}${entry.expect ? ` (you expected: ${entry.expect}${Number.isInteger(entry.observationAfter) ? `; observation ${entry.observationAfter} is what followed` : ''})` : ''}`);
2447
3368
  if (shown.length < log.length) lines.unshift(`(the first ${log.length - shown.length} are left out)`);
2448
3369
  return lines.join('\n');
2449
3370
  }