ravensight-playtest 0.18.0 → 0.19.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 (85) hide show
  1. package/README.md +160 -16
  2. package/addons/desktop/RavensightDesktop.swift +367 -0
  3. package/addons/mobile/UITests/MobileInputTests.swift +67 -1
  4. package/addons/ravensight_driver/driver.gd +557 -4
  5. package/docs/ADAPTERS.md +37 -7
  6. package/docs/DESKTOP.md +117 -0
  7. package/docs/MOBILE.md +30 -3
  8. package/docs/UNITY.md +149 -0
  9. package/docs/UNREAL.md +123 -0
  10. package/docs/godot-driver.md +98 -1
  11. package/package.json +15 -5
  12. package/src/cli.js +26 -10
  13. package/src/commands/build.js +40 -0
  14. package/src/commands/feature.js +1 -1
  15. package/src/commands/hosted.js +78 -9
  16. package/src/commands/run.js +47 -13
  17. package/src/commands/validate.js +1 -1
  18. package/src/hosted/archivePreflight.js +31 -4
  19. package/src/hosted/buildStatus.js +26 -0
  20. package/src/hosted/buildUpload.js +24 -9
  21. package/src/hosted/nativeBuild.js +87 -0
  22. package/src/hosted/recordedRun.js +15 -3
  23. package/src/run/anygame/genre.js +98 -24
  24. package/src/run/anygame/genre2d.js +108 -0
  25. package/src/run/anygame/index.js +7 -4
  26. package/src/run/anygame/scene3d.js +562 -0
  27. package/src/run/anygame/shared-hashes.json +4 -2
  28. package/src/run/anygame/shared.js +3 -3
  29. package/src/run/args.js +15 -4
  30. package/src/run/drivers/desktop/app.js +104 -0
  31. package/src/run/drivers/desktop/common.js +336 -0
  32. package/src/run/drivers/desktop/driver.js +383 -0
  33. package/src/run/drivers/desktop/helper.js +98 -0
  34. package/src/run/drivers/desktop/keys.js +124 -0
  35. package/src/run/drivers/desktop/output.js +107 -0
  36. package/src/run/drivers/desktop/preflight.js +134 -0
  37. package/src/run/drivers/desktop3d.js +106 -0
  38. package/src/run/drivers/desktopSequence.js +72 -0
  39. package/src/run/drivers/godot-3d.js +298 -0
  40. package/src/run/drivers/godot.js +465 -30
  41. package/src/run/drivers/index.js +6 -0
  42. package/src/run/drivers/mobile/adb.js +25 -1
  43. package/src/run/drivers/mobile/frame.js +3 -2
  44. package/src/run/drivers/mobile/gestures.js +76 -0
  45. package/src/run/drivers/mobile/lock.js +51 -11
  46. package/src/run/drivers/mobile/multitouch.js +150 -0
  47. package/src/run/drivers/mobile/native.js +229 -31
  48. package/src/run/drivers/mobile/preflight.js +14 -1
  49. package/src/run/drivers/mobile/target.js +21 -1
  50. package/src/run/drivers/stdio.js +150 -12
  51. package/src/run/drivers/unity/app.js +72 -0
  52. package/src/run/drivers/unity/engine.js +58 -0
  53. package/src/run/drivers/unity/link.js +108 -0
  54. package/src/run/drivers/unity/logs.js +76 -0
  55. package/src/run/drivers/unreal/app.js +40 -0
  56. package/src/run/drivers/unreal/driver.js +686 -0
  57. package/src/run/drivers/unreal/frames.js +243 -0
  58. package/src/run/drivers/unreal/logs.js +276 -0
  59. package/src/run/drivers/unreal/preflight.js +61 -0
  60. package/src/run/drivers/web.js +211 -13
  61. package/src/run/drivers/webdriver.js +79 -12
  62. package/src/run/endScreen.js +88 -0
  63. package/src/run/engineErrors.js +16 -0
  64. package/src/run/featureLoop.js +1 -1
  65. package/src/run/fingers.js +99 -0
  66. package/src/run/focusForKeys.js +54 -0
  67. package/src/run/godotTesterProbes.js +21 -2
  68. package/src/run/honesty.js +11 -1
  69. package/src/run/inputs.js +3 -3
  70. package/src/run/intent.js +12 -0
  71. package/src/run/pauseHook.js +494 -0
  72. package/src/run/personaLoop.js +139 -10
  73. package/src/run/pixels.js +22 -10
  74. package/src/run/planGuard.js +103 -0
  75. package/src/run/replay.js +5 -1
  76. package/src/run/reportChecks.js +17 -4
  77. package/src/run/resume.js +6 -2
  78. package/src/run/sessions.js +170 -0
  79. package/src/run/startFrom.js +415 -0
  80. package/src/run/testerProbes.js +36 -5
  81. package/src/run/tools.js +191 -10
  82. package/src/run/view3dState.js +125 -0
  83. package/src/run/web3d.js +375 -0
  84. package/src/run/world3d.js +164 -0
  85. package/templates/godot-3d/README.md +3 -2
@@ -16,7 +16,7 @@ import { createPlayClock, clockStopDetail, timeLeftAside } from './playClock.js'
16
16
  import { appendNormalisedMarkdown, checkEvidence, createReportValidator, lintMarkdownSections, normaliseEnums, normaliseEvidence, normaliseReproSteps, repairInstruction, REQUIRED_MARKDOWN_SECTIONS, stampReport, stripTrailingToolMarkup, writeReportFiles } from './report.js';
17
17
  import { assertNoSecrets, scanForSecrets } from './secretScan.js';
18
18
  import { redactText } from './redaction.js';
19
- import { ACTION_TOOLS, NEW_TOOL_NAMES, REPORT_TOOLS, executeTool, expectationOf, modelFrameOf, toolResult, toolsFor, NEWEST_TOOL_NAMES } from './tools.js';
19
+ import { ACTION_TOOLS, NEW_TOOL_NAMES, REPORT_TOOLS, executeTool, expectationOf, modelFrameOf, toolResult, toolsFor, NEWEST_TOOL_NAMES, SENSOR_TOOL_NAMES } from './tools.js';
20
20
  import {
21
21
  CAPABILITY_HEADING, DIALOGS_HEADING, EVIDENCE_HEADING, MAX_WIN_CONTINUES, RUNNER_FINDINGS_HEADING, WIN_TEXT,
22
22
  addRunnerFindings, attachWhereToLook, uniqueFindingIds, blankFinding, capabilityPrompt, createBlankWatch, createCapabilityLedger, describeInput, dialogNote, gameEndedFinding, gameEndedOf, mergeRunnerDuplicates,
@@ -28,6 +28,10 @@ import { createTesterLedger, testerFindings, testedMarkdown, TESTED_HEADING } fr
28
28
  import { runTesterProbes, probeFindings, probesMarkdown, probeObserver, PROBES_HEADING } from './testerProbes.js';
29
29
  import { avoidLinesOf } from './avoid.js';
30
30
  import { runGodotTesterProbes, godotProbesMarkdown } from './godotTesterProbes.js';
31
+ // [native hooks] Several sessions in one run, and a plan's steps checked one by one (./sessions.js, ./planGuard.js).
32
+ import { createSessions, sessionTurn, notRestartedFinding } from './sessions.js';
33
+ import { createPlanGuard, notPlayedText } from './planGuard.js';
34
+ import { startRecord, startReportLine, withStartLine } from './startFrom.js';
31
35
  import { runGodotEdgePass } from './godotEdgePass.js';
32
36
  import { recordingMetadata, saveRecording } from './drivers/recording.js';
33
37
  import { createTranscript } from './transcript.js';
@@ -106,6 +110,32 @@ const nextOrder = () => {
106
110
  * `status: 401`, `statusCode=403`, `401 Unauthorized`. A missing asset or a
107
111
  * refused call, not a crash.
108
112
  */
113
+ /** The time a replay of a local Unreal run gets for starting the game, on top of its share of play time, per replay. */
114
+ export const UNREAL_REPLAY_LAUNCH_MS = 30000;
115
+
116
+ /** Drivers whose findings are replayed by launching the build again and playing the recorded inputs with no model (./reportChecks.js replayWebFindings). */
117
+ export const REPLAY_DRIVERS = Object.freeze(['playwright_web', 'unreal_driver', 'unity_driver', 'desktop_driver']);
118
+
119
+ /**
120
+ * The replay's check for a finding the game's own 3D state measured
121
+ * (./world3d.js): the same finding filed again by the replay's own watch by
122
+ * the time its input is replayed. Null for any other finding, which the
123
+ * screen decides.
124
+ *
125
+ * @param {Array<Object>} findings the run's own findings, with their runner keys
126
+ */
127
+ export function worldStateCheck(findings = []) {
128
+ const measured = new Set(findings.filter(finding => finding && finding.runner && String(finding.runner.key).startsWith('world:')).map(finding => finding.title));
129
+ if (measured.size === 0) return null;
130
+ return (replayDriver, finding) => {
131
+ if (!finding || !measured.has(finding.title) || !replayDriver || typeof replayDriver.worldFindings !== 'function') return null;
132
+ const again = replayDriver.worldFindings({ actionRecords: [] }).some(item => item.title === finding.title);
133
+ return again
134
+ ? { verdict: 'match', detail: 'the game\'s own 3D state showed the same thing again when the recorded inputs were replayed' }
135
+ : { verdict: 'no_match', detail: 'the game\'s own 3D state did not show it again when the recorded inputs were replayed' };
136
+ };
137
+ }
138
+
109
139
  export const RESOURCE_4XX = /Failed to load resource: the server responded with a status of 4\d\d|\bHTTP 4\d\d\b|status(?:Code)?\s*[:=]?\s*4\d\d\b|\b4\d\d (?:Unauthorized|Forbidden|Not Found|Bad Request)\b/i;
110
140
 
111
141
  /** The screenshots the runner takes on its own, which no persona described. */
@@ -387,8 +417,15 @@ export async function runPersona(args) {
387
417
  // What the brief asks the run to stay out of: the driver refuses an input on it, whoever chose the input (./avoid.js).
388
418
  if (typeof driver.setAvoid === 'function') driver.setAvoid(avoidLinesOf(brief));
389
419
  await driver.launch({ target, runDir: runDirectory, recordVideo, viewport, signal: args.signal });
420
+ // [native hooks] Where the run started (./startFrom.js): what was placed, the spec, and what the game said it loaded.
421
+ const startAnswer = driver.startAnswer || null;
422
+ const startRec = driver.start ? startRecord(driver.start) : startAnswer && startAnswer.record ? startAnswer.record : null;
423
+ if (startRec) {
424
+ honesty.start = { record: startRec, answer: startAnswer };
425
+ transcript.write({ kind: 'start_from', ...startRec, answer: startAnswer ? { ...startAnswer, record: undefined } : null });
426
+ }
390
427
  // A web run keeps its inputs, in this process only, so its findings can be replayed after the report.
391
- if (driverName === 'playwright_web' && typeof args.replayDriver === 'function' && args.replayFindings !== false) traceWebInputs(driver, { fingerprint: pngFingerprint });
428
+ if (REPLAY_DRIVERS.includes(driverName) && typeof args.replayDriver === 'function' && args.replayFindings !== false) traceWebInputs(driver, { fingerprint: pngFingerprint });
392
429
  await advance('playing');
393
430
 
394
431
  const play = await playLoop({
@@ -419,7 +456,7 @@ export async function runPersona(args) {
419
456
  // When the recording began, read before the driver is stopped: a finding's
420
457
  // video time is measured from it.
421
458
  const recordingStartedAt = typeof driver.recordingStartedAt === 'function' ? driver.recordingStartedAt() : null;
422
- await driverStop(driver, outcome, log, play.canceled ? 'canceled' : play.gameEnded ? 'game_crashed' : 'completed');
459
+ await driverStop(driver, outcome, log, play.canceled ? 'canceled' : play.gameEnded ? 'game_crashed' : 'completed', transcript);
423
460
  if (outcome.videoPath && Number.isFinite(recordingStartedAt)) {
424
461
  honesty.video = { startedAt: recordingStartedAt, file: path.basename(outcome.videoPath), ...(outcome.recording && Number.isFinite(outcome.recording.durationMs) ? { durationMs: outcome.recording.durationMs } : {}) };
425
462
  }
@@ -502,7 +539,11 @@ export async function runPersona(args) {
502
539
  // already had watched is written as it was (only the judge's watched claims say nothing happens by their words).
503
540
  ...(webReplay ? { watch: webReplay.watch } : {}), prior: watchedFor(written.report, watchedStill),
504
541
  // [tester hook] The probes that found something are run once more at the end of this one replay (./testerProbes.js probeObserver).
505
- observer: probeObserver({ probes: honesty.probes, report: written.report, actionRecords, signal: args.signal }) })
542
+ observer: probeObserver({ probes: honesty.probes, report: written.report, actionRecords, signal: args.signal }),
543
+ // A 3D finding of the game's own state (./world3d.js) is checked against the replay's own watch, not the screen.
544
+ stateCheck: worldStateCheck(honesty.findings),
545
+ // A packaged native game takes seconds to start before its first replayed input.
546
+ ...(['unreal_driver', 'unity_driver', 'desktop_driver'].includes(driverName) ? { launchAllowanceMs: UNREAL_REPLAY_LAUNCH_MS } : {}) })
506
547
  : replayFindings({ report: written.report, index: written.index || [], traceSteps: honesty.traceSteps, runDirectory, driver, playMs, transcript, signal: args.signal });
507
548
  await replayed
508
549
  .then(pass => {
@@ -545,7 +586,7 @@ export async function runPersona(args) {
545
586
  // screenshots and avoided inputs can be logged without spending an action.
546
587
  outcome.actionsTaken = actionRecords.reduce((count, record) => record?.kind === 'action' && Number.isSafeInteger(record.actions)
547
588
  ? Math.max(count, record.actions) : count, outcome.actionsTaken || 0);
548
- await driverStop(driver, outcome, log, args.signal?.aborted ? 'canceled' : 'failed');
589
+ await driverStop(driver, outcome, log, args.signal?.aborted ? 'canceled' : 'failed', transcript);
549
590
  if (error instanceof ProxyError && error.isBudget) {
550
591
  outcome.state = 'budget_exceeded';
551
592
  outcome.quitReason = 'cost_cap';
@@ -920,6 +961,8 @@ async function playLoop({
920
961
  // The run's clock, for a run sold by the minute (./playClock.js): seconds of
921
962
  // play, and the wall clock the server stops serving the run at.
922
963
  playClock: clockLimits = null,
964
+ // How many sessions the run is played as, each a launch of the game (./sessions.js).
965
+ sessions: sessionCount = 1,
923
966
  log = () => {}
924
967
  }) {
925
968
  const system = buildSystem({ skill, persona, brief, localBrief, intentNotes, driverName, target, maxActions, runId });
@@ -930,7 +973,7 @@ async function playLoop({
930
973
  const noisePatterns = (localBrief && Array.isArray(localBrief.expected_noise)) ? localBrief.expected_noise : [];
931
974
  // any-game hook: one notebook a run, on the honesty record so the report step reads the same one.
932
975
  const briefFields = brief && brief.fields && typeof brief.fields === 'object' ? brief.fields : brief || {};
933
- const anyGame = honesty.anygame || (honesty.anygame = createLocalAnyGame({ briefText: briefForPrompt(brief), controls: briefFields.build_notes && typeof briefFields.build_notes.controls === 'string' ? briefFields.build_notes.controls : null, touch: Boolean(driver && driver.touch), reportLanguageHint: briefFields.play && typeof briefFields.play.report_language === 'string' ? briefFields.play.report_language : null, continuousTime: driver?.inputProfile === 'native-mobile' && driver.frozenBetweenActions === false, driverName: typeof driver.soundSelfTest === 'function' ? '' : driverName, selfNotes: Boolean(earlierMemory) && earlierMemory.self !== false }));
976
+ const anyGame = honesty.anygame || (honesty.anygame = createLocalAnyGame({ briefText: briefForPrompt(brief), controls: briefFields.build_notes && typeof briefFields.build_notes.controls === 'string' ? briefFields.build_notes.controls : null, touch: Boolean(driver && driver.touch), reportLanguageHint: briefFields.play && typeof briefFields.play.report_language === 'string' ? briefFields.play.report_language : null, continuousTime: driver?.inputProfile === 'native-mobile' && driver.frozenBetweenActions === false, driverName: typeof driver.soundSelfTest === 'function' ? '' : driverName, selfNotes: Boolean(earlierMemory) && earlierMemory.self !== false, is3d: () => Boolean(driver && driver.scene3d) }));
934
977
  system.push({ type: 'text', text: anyGame.systemText() });
935
978
  // The intent check (./intent.js): one watch a run, on the honesty record so the report step reads the same one. Every answer,
936
979
  // miss and refused repeat is a line of the step log.
@@ -956,7 +999,10 @@ async function playLoop({
956
999
  // pinch and gamepad are newer still: a server may allow the pointer tools
957
1000
  // and not yet these two, so they are given up first, on their own.
958
1001
  let newestTools = true;
959
- const toolsNow = () => controllerTools(toolsFor(driver, { newTools, newestTools }));
1002
+ // tilt is newer again: a server may allow every touch tool and not yet the
1003
+ // device's motion sensor, so it alone is given up first.
1004
+ let sensorTools = true;
1005
+ const toolsNow = () => controllerTools(toolsFor(driver, { newTools, newestTools, sensorTools: newestTools && sensorTools }));
960
1006
  // The tools a driver offers can grow during play (the gamepad, once the
961
1007
  // page has looked for one): the names it offers now, to notice when.
962
1008
  const offeredNow = () => (Array.isArray(driver && driver.pointerTools) ? driver.pointerTools.join(',') : '');
@@ -1020,6 +1066,10 @@ async function playLoop({
1020
1066
  let declinedEnded = false;
1021
1067
  // The clock a run sold by the minute stops on; never stops a run with no limit.
1022
1068
  const clock = createPlayClock({ ...(clockLimits || {}) });
1069
+ // [native hooks] The sessions share the run's own budget and clock; the plan guard asks no model anything.
1070
+ const sessions = createSessions({ count: sessionCount, maxActions, playSeconds: clockLimits && clockLimits.playSeconds });
1071
+ const planGuard = createPlanGuard();
1072
+ let planScene = null;
1023
1073
  let clockStopped = false;
1024
1074
  let timeLeftSaid = false;
1025
1075
  // Inputs that changed nothing, by the screen they were tried on, so a stuck
@@ -1110,6 +1160,7 @@ async function playLoop({
1110
1160
  };
1111
1161
 
1112
1162
  const first = await driver.observe();
1163
+ planScene = first && first.scene ? first.scene : null;
1113
1164
  observed(first);
1114
1165
  anyGame.seeScreen(first.text);
1115
1166
  latestObservation = first.text;
@@ -1189,9 +1240,26 @@ async function playLoop({
1189
1240
  imageBudget = next;
1190
1241
  }
1191
1242
  });
1243
+ // A server from before tilt: play on without it, and say so. Any other
1244
+ // refusal, or a second one, goes on to the fallbacks below.
1245
+ const askActWithSensors = async () => {
1246
+ try {
1247
+ return await askAct();
1248
+ } catch (error) {
1249
+ const offersSensors = playTools.some(tool => SENSOR_TOOL_NAMES.includes(tool.name));
1250
+ if (completionRepairPending || !(error instanceof ProxyError) || error.code !== 'tool_not_allowed' || !sensorTools || !offersSensors) throw error;
1251
+ sensorTools = false;
1252
+ playTools = toolsNow();
1253
+ const dropped = SENSOR_TOOL_NAMES.filter(name => Array.isArray(driver.pointerTools) && driver.pointerTools.includes(name));
1254
+ 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` });
1255
+ transcript.write({ kind: 'tools_fallback', dropped, message: String(error.message || '') });
1256
+ log(`the server does not allow ${dropped.join(' or ')} yet (${error.message}); playing on without ${dropped.length === 1 ? 'it' : 'them'}.`);
1257
+ return askAct();
1258
+ }
1259
+ };
1192
1260
  try {
1193
1261
  try {
1194
- answer = await askAct();
1262
+ answer = await askActWithSensors();
1195
1263
  } catch (error) {
1196
1264
  // The provider refused the body. Every tool_result is already made
1197
1265
  // valid before it is sent (./context.js), so this is a shape nobody
@@ -1441,9 +1509,16 @@ async function playLoop({
1441
1509
  let screenChangedThisTurn = false;
1442
1510
  // The playtester's answer about its last input is read from this turn's calls until one of them plays an input (./intent.js).
1443
1511
  let answerOpen = true;
1512
+ planGuard.begin(answer.toolUses.filter(tool => ACTION_TOOLS.includes(tool.name) && !tool.malformed && (!selection || tool.id === selection.toolId)).length);
1444
1513
  for (const toolUse of answer.toolUses) {
1445
1514
  if (argsSignal?.aborted || heartbeat?.canceled) { canceled = true; quitReason = 'error'; quitDetail = 'the job was cancelled'; break; }
1446
1515
  if (selection && toolUse.id !== selection.toolId) { results.push({ type: 'tool_result', tool_use_id: toolUse.id, content: 'Alternative not selected. No action executed.' }); continue; }
1516
+ // [native hooks] A step of a plan whose earlier step the frame contradicted is not sent (./planGuard.js).
1517
+ if (ACTION_TOOLS.includes(toolUse.name) && planGuard.stopped) {
1518
+ results.push(toolResult(toolUse.id, notPlayedText(planGuard.stopped, planGuard.stopped.after)));
1519
+ transcript.write({ kind: 'action_not_played', tool: toolUse.name, reason: 'plan_stopped', stop: planGuard.stopped.reason });
1520
+ continue;
1521
+ }
1447
1522
  // One turn can send many actions, and the budget is a promise to the
1448
1523
  // developer about all of them, so it is checked per action. Every tool_use
1449
1524
  // still needs its tool_result, or the next message would be refused.
@@ -1476,6 +1551,7 @@ async function playLoop({
1476
1551
  }
1477
1552
  const notesBefore = notes.length;
1478
1553
  const screenBefore = latestObservation;
1554
+ const deathsBefore = Number.isFinite(driver.deaths) ? driver.deaths : null;
1479
1555
  // A note about something wrong is about the screen as it is now, before
1480
1556
  // this call changes it: that screen is saved, so the finding it becomes
1481
1557
  // can cite the moment and not the next screenshot that happened along.
@@ -1532,6 +1608,12 @@ async function playLoop({
1532
1608
  if (ACTION_TOOLS.includes(toolUse.name) || toolUse.name === 'wait') clock.ran(Date.now() - ranAt);
1533
1609
  results.push(executed.result);
1534
1610
  if (executed.spentAction) actions += 1;
1611
+ if (ACTION_TOOLS.includes(toolUse.name) && !toolUse.malformed) {
1612
+ const sceneAfter = executed.observation && executed.observation.scene ? executed.observation.scene : planScene;
1613
+ const stop = planGuard.played({ executed, expected: expectationOf(toolUse.input), sceneBefore: planScene, sceneAfter, deathsBefore, deathsAfter: Number.isFinite(driver.deaths) ? driver.deaths : null });
1614
+ planScene = sceneAfter;
1615
+ if (stop) transcript.write({ kind: 'plan_stop', after_step: stop.after, reason: stop.reason, detail: stop.detail, action: actions });
1616
+ }
1535
1617
  if (executed.changed && ACTION_TOOLS.includes(toolUse.name)) screenChangedThisTurn = true;
1536
1618
  const actionLine = {
1537
1619
  kind: 'action',
@@ -1560,6 +1642,8 @@ async function playLoop({
1560
1642
  }
1561
1643
  if (honesty.traceSteps && Number.isInteger(actionLine.trace_steps)) honesty.traceSteps.set(actions, actionLine.trace_steps);
1562
1644
  if (honesty.tester) honesty.tester.acted(actionLine); // [tester hook]
1645
+ // A 3D game's own state after this input (./world3d.js): the watch learns the input's action number.
1646
+ if (typeof driver.worldActed === 'function') driver.worldActed(actionLine);
1563
1647
  if (executed.unsupported && honesty.capability.add(executed.unsupported)) {
1564
1648
  transcript.write({ kind: 'capability_note', input: executed.unsupported.input, reason: executed.unsupported.reason });
1565
1649
  }
@@ -1654,6 +1738,25 @@ async function playLoop({
1654
1738
  onProgress({ phase: 'playing', persona: persona.slug, actions, maxActions, tool: toolUse.name });
1655
1739
  }
1656
1740
 
1741
+ // [native hooks] The end of a session: the game is closed and started again on its own saved data (./sessions.js).
1742
+ const sessionNow = gameEnded || canceled ? {} : await sessionTurn({ sessions, driver, actions, playedSeconds: clock.read().play_seconds, transcript, log });
1743
+ if (sessionNow.failed) {
1744
+ const last = [...screenshots].reverse().find(entry => entry && entry.relativePath);
1745
+ const finding = notRestartedFinding(sessionNow.failed, { actionRecords, screenshot: last ? last.relativePath : null, action: actions, at: Date.now() });
1746
+ honesty.findings.push(finding);
1747
+ transcript.write({ kind: 'runner_finding', key: 'game_not_restarted', title: finding.title, action: actions });
1748
+ quitReason = 'blocker';
1749
+ quitDetail = `the game did not start again for session ${sessions.current + 1}`;
1750
+ break;
1751
+ }
1752
+ if (sessionNow.observation) {
1753
+ observed(sessionNow.observation);
1754
+ latestObservation = sessionNow.observation.text;
1755
+ visualObservation = Boolean(sessionNow.observation.screenshotBase64);
1756
+ planScene = sessionNow.observation.scene || null;
1757
+ transcript.write({ kind: 'observation', step: sessionNow.observation.step, text: sessionNow.observation.text, url: sessionNow.observation.url, ...seenScreen(sessionNow.observation.text, sessionNow.observation.url, false) });
1758
+ }
1759
+
1657
1760
  if (gameEnded) {
1658
1761
  const errors = typeof driver.consoleErrors === 'function' ? await Promise.resolve().then(() => driver.consoleErrors()).catch(() => []) : [];
1659
1762
  // A frozen page can often still be photographed; a crashed one cannot.
@@ -1737,6 +1840,7 @@ async function playLoop({
1737
1840
  transcript.write({ kind: 'note', note: scrubSecrets(note, secrets) });
1738
1841
  }
1739
1842
 
1843
+ if (sessionNow.aside && !sessionNow.observation) asides.push(sessionNow.aside);
1740
1844
  if (!timeLeftSaid && clock.nearlyDue()) {
1741
1845
  timeLeftSaid = true;
1742
1846
  asides.push(timeLeftAside(clock.read()));
@@ -1771,6 +1875,11 @@ async function playLoop({
1771
1875
  // The picture goes last, outside the tool results, so the cache
1772
1876
  // breakpoint can sit before it (withPlayCacheBreakpoint).
1773
1877
  const hoisted = hoistImages(results);
1878
+ // [native hooks] After a relaunch the picture is the game as it started again, said with the screen's text.
1879
+ if (sessionNow.observation) {
1880
+ asides.push(`${sessionNow.aside}\nstep ${sessionNow.observation.step}\n${sessionNow.observation.text}`);
1881
+ hoisted.image = sessionNow.observation.screenshotBase64 ? { type: 'image', source: { type: 'base64', media_type: sessionNow.observation.screenshotMediaType || 'image/png', data: sessionNow.observation.screenshotBase64 } } : null;
1882
+ }
1774
1883
  messages.push({
1775
1884
  role: 'user',
1776
1885
  content: [
@@ -1836,6 +1945,8 @@ async function playLoop({
1836
1945
  }
1837
1946
  transcript.write({ kind: 'capture_check', inputs: pictures.inputs, pictures: pictures.pictures, stale: pictures.stretches.map(stretch => ({ from: stretch.from, to: stretch.to, inputs: stretch.inputs, shows_action: stretch.freshAction })), stale_screenshots: screenshots.filter(shot => shot.stale).map(shot => shot.relativePath) });
1838
1947
  for (const note of captureNotes(pictures)) if (honesty.capability.add(note)) transcript.write({ kind: 'capability_note', input: note.input, reason: note.reason });
1948
+ transcript.write({ kind: 'plan_guard', ...planGuard.summary(), sessions: sessions.total, sessions_played: sessions.current });
1949
+ if (sessions.total > 1) honesty.sessions = { total: sessions.total, played: sessions.current };
1839
1950
  transcript.write({ kind: 'play_summary', actions, turns, observations: observations.length, screenshots: screenshots.length, distinct_screens: keeper.distinctScreens, distinct_pictures: pictures.pictures, scenes: keeper.scenes, model_declined: declined, clock: clock.read() });
1840
1951
  // The last screen as the model is shown it, for the brief choice check.
1841
1952
  const finalFrame = brief && !gameEnded ? await modelFrameOf(driver) : null;
@@ -1931,6 +2042,11 @@ async function playLoop({
1931
2042
  log(`the edge behaviour checks did not finish: ${String(error && error.message)}`);
1932
2043
  }
1933
2044
  }
2045
+ // What a 3D game's own state showed in play (./world3d.js): a fall out of the world, a player stuck on geometry, a camera
2046
+ // inside a wall or upside down, moves that got nowhere. Read from the game's numbers, with no model call.
2047
+ if (driver && typeof driver.worldFindings === 'function') {
2048
+ for (const finding of driver.worldFindings({ 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 }); }
2049
+ }
1934
2050
  // [tester hook] What the runner's own ledger saw break a rule during play.
1935
2051
  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 }); }
1936
2052
  // The game's own events: every check after play is done, so the SDK is asked to send what it still holds before the page closes.
@@ -2443,6 +2559,9 @@ async function reportPhase({
2443
2559
  transcript.write({ kind: 'played_scope', line: scope.line });
2444
2560
  log(`what was played: ${scope.line}`);
2445
2561
  }
2562
+ // [native hooks] Where the run started and how many sessions it played, under the same stamp (./startFrom.js).
2563
+ const startLine = honesty && (honesty.start || honesty.sessions) ? startReportLine({ ...(honesty.start || {}), sessions: honesty.sessions || null }) : null;
2564
+ if (startLine) markdown = withStartLine(markdown, startLine);
2446
2565
  // The in-character section held to the record: a sentence the record or the frames show otherwise is left out, and the
2447
2566
  // record's own fact said instead.
2448
2567
  const heldBack = holdInCharacter(markdown, { families: honesty && honesty.intent ? honesty.intent.families() : [], movedAtAll: couldMove(play.records), turnedAway, repeats: repeatsTurnedAway });
@@ -2539,7 +2658,7 @@ export function scopeForUsage(scope) {
2539
2658
  */
2540
2659
  export function couldMove(records) {
2541
2660
  return (Array.isArray(records) ? records : []).some(record => record && record.kind === 'action' && record.ok
2542
- && (movementInput(record.tool, record.input || {}) || ['click', 'hover', 'drag', 'swipe', 'gamepad', 'pinch'].includes(record.tool)));
2661
+ && (movementInput(record.tool, record.input || {}) || ['click', 'hover', 'drag', 'swipe', 'gamepad', 'pinch', 'touches'].includes(record.tool)));
2543
2662
  }
2544
2663
 
2545
2664
  /**
@@ -3435,10 +3554,20 @@ export async function safeScreenshot(driver, name, screenshots, transcript, obse
3435
3554
  }
3436
3555
  }
3437
3556
 
3438
- async function driverStop(driver, outcome, log, reason) {
3557
+ async function driverStop(driver, outcome, log, reason, transcript = null) {
3439
3558
  try {
3440
3559
  const stopped = await driver.stop({ reason });
3441
3560
  if (stopped?.recording) outcome.recording = stopped.recording;
3561
+ // The SDK pause hook (./pauseHook.js): what the game said, never the nonce.
3562
+ if (stopped?.timeControl) {
3563
+ outcome.timeControl = stopped.timeControl;
3564
+ // Into the uploaded step log too, so the report can say whether the game was paused (the summary never holds the nonce).
3565
+ if (transcript && typeof transcript.write === 'function') {
3566
+ try { transcript.write({ kind: 'time_control', ...stopped.timeControl }); } catch { /* the step log is closed: the outcome still has it */ }
3567
+ }
3568
+ if (stopped.timeControl.used) log(`the game's SDK paused it between decisions (${stopped.timeControl.pause_mode}; unscaled time ${String(stopped.timeControl.unscaled_time).replace('_', ' ')}${stopped.timeControl.auto_resumed ? `; resumed on its own ${stopped.timeControl.auto_resumed} times` : ''}${stopped.timeControl.auto_resume_refused ? `; the game's own handler refused ${stopped.timeControl.auto_resume_refused} of those resumes, so it may have stayed frozen` : ''}).`);
3569
+ else if (stopped.timeControl.hook && stopped.timeControl.pause_mode === 'none') log("the game's SDK offered the pause hook but the game registered no time handler, so it ran in real time.");
3570
+ }
3442
3571
  if (stopped && stopped.videoPath) outcome.videoPath = stopped.videoPath;
3443
3572
  // A default recording that could not be made here is said once, with why.
3444
3573
  if (stopped && stopped.recordingSkipped && !stopped.videoPath) {
package/src/run/pixels.js CHANGED
@@ -8,9 +8,11 @@
8
8
  // on both sides: a caret (about 2 by 30 pixels) is neither, one typed character
9
9
  // (about 10 by 16) is.
10
10
  //
11
- // The decoder reads the 8-bit, non-interlaced RGB and RGBA PNGs that Chromium
12
- // and Godot write. Anything else answers null, and every caller falls back to
13
- // the bytes.
11
+ // The decoder reads the non-interlaced RGB and RGBA PNGs that Chromium and
12
+ // Godot write (8 bits a channel) and that Flutter's Impeller writes on macOS
13
+ // (16 bits a channel, read as their high byte: a game's own frame from the
14
+ // Flutter SDK, measured). Anything else answers null, and every caller falls
15
+ // back to the bytes.
14
16
  import { createHash } from 'node:crypto';
15
17
  import zlib from 'node:zlib';
16
18
 
@@ -21,7 +23,8 @@ export const MAX_PIXELS = 4096 * 4096;
21
23
 
22
24
  /**
23
25
  * @param {Buffer} buf
24
- * @returns {{width: number, height: number, channels: number, data: Buffer}|null}
26
+ * @returns {{width: number, height: number, channels: number, depth: number, data: Buffer}|null} 8 bits a channel in
27
+ * `data` whatever the PNG's own `depth`
25
28
  */
26
29
  export function decodePng(buf) {
27
30
  if (!Buffer.isBuffer(buf) || buf.length < 33 || !buf.subarray(0, 8).equals(SIGNATURE)) return null;
@@ -29,6 +32,7 @@ export function decodePng(buf) {
29
32
  let width = 0;
30
33
  let height = 0;
31
34
  let channels = 0;
35
+ let depth = 8;
32
36
  const idat = [];
33
37
  while (off + 8 <= buf.length) {
34
38
  const len = buf.readUInt32BE(off);
@@ -38,10 +42,10 @@ export function decodePng(buf) {
38
42
  if (body.length < 13) return null;
39
43
  width = body.readUInt32BE(0);
40
44
  height = body.readUInt32BE(4);
41
- const depth = body[8];
45
+ depth = body[8];
42
46
  const colour = body[9];
43
47
  const interlace = body[12];
44
- if (depth !== 8 || interlace !== 0 || ![2, 6].includes(colour)) return null;
48
+ if (![8, 16].includes(depth) || interlace !== 0 || ![2, 6].includes(colour)) return null;
45
49
  if (width * height > MAX_PIXELS) return null;
46
50
  channels = colour === 6 ? 4 : 3;
47
51
  } else if (type === 'IDAT') idat.push(body);
@@ -55,7 +59,9 @@ export function decodePng(buf) {
55
59
  } catch {
56
60
  return null;
57
61
  }
58
- const stride = width * channels;
62
+ // Filters work on bytes, a whole pixel apart: 2 bytes a channel at 16 bits.
63
+ const bpp = channels * (depth / 8);
64
+ const stride = width * bpp;
59
65
  if (raw.length < height * (stride + 1)) return null;
60
66
  const data = Buffer.alloc(height * stride);
61
67
  for (let y = 0; y < height; y += 1) {
@@ -64,9 +70,9 @@ export function decodePng(buf) {
64
70
  const out = data.subarray(y * stride, (y + 1) * stride);
65
71
  const prev = y ? data.subarray((y - 1) * stride, y * stride) : null;
66
72
  for (let x = 0; x < stride; x += 1) {
67
- const a = x >= channels ? out[x - channels] : 0;
73
+ const a = x >= bpp ? out[x - bpp] : 0;
68
74
  const b = prev ? prev[x] : 0;
69
- const c = prev && x >= channels ? prev[x - channels] : 0;
75
+ const c = prev && x >= bpp ? prev[x - bpp] : 0;
70
76
  let v = line[x];
71
77
  if (filter === 1) v += a;
72
78
  else if (filter === 2) v += b;
@@ -81,7 +87,13 @@ export function decodePng(buf) {
81
87
  out[x] = v & 0xff;
82
88
  }
83
89
  }
84
- return { width, height, channels, data };
90
+ if (depth === 16) {
91
+ // Each channel's high byte: 8 bits a channel from here on.
92
+ const narrow = Buffer.alloc(width * height * channels);
93
+ for (let i = 0; i < narrow.length; i += 1) narrow[i] = data[i * 2];
94
+ return { width, height, channels, depth, data: narrow };
95
+ }
96
+ return { width, height, channels, depth, data };
85
97
  }
86
98
 
87
99
  export const BLOCK = 4;
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Faster decisions: one model turn plans several inputs, the runner plays
3
+ * them back to back, and each is checked against the frame after it before
4
+ * the next is sent. docs/hosted-direct/NATIVE_GPU_PLAN.md section 4c in the
5
+ * platform repository is the design; this is the local half.
6
+ *
7
+ * A turn that sends several inputs already plays them in order (the persona
8
+ * loop, one model call for all of them), and on a game that stands still
9
+ * between inputs the model's thinking costs no game time. What was missing
10
+ * is the check between them: a plan of "jump, run right, jump" went on
11
+ * running right after the first jump landed the character in a pit, and a
12
+ * click planned for a menu landed on the level that replaced it. This file
13
+ * is that check. It asks no model anything and reads only what the runner
14
+ * measured:
15
+ *
16
+ * failed the step did not reach the game (a target that did not
17
+ * resolve, an input the driver cannot send);
18
+ * unchanged the step said what it expected and the screen did not change
19
+ * at all;
20
+ * scene the game moved to another scene (Godot's current scene file),
21
+ * which no step after it was planned against;
22
+ * death the game's own state counted a death or a lost life
23
+ * (a `deaths` value from a _ravensight_state() hook).
24
+ *
25
+ * The steps after a stop are answered "Not played" and spend nothing, so the
26
+ * next turn plans again from the screen as it is. The record of plans, how
27
+ * many steps each played and why any stopped, is one line of the step log.
28
+ */
29
+
30
+ /** The reasons a plan stops, in the step log's words. */
31
+ export const STOP_REASONS = Object.freeze(['failed', 'unchanged', 'scene', 'death']);
32
+
33
+ const clip = (value, n) => String(value ?? '').replace(/\s+/g, ' ').trim().slice(0, n);
34
+
35
+ /**
36
+ * Whether the rest of a plan should be played after this step, and why not.
37
+ *
38
+ * @param {Object} step
39
+ * @param {{changed?: boolean, error?: string|null, driverError?: boolean, refused?: string}} step.executed what executeTool answered
40
+ * @param {string|null} [step.expected] what the step said it expected (expect / intent)
41
+ * @param {string|null} [step.sceneBefore]
42
+ * @param {string|null} [step.sceneAfter]
43
+ * @param {number|null} [step.deathsBefore]
44
+ * @param {number|null} [step.deathsAfter]
45
+ * @returns {null|{reason: string, detail: string}}
46
+ */
47
+ export function planStop({ executed, expected = null, sceneBefore = null, sceneAfter = null, deathsBefore = null, deathsAfter = null } = {}) {
48
+ if (!executed) return null;
49
+ if (executed.refused) return null;
50
+ if (executed.error) return { reason: 'failed', detail: `it did not reach the game (${clip(executed.error, 120)})` };
51
+ if (Number.isFinite(deathsBefore) && Number.isFinite(deathsAfter) && deathsAfter > deathsBefore) return { reason: 'death', detail: 'the game counted a death or a lost life' };
52
+ if (sceneBefore && sceneAfter && sceneBefore !== sceneAfter) return { reason: 'scene', detail: `the game moved to another scene (${clip(sceneAfter, 80)})` };
53
+ if (expected && executed.changed === false) return { reason: 'unchanged', detail: `it was meant to "${clip(expected, 80)}" and the screen did not change` };
54
+ return null;
55
+ }
56
+
57
+ /** What the persona reads for a step the stopped plan did not play. */
58
+ export function notPlayedText(stop, stepNumber) {
59
+ return `Not played: the plan stopped after step ${stepNumber} because ${stop.detail}. Nothing was spent on this step. Look at the screen above and plan again from it.`;
60
+ }
61
+
62
+ /**
63
+ * The run's record of its plans.
64
+ */
65
+ export function createPlanGuard() {
66
+ const totals = { plans: 0, planned_steps: 0, played_steps: 0, stopped: 0, single_steps: 0, model_turns: 0 };
67
+ const reasons = Object.fromEntries(STOP_REASONS.map(reason => [reason, 0]));
68
+ let turn = null;
69
+ return {
70
+ /** A model turn with this many input steps in it. */
71
+ begin(inputs) {
72
+ totals.model_turns += 1;
73
+ turn = { inputs: Math.max(0, inputs | 0), played: 0, stop: null };
74
+ if (turn.inputs >= 2) { totals.plans += 1; totals.planned_steps += turn.inputs; } else if (turn.inputs === 1) totals.single_steps += 1;
75
+ },
76
+ /** One input step was played; answers the stop when the rest should not be. */
77
+ played(check) {
78
+ if (!turn) return null;
79
+ turn.played += 1;
80
+ if (turn.inputs >= 2) totals.played_steps += 1;
81
+ if (turn.stop || turn.played >= turn.inputs) return null;
82
+ const stop = planStop(check);
83
+ if (stop) {
84
+ turn.stop = { ...stop, after: turn.played };
85
+ totals.stopped += 1;
86
+ reasons[stop.reason] += 1;
87
+ }
88
+ return turn.stop;
89
+ },
90
+ /** The stop in effect for the rest of this turn, or null. */
91
+ get stopped() { return turn && turn.stop ? turn.stop : null; },
92
+ summary() {
93
+ return {
94
+ ...totals,
95
+ stop_reasons: { ...reasons },
96
+ // Inputs played per model turn that sent any: what "faster decisions" buys.
97
+ inputs_per_turn: totals.model_turns > 0 ? Number(((totals.played_steps + totals.single_steps) / Math.max(1, totals.plans + totals.single_steps)).toFixed(2)) : 0
98
+ };
99
+ }
100
+ };
101
+ }
102
+
103
+ export default { planStop, notPlayedText, createPlanGuard, STOP_REASONS };
package/src/run/replay.js CHANGED
@@ -84,7 +84,7 @@ function divergence(step, frame, expected, actual) {
84
84
  * @param {(options: Object) => Object} [input.makeDriver] - test seam
85
85
  * @returns {Promise<Object>} the simulation replay's result shape, plus counts
86
86
  */
87
- export async function replayTrace({ text, projectDir, godotPath, headless, runDir, signal, env, makeDriver = options => new GodotDriver(options) }) {
87
+ export async function replayTrace({ text, projectDir, godotPath, headless, runDir, signal, env, extraEnv = null, start = null, makeDriver = options => new GodotDriver(options) }) {
88
88
  const trace = parseTrace(text);
89
89
  const { header, boot, steps } = trace;
90
90
  const driver = makeDriver({
@@ -97,6 +97,10 @@ export async function replayTrace({ text, projectDir, godotPath, headless, runDi
97
97
  seed: header.seed,
98
98
  recordTrace: false,
99
99
  ...(env ? { env } : {}),
100
+ // The variables the run was started with beyond the allowlist are the same game's too.
101
+ ...(extraEnv && Object.keys(extraEnv).length ? { extraEnv } : {}),
102
+ // A run that started from a save or a start spec is replayed from the same start.
103
+ ...(start ? { start } : {}),
100
104
  });
101
105
  const result = {
102
106
  matched: true,
@@ -293,7 +293,7 @@ export async function replayFindings({ report, index = [], traceSteps = new Map(
293
293
  };
294
294
  const none = (state, detail) => finish({ ran: false, runs: 0, skipped: detail }, issues.map(finding => ({ id: finding.id, state, runs: 0, of: 0, trace_steps: 0, detail })));
295
295
  if (issues.length === 0) return finish({ ran: false, runs: 0, skipped: 'the report has no issue to replay' }, []);
296
- if (!driver || !driver.projectDir || !driver.trace) return none('not_possible', 'this run has no input trace with state hashes, so its inputs cannot be played again without a model');
296
+ if (!driver || !driver.projectDir || !(driver.trace || driver.closedTrace)) return none('not_possible', 'this run has no input trace with state hashes, so its inputs cannot be played again without a model');
297
297
  let text;
298
298
  try { text = await readFile(path.join(runDirectory, TRACE_FILE), 'utf8'); parseTrace(text); } catch { return none('not_possible', 'the input trace of this run could not be read'); }
299
299
  const targets = replayTargets(report, index, traceSteps);
@@ -319,7 +319,7 @@ export async function replayFindings({ report, index = [], traceSteps = new Map(
319
319
  if (signal) signal.addEventListener('abort', onAbort, { once: true });
320
320
  let result;
321
321
  try {
322
- result = await replay({ text: prefix, projectDir: driver.projectDir, godotPath: driver.godotPath, headless: driver.headless, runDir: path.join(runDirectory, '.replay'), signal: timer.signal, ...(driver.env ? { env: driver.env } : {}) });
322
+ result = await replay({ text: prefix, projectDir: driver.projectDir, godotPath: driver.godotPath, headless: driver.headless, runDir: path.join(runDirectory, '.replay'), signal: timer.signal, ...(driver.env ? { env: driver.env } : {}), ...(driver.extraEnv && Object.keys(driver.extraEnv).length ? { extraEnv: driver.extraEnv } : {}), ...(driver.start ? { start: driver.start } : {}) });
323
323
  } catch (error) {
324
324
  problem = timer.signal.aborted ? 'the replay ran out of its time' : `a replay could not finish (${String(error && error.message ? error.message : error).slice(0, 80)})`;
325
325
  break;
@@ -415,10 +415,19 @@ export function traceWebInputs(driver, { fingerprint }) {
415
415
  * `prior` holds results already made for findings (the watch the claim judge
416
416
  * asked for, before the report): each is written as it is, not replayed again.
417
417
  *
418
+ * `launchAllowanceMs` is added to the replay's time for each run, at most a
419
+ * minute each: a native build (unreal_driver) spends most of a short budget
420
+ * starting.
421
+ *
422
+ * `stateCheck(replayDriver, finding)` may answer `{verdict, detail}` for a
423
+ * finding the game's own state measured: unreal_driver's 3D findings are
424
+ * `match` when the replay's world watch files the same finding again by the
425
+ * time its input is replayed, whatever the screen shows.
426
+ *
418
427
  * @param {Object} args
419
428
  * @returns {Promise<{ran: boolean, runs: number, skipped: string|null, results: Array<Object>}>}
420
429
  */
421
- export async function replayWebFindings({ report, index = [], traceSteps = new Map(), trace = [], makeDriver, target, viewport = null, playMs = 0, transcript, signal = null, fingerprint, differs, observer = null, now = Date.now, runs = REPLAY_RUNS, tempDir = null, watch = null, stuck = new Set(), prior = new Map() }) {
430
+ export async function replayWebFindings({ report, index = [], traceSteps = new Map(), trace = [], makeDriver, target, viewport = null, playMs = 0, transcript, signal = null, fingerprint, differs, observer = null, now = Date.now, runs = REPLAY_RUNS, tempDir = null, watch = null, stuck = new Set(), prior = new Map(), stateCheck = null, launchAllowanceMs = 0 }) {
422
431
  const issues = (report && Array.isArray(report.findings) ? report.findings : []).filter(finding => finding && SEVERITY_ORDER.includes(finding.severity));
423
432
  const finish = (pass, results) => {
424
433
  for (const result of results) transcript.write({ kind: 'replay_check', ...result });
@@ -447,7 +456,8 @@ export async function replayWebFindings({ report, index = [], traceSteps = new M
447
456
  const last = Math.max(0, ...targets.map(entry => entry.trace_steps), scripted.size > 0 ? trace.length : 0);
448
457
  const lastStill = Math.max(0, ...targets.filter(entry => still.has(entry.id)).map(entry => entry.trace_steps));
449
458
  const started = now();
450
- const deadline = started + replayBudget(playMs);
459
+ // A build that takes a while to start (a native game) gets that time on top for each replay, bounded by the caller.
460
+ const deadline = started + replayBudget(playMs) + runs * Math.max(0, Math.min(Number(launchAllowanceMs) || 0, 60000));
451
461
  const verdicts = new Map([...targets.map(entry => [entry.id, []]), ...[...scripted].map(id => [id, []])]);
452
462
  const same = (a, b) => (a && b ? !differs(a, b) : null);
453
463
  const seconds = ms => (ms / 1000).toFixed(1);
@@ -486,6 +496,9 @@ export async function replayWebFindings({ report, index = [], traceSteps = new M
486
496
  }
487
497
  for (const hit of hits) {
488
498
  let verdict, detail, gameMs;
499
+ // A finding the game's own state measured (unreal_driver's 3D watch) is checked against that state in the replay, not the screen.
500
+ const measured = stateCheck ? await Promise.resolve().then(() => stateCheck(driver, issues.find(finding => finding.id === hit.id))).catch(() => null) : null;
501
+ if (measured && !(watchRun && watched)) { verdicts.get(hit.id).push({ verdict: measured.verdict, detail: measured.detail }); continue; }
489
502
  if (still.has(hit.id)) {
490
503
  if (sameBefore === false) ({ verdict, detail } = watched ? { verdict: 'unverifiable', detail: 'not verifiable: the watch of an earlier finding moved the game on, so this moment was not reached again' } : { verdict: 'diverged', detail: 'the replay was on a different screen before this input' });
491
504
  // An input the brief kept the run out of was never sent, by play or by the replay: its quiet screen says nothing.
package/src/run/resume.js CHANGED
@@ -1,4 +1,5 @@
1
- import { MOBILE_DRIVERS, buildDigest } from './drivers/mobile/target.js';
1
+ import { MOBILE_DRIVERS, DESKTOP_NATIVE_DRIVERS, buildDigest } from './drivers/mobile/target.js';
2
+ import { DESKTOP_LOCK } from './drivers/desktop/common.js';
2
3
  import { lockDevice } from './drivers/mobile/lock.js';
3
4
  import { archiveNativeAttempt } from './drivers/mobile/attempt.js';
4
5
  import { optionsFrom } from './args.js';
@@ -246,6 +247,9 @@ export async function resumeJob({ api, gameId, jobId, job, runs, state, repoRoot
246
247
  runLength: typeof journal.options?.runLength === 'string' ? journal.options.runLength : 'standard',
247
248
  ...(Array.isArray(journal.options?.focus) ? { focus: journal.options.focus } : {}), ...(Array.isArray(journal.options?.avoid) ? { avoid: journal.options.avoid } : {}),
248
249
  ...(Number.isInteger(journal.options?.longRunFactor) ? { longRunFactor: journal.options.longRunFactor } : {}),
250
+ // The run's start and sessions, as the journal kept them: a resumed run starts where the paid one did.
251
+ ...(journal.options?.startFrom && typeof journal.options.startFrom === 'object' ? { startFrom: journal.options.startFrom } : {}),
252
+ ...(Number.isSafeInteger(journal.options?.sessions) ? { sessions: journal.options.sessions } : {}),
249
253
  concurrency: options.concurrency ?? (journal.options && journal.options.concurrency),
250
254
  uploadVideo: options.uploadVideo ?? (journal.options && journal.options.uploadVideo),
251
255
  uploadTranscript: options.uploadTranscript ?? (journal.options && journal.options.uploadTranscript),
@@ -260,7 +264,7 @@ export async function resumeJob({ api, gameId, jobId, job, runs, state, repoRoot
260
264
  const native = resumeOptions.nativePlan;
261
265
  if (!native.resolvedDevice) throw new Error('The native journal has no pinned device. Start a new job.');
262
266
  if (native.buildHash && await buildDigest(native.build || target) !== native.buildHash) throw new Error('The saved native build changed. Start a new job for the changed build.');
263
- const key = `${driverName === 'android_driver' ? 'android' : 'ios'}:${native.resolvedDevice}`;
267
+ const key = DESKTOP_NATIVE_DRIVERS.includes(driverName) ? DESKTOP_LOCK : `${driverName === 'android_driver' ? 'android' : 'ios'}:${native.resolvedDevice}`;
264
268
  const release = await (injected.lockDevice || lockDevice)(key);
265
269
  nativeLease = { release, lock: async requested => { if (requested !== key) throw new Error('The resumed device does not match its lease.'); return async () => {}; } };
266
270
  for (const row of outstanding.filter(row => row.module === 'persona_playtest')) {