ravensight-playtest 0.11.0 → 0.12.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 (63) hide show
  1. package/README.md +89 -21
  2. package/addons/mobile/Host/AppDelegate.swift +11 -0
  3. package/addons/mobile/RavensightMobile.xcodeproj/project.pbxproj +398 -0
  4. package/addons/mobile/RavensightMobile.xcodeproj/project.xcworkspace/contents.xcworkspacedata +7 -0
  5. package/addons/mobile/RavensightMobile.xcodeproj/xcshareddata/xcschemes/RavensightMobile.xcscheme +116 -0
  6. package/addons/mobile/UITests/MobileInputTests.swift +152 -0
  7. package/addons/mobile/project.yml +45 -0
  8. package/docs/ADAPTERS.md +5 -4
  9. package/docs/MOBILE.md +107 -0
  10. package/docs/NATIVE_RUNNER.md +7 -3
  11. package/docs/godot-driver.md +1 -1
  12. package/package.json +7 -5
  13. package/src/api/README.md +3 -3
  14. package/src/cli.js +36 -6
  15. package/src/commands/check.js +17 -3
  16. package/src/commands/device.js +64 -0
  17. package/src/commands/fakeCore.js +1 -1
  18. package/src/commands/hosted.js +16 -13
  19. package/src/commands/login.js +1 -1
  20. package/src/commands/run.js +39 -11
  21. package/src/dashboard.js +2 -3
  22. package/src/detect.js +17 -0
  23. package/src/fsutil.js +1 -1
  24. package/src/hosted/archivePreflight.js +3 -3
  25. package/src/hosted/buildUpload.js +8 -7
  26. package/src/hosted/recordedRun.js +19 -3
  27. package/src/run/anygame/index.js +9 -3
  28. package/src/run/args.js +6 -0
  29. package/src/run/budgetReserve.js +29 -9
  30. package/src/run/claimProtocol.js +27 -0
  31. package/src/run/completion.js +86 -0
  32. package/src/run/context.js +2 -2
  33. package/src/run/drivers/android.js +3 -0
  34. package/src/run/drivers/godot.js +1 -1
  35. package/src/run/drivers/index.js +4 -0
  36. package/src/run/drivers/ios.js +3 -0
  37. package/src/run/drivers/mobile/adb.js +91 -0
  38. package/src/run/drivers/mobile/attempt.js +18 -0
  39. package/src/run/drivers/mobile/crash.js +115 -0
  40. package/src/run/drivers/mobile/frame.js +64 -0
  41. package/src/run/drivers/mobile/ios-helper.js +102 -0
  42. package/src/run/drivers/mobile/lock.js +32 -0
  43. package/src/run/drivers/mobile/native.js +227 -0
  44. package/src/run/drivers/mobile/preflight.js +80 -0
  45. package/src/run/drivers/mobile/process.js +57 -0
  46. package/src/run/drivers/mobile/recording.js +88 -0
  47. package/src/run/drivers/mobile/screenshot.js +34 -0
  48. package/src/run/drivers/mobile/simctl.js +60 -0
  49. package/src/run/drivers/mobile/target.js +53 -0
  50. package/src/run/honesty.js +66 -26
  51. package/src/run/inputMeasurement.js +49 -0
  52. package/src/run/model.js +24 -31
  53. package/src/run/paths.js +1 -1
  54. package/src/run/personaLoop.js +282 -74
  55. package/src/run/proxyClient.js +173 -0
  56. package/src/run/repoTools.js +1 -1
  57. package/src/run/report.js +19 -0
  58. package/src/run/resume.js +33 -4
  59. package/src/run/screenshots.js +3 -1
  60. package/src/run/tools.js +31 -5
  61. package/src/run/usage.js +2 -2
  62. package/src/upload/allowlist.js +2 -2
  63. package/src/upload/index.js +9 -9
@@ -5,18 +5,20 @@ import path from 'node:path';
5
5
  import { prepareMessages, repairLastTurn, frozenEnds, frozenEnd, createCacheLayout, MAX_IMAGES_IN_CONTEXT, KEEP_OBSERVATIONS, shrinkImages } from './context.js';
6
6
  import { callStepWithRetry, ProxyError, STEPS } from './model.js';
7
7
  import { RUN_FILES } from './paths.js';
8
- import { reserveDecision } from './budgetReserve.js';
8
+ import { requestBytes, reserveDecision } from './budgetReserve.js';
9
+ import { measureActInput } from './inputMeasurement.js';
10
+ import { completionClaim, completionCriteria, completionPrompt, completionRepairPrompt, MAX_COMPLETION_TEXT } from './completion.js';
9
11
  import { createScreenshotKeeper } from './screenshots.js';
10
12
  import { checkBriefChoice, screensForCheck, writeChoiceIntoMarkdown, CHOICE_CHECK_FILE } from './choiceCheck.js';
11
13
  import { declinedAnswer, declinedPrompt, declinedStopDetail, NEUTRAL_RESTATEMENT } from './refusal.js';
12
14
  import { createPlayClock, clockStopDetail, timeLeftAside } from './playClock.js';
13
- import { appendNormalisedMarkdown, checkEvidence, createReportValidator, lintMarkdownSections, normaliseEnums, normaliseEvidence, repairInstruction, REQUIRED_MARKDOWN_SECTIONS, stampReport, stripTrailingToolMarkup, writeReportFiles } from './report.js';
15
+ import { appendNormalisedMarkdown, checkEvidence, createReportValidator, lintMarkdownSections, normaliseEnums, normaliseEvidence, normaliseReproSteps, repairInstruction, REQUIRED_MARKDOWN_SECTIONS, stampReport, stripTrailingToolMarkup, writeReportFiles } from './report.js';
14
16
  import { assertNoSecrets, scanForSecrets } from './secretScan.js';
15
17
  import { ACTION_TOOLS, NEW_TOOL_NAMES, REPORT_TOOLS, executeTool, expectationOf, modelFrameOf, toolResult, toolsFor, NEWEST_TOOL_NAMES } from './tools.js';
16
18
  import {
17
19
  CAPABILITY_HEADING, DIALOGS_HEADING, EVIDENCE_HEADING, MAX_WIN_CONTINUES, RUNNER_FINDINGS_HEADING, WIN_TEXT,
18
20
  addRunnerFindings, attachWhereToLook, blankFinding, capabilityPrompt, createBlankWatch, createCapabilityLedger, describeInput, dialogNote, gameEndedFinding, gameEndedOf, mergeRunnerDuplicates,
19
- playOnText, replaceSection, runnerFinding, runnerFindingsMarkdown, stepsBefore, whereToLookMarkdown, writeCapabilitySection
21
+ playOnText, replaceSection, runnerFinding, runnerFindingsMarkdown, stepsBefore, videoTime, whereToLookMarkdown, writeCapabilitySection
20
22
  } from './honesty.js';
21
23
  import { runEdgePass, edgeFindings, edgeMarkdown, EDGE_HEADING, blankCapabilityNote } from './edgePass.js';
22
24
  // Tester techniques (./testerLedger.js): a coverage map, the game's own numbers and placeholder text, kept by the runner.
@@ -35,6 +37,7 @@ import { claimShape, judgeIssue, legacyIssue, impressionOf } from './judge.js';
35
37
  import { EVENTS_RULE, eventsBlock, eventsReportLines, eventsUsage, withEventEvidence } from './events.js';
36
38
  import { memoryBlock, extractLocalNotes, gameMemoryBody } from './gameMemory.js';
37
39
  import { CLAIM_SYSTEM, CLAIM_WIRE, claimText, claimRead, claimMessage } from './claimwords.js';
40
+ import { claimCheckSystem, claimReply, claimFormatRepair, MAX_CLAIM_REPLY_TEXT } from './claimProtocol.js';
38
41
  import { captureNotes, createCaptureWatch, rewriteStaleEvidence, staleSentence } from './captureCheck.js';
39
42
  import { gameRefusal } from './gameRefusal.js';
40
43
  import { BUILT_IN_NOISE, expectedNoiseForPrompt, isExpectedNoise } from './noise.js';
@@ -187,9 +190,12 @@ export function keepGoingBelow(maxActions) {
187
190
  return max >= MIN_SESSION_ACTIONS ? Math.max(MIN_SESSION_ACTIONS, Math.ceil(max / 2)) : 0;
188
191
  }
189
192
 
193
+ /** A run's stop reason after an accepted completion account: the persona's claim, which the report checks. */
194
+ export const COMPLETION_QUIT_DETAIL = 'the persona gave an account of every explicit success criterion citing observed steps; the report checks those claims';
195
+
190
196
  /** What a persona that stopped early is asked, once. */
191
197
  export function keepGoingText(actions, maxActions) {
192
- 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.`;
198
+ return `You stopped after ${actions} of ${maxActions} actions, and the run's budget has room for more. Keep playing in scope if the brief has unfinished goals: try the systems you have not touched and go further into the ones you have. If all explicit success criteria and their verification are complete, use the brief completion statement with observed evidence and preserve the requested end state. 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.`;
193
199
  }
194
200
 
195
201
  /** What the persona is told on the turn before its last. */
@@ -204,8 +210,8 @@ export const PLAY_NOTES = [
204
210
  '- 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.',
205
211
  '- 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.',
206
212
  '- 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.',
207
- '- 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.',
208
- '- 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.',
213
+ '- Keep playing in scope beyond a first win or partial goal. When the brief gives explicit success criteria, complete all of them and their requested verification, then use the completion statement below to stop while preserving the requested end state. Without a completed brief, explore until your actions or budget run out or a persona stop condition fires.',
214
+ '- When you do stop, use the brief completion statement if applicable, otherwise one short sentence, and no tool call. Never write the report here: a separate step writes it from your notes.',
209
215
  '- 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.'
210
216
  ].join('\n');
211
217
 
@@ -490,6 +496,11 @@ export async function runPersona(args) {
490
496
  }
491
497
  return finish(outcome, ledger, runDirectory, transcript, heartbeat);
492
498
  } catch (error) {
499
+ // A thrown play phase never returned its counter. Recover the loop's own
500
+ // recorded cumulative count, not the number of tool records: waits,
501
+ // screenshots and avoided inputs can be logged without spending an action.
502
+ outcome.actionsTaken = actionRecords.reduce((count, record) => record?.kind === 'action' && Number.isSafeInteger(record.actions)
503
+ ? Math.max(count, record.actions) : count, outcome.actionsTaken || 0);
493
504
  await driverStop(driver, outcome, log, args.signal?.aborted ? 'canceled' : 'failed');
494
505
  if (error instanceof ProxyError && error.isBudget) {
495
506
  outcome.state = 'budget_exceeded';
@@ -507,8 +518,7 @@ export async function runPersona(args) {
507
518
  // cost unless the server recorded a failure of its own on the run.
508
519
  outcome.state = error.budgetPressure ? 'budget_exceeded' : 'failed';
509
520
  outcome.quitReason = error.budgetPressure ? 'cost_cap' : 'error';
510
- const actionsTaken = Math.max(outcome.actionsTaken || 0, actionLogFrom(actionRecords).length);
511
- const play = { actionsTaken, quitReason: outcome.quitReason, quitDetail: safeErrorDetail(error, localBrief) };
521
+ const play = { actionsTaken: outcome.actionsTaken, quitReason: outcome.quitReason, quitDetail: safeErrorDetail(error, localBrief) };
512
522
  await writeSomeReport({ outcome, runDirectory, persona, driverName, target, notes, screenshots, actionRecords, play, skill, ledger, runId, jobId, startedAt,
513
523
  endedAt: new Date().toISOString(), log, honesty, observations, quitReason: outcome.quitReason, reason: REPORT_INCOMPLETE_REASON, bareReason: REPORT_INCOMPLETE_REASON,
514
524
  preservedMarkdown: error.completedReportMarkdown });
@@ -525,10 +535,7 @@ export async function runPersona(args) {
525
535
  // call. An abort is the person stopping it, not a failure.
526
536
  if (!args.signal?.aborted) {
527
537
  const detail = safeErrorDetail(error, localBrief);
528
- // The play loop's count only reaches `outcome` when it returns, and this
529
- // may be the play loop dying.
530
- const actionsTaken = Math.max(outcome.actionsTaken || 0, actionLogFrom(actionRecords).length);
531
- const play = { actionsTaken, quitReason: 'error', quitDetail: detail };
538
+ const play = { actionsTaken: outcome.actionsTaken, quitReason: 'error', quitDetail: detail };
532
539
  await writeSomeReport({
533
540
  outcome, runDirectory, persona, driverName, target, notes, screenshots, actionRecords, play, skill, ledger, runId, jobId, startedAt, endedAt: new Date().toISOString(), log, honesty, observations,
534
541
  quitReason: 'error',
@@ -796,7 +803,9 @@ async function playLoop({
796
803
  // the loop stops early enough that the report still fits; without it (an
797
804
  // older server) only the server's 80 percent warning does.
798
805
  modelBudgetUsd = null,
806
+ inputMeasurement = null,
799
807
  reportSkill = null,
808
+ schemas = [],
800
809
  honesty = { capability: createCapabilityLedger(), findings: [], dialogs: [], edge: null, video: null, tester: createTesterLedger() },
801
810
  // The scripted edge behaviour checks after play (./edgePass.js): on unless
802
811
  // the run turned them off.
@@ -812,7 +821,7 @@ async function playLoop({
812
821
  const noisePatterns = (localBrief && Array.isArray(localBrief.expected_noise)) ? localBrief.expected_noise : [];
813
822
  // any-game hook: one notebook a run, on the honesty record so the report step reads the same one.
814
823
  const briefFields = brief && brief.fields && typeof brief.fields === 'object' ? brief.fields : brief || {};
815
- 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 }));
824
+ const anyGame = honesty.anygame || (honesty.anygame = createLocalAnyGame({ briefText: briefForPrompt(brief), controls: briefFields.build_notes && typeof briefFields.build_notes.controls === 'string' ? briefFields.build_notes.controls : null, touch: Boolean(driver && driver.touch), continuousTime: driver?.inputProfile === 'native-mobile' && driver.frozenBetweenActions === false, driverName: typeof driver.soundSelfTest === 'function' ? '' : driverName }));
816
825
  system.push({ type: 'text', text: anyGame.systemText() });
817
826
  // What earlier playtests of this game learned (./gameMemory.js): the same block every request carries, so it is cached.
818
827
  const earlier = earlierMemory && earlierMemory.save !== false ? memoryBlock(earlierMemory) : '';
@@ -821,6 +830,10 @@ async function playLoop({
821
830
  transcript.write({ kind: 'game_memory_read', notes: Array.isArray(earlierMemory.notes) ? earlierMemory.notes.length : 0, chars: earlier.length });
822
831
  }
823
832
  system.push({ type: 'text', text: PLAY_NOTES });
833
+ const criteria = completionCriteria(brief);
834
+ const completionMinimum = Math.min(MIN_SESSION_ACTIONS, maxActions);
835
+ const completionInstructions = completionPrompt(criteria, completionMinimum);
836
+ if (completionInstructions) system.push({ type: 'text', text: completionInstructions });
824
837
  if (typeof driver.soundSelfTest === 'function') anyGame.soundAvailable(await Promise.resolve().then(() => driver.soundSelfTest()).catch(() => null));
825
838
  if (['jev', 'rune'].includes(controller)) system.push({ type: 'text', text: JEV_CONTROLLER_PROMPT });
826
839
  // The tools this driver can do. The newest names (drag, hover, scroll,
@@ -857,6 +870,10 @@ async function playLoop({
857
870
  let gameEnded = null;
858
871
  let gameEndedAt = null;
859
872
  let winContinues = 0;
873
+ let completionAccount = null;
874
+ const completionAttempts = [];
875
+ let completionRepairPending = false;
876
+ let completionRepairUsed = false;
860
877
  const recentActions = [];
861
878
  let latestObservation = '';
862
879
  let visualObservation = false;
@@ -913,22 +930,28 @@ async function playLoop({
913
930
  const spend = modelBudgetUsd ? ledger.spendEstimate() : null;
914
931
  if (!spend) return { stop: false, known: false, figures: {} };
915
932
  const prepared = withPlayCacheBreakpoint(prepareMessages(messages, { maxImages: imageBudget, keepObservations, layout: cacheLayout }), cacheLayout);
916
- const actChars = JSON.stringify({ messages: prepared, max_tokens: ACT_MAX_TOKENS, stream: true, system, tools: playTools }).length;
933
+ const measured = measureActInput({ messages: prepared, max_tokens: ACT_MAX_TOKENS, stream: true, system, tools: completionRepairPending ? [] : playTools }, inputMeasurement, { controller });
917
934
  const reportRequest = buildReportRequest({
918
- skill: reportSkill || skill, persona, brief, localBrief, intentNotes, driverName, target, runId, jobId,
919
- play: { actionsTaken: actions, quitReason: 'budget_exhausted', quitDetail: RESERVE_STOP_DETAIL, actionLog: actionLogFrom(actionRecords), records: actionRecords },
935
+ skill: reportSkill || skill, schemas, persona, brief, localBrief, intentNotes, driverName, target, runId, jobId,
936
+ play: { actionsTaken: actions, quitReason: 'budget_exhausted', quitDetail: RESERVE_STOP_DETAIL, actionLog: actionLogFrom(actionRecords), records: actionRecords,
937
+ completionClaim: completionAccount, completionAttempts },
920
938
  notes, observations, screenshots
921
939
  });
922
- const reportChars = JSON.stringify({ messages: reportRequest.messages, max_tokens: REPORT_MAX_TOKENS, stream: true, system: reportRequest.system, tools: REPORT_TOOLS }).length;
923
- return reserveDecision({
940
+ const reportChars = requestBytes({ messages: reportRequest.messages, max_tokens: REPORT_MAX_TOKENS, stream: true, system: reportRequest.system, tools: REPORT_TOOLS });
941
+ const decision = reserveDecision({
924
942
  usdMax: modelBudgetUsd,
925
943
  spend,
926
- actChars,
944
+ actChars: measured.chars,
945
+ actImageUnits: measured.imageUnits,
927
946
  actMaxTokens: ACT_MAX_TOKENS,
928
947
  actCostUnits: recentActUnits.length > 0 ? Math.max(...recentActUnits) : 0,
948
+ // The tools-free completion repair turn cannot read the cached prompt.
949
+ actUncached: completionRepairPending,
929
950
  reportChars,
930
951
  reportMaxTokens: REPORT_MAX_TOKENS
931
952
  });
953
+ if (decision.known) Object.assign(decision.figures, { act_measurement: measured.measurement, act_images: measured.images, act_image_units: measured.imageUnits });
954
+ return decision;
932
955
  };
933
956
 
934
957
  // Notes waiting for the next observation, which is the screen they are
@@ -1001,9 +1024,13 @@ async function playLoop({
1001
1024
  if (reserve.stop) {
1002
1025
  reserveStopped = true;
1003
1026
  quitReason = 'budget_exhausted';
1004
- quitDetail = RESERVE_STOP_DETAIL;
1027
+ quitDetail = reserve.figures.stop_reason === 'act_projection'
1028
+ ? 'stopped early because the next action reservation exceeds the remaining model budget'
1029
+ : reserve.figures.stop_reason === 'act_projection_and_report_reserve'
1030
+ ? 'stopped early because the next action reservation and the report reserve exceed the remaining model budget'
1031
+ : RESERVE_STOP_DETAIL;
1005
1032
  transcript.write({ kind: 'budget_reserve_stop', ...reserve.figures });
1006
- log(`stopping play after ${actions} action(s) so the rest of the model budget pays for the report (spent about $${reserve.figures.usd_spent} of $${reserve.figures.usd_max}; the report needs about $${reserve.figures.report_reserve_usd}).`);
1033
+ log(`stopping play after ${actions} action(s): ${quitDetail} (spent about $${reserve.figures.usd_spent} of $${reserve.figures.usd_max}; next action projection $${reserve.figures.act_projected_usd}; report reserve $${reserve.figures.report_reserve_usd}; reason ${reserve.figures.stop_reason}).`);
1007
1034
  break;
1008
1035
  }
1009
1036
  }
@@ -1026,7 +1053,7 @@ async function playLoop({
1026
1053
  step: STEPS.personaAct,
1027
1054
  system,
1028
1055
  messages,
1029
- tools: playTools,
1056
+ tools: completionRepairPending ? [] : playTools,
1030
1057
  maxTokens: ACT_MAX_TOKENS,
1031
1058
  escalate: shouldEscalate(persona),
1032
1059
  imageBudget,
@@ -1047,7 +1074,7 @@ async function playLoop({
1047
1074
  // from its step log (runPersona's error path), because a run that
1048
1075
  // played never comes back empty.
1049
1076
  const offersNewest = playTools.some(tool => NEWEST_TOOL_NAMES.includes(tool.name));
1050
- if (error instanceof ProxyError && error.code === 'tool_not_allowed' && newTools && newestTools && offersNewest) {
1077
+ if (!completionRepairPending && error instanceof ProxyError && error.code === 'tool_not_allowed' && newTools && newestTools && offersNewest) {
1051
1078
  // A server from before pinch and the gamepad: play on without those
1052
1079
  // two, and say so. If it refuses the pointer tools as well, the next
1053
1080
  // refusal drops them the same way.
@@ -1069,7 +1096,7 @@ async function playLoop({
1069
1096
  log(`the server does not allow the pointer tools either (${again.message}); playing on without ${older.join(', ') || 'them'}, with drag sent as swipe.`);
1070
1097
  answer = await askAct();
1071
1098
  }
1072
- } else if (error instanceof ProxyError && error.code === 'tool_not_allowed' && newTools) {
1099
+ } else if (!completionRepairPending && error instanceof ProxyError && error.code === 'tool_not_allowed' && newTools) {
1073
1100
  // A server from before the pointer tools: play on with the names it
1074
1101
  // allows, and say what could not be offered.
1075
1102
  newTools = false;
@@ -1122,16 +1149,81 @@ async function playLoop({
1122
1149
  // moment where telling them costs nothing and saying nothing costs a
1123
1150
  // report. Recorded before anything else can fail, so the journal and
1124
1151
  // the transcript both say the run was warned.
1125
- 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.');
1152
+ log(completionRepairPending
1153
+ ? 'budget warning: this run has used at least 80 percent of its model budget. This completion formatting turn sends no gameplay inputs; the existing report budget still applies.'
1154
+ : '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.');
1126
1155
  transcript.write({ kind: 'budget_warning', wrap_up_turns: WRAP_UP_TURNS });
1127
1156
  if (typeof onBudgetWarning === 'function') await onBudgetWarning();
1128
1157
  }
1129
1158
 
1130
1159
  if (argsSignal?.aborted || heartbeat?.canceled) { canceled = true; quitReason = 'error'; quitDetail = 'the job was cancelled'; break; }
1160
+ const how = declinedAnswer(answer);
1161
+ let completion = answer.toolUses.length === 0 ? completionClaim({ text: answer.text, criteria, observations, actions, minimumActions: completionMinimum }) : null;
1162
+ const eligibleCompletion = completion && criteria.length > 0 && actions >= completionMinimum;
1163
+ if (completionRepairPending || eligibleCompletion) {
1164
+ // Formatting a deliberate completion attempt never sends another input.
1165
+ // Even an unsolicited tool call from this tools-free turn is discarded.
1166
+ if (completionRepairPending && answer.toolUses.length > 0) completion = { accepted: false, reason: 'completion_repair_tool_call' };
1167
+ else if (how) completion = { accepted: false, reason: `completion_response_${how}` };
1168
+ else if (!completion) completion = { accepted: false, reason: 'completion_marker_missing' };
1169
+ }
1170
+ if (completion) {
1171
+ const attempt = scrubSecrets({ ...completion, phase: completionRepairPending ? 'repair' : 'initial',
1172
+ text: scrubSecrets(String(answer.text || ''), secrets).slice(0, MAX_COMPLETION_TEXT), text_length: String(answer.text || '').length,
1173
+ text_truncated: String(answer.text || '').length > MAX_COMPLETION_TEXT,
1174
+ ...(completionRepairPending && answer.toolUses.length ? { ignored_tools: answer.toolUses.map(tool => tool.name) } : {}) }, secrets);
1175
+ completionAttempts.push(attempt);
1176
+ transcript.write({ kind: 'brief_completion_claim', ...attempt, actions, minimum_actions: completionMinimum, independently_verified: false });
1177
+ }
1178
+ if (completionRepairPending) {
1179
+ completionRepairPending = false;
1180
+ if (completion.accepted) completionAccount = completion.criteria;
1181
+ else if (!keepGoingAsked && !budgetWarned && !wrappingUp && actions < keepGoingBelow(maxActions)) {
1182
+ // An account that still fails is not a finished brief: a mention of
1183
+ // the marker, or "I cannot support every criterion", must not end a
1184
+ // paid session early. Ask once to keep going, as for any early stop;
1185
+ // gameplay tools come back only with that question.
1186
+ keepGoingAsked = true;
1187
+ transcript.write({ kind: 'keep_going', actions, max_actions: maxActions, after: 'completion_repair_unverified', text: String(answer.text || '').slice(0, 400) });
1188
+ log(`the completion account stayed unverified after its one formatting repair at ${actions} of ${maxActions} actions; asking once whether the session is really over.`);
1189
+ messages.push({ role: 'assistant', content: [{ type: 'text', text: answer.text && answer.text.trim() ? String(answer.text).slice(0, MAX_COMPLETION_TEXT) : '(stopped)' }] });
1190
+ messages.push({ role: 'user', content: [{ type: 'text', text: keepGoingText(actions, maxActions) }] });
1191
+ continue;
1192
+ }
1193
+ quitReason = warnedNow || wrappingUp ? 'budget_exhausted' : 'persona_quit';
1194
+ quitDetail = completion.accepted
1195
+ ? COMPLETION_QUIT_DETAIL
1196
+ : `play stopped after one completion formatting repair remained unverified (${completion.reason}); no further gameplay input was sent`;
1197
+ transcript.write({ kind: 'quit', reason: quitReason, detail: quitDetail, independently_verified: false });
1198
+ break;
1199
+ }
1200
+ if (eligibleCompletion && !completion.accepted) {
1201
+ if (completionRepairUsed) {
1202
+ // One formatting repair a run: a second unverified account after the
1203
+ // keep-going question ends play, and sends no input.
1204
+ quitReason = 'persona_quit';
1205
+ quitDetail = 'the completion account remained unverified after the run\'s one formatting repair; no further gameplay input was sent';
1206
+ transcript.write({ kind: 'brief_completion_repair_unavailable', reason: 'repair_already_used', detail: quitDetail, independently_verified: false });
1207
+ transcript.write({ kind: 'quit', reason: quitReason, detail: quitDetail, independently_verified: false });
1208
+ break;
1209
+ }
1210
+ if (budgetWarned || wrappingUp) {
1211
+ quitReason = 'budget_exhausted';
1212
+ quitDetail = 'the completion account remained unverified; the existing budget warning allowed no further formatting turn or gameplay input';
1213
+ transcript.write({ kind: 'brief_completion_repair_unavailable', reason: wrappingUp ? 'wrap_up_limit' : 'budget_warning', detail: quitDetail, independently_verified: false });
1214
+ transcript.write({ kind: 'quit', reason: quitReason, detail: quitDetail, independently_verified: false });
1215
+ break;
1216
+ }
1217
+ completionRepairPending = true;
1218
+ completionRepairUsed = true;
1219
+ transcript.write({ kind: 'brief_completion_repair', reason: completion.reason, max_attempts: 1, actions, independently_verified: false });
1220
+ messages.push({ role: 'assistant', content: [{ type: 'text', text: String(answer.text || '').slice(0, MAX_COMPLETION_TEXT) }] });
1221
+ messages.push({ role: 'user', content: [{ type: 'text', text: completionRepairPrompt(criteria, completion.reason) }] });
1222
+ continue;
1223
+ }
1131
1224
  // An answer that is not the persona's (a refusal, or nothing usable) is
1132
1225
  // counted and asked once more. It is never the persona quitting, never a
1133
1226
  // finding, and one of them never ends the session.
1134
- const how = declinedAnswer(answer);
1135
1227
  if (how && !wrappingUp) {
1136
1228
  declined += 1;
1137
1229
  const again = !declinedLastTurn;
@@ -1154,17 +1246,18 @@ async function playLoop({
1154
1246
  break;
1155
1247
  }
1156
1248
  declinedLastTurn = false;
1157
- if (answer.toolUses.length === 0 && !budgetWarned && !wrappingUp && actions < maxActions && winContinues < MAX_WIN_CONTINUES && WIN_TEXT.test(String(answer.text || ''))) {
1158
- // A win or a finished level never ends the session early: it is noted,
1159
- // and play goes on to the limits.
1249
+ if (completion?.accepted) completionAccount = completion.criteria;
1250
+ if (!completion?.accepted && answer.toolUses.length === 0 && !budgetWarned && !wrappingUp && actions < maxActions && winContinues < MAX_WIN_CONTINUES && WIN_TEXT.test(String(answer.text || ''))) {
1251
+ // A partial win is not completion of the brief. A deliberate completion
1252
+ // claim with observed references proceeds to the existing report checks.
1160
1253
  winContinues += 1;
1161
1254
  transcript.write({ kind: 'play_on_after_win', actions, max_actions: maxActions, text: String(answer.text || '').slice(0, 400) });
1162
- 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.`);
1255
+ log(`the persona stopped on a win after ${actions} of ${maxActions} actions without a complete brief account; asking it to continue in scope.`);
1163
1256
  messages.push({ role: 'assistant', content: [{ type: 'text', text: answer.text && answer.text.trim() ? answer.text : '(stopped)' }] });
1164
1257
  messages.push({ role: 'user', content: [{ type: 'text', text: playOnText(actions, maxActions) }] });
1165
1258
  continue;
1166
1259
  }
1167
- if (answer.toolUses.length === 0 && !keepGoingAsked && !budgetWarned && actions < keepGoingBelow(maxActions)) {
1260
+ if (!completion?.accepted && answer.toolUses.length === 0 && !keepGoingAsked && !budgetWarned && actions < keepGoingBelow(maxActions)) {
1168
1261
  // An early stop with budget left is asked about once. The persona may
1169
1262
  // still stop: its own stop conditions are its own.
1170
1263
  keepGoingAsked = true;
@@ -1183,7 +1276,7 @@ async function playLoop({
1183
1276
  // is often the persona starting on its report ("Now writing the final
1184
1277
  // report. **report.md:** ..."), which in 0.7.1 ended up as a
1185
1278
  // succeeded run's reason on the dashboard.
1186
- quitDetail = personaQuitDetail(answer.text);
1279
+ quitDetail = completion?.accepted ? COMPLETION_QUIT_DETAIL : personaQuitDetail(answer.text);
1187
1280
  transcript.write({ kind: 'quit', reason: quitReason, text: answer.text });
1188
1281
  break;
1189
1282
  }
@@ -1674,6 +1767,7 @@ async function playLoop({
1674
1767
  const kept = driver.gameEvents.record();
1675
1768
  if (kept.total > 0) transcript.write({ kind: 'game_events', total: kept.total, kept: kept.kept, clock: kept.clock, names: kept.names });
1676
1769
  }
1770
+ if (completionRepairPending) transcript.write({ kind: 'brief_completion_repair_unavailable', reason: quitReason, detail: quitDetail, independently_verified: false });
1677
1771
  return {
1678
1772
  actionsTaken: actions,
1679
1773
  turns,
@@ -1693,6 +1787,8 @@ async function playLoop({
1693
1787
  budgetExceeded,
1694
1788
  reportBudgetAvailable,
1695
1789
  reserveStopped,
1790
+ completionClaim: completionAccount,
1791
+ completionAttempts,
1696
1792
  canceled,
1697
1793
  imageBudget,
1698
1794
  finalScreenshot: final ? final.relativePath : null,
@@ -1757,7 +1853,7 @@ async function reportPhase({
1757
1853
  if (choiceCheck) log(`brief choice check: ${choiceCheck.choice}: ${choiceCheck.result}${choiceCheck.shown ? ` (${choiceCheck.shown})` : ''}`);
1758
1854
  }
1759
1855
 
1760
- const { system, messages } = buildReportRequest({ skill, persona, brief, localBrief, intentNotes, driverName, target, runId, jobId, play, notes, observations, screenshots, choiceCheck, honesty });
1856
+ const { system, messages } = buildReportRequest({ skill, schemas, persona, brief, localBrief, intentNotes, driverName, target, runId, jobId, play, notes, observations, screenshots, choiceCheck, honesty });
1761
1857
 
1762
1858
  let report = null;
1763
1859
  let markdown = null;
@@ -1903,13 +1999,17 @@ async function reportPhase({
1903
1999
  // judges the report, so a run is never lost to them for want of a repair
1904
2000
  // turn. The server's schema stays strict.
1905
2001
  const enumFixed = normalised ? normaliseEnums(normalised.report, reportSchema) : { report: null, changes: [] };
1906
- normalisedByRunner = enumFixed.changes;
2002
+ const reproFixed = normaliseReproSteps(enumFixed.report, reportSchema);
2003
+ normalisedByRunner = [...enumFixed.changes, ...reproFixed.changes];
1907
2004
  if (enumFixed.changes.length > 0) {
1908
2005
  transcript.write({ kind: 'report_values_normalised', attempt, changes: enumFixed.changes.map(change => ({ id: change.id, field: change.field, from: change.from, to: change.to })) });
1909
2006
  }
2007
+ if (reproFixed.changes.length > 0) {
2008
+ transcript.write({ kind: 'report_repro_steps_normalised', attempt, changes: reproFixed.changes.map(({ id, field, fromType, toType }) => ({ id, field, fromType, toType, textPreserved: true })) });
2009
+ }
1910
2010
  const reportCandidate = play.budgetExceeded
1911
- ? { ...enumFixed.report, partial: true, quit_reason: 'cost_cap', quit_detail: play.quitDetail }
1912
- : enumFixed.report;
2011
+ ? { ...reproFixed.report, partial: true, quit_reason: 'cost_cap', quit_detail: play.quitDetail }
2012
+ : reproFixed.report;
1913
2013
  const capped = normalised ? capNetworkOnlyFindings(stampReport(reportCandidate, facts), { notes, screenshots }) : null;
1914
2014
  const runnerDrop = capped ? dropRunnerRejectedFindings(capped, { notes, observations }) : { report: null, dropped: [] };
1915
2015
  for (const entry of runnerDrop.dropped) {
@@ -1935,6 +2035,9 @@ async function reportPhase({
1935
2035
  // A markdown that was never written is missing all four, which is what
1936
2036
  // asks for it in the repair turn rather than silently falling back.
1937
2037
  const missingSections = lintMarkdownSections(markdown || '');
2038
+ transcript.write(scrubSecrets({ kind: 'report_validation', attempt, schema_valid: validation.ok,
2039
+ details: validation.details, evidence_problems: evidenceProblems, missing_sections: missingSections,
2040
+ schema_repair_used: repaired }, secrets));
1938
2041
 
1939
2042
  if (validation.ok && evidenceProblems.length === 0 && missingSections.length === 0) {
1940
2043
  report = candidate;
@@ -1983,6 +2086,17 @@ async function reportPhase({
1983
2086
  continue;
1984
2087
  }
1985
2088
 
2089
+ // A truncated write with no parseable draft has nothing whose schema can
2090
+ // be repaired yet. Its existing one shorter retry must not spend that
2091
+ // allowance before the first complete report arrives.
2092
+ if (cutOff && !candidate && !repaired) {
2093
+ transcript.write({ kind: 'report_shorter_retry', attempt, reason: 'truncated_without_parseable_report', schema_repair_used: false });
2094
+ messages.push({ role: 'assistant', content: assistantContent(answer) });
2095
+ messages.push({ role: 'user', content: toolResults.concat([{ type: 'text', text: 'The last turn was cut off before a complete, parseable report.json was written. Write the unfinished report files using the supplied report.json schema.' }]) });
2096
+ askShorter(messages, maxTokens);
2097
+ continue;
2098
+ }
2099
+
1986
2100
  // A first cut-off on the repair turn still gets its one shorter retry.
1987
2101
  if (repaired && !(cutOff && cutOffs === 1)) {
1988
2102
  // No report.json after the repair: the run still played, so the notes
@@ -2001,6 +2115,7 @@ async function reportPhase({
2001
2115
  }
2002
2116
 
2003
2117
  repaired = true;
2118
+ transcript.write(scrubSecrets({ kind: 'report_schema_repair', attempt, details: validation.details, evidence_problems: evidenceProblems, missing_sections: missingSections }, secrets));
2004
2119
  messages.push({ role: 'assistant', content: assistantContent(answer) });
2005
2120
  messages.push({
2006
2121
  role: 'user',
@@ -2014,6 +2129,18 @@ async function reportPhase({
2014
2129
  // after the report is settled, so a refusal can cost the check and never
2015
2130
  // the report.
2016
2131
  report = scrubSecrets(report, secrets);
2132
+ const submittedSchemaValid = validator.validate(report).ok;
2133
+ // Preserve the submitted account before attribution or judgement changes it.
2134
+ // Bounded and scrubbed; a truncated audit is explicitly not a full draft.
2135
+ for (const finding of report.findings || []) {
2136
+ const text = JSON.stringify(finding);
2137
+ const evidence = JSON.stringify(finding?.evidence || []);
2138
+ transcript.write({ kind: 'finding_submitted', id: finding?.id || null, stage: submittedSchemaValid ? 'validated_report_before_claim_judgment' : 'unvalidated_report_before_claim_judgment', schema_valid: submittedSchemaValid,
2139
+ ...(text.length <= 24000 ? { finding } : { finding_text: text.slice(0, 24000) }),
2140
+ text_length: text.length, truncated: text.length > 24000,
2141
+ ...(evidence.length <= 12000 ? { evidence: finding?.evidence || [] } : { evidence_text: evidence.slice(0, 12000) }),
2142
+ evidence_length: evidence.length, evidence_truncated: evidence.length > 12000 });
2143
+ }
2017
2144
  // A crash, a freeze or a blank screen the runner saw and the report also
2018
2145
  // names is one finding, counted once, at the moment it happened.
2019
2146
  report = mergeRunnerTwins({ report, honesty, observations, transcript, log });
@@ -2033,7 +2160,7 @@ async function reportPhase({
2033
2160
  let impressions = [];
2034
2161
  if (!shrunk && !play.budgetExceeded) {
2035
2162
  const impressionsAllowed = Boolean(reportSchema && reportSchema.properties && reportSchema.properties.impressions);
2036
- const checked = await checkClaimsAgainstScreenshots({ client, jobId, runId, report, screenshots, runDirectory, ledger, transcript, log, frames, measured: new Set(mergedAnchors(honesty).keys()), observations, notes, index: where, run: eventRun, impressionsAllowed: impressionsAllowed && claimGate !== 'legacy', gate: claimGate });
2163
+ const checked = await checkClaimsAgainstScreenshots({ client, jobId, runId, report, screenshots, runDirectory, ledger, transcript, log, frames, measured: new Set(mergedAnchors(honesty).keys()), observations, notes, index: where, run: eventRun, impressionsAllowed: impressionsAllowed && claimGate !== 'legacy', gate: claimGate, secrets });
2037
2164
  report = checked.report;
2038
2165
  turnedAway = checked.turnedAway;
2039
2166
  impressions = checked.impressions;
@@ -2070,7 +2197,10 @@ async function reportPhase({
2070
2197
  }
2071
2198
  if (normalisedByRunner.length > 0) {
2072
2199
  markdown = appendNormalisedMarkdown(markdown, normalisedByRunner);
2073
- 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(', ')}`);
2200
+ log(`normalised ${normalisedByRunner.length} value(s) the report schema does not allow: ${normalisedByRunner.map(change => `${change.id ? `${change.id} ` : ''}${change.fromType ? change.note : `${change.field} ${JSON.stringify(change.from)} to ${JSON.stringify(change.to)}`}`).join(', ')}`);
2201
+ }
2202
+ if (play.completionAttempts?.some(attempt => !attempt.accepted)) {
2203
+ markdown = replaceSection(markdown, '## Completion statement checks', completionReportNote(play));
2074
2204
  }
2075
2205
  const generatedAt = new Date().toISOString();
2076
2206
  const facts = reportFacts({ persona, driverName, target, play });
@@ -2079,7 +2209,21 @@ async function reportPhase({
2079
2209
  report = fillReportPlaceholders(report, { generatedAt, ...facts });
2080
2210
  // A finding the server would drop for want of an uploaded file it can
2081
2211
  // open gets the screenshot taken where it happened.
2082
- const withShots = attachScreenshotEvidence(report, { screenshots, notes });
2212
+ // A look checked on an exact video frame keeps that frame's observation
2213
+ // through final report indexing. A later generic screenshot cannot replace it.
2214
+ const reportScreenshots = [...screenshots];
2215
+ const retained = new Set((report.findings || []).map(finding => finding.id));
2216
+ const evidenceBindings = new Map(where.filter(entry => retained.has(entry.id)).map(entry => [entry.id, entry]));
2217
+ for (const entry of where) {
2218
+ const frame = frames.get(entry.id);
2219
+ if (retained.has(entry.id) && entry.look && !entry.look_shot && frame?.look && Number.isFinite(entry.look_ms) && Number.isInteger(entry.look_observation)) {
2220
+ reportScreenshots.push({ relativePath: frame.path, observation: entry.look_observation, at: honesty.video.startedAt + frame.video_ms, derived: 'video_frame' });
2221
+ evidenceBindings.set(entry.id, { ...entry, screenshot: frame.path, look_shot: frame.path, look_ms: frame.video_ms,
2222
+ video_ms: frame.video_ms, video: videoTime(frame.video_ms),
2223
+ evidence_source: { ...entry.evidence_source, screenshot: frame.path, at: honesty.video.startedAt + frame.video_ms, derived: 'video_frame' } });
2224
+ }
2225
+ }
2226
+ const withShots = attachScreenshotEvidence(report, { screenshots: reportScreenshots, notes, index: where, frames });
2083
2227
  if (withShots.attached.length > 0) {
2084
2228
  report = withShots.report;
2085
2229
  transcript.write({ kind: 'evidence_attached', findings: withShots.attached });
@@ -2089,7 +2233,7 @@ async function reportPhase({
2089
2233
  // What the runner itself knows goes in last, in fixed sections: its own
2090
2234
  // findings, where to look for every finding, the inputs it could not send,
2091
2235
  // the dialogs and the edge checks.
2092
- const honest = writeHonesty({ report, markdown, honesty, driverName, notes, screenshots, observations });
2236
+ const honest = writeHonesty({ report, markdown, honesty, driverName, notes, screenshots: reportScreenshots, observations, bindings: evidenceBindings });
2093
2237
  report = honest.report;
2094
2238
  markdown = honest.markdown;
2095
2239
  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(', ')}`);
@@ -2152,13 +2296,13 @@ export function mergedAnchors(honesty) {
2152
2296
  * @param {Object} args
2153
2297
  * @returns {{report: Object, markdown: string, added: Array<Object>, index: Array<Object>}}
2154
2298
  */
2155
- export function writeHonesty({ report: given, markdown, honesty, driverName, notes = [], screenshots = [], observations = [] }) {
2299
+ export function writeHonesty({ report: given, markdown, honesty, driverName, notes = [], screenshots = [], observations = [], bindings = new Map() }) {
2156
2300
  if (!honesty || !given) return { report: given, markdown, added: [], index: [] };
2157
2301
  // A report that did not pass through the claim checks (a fallback report) is merged here.
2158
2302
  const report = mergeRunnerTwins({ report: given, honesty, observations });
2159
2303
  const merged = addRunnerFindings(report, honesty.findings);
2160
2304
  for (const [id, anchor] of mergedAnchors(honesty)) merged.anchors.set(id, anchor);
2161
- const located = attachWhereToLook(merged.report, { observations, notes, screenshots, video: honesty.video, anchors: merged.anchors });
2305
+ const located = attachWhereToLook(merged.report, { observations, notes, screenshots, video: honesty.video, anchors: merged.anchors, bindings });
2162
2306
  let text = markdown;
2163
2307
  // The findings as they now stand, with the evidence the pass attached: the
2164
2308
  // ones the persona also reported first, each said once.
@@ -2235,13 +2379,16 @@ export function citedAfterScreenshot(finding, screenshots) {
2235
2379
  * The bounded verification turn of the report step, and the claim judge after
2236
2380
  * it (./judge.js, the hosted runner's rules). Every issue the report names, the
2237
2381
  * most severe first and at most {@link MAX_CLAIM_CHECKS}, is asked about once
2238
- * with the picture of its moment and the hosted runner's own question
2382
+ * per original picture, with the picture of its moment and the hosted runner's own question
2239
2383
  * (./claimwords.js claimText): a claim of what the game did, or that something
2240
2384
  * is missing, is asked whether the GAME is at fault ("game at fault", "as
2241
2385
  * designed", "shows the opposite", "cannot tell"); a matter of taste is asked
2242
2386
  * whether the frame shows what it rests on; a judgement of how a marked canvas
2243
2387
  * game is drawn is asked about the game's own frame. A claim that something is
2244
2388
  * missing is also asked about the screen play was on before it.
2389
+ * The normal judge permits one neutral format repair per finding when an
2390
+ * answer is outside that question's vocabulary. Valid uncertainty is final;
2391
+ * the legacy money-affecting gate keeps its old path.
2245
2392
  *
2246
2393
  * The picture: a judgement made from a look (it cites an observation, a note
2247
2394
  * made on one, or a screenshot) is checked on the screen that look saw, never
@@ -2261,7 +2408,7 @@ export function citedAfterScreenshot(finding, screenshots) {
2261
2408
  *
2262
2409
  * @returns {Promise<{report: Object, turnedAway: Array<Object>, impressions: Array<Object>}>}
2263
2410
  */
2264
- export async function checkClaimsAgainstScreenshots({ client, jobId, runId, report, screenshots, runDirectory, ledger, transcript, log = () => {}, frames = new Map(), measured = new Set(), observations = [], notes = [], index = null, run = null, impressionsAllowed = true, gate = 'judge' }) {
2411
+ export async function checkClaimsAgainstScreenshots({ client, jobId, runId, report, screenshots, runDirectory, ledger, transcript, log = () => {}, frames = new Map(), measured = new Set(), observations = [], notes = [], index = null, run = null, impressionsAllowed = true, gate = 'judge', secrets = [] }) {
2265
2412
  if (!report || !Array.isArray(report.findings)) return { report, turnedAway: [], impressions: [] };
2266
2413
  const placedIndex = Array.isArray(index) ? index : attachWhereToLook(report, { observations, notes, screenshots }).index;
2267
2414
  const where = new Map(placedIndex.map(entry => [entry.id, entry]));
@@ -2288,8 +2435,14 @@ export async function checkClaimsAgainstScreenshots({ client, jobId, runId, repo
2288
2435
  const frame = frames.get(finding.id) || null;
2289
2436
  // A look's own screenshot, else the frame cut at its moment (for a look, the look's moment), else the screenshot it cites, else the one the runner places.
2290
2437
  const lookShot = placed.look && placed.look_shot ? { relativePath: placed.look_shot } : null;
2291
- const shot = lookShot || (frame ? { relativePath: frame.path } : null) || citedAfterScreenshot(finding, screenshots) || (placed.screenshot ? { relativePath: placed.screenshot } : null);
2438
+ const boundFrame = frame && (!placed.look || (frame.look && Number.isFinite(placed.look_ms))) ? { relativePath: frame.path } : null;
2439
+ const shot = placed.look ? (lookShot || boundFrame)
2440
+ : boundFrame || citedAfterScreenshot(finding, screenshots) || (placed.screenshot ? { relativePath: placed.screenshot } : null);
2292
2441
  const on = !lookShot && frame ? { frame: frame.path } : {};
2442
+ transcript.write({ kind: 'finding_evidence_selection', id: finding.id, screenshot: shot?.relativePath || null,
2443
+ source: lookShot ? 'cited_look' : boundFrame ? 'derived_video_frame' : shot ? 'cited_screenshot' : 'unavailable',
2444
+ provenance: placed.evidence_source || null, action: placed.action ?? null,
2445
+ observation: placed.look_observation ?? null, video_ms: lookShot ? placed.look_ms : boundFrame ? frame.video_ms : null });
2293
2446
  if (!shot) { skip(finding, 'no frame of its moment and no cited screenshot'); continue; }
2294
2447
  // A claim that something is missing is asked about the screen play was on before it too.
2295
2448
  const pictures = [shot.relativePath];
@@ -2301,6 +2454,7 @@ export async function checkClaimsAgainstScreenshots({ client, jobId, runId, repo
2301
2454
  }
2302
2455
  const question = claimText(finding, { cls: shape.cls === 'difficulty' ? 'other' : shape.cls, fault: shape.question !== null && shape.question !== 'plain' && shape.question !== 'layout' });
2303
2456
  const answers = [];
2457
+ let formatRepairUsed = false;
2304
2458
  for (const picture of pictures) {
2305
2459
  let data;
2306
2460
  try {
@@ -2309,30 +2463,46 @@ export async function checkClaimsAgainstScreenshots({ client, jobId, runId, repo
2309
2463
  if (picture === shot.relativePath) { skip(finding, 'the picture could not be read', picture, on); answers.length = 0; break; }
2310
2464
  continue;
2311
2465
  }
2312
- let answer;
2313
- const askedAt = Date.now();
2314
- try {
2315
- answer = await callStepWithRetry({
2316
- client,
2317
- jobId,
2318
- runId,
2319
- step: STEPS.personaAct,
2320
- system: CLAIM_SYSTEM,
2321
- messages: [{ role: 'user', content: [
2322
- { type: 'image', source: { type: 'base64', media_type: /\.jpe?g$/i.test(picture) ? 'image/jpeg' : 'image/png', data } },
2323
- { type: 'text', text: question }
2324
- ] }],
2325
- maxTokens: CLAIM_CHECK_MAX_TOKENS,
2326
- escalate: false,
2327
- maxAttempts: 1
2328
- });
2329
- } catch (error) {
2330
- stopped = error instanceof ProxyError && error.isBudget ? 'the run budget is spent' : String(error && error.message ? error.message : error);
2331
- log(`the screenshot check stopped (${stopped}); a claim it did not reach is not confirmed by it.`);
2332
- break;
2466
+ let answer, parsed;
2467
+ const messages = [{ role: 'user', content: [
2468
+ { type: 'image', source: { type: 'base64', media_type: /\.jpe?g$/i.test(picture) ? 'image/jpeg' : 'image/png', data } },
2469
+ { type: 'text', text: question }
2470
+ ] }];
2471
+ for (let attempt = 1; attempt <= 2; attempt++) {
2472
+ const askedAt = Date.now();
2473
+ try {
2474
+ answer = await callStepWithRetry({
2475
+ client,
2476
+ jobId,
2477
+ runId,
2478
+ step: STEPS.personaAct,
2479
+ system: gate === 'legacy' ? CLAIM_SYSTEM : claimCheckSystem(shape.question),
2480
+ messages: [...messages],
2481
+ maxTokens: CLAIM_CHECK_MAX_TOKENS,
2482
+ escalate: false,
2483
+ maxAttempts: 1
2484
+ });
2485
+ } catch (error) {
2486
+ stopped = error instanceof ProxyError && error.isBudget ? 'the run budget is spent' : String(error && error.message ? error.message : error);
2487
+ if (attempt === 2) transcript.write({ kind: 'claim_format_repair_unavailable', id: finding.id, screenshot: picture, reason: scrubSecrets(stopped, secrets).slice(0, 400) });
2488
+ log(`the screenshot check stopped (${stopped}); a claim it did not reach is not confirmed by it.`);
2489
+ break;
2490
+ }
2491
+ if (ledger) ledger.record({ model: answer.model, usage: answer.usage, ms: Date.now() - askedAt });
2492
+ parsed = claimReply(shape.question, answer.text, answer.toolUses);
2493
+ const safeText = scrubSecrets(String(answer.text || ''), secrets);
2494
+ transcript.write({ kind: 'claim_check_attempt', id: finding.id, screenshot: picture, question: shape.question || 'plain', attempt,
2495
+ protocol: gate === 'legacy' ? 'legacy' : 'question_v1', parsed: parsed.says, protocol_valid: parsed.valid, reason: parsed.reason,
2496
+ text: safeText.slice(0, MAX_CLAIM_REPLY_TEXT), text_length: safeText.length, truncated: safeText.length > MAX_CLAIM_REPLY_TEXT,
2497
+ stop_reason: scrubSecrets(String(answer.stopReason || ''), secrets).slice(0, 80) });
2498
+ if (gate === 'legacy' || parsed.valid || formatRepairUsed) break;
2499
+ formatRepairUsed = true;
2500
+ transcript.write({ kind: 'claim_format_repair', id: finding.id, screenshot: picture, question: shape.question || 'plain', reason: parsed.reason });
2501
+ messages.push({ role: 'assistant', content: safeText.slice(0, MAX_CLAIM_REPLY_TEXT) || '[No textual answer was returned.]' },
2502
+ { role: 'user', content: claimFormatRepair(shape.question) });
2333
2503
  }
2334
- if (ledger) ledger.record({ model: answer.model, usage: answer.usage, ms: Date.now() - askedAt });
2335
- const says = claimRead(answer.text) || 'cannot_tell';
2504
+ if (stopped) break;
2505
+ const says = gate === 'legacy' ? claimRead(answer.text) || 'cannot_tell' : parsed.valid ? parsed.says : 'cannot_tell';
2336
2506
  answers.push({ picture, says, message: says === 'as_designed' ? claimMessage(answer.text) : '' });
2337
2507
  // The thing it says is missing is on screen, or the game explained it: nothing more to ask.
2338
2508
  if (says === 'shows_opposite' || says === 'as_designed') break;
@@ -2387,8 +2557,9 @@ export async function checkClaimsAgainstScreenshots({ client, jobId, runId, repo
2387
2557
  *
2388
2558
  * @returns {{system: Array, messages: Array}}
2389
2559
  */
2390
- export function buildReportRequest({ skill, persona, brief, localBrief = {}, intentNotes, driverName, target, runId, jobId, play, notes, observations = [], screenshots, choiceCheck = null, honesty = null }) {
2560
+ export function buildReportRequest({ skill, schemas = [], persona, brief, localBrief = {}, intentNotes, driverName, target, runId, jobId, play, notes, observations = [], screenshots, choiceCheck = null, honesty = null }) {
2391
2561
  const secrets = secretsOf(localBrief);
2562
+ const reportSchema = schemas.find(schema => schema?.name === 'playtest-report')?.content;
2392
2563
  const reportLocal = localBrief && Array.isArray(localBrief.expected_noise) ? { expected_noise: localBrief.expected_noise } : {};
2393
2564
  const system = buildSystem({ skill, persona, brief, localBrief: reportLocal, intentNotes, driverName, target, maxActions: play.actionsTaken, runId });
2394
2565
  const text = [
@@ -2396,6 +2567,10 @@ export function buildReportRequest({ skill, persona, brief, localBrief = {}, int
2396
2567
  `persona: ${persona.slug} driver: ${driverName} target: ${target}`,
2397
2568
  `actions taken: ${play.actionsTaken} stop reason: ${play.quitReason}${play.quitDetail ? ` (${play.quitDetail})` : ''}`,
2398
2569
  '',
2570
+ ...(reportSchema ? [
2571
+ 'The following is the authoritative report.json schema loaded for this run and used by its validator. Write JSON that follows it, including every required finding field. Do not treat the Markdown section headings as extra JSON keys; narrative sections belong in report.md. Preserve narrative content there when correcting a field the schema does not allow.',
2572
+ ''
2573
+ ] : []),
2399
2574
  'Notes you logged, in order:',
2400
2575
  notes.length > 0 ? notes.map((note, i) => noteLine(note, i)).join('\n') : '(none)',
2401
2576
  '',
@@ -2426,12 +2601,18 @@ export function buildReportRequest({ skill, persona, brief, localBrief = {}, int
2426
2601
  ...(capabilityPrompt(driverName, honesty ? honesty.capability.list() : []) ? ['', capabilityPrompt(driverName, honesty ? honesty.capability.list() : [])] : []),
2427
2602
  ...(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')}`] : []),
2428
2603
  '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.',
2429
- '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.',
2604
+ play.completionClaim
2605
+ ? `The persona stopped with this account of completing the brief: ${JSON.stringify(play.completionClaim)}. These are model claims with observation references, not independent verification. Check each against the actual observations, actions and screenshots; do not mark a criterion met merely because play stopped. Say what was verified and what remains uncertain.`
2606
+ : 'A first win or partial goal can be followed by further play in scope. Say in "What worked" how far the session actually got. Distinguish the runner asking for more play from a defect in the game.',
2607
+ ...(play.completionAttempts?.some(attempt => !attempt.accepted) ? [
2608
+ `Completion accounts rejected by the runner: ${JSON.stringify(play.completionAttempts.filter(attempt => !attempt.accepted).map(({ phase, reason }) => ({ phase, reason })))}. An explicit completion attempt may end play after one formatting repair, or before that repair if the existing budget or clock prevents it. This does not establish completion or a game defect. Evaluate each success criterion from the actual recorded observations; state any unverified result and the runner limitation. Do not promote these attempts into findings or proof.`
2609
+ ] : []),
2430
2610
  '',
2431
2611
  '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):',
2432
2612
  networkNoteLines(notes),
2433
2613
  '',
2434
2614
  '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"}.',
2615
+ 'Make each finding one independently supported claim, with a title and description that say the same thing. Describe directly visible content separately from a claim that something fails to change, finish or respond over time. Cite the observation that supports each claim. Do not infer that a game or value is stuck from one still picture. Preserve a temporal claim and its supporting observations when it is what you observed; do not silently replace it with a different static claim. Report only the behavior and content actually observed.',
2435
2616
  '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.',
2436
2617
  '',
2437
2618
  '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".',
@@ -2447,7 +2628,10 @@ export function buildReportRequest({ skill, persona, brief, localBrief = {}, int
2447
2628
  ].join('\n');
2448
2629
  // The prompt is built from notes, observations and the action log; none
2449
2630
  // of them may carry the test account password into the report step.
2450
- return { system, messages: [{ role: 'user', content: [{ type: 'text', text: scrubSecrets(text, secrets) }] }] };
2631
+ return { system, messages: [{ role: 'user', content: [{ type: 'text', text: scrubSecrets(text, secrets) },
2632
+ // This is the public pack contract, not local-account or gameplay data.
2633
+ // Keep its exact keys/constraints identical to the validator's schema.
2634
+ ...(reportSchema ? [{ type: 'text', text: `<report_json_schema>\n${JSON.stringify(reportSchema)}\n</report_json_schema>` }] : [])] }] };
2451
2635
  }
2452
2636
 
2453
2637
  /** What a report turn is told when its ceiling is tight or it was cut off. */
@@ -2893,6 +3077,18 @@ async function finish(outcome, ledger, runDirectory, transcript, heartbeat) {
2893
3077
  return outcome;
2894
3078
  }
2895
3079
 
3080
+ /** Deterministic audit context, never a finding or a completion verdict. */
3081
+ function completionReportNote(play) {
3082
+ if (!play.completionAttempts?.some(attempt => !attempt.accepted)) return '';
3083
+ return [
3084
+ 'The runner rejected these completion accounts: ' + play.completionAttempts.filter(attempt => !attempt.accepted).map(attempt => `${attempt.phase}: ${attempt.reason}`).join('; ') + '.',
3085
+ play.completionClaim
3086
+ ? 'A later account passed the format and observed-step checks. It remains a model claim, not independent verification.'
3087
+ : 'No completion account passed the format and observed-step checks. The stopping decision does not establish success or a defect in the game.',
3088
+ 'The bounded, scrubbed account text and each reason are preserved in transcript.jsonl. Assess the requested results from the recorded evidence.'
3089
+ ].join('\n\n');
3090
+ }
3091
+
2896
3092
  /**
2897
3093
  * The markdown written when there is no model turn left to write a real
2898
3094
  * report with: cancelled, or out of budget. It carries the notes and the
@@ -2935,6 +3131,7 @@ export function renderFallbackMarkdown({ persona, driverName, target, notes, scr
2935
3131
  '## Suggested next step',
2936
3132
  'Run this persona again once the reason above is resolved.',
2937
3133
  '',
3134
+ ...(completionReportNote(play) ? ['## Completion statement checks', completionReportNote(play), ''] : []),
2938
3135
  ...(network.length > 0 ? ['## Network notes', network.map(note => `- ${note.status ? `${note.status} ` : ''}${note.url}`).join('\n'), ''] : []),
2939
3136
  '## Evidence',
2940
3137
  screenshots.length > 0 ? screenshots.map(shot => `- ${shot.relativePath}`).join('\n') : '- (none)',
@@ -3317,15 +3514,25 @@ export function observationLines(observations) {
3317
3514
  * @param {{screenshots: Array<Object>, notes?: Array<Object>}} context
3318
3515
  * @returns {{report: Object, attached: Array<{id: string, ref: string}>}}
3319
3516
  */
3320
- export function attachScreenshotEvidence(report, { screenshots = [], notes = [] } = {}) {
3517
+ export function attachScreenshotEvidence(report, { screenshots = [], notes = [], index = [], frames = new Map() } = {}) {
3321
3518
  // Never a picture the edge checks took after play: it shows another window
3322
3519
  // size or the game after a reload, not what the persona saw.
3323
3520
  const usable = (screenshots || []).filter(shot => shot && typeof shot.relativePath === 'string' && shot.relativePath && !shot.edge);
3521
+ const generic = usable.filter(shot => !shot.derived);
3324
3522
  if (!report || !Array.isArray(report.findings) || usable.length === 0) return { report, attached: [] };
3325
3523
  const known = new Set(usable.map(shot => shot.relativePath));
3524
+ const bound = new Map(index.map(entry => [entry.id, entry]));
3326
3525
  const attached = [];
3327
3526
  const findings = report.findings.map(finding => {
3328
3527
  const evidence = Array.isArray(finding && finding.evidence) ? finding.evidence : [];
3528
+ const placed = bound.get(finding?.id);
3529
+ if (placed?.look) {
3530
+ const frame = frames.get(finding.id);
3531
+ const exact = placed.look_shot || (frame?.look && Number.isFinite(placed.look_ms) ? frame.path : null);
3532
+ if (!exact || !known.has(exact) || evidence.some(item => item?.type === 'screenshot' && item.ref === exact)) return finding;
3533
+ attached.push({ id: finding.id, ref: exact });
3534
+ return { ...finding, evidence: [...evidence, { type: 'screenshot', ref: exact }] };
3535
+ }
3329
3536
  if (evidence.some(item => item && item.type === 'screenshot' && known.has(item.ref))) return finding;
3330
3537
  let latest = null;
3331
3538
  // The picture saved when a cited note was written is the one that shows it.
@@ -3345,10 +3552,11 @@ export function attachScreenshotEvidence(report, { screenshots = [], notes = []
3345
3552
  const at = observation ? Number(observation[1]) : note && notes[Number(note[1]) - 1] ? Number(notes[Number(note[1]) - 1].observation) : null;
3346
3553
  if (Number.isFinite(at) && (latest === null || at > latest)) latest = at;
3347
3554
  }
3348
- const after = latest === null ? [] : usable.filter(shot => Number.isFinite(shot.observation) && shot.observation >= latest);
3555
+ const after = latest === null ? [] : generic.filter(shot => Number.isFinite(shot.observation) && shot.observation >= latest);
3349
3556
  const shot = after.length > 0
3350
3557
  ? after.reduce((best, candidate) => (candidate.observation < best.observation || (candidate.observation === best.observation && (candidate.order ?? 0) < (best.order ?? 0)) ? candidate : best))
3351
- : usable[usable.length - 1];
3558
+ : generic[generic.length - 1];
3559
+ if (!shot) return finding;
3352
3560
  attached.push({ id: finding.id, ref: shot.relativePath });
3353
3561
  return { ...finding, evidence: [...evidence, { type: 'screenshot', ref: shot.relativePath }] };
3354
3562
  });