@tangle-network/agent-eval 0.161.0 → 0.163.2

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 (139) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/dist/{active-curriculum-CD5TU2yW.js → active-curriculum-OjIWgrUJ.js} +2 -2
  3. package/dist/{active-curriculum-CD5TU2yW.js.map → active-curriculum-OjIWgrUJ.js.map} +1 -1
  4. package/dist/analyst/index.d.ts +2 -2
  5. package/dist/analyst/index.d.ts.map +1 -1
  6. package/dist/analyst/index.js +3 -3
  7. package/dist/{baseline-BhPRQBVn.js → baseline-BC-eBZ7U.js} +2 -2
  8. package/dist/{baseline-BhPRQBVn.js.map → baseline-BC-eBZ7U.js.map} +1 -1
  9. package/dist/{benchmark-command-BVtaq_ve.js → benchmark-command-CF-4GEWZ.js} +9 -8
  10. package/dist/benchmark-command-CF-4GEWZ.js.map +1 -0
  11. package/dist/benchmarks/index.d.ts +1 -1
  12. package/dist/benchmarks/index.js +3 -3
  13. package/dist/builder-eval/index.d.ts.map +1 -1
  14. package/dist/builder-eval/index.js +22 -8
  15. package/dist/builder-eval/index.js.map +1 -1
  16. package/dist/campaign/index.js +8 -8
  17. package/dist/{campaign-BSmOwskD.js → campaign-DQZmc2Dq.js} +12 -12
  18. package/dist/{campaign-BSmOwskD.js.map → campaign-DQZmc2Dq.js.map} +1 -1
  19. package/dist/{chat-json-call-6g5sJobJ.js → chat-json-call-5Jxna-aV.js} +2 -2
  20. package/dist/{chat-json-call-6g5sJobJ.js.map → chat-json-call-5Jxna-aV.js.map} +1 -1
  21. package/dist/cli.js +3 -3
  22. package/dist/contract/index.js +7 -7
  23. package/dist/{counterfactual-D_VWavVm.js → counterfactual-Bjq1mlUu.js} +2 -2
  24. package/dist/{counterfactual-D_VWavVm.js.map → counterfactual-Bjq1mlUu.js.map} +1 -1
  25. package/dist/{define-agent-eval-h-s-sI-v.js → define-agent-eval-D08pWIJb.js} +13 -13
  26. package/dist/{define-agent-eval-h-s-sI-v.js.map → define-agent-eval-D08pWIJb.js.map} +1 -1
  27. package/dist/{descriptive-jDOuI6mz.js → descriptive-1V17A-qa.js} +2 -2
  28. package/dist/{descriptive-jDOuI6mz.js.map → descriptive-1V17A-qa.js.map} +1 -1
  29. package/dist/{dspy-rlm-engine-DptEII26.js → dspy-rlm-engine-DhA9qKIm.js} +2 -2
  30. package/dist/{dspy-rlm-engine-DptEII26.js.map → dspy-rlm-engine-DhA9qKIm.js.map} +1 -1
  31. package/dist/emitter-D_jYSGRd.d.ts.map +1 -1
  32. package/dist/{emitter-BpYFQPj4.js → emitter-DeQHiDMm.js} +13 -6
  33. package/dist/emitter-DeQHiDMm.js.map +1 -0
  34. package/dist/{eval-campaign-BsXWL2-2.js → eval-campaign-BfohKmzx.js} +3 -3
  35. package/dist/{eval-campaign-BsXWL2-2.js.map → eval-campaign-BfohKmzx.js.map} +1 -1
  36. package/dist/experiment/index.js +8 -8
  37. package/dist/{experiment-tracker-Ym6rEQT1.js → experiment-tracker-BKEumQug.js} +2 -2
  38. package/dist/{experiment-tracker-Ym6rEQT1.js.map → experiment-tracker-BKEumQug.js.map} +1 -1
  39. package/dist/{external-optimizer-process-WosTBChy.js → external-optimizer-process-BFmh36vW.js} +2 -2
  40. package/dist/{external-optimizer-process-WosTBChy.js.map → external-optimizer-process-BFmh36vW.js.map} +1 -1
  41. package/dist/{external-optimizer-subprocess-BIWbHpgD.js → external-optimizer-subprocess-CqLMW3nh.js} +2 -2
  42. package/dist/{external-optimizer-subprocess-BIWbHpgD.js.map → external-optimizer-subprocess-CqLMW3nh.js.map} +1 -1
  43. package/dist/fuzz.d.ts +1 -2
  44. package/dist/fuzz.d.ts.map +1 -1
  45. package/dist/fuzz.js +4 -10
  46. package/dist/fuzz.js.map +1 -1
  47. package/dist/index.d.ts +3 -3
  48. package/dist/index.js +26 -26
  49. package/dist/index.js.map +1 -1
  50. package/dist/{internal-BDHPCnjk.js → internal-BMFSR8Ns.js} +3 -19
  51. package/dist/internal-BMFSR8Ns.js.map +1 -0
  52. package/dist/{judge-calibration-zZjLz8hr.js → judge-calibration-BnpVKtnb.js} +3 -13
  53. package/dist/judge-calibration-BnpVKtnb.js.map +1 -0
  54. package/dist/judge-calibration-C5CbMYce.d.ts.map +1 -1
  55. package/dist/{llm-client-hgDieDNN.js → llm-client-BFMRpmqb.js} +8 -11
  56. package/dist/llm-client-BFMRpmqb.js.map +1 -0
  57. package/dist/{llm-judge-BhasIPFT.js → llm-judge-Du7WQPh7.js} +7 -7
  58. package/dist/{llm-judge-BhasIPFT.js.map → llm-judge-Du7WQPh7.js.map} +1 -1
  59. package/dist/meta-eval/index.d.ts +2 -1
  60. package/dist/meta-eval/index.d.ts.map +1 -1
  61. package/dist/meta-eval/index.js +14 -22
  62. package/dist/meta-eval/index.js.map +1 -1
  63. package/dist/openapi.json +1 -1
  64. package/dist/{paired-arms-D-XRF_fy.js → paired-arms-D4aeIHUy.js} +3 -3
  65. package/dist/{paired-arms-D-XRF_fy.js.map → paired-arms-D4aeIHUy.js.map} +1 -1
  66. package/dist/{paired-tests-BHIhYVdu.js → paired-tests-C8iCsioC.js} +3 -3
  67. package/dist/{paired-tests-BHIhYVdu.js.map → paired-tests-C8iCsioC.js.map} +1 -1
  68. package/dist/pipelines/index.d.ts +3 -2
  69. package/dist/pipelines/index.d.ts.map +1 -1
  70. package/dist/pipelines/index.js +4 -19
  71. package/dist/pipelines/index.js.map +1 -1
  72. package/dist/{power-and-mde-CHIrXJll.js → power-and-mde-B8F2RdcD.js} +3 -3
  73. package/dist/{power-and-mde-CHIrXJll.js.map → power-and-mde-B8F2RdcD.js.map} +1 -1
  74. package/dist/{power-preflight-DEw-uC7q.js → power-preflight-CFXm0Vjo.js} +3 -3
  75. package/dist/{power-preflight-DEw-uC7q.js.map → power-preflight-CFXm0Vjo.js.map} +1 -1
  76. package/dist/{produced-state-DZ89riy5.js → produced-state-Be0BK3RN.js} +3 -3
  77. package/dist/{produced-state-DZ89riy5.js.map → produced-state-Be0BK3RN.js.map} +1 -1
  78. package/dist/{promotion-policy-xzA40Evo.js → promotion-policy-LY9mVQ7W.js} +3 -3
  79. package/dist/{promotion-policy-xzA40Evo.js.map → promotion-policy-LY9mVQ7W.js.map} +1 -1
  80. package/dist/{query-DxPYqpmT.d.ts → query-CwnHlu5p.d.ts} +19 -2
  81. package/dist/query-CwnHlu5p.d.ts.map +1 -0
  82. package/dist/{query-CHmMP42p.js → query-_5g6re3_.js} +44 -2
  83. package/dist/query-_5g6re3_.js.map +1 -0
  84. package/dist/random-Dn5fPWkt.js +21 -0
  85. package/dist/random-Dn5fPWkt.js.map +1 -0
  86. package/dist/record-id-DUgsK5qp.js +17 -0
  87. package/dist/record-id-DUgsK5qp.js.map +1 -0
  88. package/dist/{release-confidence-DKfD2RYU.js → release-confidence-nGDJiiwc.js} +2 -2
  89. package/dist/{release-confidence-DKfD2RYU.js.map → release-confidence-nGDJiiwc.js.map} +1 -1
  90. package/dist/reporting.js +6 -6
  91. package/dist/{reward-hacking-t4lB1yt8.js → reward-hacking-O5zKDANP.js} +2 -2
  92. package/dist/{reward-hacking-t4lB1yt8.js.map → reward-hacking-O5zKDANP.js.map} +1 -1
  93. package/dist/rl.d.ts.map +1 -1
  94. package/dist/rl.js +9 -15
  95. package/dist/rl.js.map +1 -1
  96. package/dist/{rubric-predictive-validity-CK8SCOg-.js → rubric-predictive-validity-2D5Gw9z9.js} +3 -3
  97. package/dist/{rubric-predictive-validity-CK8SCOg-.js.map → rubric-predictive-validity-2D5Gw9z9.js.map} +1 -1
  98. package/dist/{semantic-concept-judge-BSkKKHeq.js → semantic-concept-judge-BsDMOwJr.js} +2 -2
  99. package/dist/{semantic-concept-judge-BSkKKHeq.js.map → semantic-concept-judge-BsDMOwJr.js.map} +1 -1
  100. package/dist/{sequential-rYW-Ophm.js → sequential-BLMbdrD7.js} +3 -3
  101. package/dist/{sequential-rYW-Ophm.js.map → sequential-BLMbdrD7.js.map} +1 -1
  102. package/dist/{server-BtFd4uzB.js → server-BjYiJHoJ.js} +2 -2
  103. package/dist/{server-BtFd4uzB.js.map → server-BjYiJHoJ.js.map} +1 -1
  104. package/dist/{skillopt-optimization-method-DbaekMcn.js → skillopt-optimization-method-UArRo-nr.js} +6 -6
  105. package/dist/{skillopt-optimization-method-DbaekMcn.js.map → skillopt-optimization-method-UArRo-nr.js.map} +1 -1
  106. package/dist/{store-tool-spans-Dlh9vkFK.js → store-tool-spans-BVga3c37.js} +21 -17
  107. package/dist/store-tool-spans-BVga3c37.js.map +1 -0
  108. package/dist/store-tool-spans-DPUG7UUY.d.ts.map +1 -1
  109. package/dist/{student-t-CvBq2mve.js → student-t-BA-Uy51p.js} +2 -2
  110. package/dist/{student-t-CvBq2mve.js.map → student-t-BA-Uy51p.js.map} +1 -1
  111. package/dist/{summary-report-BI5hUtvK.js → summary-report-BXeQ5Ues.js} +6 -6
  112. package/dist/{summary-report-BI5hUtvK.js.map → summary-report-BXeQ5Ues.js.map} +1 -1
  113. package/dist/supervisor-run/index.js +1 -1
  114. package/dist/{tool-waste-BqzmVdJk.js → tool-waste-8BQiUc8K.js} +4 -4
  115. package/dist/{tool-waste-BqzmVdJk.js.map → tool-waste-8BQiUc8K.js.map} +1 -1
  116. package/dist/{tool-waste-Dro0gJi3.d.ts → tool-waste-CKc7bYIg.d.ts} +2 -2
  117. package/dist/{tool-waste-Dro0gJi3.d.ts.map → tool-waste-CKc7bYIg.d.ts.map} +1 -1
  118. package/dist/trace-repair/index.js +1 -1
  119. package/dist/traces.d.ts +2 -2
  120. package/dist/traces.d.ts.map +1 -1
  121. package/dist/traces.js +8 -17
  122. package/dist/traces.js.map +1 -1
  123. package/dist/trajectory-replay/index.d.ts.map +1 -1
  124. package/dist/trajectory-replay/index.js +3 -13
  125. package/dist/trajectory-replay/index.js.map +1 -1
  126. package/dist/{types-BPb2Kf_C2.d.ts → types-BPb2Kf_C.d.ts} +1 -1
  127. package/dist/types-BPb2Kf_C.d.ts.map +1 -0
  128. package/dist/types-Bfk0uxRj.d.ts.map +1 -1
  129. package/dist/wire/index.js +1 -1
  130. package/package.json +2 -2
  131. package/dist/benchmark-command-BVtaq_ve.js.map +0 -1
  132. package/dist/emitter-BpYFQPj4.js.map +0 -1
  133. package/dist/internal-BDHPCnjk.js.map +0 -1
  134. package/dist/judge-calibration-zZjLz8hr.js.map +0 -1
  135. package/dist/llm-client-hgDieDNN.js.map +0 -1
  136. package/dist/query-CHmMP42p.js.map +0 -1
  137. package/dist/query-DxPYqpmT.d.ts.map +0 -1
  138. package/dist/store-tool-spans-Dlh9vkFK.js.map +0 -1
  139. package/dist/types-BPb2Kf_C2.d.ts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/trajectory-replay/corpus.ts","../../src/trajectory-replay/fix.ts","../../src/trajectory-replay/fix-loop.ts","../../src/trajectory-replay/image-preparer.ts","../../src/trajectory-replay/verify.ts","../../src/trajectory-replay/batch.ts","../../src/trajectory-replay/wire.ts","../../src/trajectory-replay/findings.ts"],"sourcesContent":["/**\n * Corpus enumeration for batch replay verification.\n *\n * A labeled trajectory corpus is a gold label file (array of trajectory\n * entries with `incorrect_stages[].incorrect_step_ids`) plus a prepared\n * directory:\n * <prepared>/normalized/<traj_id>/steps.json normalized steps\n * <prepared>/normalized/<traj_id>/task.md optional task statement\n * <prepared>/extracted/<traj_id>/swe_raw/** raw mini-SWE trajectory\n *\n * Only trajectories that record their environment are replayable: the raw\n * trajectory must carry `info.docker_config.base_image`. Every excluded case\n * is returned with a machine-readable reason — the batch report surfaces the\n * full exclusion table, never a silently shrunk denominator.\n */\n\nimport { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport {\n isSubmitAction,\n parseObservationOutput,\n parseRecordedReturncode,\n type RecordedTrajectoryStep,\n} from './steps'\n\nexport interface CorpusSpec {\n readonly name: string\n readonly labelsPath: string\n readonly preparedDir: string\n}\n\n/** Parses `name=<labelsPath>::<preparedDir>` (paths may contain `=`, not `::`). */\nexport function parseCorpusFlag(value: string): CorpusSpec {\n const eq = value.indexOf('=')\n if (eq <= 0) throw new Error(`--corpus must be name=<labels>::<prepared>, got: ${value}`)\n const name = value.slice(0, eq)\n const rest = value.slice(eq + 1)\n const sep = rest.indexOf('::')\n if (sep <= 0 || sep === rest.length - 2) {\n throw new Error(`--corpus must be name=<labels>::<prepared>, got: ${value}`)\n }\n return { name, labelsPath: rest.slice(0, sep), preparedDir: rest.slice(sep + 2) }\n}\n\nexport type ReplayExclusionReason =\n | 'no-swe-raw-trajectory'\n | 'ambiguous-swe-raw-trajectory'\n | 'unreadable-raw-trajectory'\n | 'no-docker-image'\n | 'no-gold-incorrect-step'\n | 'gold-only-submit-step'\n | 'missing-steps-json'\n | 'gold-step-outside-steps'\n | 'cwd-underivable'\n\nexport interface ExcludedCase {\n readonly corpus: string\n readonly trajId: string\n readonly reason: ReplayExclusionReason\n readonly detail?: string\n}\n\nexport type CwdSource = 'run-config' | 'docker-config' | 'pwd-observation'\n\n/** Everything needed to replay one trajectory. */\nexport interface CaseResources {\n readonly corpus: string\n readonly trajId: string\n readonly stepsPath: string\n readonly steps: readonly RecordedTrajectoryStep[]\n readonly taskStatement: string | null\n readonly image: string\n readonly cwd: string\n readonly cwdSource: CwdSource\n /** Per-step timeout the recorded run used, when the raw config carries one. */\n readonly recordedStepTimeoutMs: number | null\n}\n\nexport interface ReplayableCase extends CaseResources {\n /** 1-based gold incorrect step ids, ascending. */\n readonly goldIncorrectSteps: readonly number[]\n /** k — the first gold incorrect step that is a real mid-trajectory action;\n * submit-command golds are skipped (see SUBMIT_ACTION_SIGNATURE). */\n readonly k: number\n /** Gold steps before k skipped because their action is the submit command. */\n readonly submitGoldsSkipped: number\n /** Recorded returncode at k; null when the observation carries none. */\n readonly recordedReturncodeAtK: number | null\n}\n\ninterface LabelEntry {\n readonly traj_id: string\n readonly incorrect_stages?: readonly { readonly incorrect_step_ids?: readonly number[] }[]\n}\n\nexport function readLabelEntries(labelsPath: string): LabelEntry[] {\n const parsed: unknown = JSON.parse(readFileSync(labelsPath, 'utf8'))\n if (!Array.isArray(parsed)) throw new Error(`${labelsPath} is not a JSON array of label entries`)\n for (const entry of parsed) {\n if (typeof (entry as LabelEntry).traj_id !== 'string') {\n throw new Error(`${labelsPath} has an entry without a string traj_id`)\n }\n }\n return parsed as LabelEntry[]\n}\n\nexport function goldIncorrectSteps(entry: LabelEntry): number[] {\n const ids = new Set<number>()\n for (const stage of entry.incorrect_stages ?? []) {\n for (const id of stage.incorrect_step_ids ?? []) ids.add(id)\n }\n return [...ids].sort((a, b) => a - b)\n}\n\ninterface RawTrajInfo {\n readonly docker_config?: { readonly base_image?: unknown; readonly cwd?: unknown }\n readonly config?: {\n readonly environment?: { readonly cwd?: unknown; readonly timeout?: unknown }\n }\n}\n\ninterface RawTrajFile {\n readonly info?: RawTrajInfo\n readonly messages?: readonly { readonly role?: unknown; readonly content?: unknown }[]\n}\n\nfunction findRawTrajFiles(sweRawDir: string): string[] {\n if (!existsSync(sweRawDir)) return []\n const entries = readdirSync(sweRawDir, { recursive: true, encoding: 'utf8' })\n return entries\n .filter((relative) => relative.endsWith('.traj.json'))\n .map((relative) => join(sweRawDir, relative))\n .sort()\n}\n\n/** First non-empty output line of the trajectory's first bare `pwd` step. */\nfunction cwdFromPwdObservation(steps: readonly RecordedTrajectoryStep[]): string | null {\n for (const step of steps) {\n if (step.action.trim() !== 'pwd') continue\n const line = parseObservationOutput(step.observation)\n .split('\\n')\n .map((l) => l.trim())\n .find((l) => l.startsWith('/'))\n if (line) return line\n }\n return null\n}\n\nfunction taskStatementOf(preparedDir: string, trajId: string, raw: RawTrajFile): string | null {\n const taskPath = join(preparedDir, 'normalized', trajId, 'task.md')\n if (existsSync(taskPath)) {\n const text = readFileSync(taskPath, 'utf8').trim()\n if (text.length > 0) return text\n }\n const userMessage = raw.messages?.find((m) => m.role === 'user')\n if (typeof userMessage?.content === 'string' && userMessage.content.trim().length > 0) {\n return userMessage.content.trim()\n }\n return null\n}\n\nexport type ResourceResolution =\n | { readonly resolved: true; readonly resources: CaseResources }\n | { readonly resolved: false; readonly reason: ReplayExclusionReason; readonly detail?: string }\n\n/**\n * Resolves the replay resources for one trajectory, independent of gold\n * labels — the finding wire uses this with a finding-supplied step instead.\n */\nexport function resolveCaseResources(corpus: CorpusSpec, trajId: string): ResourceResolution {\n const sweRawDir = join(corpus.preparedDir, 'extracted', trajId, 'swe_raw')\n const rawFiles = findRawTrajFiles(sweRawDir)\n if (rawFiles.length === 0) {\n return { resolved: false, reason: 'no-swe-raw-trajectory', detail: sweRawDir }\n }\n if (rawFiles.length > 1) {\n return { resolved: false, reason: 'ambiguous-swe-raw-trajectory', detail: rawFiles.join(', ') }\n }\n let raw: RawTrajFile\n try {\n raw = JSON.parse(readFileSync(rawFiles[0]!, 'utf8')) as RawTrajFile\n } catch (err) {\n return {\n resolved: false,\n reason: 'unreadable-raw-trajectory',\n detail: `${rawFiles[0]}: ${err instanceof Error ? err.message : String(err)}`,\n }\n }\n const dockerConfig = raw.info?.docker_config\n const image = dockerConfig?.base_image\n if (typeof image !== 'string' || image.length === 0) {\n return { resolved: false, reason: 'no-docker-image', detail: rawFiles[0] }\n }\n const stepsPath = join(corpus.preparedDir, 'normalized', trajId, 'steps.json')\n if (!existsSync(stepsPath)) {\n return { resolved: false, reason: 'missing-steps-json', detail: stepsPath }\n }\n const steps = JSON.parse(readFileSync(stepsPath, 'utf8')) as RecordedTrajectoryStep[]\n\n const runConfigCwd = raw.info?.config?.environment?.cwd\n const dockerCwd = dockerConfig?.cwd\n let cwd: string\n let cwdSource: CwdSource\n if (typeof runConfigCwd === 'string' && runConfigCwd.length > 0) {\n cwd = runConfigCwd\n cwdSource = 'run-config'\n } else if (typeof dockerCwd === 'string' && dockerCwd.length > 0) {\n cwd = dockerCwd\n cwdSource = 'docker-config'\n } else {\n const observed = cwdFromPwdObservation(steps)\n if (!observed) return { resolved: false, reason: 'cwd-underivable' }\n cwd = observed\n cwdSource = 'pwd-observation'\n }\n\n const recordedTimeout = raw.info?.config?.environment?.timeout\n return {\n resolved: true,\n resources: {\n corpus: corpus.name,\n trajId,\n stepsPath,\n steps,\n taskStatement: taskStatementOf(corpus.preparedDir, trajId, raw),\n image,\n cwd,\n cwdSource,\n recordedStepTimeoutMs:\n typeof recordedTimeout === 'number' && recordedTimeout > 0 ? recordedTimeout * 1000 : null,\n },\n }\n}\n\nexport interface EnumerationResult {\n readonly replayable: ReplayableCase[]\n readonly excluded: ExcludedCase[]\n readonly labelEntryCount: number\n}\n\n/**\n * Replayable = a raw trajectory with a recorded image AND at least one gold\n * incorrect step that is a real mid-trajectory action. Gold steps whose action\n * is the submit command are skipped when choosing k (counted per case); a case\n * whose golds are ALL submit steps is excluded as gold-only-submit-step.\n * Exclusion reasons are reported in resolution order:\n * raw trajectory → image → gold labels → steps.json → k range → cwd.\n */\nexport function enumerateReplayableCases(corpora: readonly CorpusSpec[]): EnumerationResult {\n const replayable: ReplayableCase[] = []\n const excluded: ExcludedCase[] = []\n let labelEntryCount = 0\n for (const corpus of corpora) {\n for (const entry of readLabelEntries(corpus.labelsPath)) {\n labelEntryCount += 1\n const trajId = entry.traj_id\n const resolution = resolveCaseResources(corpus, trajId)\n if (!resolution.resolved) {\n excluded.push({\n corpus: corpus.name,\n trajId,\n reason: resolution.reason,\n detail: resolution.detail,\n })\n continue\n }\n const gold = goldIncorrectSteps(entry)\n if (gold.length === 0) {\n excluded.push({ corpus: corpus.name, trajId, reason: 'no-gold-incorrect-step' })\n continue\n }\n const resources = resolution.resources\n let submitGoldsSkipped = 0\n let target: RecordedTrajectoryStep | null = null\n let missingGoldId: number | null = null\n for (const goldId of gold) {\n const step = resources.steps.find((s) => s.step_id === goldId)\n if (!step) {\n missingGoldId = goldId\n break\n }\n if (isSubmitAction(step.action)) {\n submitGoldsSkipped += 1\n continue\n }\n target = step\n break\n }\n if (missingGoldId !== null) {\n excluded.push({\n corpus: corpus.name,\n trajId,\n reason: 'gold-step-outside-steps',\n detail: `k=${missingGoldId}, steps=${resources.steps.length}`,\n })\n continue\n }\n if (!target) {\n excluded.push({\n corpus: corpus.name,\n trajId,\n reason: 'gold-only-submit-step',\n detail: `${submitGoldsSkipped} gold step(s), all submit commands`,\n })\n continue\n }\n replayable.push({\n ...resources,\n goldIncorrectSteps: gold,\n k: target.step_id,\n submitGoldsSkipped,\n recordedReturncodeAtK: parseRecordedReturncode(target.observation),\n })\n }\n }\n return { replayable, excluded, labelEntryCount }\n}\n","/**\n * Counterfactual patch synthesis: turn a recorded incorrect step into a\n * corrected shell command for replay arm B.\n *\n * The caller is a typed outcome boundary ({ succeeded, value, error }) so a\n * provider failure is a per-case report row, never a thrown batch abort and\n * never a silent empty fix. Concrete chat transports live with the consumer;\n * this module only builds prompts and reads replies.\n */\n\nimport {\n parseObservationOutput,\n parseRecordedReturncode,\n type RecordedTrajectoryStep,\n} from './steps'\n\nexport interface ChatUsage {\n readonly promptTokens: number\n readonly completionTokens: number\n}\n\nexport type ChatOutcome =\n | { readonly succeeded: true; readonly value: { content: string; usage: ChatUsage | null } }\n | { readonly succeeded: false; readonly error: string }\n\nexport interface ChatCompletionCaller {\n complete(system: string, user: string): Promise<ChatOutcome>\n}\n\nexport interface FixPromptInput {\n readonly taskStatement: string | null\n readonly steps: readonly RecordedTrajectoryStep[]\n /** 1-based step_id of the incorrect step. */\n readonly k: number\n /** Steps of context on each side of k (default 3). */\n readonly contextRadius?: number\n}\n\n/** Head+tail excerpt with an elision marker; identity below the limit. */\nexport function clipText(text: string, limit: number): string {\n if (text.length <= limit) return text\n const half = Math.floor(limit / 2)\n return `${text.slice(0, half)}\\n… [${text.length - limit} chars elided] …\\n${text.slice(-half)}`\n}\n\nfunction renderStep(step: RecordedTrajectoryStep, marker: string): string {\n const rc = parseRecordedReturncode(step.observation)\n const output = clipText(parseObservationOutput(step.observation).trim(), 1600)\n return [\n `### step ${step.step_id}${marker}`,\n '```sh',\n clipText(step.action, 2000),\n '```',\n `returncode: ${rc ?? 'none recorded'}`,\n output.length > 0 ? `output:\\n\\`\\`\\`\\n${output}\\n\\`\\`\\`` : 'output: (empty)',\n ].join('\\n')\n}\n\n/** Shared user-prompt sections: task statement, ±radius context, failing step. */\nfunction promptBody(input: FixPromptInput): string[] {\n const radius = input.contextRadius ?? 3\n const target = input.steps.find((s) => s.step_id === input.k)\n if (!target) throw new Error(`trajectory-replay: no step with step_id ${input.k}`)\n const context = input.steps.filter(\n (s) => s.step_id !== input.k && Math.abs(s.step_id - input.k) <= radius,\n )\n return [\n '## Task the agent was solving',\n input.taskStatement ? clipText(input.taskStatement, 4000) : '(no task statement recorded)',\n '',\n '## Surrounding steps',\n ...context.map((s) => renderStep(s, '')),\n '',\n '## Failing step to correct',\n renderStep(target, ' (INCORRECT — correct this one)'),\n ]\n}\n\nexport function buildFixPrompt(input: FixPromptInput): { system: string; user: string } {\n const system = [\n 'You repair one failed shell command from a recorded coding-agent trajectory.',\n 'The trajectory replays inside the original docker image; every command runs as a fresh /bin/sh subshell from a fixed working directory.',\n 'You are given the failing step, its recorded output, surrounding steps, and the task statement.',\n 'Reply with exactly ONE corrected shell command (compound commands with && or pipes are fine) inside a single ```sh fenced block.',\n \"The corrected command must accomplish the failing step's intent and exit 0. No prose outside the fenced block.\",\n ].join('\\n')\n const user = [\n ...promptBody(input),\n '',\n 'Output the single corrected replacement for the failing step now.',\n ].join('\\n')\n return { system, user }\n}\n\n/** One prior attempt of the fix loop, rendered into the retry prompt. */\nexport interface FailedFixAttempt {\n readonly attempt: number\n /** Null when the model call itself failed before producing a command. */\n readonly command: string | null\n readonly exitCode: number | null\n readonly stdoutTail: string | null\n readonly stderrTail: string | null\n readonly llmError: string | null\n}\n\nfunction renderFailedAttempt(prior: FailedFixAttempt): string {\n if (prior.command === null) {\n return [\n `### attempt ${prior.attempt}`,\n `model call failed before producing a command: ${prior.llmError ?? 'unknown error'}`,\n ].join('\\n')\n }\n const stdout = (prior.stdoutTail ?? '').trim()\n const stderr = (prior.stderrTail ?? '').trim()\n return [\n `### attempt ${prior.attempt}`,\n '```sh',\n clipText(prior.command, 2000),\n '```',\n `exit code: ${prior.exitCode ?? 'not executed'}`,\n stdout.length > 0 ? `stdout:\\n\\`\\`\\`\\n${stdout}\\n\\`\\`\\`` : 'stdout: (empty)',\n stderr.length > 0 ? `stderr:\\n\\`\\`\\`\\n${stderr}\\n\\`\\`\\`` : 'stderr: (empty)',\n ].join('\\n')\n}\n\n/**\n * Retry prompt for fix-loop attempts ≥2: the original context plus every prior\n * attempt with its REAL executed output, and permission to answer with a short\n * script (the block still executes as one /bin/sh unit).\n */\nexport function buildRetryFixPrompt(\n input: FixPromptInput,\n priorAttempts: readonly FailedFixAttempt[],\n maxScriptCommands = 5,\n): { system: string; user: string } {\n if (priorAttempts.length === 0) {\n throw new Error('trajectory-replay: buildRetryFixPrompt requires at least one prior attempt')\n }\n const system = [\n 'You repair one failed shell command from a recorded coding-agent trajectory.',\n 'The trajectory replays inside the original docker image; every command runs as a fresh /bin/sh subshell from a fixed working directory.',\n 'Earlier corrected commands were executed for real and failed; their actual output is included below.',\n `Reply with a corrected fix inside a single \\`\\`\\`sh fenced block: either one command, or a short script of at most ${maxScriptCommands} commands (one per line).`,\n 'The whole block executes as ONE /bin/sh unit from the fixed working directory and must exit 0.',\n 'Do not repeat a command that already failed. Keep reasoning brief. No prose outside the fenced block.',\n ].join('\\n')\n const user = [\n ...promptBody(input),\n '',\n '## Previous fix attempts (executed for real — all failed)',\n ...priorAttempts.map((prior) => renderFailedAttempt(prior)),\n '',\n `Output a corrected fix now — one \\`\\`\\`sh block, at most ${maxScriptCommands} commands.`,\n ].join('\\n')\n return { system, user }\n}\n\n/** Non-empty, non-comment lines of a fix script — the loop's script-size cap. */\nexport function countScriptCommands(script: string): number {\n return script.split('\\n').filter((line) => line.trim().length > 0 && !line.trim().startsWith('#'))\n .length\n}\n\n/** Last fenced code block, else the whole trimmed content; null when empty. */\nexport function extractFixCommand(content: string): string | null {\n const blocks = [...content.matchAll(/```(?:sh|bash|shell)?\\n([\\s\\S]*?)```/g)]\n const candidate = blocks.length > 0 ? blocks[blocks.length - 1]![1]! : content\n const command = candidate.trim()\n if (command.length === 0 || command.includes('```')) return null\n return command\n}\n\nexport type FixGenerationOutcome =\n | { readonly succeeded: true; readonly value: { command: string; usage: ChatUsage | null } }\n | { readonly succeeded: false; readonly error: string }\n\nexport async function generateFixCommand(\n caller: ChatCompletionCaller,\n input: FixPromptInput,\n): Promise<FixGenerationOutcome> {\n const { system, user } = buildFixPrompt(input)\n const outcome = await caller.complete(system, user)\n if (!outcome.succeeded) return outcome\n const command = extractFixCommand(outcome.value.content)\n if (command === null) {\n return {\n succeeded: false,\n error: `completion carried no usable command: ${clipText(outcome.value.content, 300)}`,\n }\n }\n return { succeeded: true, value: { command, usage: outcome.value.usage } }\n}\n","/**\n * Iterative counterfactual fix loop.\n *\n * Attempt 1 is exactly the one-shot generator (same prompt, same caller), so\n * flip@1 stays comparable to one-shot fix mode. When an attempt does not flip\n * the failure — nonzero exit, signature still present, or the model call\n * itself failed — the next attempt's prompt carries every prior command and\n * its REAL executed stdout/stderr, up to a fixed attempt budget.\n *\n * Isolation invariant: every attempt executes through the injected executor,\n * which must provide a FRESH sandbox with the same replayed prefix. A used\n * sandbox is never mutated mid-arm; a flip therefore always proves the\n * corrected step against the recorded prefix state, not against debris from\n * an earlier attempt.\n */\n\nimport {\n buildFixPrompt,\n buildRetryFixPrompt,\n type ChatCompletionCaller,\n clipText,\n countScriptCommands,\n extractFixCommand,\n type FailedFixAttempt,\n type FixPromptInput,\n} from './fix'\n\n/** Result of executing one corrected command as a full arm. */\nexport interface FixArmExecution {\n readonly exitCode: number\n readonly prefixExecuted: number\n readonly prefixDivergences: number\n /** Divergent prefix steps over executed ones, in percent. */\n readonly prefixDivergencePct: number\n readonly failureVanished: boolean\n readonly stdout: string\n readonly stderr: string\n}\n\n/** Runs one corrected command as a full arm: fresh sandbox + prefix replay. */\nexport type FixArmExecutor = (command: string, attempt: number) => Promise<FixArmExecution>\n\nexport interface FixLoopOptions {\n /** Total LLM attempts per case (≥1); 1 degenerates to the one-shot path. */\n readonly maxAttempts: number\n /** Command-line cap on retry scripts (default 5). */\n readonly maxScriptCommands?: number\n /** Chars kept per stdout/stderr tail in records and retry prompts. */\n readonly outputTailChars?: number\n readonly onProgress?: (message: string) => void\n}\n\nexport interface FixLoopAttemptRecord {\n readonly attempt: number\n readonly command: string | null\n readonly llmError: string | null\n readonly usage: { readonly promptTokens: number; readonly completionTokens: number } | null\n readonly executed: boolean\n readonly exitCode: number | null\n readonly prefixExecuted: number | null\n readonly prefixDivergences: number | null\n readonly prefixDivergencePct: number | null\n readonly failureVanished: boolean | null\n readonly stdoutTail: string | null\n readonly stderrTail: string | null\n readonly armBError: string | null\n readonly wallMs: number\n}\n\nexport interface FixLoopResult {\n readonly flipped: boolean\n readonly flippedAtAttempt: number | null\n readonly attempts: readonly FixLoopAttemptRecord[]\n /** True when a sandbox error ended the loop before the attempt budget. */\n readonly aborted: boolean\n readonly llmCalls: number\n /** Calls that produced no runnable fix: transport errors, empty replies,\n * and retry scripts over the command cap. */\n readonly llmFailures: number\n readonly promptTokens: number\n readonly completionTokens: number\n /** Successful calls whose provider reported no usage. Their tokens are absent\n * from the two totals above, so a nonzero count makes those totals a lower\n * bound rather than a measurement. */\n readonly callsWithoutUsage: number\n}\n\nfunction toFailedAttempt(record: FixLoopAttemptRecord): FailedFixAttempt {\n return {\n attempt: record.attempt,\n command: record.command,\n exitCode: record.exitCode,\n stdoutTail: record.stdoutTail,\n stderrTail: record.stderrTail,\n llmError: record.llmError ?? record.armBError,\n }\n}\n\nexport async function runFixLoop(\n caller: ChatCompletionCaller,\n input: FixPromptInput,\n executor: FixArmExecutor,\n options: FixLoopOptions,\n): Promise<FixLoopResult> {\n if (!Number.isInteger(options.maxAttempts) || options.maxAttempts < 1) {\n throw new Error(\n `trajectory-replay: maxAttempts must be a positive integer, got ${options.maxAttempts}`,\n )\n }\n const scriptCap = options.maxScriptCommands ?? 5\n const tailChars = options.outputTailChars ?? 1600\n const attempts: FixLoopAttemptRecord[] = []\n let llmCalls = 0\n let llmFailures = 0\n let promptTokens = 0\n let completionTokens = 0\n let callsWithoutUsage = 0\n\n const unexecuted = (\n attempt: number,\n llmError: string,\n usage: FixLoopAttemptRecord['usage'],\n command: string | null,\n started: number,\n ): FixLoopAttemptRecord => ({\n attempt,\n command,\n llmError,\n usage,\n executed: false,\n exitCode: null,\n prefixExecuted: null,\n prefixDivergences: null,\n prefixDivergencePct: null,\n failureVanished: null,\n stdoutTail: null,\n stderrTail: null,\n armBError: null,\n wallMs: Date.now() - started,\n })\n\n for (let attempt = 1; attempt <= options.maxAttempts; attempt++) {\n const started = Date.now()\n const prompt =\n attempt === 1\n ? buildFixPrompt(input)\n : buildRetryFixPrompt(input, attempts.map(toFailedAttempt), scriptCap)\n llmCalls += 1\n const outcome = await caller.complete(prompt.system, prompt.user)\n if (!outcome.succeeded) {\n llmFailures += 1\n attempts.push(unexecuted(attempt, outcome.error, null, null, started))\n options.onProgress?.(\n `fix-loop attempt ${attempt}: LLM failed — ${outcome.error.slice(0, 160)}`,\n )\n continue\n }\n const usage = outcome.value.usage\n if (usage === null || usage === undefined) callsWithoutUsage += 1\n promptTokens += usage?.promptTokens ?? 0\n completionTokens += usage?.completionTokens ?? 0\n const command = extractFixCommand(outcome.value.content)\n if (command === null) {\n llmFailures += 1\n attempts.push(\n unexecuted(\n attempt,\n `completion carried no usable command: ${clipText(outcome.value.content, 300)}`,\n usage,\n null,\n started,\n ),\n )\n continue\n }\n // Attempt 1 mirrors one-shot exactly, so only retries enforce the cap.\n if (attempt > 1) {\n const commandLines = countScriptCommands(command)\n if (commandLines > scriptCap) {\n llmFailures += 1\n attempts.push(\n unexecuted(\n attempt,\n `script exceeds ${scriptCap} command lines (${commandLines})`,\n usage,\n null,\n started,\n ),\n )\n options.onProgress?.(\n `fix-loop attempt ${attempt}: rejected script with ${commandLines} command lines`,\n )\n continue\n }\n }\n let execution: FixArmExecution\n try {\n execution = await executor(command, attempt)\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n attempts.push({\n ...unexecuted(attempt, '', usage, command, started),\n llmError: null,\n armBError: message.slice(0, 500),\n })\n options.onProgress?.(`fix-loop attempt ${attempt}: sandbox error — ${message.slice(0, 160)}`)\n return {\n flipped: false,\n flippedAtAttempt: null,\n attempts,\n aborted: true,\n llmCalls,\n llmFailures,\n promptTokens,\n completionTokens,\n callsWithoutUsage,\n }\n }\n attempts.push({\n attempt,\n command,\n llmError: null,\n usage,\n executed: true,\n exitCode: execution.exitCode,\n prefixExecuted: execution.prefixExecuted,\n prefixDivergences: execution.prefixDivergences,\n prefixDivergencePct: execution.prefixDivergencePct,\n failureVanished: execution.failureVanished,\n stdoutTail: clipText(execution.stdout, tailChars),\n stderrTail: clipText(execution.stderr, tailChars),\n armBError: null,\n wallMs: Date.now() - started,\n })\n options.onProgress?.(\n `fix-loop attempt ${attempt}: exit=${execution.exitCode} failureVanished=${execution.failureVanished}`,\n )\n if (execution.failureVanished) {\n return {\n flipped: true,\n flippedAtAttempt: attempt,\n attempts,\n aborted: false,\n llmCalls,\n llmFailures,\n promptTokens,\n completionTokens,\n callsWithoutUsage,\n }\n }\n }\n return {\n flipped: false,\n flippedAtAttempt: null,\n attempts,\n aborted: false,\n llmCalls,\n llmFailures,\n promptTokens,\n completionTokens,\n callsWithoutUsage,\n }\n}\n","/**\n * Replay-ready image derivation.\n *\n * A recorded trajectory names the image it ran in, but the image is not always\n * runnable as-is: sandbox platforms pin customer commands to a non-root\n * identity, so a root-owned working tree must be chowned before the replay can\n * write to it. `ImagePreparer` is that step, injectable so a consumer whose\n * images are already replay-ready supplies its own no-op or none at all.\n */\n\nimport { execFile } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport { mkdtempSync, writeFileSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport { promisify } from 'node:util'\n\nconst execFileAsync = promisify(execFile)\n\nexport type ImagePreparation =\n | {\n readonly succeeded: true\n readonly value: { derivedImage: string; pulled: boolean; built: boolean }\n }\n | { readonly succeeded: false; readonly error: string }\n\nexport interface ImagePreparer {\n ensure(image: string, cwd: string): Promise<ImagePreparation>\n}\n\nexport interface DockerImagePreparerOptions {\n readonly pullTimeoutMs?: number\n readonly buildTimeoutMs?: number\n}\n\nexport function derivedImageTag(image: string, cwd: string): string {\n const digest = createHash('sha256').update(`${image}\\n${cwd}`).digest('hex').slice(0, 12)\n return `ctb-replay:${digest}-uid1000`\n}\n\n/**\n * Pulls the base image when absent and builds `FROM <base>; RUN chown -R\n * 1000:1000 <cwd>` tagged by content hash, so repeated batches reuse both\n * the pull and the build. cwd `/` skips the chown (never chown -R /) and\n * replays on the base image directly.\n */\nexport function dockerImagePreparer(options: DockerImagePreparerOptions = {}): ImagePreparer {\n const pullTimeoutMs = options.pullTimeoutMs ?? 1_200_000\n const buildTimeoutMs = options.buildTimeoutMs ?? 900_000\n const imageExists = async (tag: string): Promise<boolean> => {\n try {\n await execFileAsync('docker', ['image', 'inspect', tag], { maxBuffer: 8 * 1024 * 1024 })\n return true\n } catch {\n return false\n }\n }\n const errorTail = (err: unknown): string => {\n const raw =\n err &&\n typeof err === 'object' &&\n 'stderr' in err &&\n typeof err.stderr === 'string' &&\n err.stderr.length > 0\n ? err.stderr\n : err instanceof Error\n ? err.message\n : String(err)\n return raw.trim().split('\\n').slice(-3).join(' | ').slice(0, 400)\n }\n return {\n async ensure(image: string, cwd: string): Promise<ImagePreparation> {\n if (cwd === '/') {\n if (await imageExists(image)) {\n return { succeeded: true, value: { derivedImage: image, pulled: false, built: false } }\n }\n try {\n await execFileAsync('docker', ['pull', image], {\n timeout: pullTimeoutMs,\n maxBuffer: 32 * 1024 * 1024,\n })\n } catch (err) {\n return { succeeded: false, error: `pull ${image}: ${errorTail(err)}` }\n }\n return { succeeded: true, value: { derivedImage: image, pulled: true, built: false } }\n }\n const derived = derivedImageTag(image, cwd)\n if (await imageExists(derived)) {\n return { succeeded: true, value: { derivedImage: derived, pulled: false, built: false } }\n }\n let pulled = false\n if (!(await imageExists(image))) {\n try {\n await execFileAsync('docker', ['pull', image], {\n timeout: pullTimeoutMs,\n maxBuffer: 32 * 1024 * 1024,\n })\n pulled = true\n } catch (err) {\n return { succeeded: false, error: `pull ${image}: ${errorTail(err)}` }\n }\n }\n const contextDir = mkdtempSync(join(tmpdir(), 'ctb-replay-image-'))\n const quotedCwd = `'${cwd.replaceAll(\"'\", `'\\\\''`)}'`\n writeFileSync(\n join(contextDir, 'Dockerfile'),\n `FROM ${image}\\nRUN chown -R 1000:1000 ${quotedCwd}\\n`,\n )\n try {\n await execFileAsync('docker', ['build', '-t', derived, contextDir], {\n timeout: buildTimeoutMs,\n maxBuffer: 32 * 1024 * 1024,\n })\n } catch (err) {\n return { succeeded: false, error: `build ${derived} from ${image}: ${errorTail(err)}` }\n }\n return { succeeded: true, value: { derivedImage: derived, pulled, built: true } }\n },\n }\n}\n","/**\n * Execution-replay verification for recorded shell trajectories.\n *\n * Turns a cited claim (\"step k is the error-critical step\") into an executed\n * proof: replay steps 1..k-1 inside the trajectory's own image, then\n * arm A — run the recorded step k and check the recorded failure signature\n * reproduces (returncode + a stable output substring), and\n * arm B — run a corrected step k and check the failure vanishes.\n *\n * Built on the counterfactual scaffold: the trajectory is ingested into a\n * TraceStore, each arm is a `runCounterfactual` meta-run, and the\n * `SandboxCounterfactualRunner` here supplies the `executeFrom` callback that\n * scaffold deliberately leaves to consumers.\n *\n * Honest limits:\n * - Only trajectories that record their image can be replayed; tasks whose\n * environment needs external compose peers cannot be replayed this way.\n * - Each arm replays the prefix in its own fresh session, so a backend\n * without copy-on-write forks pays the prefix twice.\n * - Prefix divergence is recorded per step and surfaced in the verdict, never\n * hidden: a high divergence rate is a finding about replayability, not an\n * error of the harness.\n *\n * Agreement requires positive evidence. A prefix step counts as confirmed only\n * when the recording carries a returncode AND the replayed exit equals it. A\n * step the recording cannot adjudicate is a divergence of its own kind\n * (`unknown-expectation`), never silent agreement — otherwise a replay that\n * fails on every step reports a perfect prefix and every downstream verdict\n * built on it is meaningless.\n */\n\nimport { mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport {\n type CounterfactualContext,\n type CounterfactualRunner,\n runCounterfactual,\n} from '../counterfactual'\nimport { packageVersion } from '../package-version'\nimport { TraceEmitter } from '../trace/emitter'\nimport type { ToolSpan } from '../trace/schema'\nimport { InMemoryTraceStore, type TraceStore } from '../trace/store'\nimport { certificationEvidenceDigest, type DefaultVerdict } from '../verdict'\nimport type { ReplayExecBackend } from './exec'\nimport { wrapActionForExec } from './exec'\nimport {\n deriveFailureSignature,\n parseObservationOutput,\n parseRecordedReturncode,\n type RecordedTrajectoryStep,\n} from './steps'\n\n// ── Ingest: recorded steps → a trace run ─────────────────────────────\n\nexport interface IngestedTrajectory {\n runId: string\n stepCount: number\n}\n\n/**\n * Emit one tool span per trajectory step, in order, with a monotonic\n * injected clock so `buildTrajectory` ordering is deterministic even when\n * two spans would share a Date.now() millisecond.\n */\nexport async function ingestRecordedTrajectory(\n store: TraceStore,\n steps: readonly RecordedTrajectoryStep[],\n caseId: string,\n): Promise<IngestedTrajectory> {\n let tick = 0\n const emitter = new TraceEmitter(store, { now: () => ++tick })\n await emitter.startRun({\n scenarioId: caseId,\n tags: { source: 'trajectory-replay', caseId },\n })\n for (const step of steps) {\n if (typeof step.action !== 'string' || step.action.length === 0) {\n throw new Error(`trajectory-replay: step ${step.step_id} has no action`)\n }\n const handle = await emitter.tool({\n name: `step:${step.step_id}`,\n toolName: 'shell',\n args: { command: step.action },\n result: {\n returncode: parseRecordedReturncode(step.observation),\n observation: step.observation,\n },\n })\n await handle.end()\n }\n await emitter.endRun({ pass: true, notes: 'recorded trajectory (ingested for replay)' })\n return { runId: emitter.runId, stepCount: steps.length }\n}\n\n// ── Counterfactual runner over an exec backend ───────────────────────\n\n/** Why a replayed prefix step failed to confirm the recording. */\nexport type PrefixDivergenceKind =\n /** The recording carries a returncode and the replayed exit differs from it. */\n | 'returncode-mismatch'\n /** The recording carries no returncode, so agreement cannot be established. */\n | 'unknown-expectation'\n\nexport interface PrefixDivergence {\n step: number\n kind: PrefixDivergenceKind\n /** null exactly when `kind` is `unknown-expectation`. */\n expectedReturncode: number | null\n actualExit: number\n}\n\nexport interface PrefixReplayResult {\n prefixExecuted: number\n /** Every step that did not confirm the recording, of both kinds. */\n prefixDivergences: PrefixDivergence[]\n /** Steps whose recorded returncode equalled the replayed exit. */\n prefixConfirmed: number\n prefixReturncodeMismatches: number\n prefixUnknownExpectations: number\n /** Divergent steps over executed steps, in percent, one decimal.\n * 0 for an empty prefix: no step ran, so none diverged. */\n prefixDivergencePct: number\n /** `prefixDivergencePct` within `PREFIX_DIVERGENCE_TOLERANCE_PCT`. */\n prefixWithinTolerance: boolean\n wallMs: number\n}\n\n/** Admission tolerance: a prefix replay is faithful enough to build a verdict\n * on when at most this percentage of its executed steps diverged. */\nexport const PREFIX_DIVERGENCE_TOLERANCE_PCT = 10\n\n/**\n * Compare one replayed prefix step against its recording. Returns null only\n * when the recording positively confirms the replay.\n */\nexport function classifyPrefixStep(\n step: number,\n expectedReturncode: number | null,\n actualExit: number,\n): PrefixDivergence | null {\n if (expectedReturncode === null) {\n return { step, kind: 'unknown-expectation', expectedReturncode: null, actualExit }\n }\n if (expectedReturncode !== actualExit) {\n return { step, kind: 'returncode-mismatch', expectedReturncode, actualExit }\n }\n return null\n}\n\n/** Roll per-step classifications up into the rate the admission pre-pass gates on. */\nexport function summarizePrefixReplay(\n prefixExecuted: number,\n prefixDivergences: PrefixDivergence[],\n wallMs: number,\n): PrefixReplayResult {\n if (prefixDivergences.length > prefixExecuted) {\n throw new Error(\n `trajectory-replay: ${prefixDivergences.length} divergences over ${prefixExecuted} executed prefix steps`,\n )\n }\n const pct =\n prefixExecuted === 0\n ? 0\n : Number(((prefixDivergences.length / prefixExecuted) * 100).toFixed(1))\n return {\n prefixExecuted,\n prefixDivergences,\n prefixConfirmed: prefixExecuted - prefixDivergences.length,\n prefixReturncodeMismatches: prefixDivergences.filter((d) => d.kind === 'returncode-mismatch')\n .length,\n prefixUnknownExpectations: prefixDivergences.filter((d) => d.kind === 'unknown-expectation')\n .length,\n prefixDivergencePct: pct,\n prefixWithinTolerance: pct <= PREFIX_DIVERGENCE_TOLERANCE_PCT,\n wallMs,\n }\n}\n\nexport interface ArmExecutionResult {\n command: string\n exitCode: number\n stdout: string\n stderr: string\n wallMs: number\n}\n\nexport interface SandboxCounterfactualRunnerOptions {\n cwd: string\n stepTimeoutMs: number\n /** Execute at most this many prefix steps (from the start). Fast-iteration\n * knob; a truncated prefix weakens state fidelity and the verdict says so. */\n prefixLimit?: number\n onProgress?: (message: string) => void\n}\n\nfunction toolCommand(span: ToolSpan): string {\n const args = span.args as { command?: unknown } | null\n if (!args || typeof args.command !== 'string') {\n throw new Error(`trajectory-replay: span ${span.name} carries no command`)\n }\n return args.command\n}\n\nfunction recordedReturncodeOf(span: ToolSpan): number | null {\n const result = span.result as { returncode?: unknown } | null\n return typeof result?.returncode === 'number' ? result.returncode : null\n}\n\n/**\n * Replays `ctx.prefix` in a fresh session, then executes the mutated step.\n * Divergences are recorded and never abort the replay. Results land on\n * `lastPrefix` / `lastArm` for the caller; spans for every exec land in the\n * counterfactual meta-run.\n */\nexport class SandboxCounterfactualRunner implements CounterfactualRunner {\n lastPrefix: PrefixReplayResult | null = null\n lastArm: ArmExecutionResult | null = null\n\n constructor(\n private readonly backend: ReplayExecBackend,\n private readonly options: SandboxCounterfactualRunnerOptions,\n ) {}\n\n async executeFrom(ctx: CounterfactualContext, emitter: TraceEmitter): Promise<void> {\n const { cwd, stepTimeoutMs, prefixLimit, onProgress } = this.options\n const session = await this.backend.open()\n try {\n const toolSteps = ctx.prefix.filter(\n (s): s is typeof s & { span: ToolSpan } => s.span.kind === 'tool',\n )\n const toExecute = prefixLimit !== undefined ? toolSteps.slice(0, prefixLimit) : toolSteps\n const divergences: PrefixDivergence[] = []\n const prefixStart = Date.now()\n for (const step of toExecute) {\n const command = toolCommand(step.span)\n const expected = recordedReturncodeOf(step.span)\n const started = Date.now()\n const result = await session.exec(wrapActionForExec(command, cwd), stepTimeoutMs)\n const handle = await emitter.sandbox({\n name: step.span.name,\n command,\n exitCode: result.exitCode,\n wallMs: Date.now() - started,\n })\n await handle.end()\n const divergence = classifyPrefixStep(step.index + 1, expected, result.exitCode)\n if (divergence) divergences.push(divergence)\n onProgress?.(\n `prefix ${step.span.name}: exit=${result.exitCode}` +\n (divergence\n ? ` (${divergence.kind}${expected === null ? '' : `, recorded ${expected}`})`\n : ''),\n )\n }\n this.lastPrefix = summarizePrefixReplay(\n toExecute.length,\n divergences,\n Date.now() - prefixStart,\n )\n\n if (ctx.mutatedStep.span.kind !== 'tool') {\n throw new Error('trajectory-replay: mutation target is not a tool span')\n }\n const armCommand = toolCommand(ctx.mutatedStep.span as ToolSpan)\n const armStart = Date.now()\n const armResult = await session.exec(wrapActionForExec(armCommand, cwd), stepTimeoutMs)\n const armWallMs = Date.now() - armStart\n const armHandle = await emitter.sandbox({\n name: `candidate:${ctx.mutatedStep.span.name}`,\n command: armCommand,\n exitCode: armResult.exitCode,\n wallMs: armWallMs,\n })\n await armHandle.end()\n this.lastArm = {\n command: armCommand,\n exitCode: armResult.exitCode,\n stdout: armResult.stdout,\n stderr: armResult.stderr,\n wallMs: armWallMs,\n }\n onProgress?.(`candidate step: exit=${armResult.exitCode} in ${armWallMs}ms`)\n await emitter.endRun({\n pass: armResult.exitCode === 0,\n notes:\n `prefix ${toExecute.length} steps, ${divergences.length} divergences ` +\n `(${this.lastPrefix.prefixDivergencePct}%)`,\n })\n } finally {\n await session.close()\n }\n }\n}\n\n// ── Verdict assembly ─────────────────────────────────────────────────\n\nexport interface ReplayVerifyOptions {\n stepsPath: string\n image: string\n /** 1-based step_id of the error-critical step. */\n at: number\n /** Corrected command for arm B. Omit to run arm A only. */\n fixCommand?: string\n cwd: string\n out: string\n caseId?: string\n /** Override the auto-derived failure signature substring. */\n signature?: string\n stepTimeoutMs?: number\n prefixLimit?: number\n /** Label of the driver backing the exec backend (reported, not probed). */\n driverLabel?: string\n /** Execution environment for both arms; each arm opens its own session. */\n backend: ReplayExecBackend\n onProgress?: (message: string) => void\n}\n\nexport interface ReplayArmVerdict {\n command: string\n exitCode: number\n wallMs: number\n prefix: PrefixReplayResult\n}\n\n/** Extends the substrate verdict spine: `valid` = the claim the caller asked\n * to verify held under execution — arm A reproduced the recorded failure on\n * an in-tolerance prefix, and, when arm B ran, the corrected step made the\n * failure vanish. `score` is the same bit as a number; the sub-measurements\n * live in `scores`. Certified as `'replication'`: a re-execution from the\n * pinned image, deterministic given the pins. */\nexport interface ReplayVerdict extends DefaultVerdict {\n case: string\n image: string\n driver: string\n k: number\n cwd: string\n recordedReturncode: number | null\n signature: string | null\n signatureBasis: 'returncode+output-substring' | 'returncode-only'\n prefixExecuted: number\n prefixDivergences: PrefixDivergence[]\n /** Arm A's prefix divergence rate — the number admission gates on. */\n prefixDivergencePct: number\n prefixConfirmed: number\n prefixReturncodeMismatches: number\n prefixUnknownExpectations: number\n prefixWithinTolerance: boolean\n armA: ReplayArmVerdict & { failureSignatureMatch: boolean }\n armB: (ReplayArmVerdict & { failureVanished: boolean }) | null\n timings: { armAMs: number; armBMs: number | null; totalMs: number }\n runIds: { original: string; armA: string; armB: string | null }\n}\n\nfunction excerpt(text: string, limit = 2400): string {\n if (text.length <= limit) return text\n const head = text.slice(0, limit / 2)\n const tail = text.slice(-limit / 2)\n return `${head}\\n… [${text.length - limit} chars elided] …\\n${tail}`\n}\n\nexport async function replayVerify(options: ReplayVerifyOptions): Promise<ReplayVerdict> {\n const totalStart = Date.now()\n const steps = JSON.parse(readFileSync(options.stepsPath, 'utf8')) as RecordedTrajectoryStep[]\n if (!Array.isArray(steps) || steps.length === 0) {\n throw new Error(`trajectory-replay: ${options.stepsPath} is not a non-empty steps array`)\n }\n const index = options.at - 1\n if (index < 0 || index >= steps.length) {\n throw new Error(`trajectory-replay: at ${options.at} out of range [1, ${steps.length}]`)\n }\n const target = steps[index]!\n if (target.step_id !== options.at) {\n throw new Error(\n `trajectory-replay: steps[${index}].step_id=${target.step_id} != at ${options.at}; ` +\n 'steps.json must be ordered with 1-based contiguous step_ids',\n )\n }\n const caseId = options.caseId ?? options.stepsPath\n const recordedReturncode = parseRecordedReturncode(target.observation)\n const signature = options.signature ?? deriveFailureSignature(target.observation)\n const signatureBasis: ReplayVerdict['signatureBasis'] = signature\n ? 'returncode+output-substring'\n : 'returncode-only'\n\n const runnerOptions: SandboxCounterfactualRunnerOptions = {\n cwd: options.cwd,\n stepTimeoutMs: options.stepTimeoutMs ?? 300_000,\n prefixLimit: options.prefixLimit,\n onProgress: options.onProgress,\n }\n\n const store = new InMemoryTraceStore()\n const { runId } = await ingestRecordedTrajectory(store, steps, caseId)\n\n options.onProgress?.(`arm A: replaying ${index} prefix steps then recorded step ${options.at}`)\n const armARunner = new SandboxCounterfactualRunner(options.backend, runnerOptions)\n const armAStart = Date.now()\n const armAResult = await runCounterfactual(\n store,\n runId,\n { kind: 'custom', at: index, describe: 'arm-A identity replay', apply: (s) => s },\n armARunner,\n )\n const armAMs = Date.now() - armAStart\n const armAExec = requireExec(armARunner, 'arm A')\n const armAOutput = `${armAExec.stdout}\\n${armAExec.stderr}`\n const failureSignatureMatch =\n recordedReturncode !== null &&\n armAExec.exitCode === recordedReturncode &&\n (signature ? armAOutput.includes(signature) : true)\n\n let armBRunner: SandboxCounterfactualRunner | null = null\n let armBExec: ArmExecutionResult | null = null\n let armBRunId: string | null = null\n let armBMs: number | null = null\n if (options.fixCommand) {\n const fixCommand = options.fixCommand\n options.onProgress?.('arm B: replaying prefix then corrected step')\n armBRunner = new SandboxCounterfactualRunner(options.backend, runnerOptions)\n const armBStart = Date.now()\n const armBResult = await runCounterfactual(\n store,\n runId,\n {\n kind: 'custom',\n at: index,\n describe: 'arm-B corrected step',\n apply: (step) => ({\n ...step,\n span: { ...(step.span as ToolSpan), args: { command: fixCommand } },\n }),\n },\n armBRunner,\n )\n armBMs = Date.now() - armBStart\n armBRunId = armBResult.counterfactualRunId\n armBExec = requireExec(armBRunner, 'arm B')\n }\n\n const armBOutput = armBExec ? `${armBExec.stdout}\\n${armBExec.stderr}` : null\n const armAPrefix = requirePrefix(armARunner, 'arm A')\n const core = {\n case: caseId,\n image: options.image,\n driver: options.driverLabel ?? 'docker',\n k: options.at,\n cwd: options.cwd,\n recordedReturncode,\n signature,\n signatureBasis,\n prefixExecuted: armAPrefix.prefixExecuted,\n prefixDivergences: armAPrefix.prefixDivergences,\n prefixDivergencePct: armAPrefix.prefixDivergencePct,\n prefixConfirmed: armAPrefix.prefixConfirmed,\n prefixReturncodeMismatches: armAPrefix.prefixReturncodeMismatches,\n prefixUnknownExpectations: armAPrefix.prefixUnknownExpectations,\n prefixWithinTolerance: armAPrefix.prefixWithinTolerance,\n armA: {\n command: armAExec.command,\n exitCode: armAExec.exitCode,\n wallMs: armAExec.wallMs,\n prefix: armAPrefix,\n failureSignatureMatch,\n },\n armB:\n armBExec && armBRunner\n ? {\n command: armBExec.command,\n exitCode: armBExec.exitCode,\n wallMs: armBExec.wallMs,\n prefix: requirePrefix(armBRunner, 'arm B'),\n failureVanished:\n armBExec.exitCode === 0 &&\n (signature && armBOutput ? !armBOutput.includes(signature) : true),\n }\n : null,\n timings: { armAMs, armBMs, totalMs: Date.now() - totalStart },\n runIds: {\n original: runId,\n armA: armAResult.counterfactualRunId,\n armB: armBRunId,\n },\n }\n\n // Steps the certificate rests on unverified: prefix steps the recording\n // cannot adjudicate, a caller-truncated prefix, and a signature derived\n // from the returncode alone.\n const assumptions: string[] = []\n if (armAPrefix.prefixUnknownExpectations > 0) {\n assumptions.push(\n `${armAPrefix.prefixUnknownExpectations} prefix step(s) carry no recorded returncode — agreement with the recording is unestablished there`,\n )\n }\n if (options.prefixLimit !== undefined && options.prefixLimit < index) {\n assumptions.push(\n `prefix truncated at ${options.prefixLimit} of ${index} recorded steps — state fidelity at k is weakened`,\n )\n }\n if (signatureBasis === 'returncode-only') {\n assumptions.push(\n 'no output substring derived from the recording — reproduction rests on the returncode alone',\n )\n }\n const valid =\n core.prefixWithinTolerance &&\n failureSignatureMatch &&\n (core.armB === null || core.armB.failureVanished)\n const verdict: ReplayVerdict = {\n ...core,\n valid,\n score: valid ? 1 : 0,\n scores: {\n prefixFidelity: 1 - core.prefixDivergencePct / 100,\n armAReproduced: failureSignatureMatch ? 1 : 0,\n ...(core.armB === null ? {} : { armBFailureVanished: core.armB.failureVanished ? 1 : 0 }),\n },\n certification: {\n strategy: 'replication',\n checker: {\n name: 'agent-eval:trajectory-replay',\n version: packageVersion(),\n pins: { image: options.image },\n },\n assumptions,\n evidenceDigest: certificationEvidenceDigest(core),\n },\n }\n\n mkdirSync(options.out, { recursive: true })\n writeFileSync(join(options.out, 'replay-verdict.json'), `${JSON.stringify(verdict, null, 2)}\\n`)\n writeFileSync(join(options.out, 'report.md'), renderReport(verdict, target, armAExec, armBExec))\n return verdict\n}\n\nfunction requireExec(runner: SandboxCounterfactualRunner, arm: string): ArmExecutionResult {\n if (!runner.lastArm) {\n throw new Error(`trajectory-replay: ${arm} finished without executing step k`)\n }\n return runner.lastArm\n}\n\nfunction requirePrefix(runner: SandboxCounterfactualRunner, arm: string): PrefixReplayResult {\n if (!runner.lastPrefix) {\n throw new Error(`trajectory-replay: ${arm} reported no prefix replay result`)\n }\n return runner.lastPrefix\n}\n\nfunction renderReport(\n verdict: ReplayVerdict,\n target: RecordedTrajectoryStep,\n armA: ArmExecutionResult,\n armB: ArmExecutionResult | null,\n): string {\n const lines: string[] = []\n lines.push(`# Replay verification — ${verdict.case}`)\n lines.push('')\n lines.push(`- image: \\`${verdict.image}\\` (driver: ${verdict.driver})`)\n lines.push(`- error-critical step k = ${verdict.k}, cwd \\`${verdict.cwd}\\``)\n lines.push(`- recorded returncode at k: ${verdict.recordedReturncode ?? 'none recorded'}`)\n lines.push(\n `- failure signature (${verdict.signatureBasis}): ${\n verdict.signature ? `\\`${verdict.signature}\\`` : '—'\n }`,\n )\n lines.push('')\n lines.push(`## Prefix replay (steps 1..${verdict.k - 1})`)\n lines.push('')\n lines.push(\n `Executed ${verdict.prefixExecuted} steps; ${verdict.prefixConfirmed} confirmed against the ` +\n `recording, ${verdict.prefixDivergences.length} divergent (${verdict.prefixDivergencePct}%) — ` +\n `${verdict.prefixReturncodeMismatches} returncode mismatches, ` +\n `${verdict.prefixUnknownExpectations} with no recorded returncode to check.`,\n )\n lines.push('')\n lines.push(\n `Within the ${PREFIX_DIVERGENCE_TOLERANCE_PCT}% admission tolerance: **${verdict.prefixWithinTolerance}**.`,\n )\n if (verdict.prefixDivergences.length > 0) {\n lines.push('')\n lines.push('| step | kind | recorded rc | replayed exit |')\n lines.push('| --- | --- | --- | --- |')\n for (const d of verdict.prefixDivergences) {\n lines.push(\n `| ${d.step} | ${d.kind} | ${d.expectedReturncode ?? 'none recorded'} | ${d.actualExit} |`,\n )\n }\n }\n lines.push('')\n lines.push('## Arm A — recorded step k, replayed')\n lines.push('')\n lines.push('```sh')\n lines.push(armA.command)\n lines.push('```')\n lines.push('')\n lines.push(\n `Exit ${armA.exitCode} in ${armA.wallMs}ms — failureSignatureMatch: **${verdict.armA.failureSignatureMatch}**`,\n )\n lines.push('')\n lines.push('Recorded observation excerpt:')\n lines.push('')\n lines.push('```')\n lines.push(excerpt(parseObservationOutput(target.observation)))\n lines.push('```')\n lines.push('')\n lines.push('Replayed stdout+stderr excerpt:')\n lines.push('')\n lines.push('```')\n lines.push(excerpt(`${armA.stdout}\\n${armA.stderr}`.trim()))\n lines.push('```')\n if (armB && verdict.armB) {\n lines.push('')\n lines.push('## Arm B — corrected step k')\n lines.push('')\n lines.push('```sh')\n lines.push(armB.command)\n lines.push('```')\n lines.push('')\n lines.push(\n `Exit ${armB.exitCode} in ${armB.wallMs}ms — failureVanished: **${verdict.armB.failureVanished}** ` +\n `(prefix re-replayed in a fresh session: ${verdict.armB.prefix.prefixExecuted} steps, ` +\n `${verdict.armB.prefix.prefixDivergences.length} divergences, ` +\n `${verdict.armB.prefix.prefixDivergencePct}%)`,\n )\n lines.push('')\n lines.push('Replayed stdout+stderr excerpt:')\n lines.push('')\n lines.push('```')\n lines.push(excerpt(`${armB.stdout}\\n${armB.stderr}`.trim()))\n lines.push('```')\n }\n lines.push('')\n lines.push('## Timings')\n lines.push('')\n lines.push(\n `arm A ${verdict.timings.armAMs}ms, arm B ${verdict.timings.armBMs ?? '—'}ms, total ${verdict.timings.totalMs}ms.`,\n )\n lines.push('')\n return lines.join('\\n')\n}\n","/**\n * Batch replay verification across gold-labeled trajectory corpora.\n *\n * For every replayable case (a raw trajectory with a recorded image AND at\n * least one gold incorrect step) the batch:\n * 1. derives the replay-ready image through the injected `ImagePreparer`,\n * 2. replays the prefix and runs arm A — the recorded gold step k, and\n * 3. optionally generates a corrected command with one LLM call and runs\n * arm B in its own fresh session.\n *\n * Headline metrics:\n * replayability rate — fraction of replayable cases where the prefix\n * replays within the divergence tolerance AND arm A reproduces the\n * recorded returncode at k;\n * prefix fidelity — executed prefix steps and the share of them that did\n * not confirm the recording, split by kind. A corpus whose recordings\n * carry no returncodes shows up here as unknown-expectation steps, never\n * as a clean replay;\n * fix-flip rate — fraction of arm-B-executed cases where the failure\n * vanished (exit 0, signature absent).\n *\n * Image pulls and execs run strictly serially: pulls contend on disk and\n * registry bandwidth, and serial cases keep wall-time attribution per case\n * honest. Pull failures are report rows, never silent skips.\n */\n\nimport { appendFileSync, mkdirSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { runCounterfactual } from '../counterfactual'\nimport type { ToolSpan } from '../trace/schema'\nimport { InMemoryTraceStore } from '../trace/store'\nimport {\n type CorpusSpec,\n type EnumerationResult,\n enumerateReplayableCases,\n type ReplayableCase,\n} from './corpus'\nimport type { ReplayExecBackend, ReplayExecBackendFactory } from './exec'\nimport { type ChatCompletionCaller, type ChatUsage, generateFixCommand } from './fix'\nimport { type FixLoopAttemptRecord, runFixLoop } from './fix-loop'\nimport { dockerImagePreparer, type ImagePreparer } from './image-preparer'\nimport {\n ingestRecordedTrajectory,\n PREFIX_DIVERGENCE_TOLERANCE_PCT,\n type PrefixReplayResult,\n type ReplayVerdict,\n replayVerify,\n SandboxCounterfactualRunner,\n} from './verify'\n\n// ── Batch execution ──────────────────────────────────────────────────\n\nexport interface ReplayBatchOptions {\n readonly corpora: readonly CorpusSpec[]\n readonly out: string\n /** 'generate' = one LLM call per arm-A-reproduced case, then arm B.\n * 'loop' = iterative: failed arms feed their real output into up to\n * `fixAttempts` prompts, each executed in its own fresh session. */\n readonly fix: 'none' | 'generate' | 'loop'\n /** Attempt budget per case in loop mode (default 3). */\n readonly fixAttempts?: number\n readonly fixCaller?: ChatCompletionCaller\n readonly fixModelLabel?: string\n /** Cap on LLM fix calls; eligible cases beyond it are seeded-sampled out. */\n readonly maxFixCases?: number\n readonly seed?: number\n /** Overrides the per-case recorded step timeout. */\n readonly stepTimeoutMs?: number\n readonly prefixLimit?: number\n /** Run only cases whose trajId contains this substring (smoke knob). */\n readonly caseFilter?: string\n /** Run only the first N replayable cases (smoke knob). */\n readonly caseLimit?: number\n /** Derives the replay-ready image per case. Defaults to the docker preparer. */\n readonly preparer?: ImagePreparer\n /** Builds the exec backend for a case's derived image. */\n readonly backendFactory: ReplayExecBackendFactory\n readonly onProgress?: (message: string) => void\n}\n\nexport interface ReplayBatchFixResult {\n /** false when the case was eligible but seeded-sampled out of the cap. */\n readonly attempted: boolean\n readonly sampledOut: boolean\n readonly command: string | null\n readonly llmError: string | null\n /** Loop mode: token totals summed across every attempt (null when the\n * provider reported no usage). */\n readonly usage: ChatUsage | null\n readonly armBExit: number | null\n readonly armBPrefixExecuted: number | null\n readonly armBPrefixDivergences: number | null\n readonly armBPrefixDivergencePct: number | null\n readonly failureVanished: boolean | null\n readonly armBError: string | null\n /** Loop mode only: the full per-attempt trail. Null in generate mode. */\n readonly attempts: readonly FixLoopAttemptRecord[] | null\n /** 1-based attempt that flipped the failure; null when none did.\n * Generate mode: 1 when the single attempt flipped. */\n readonly flippedAtAttempt: number | null\n}\n\nexport interface ReplayBatchCaseRow {\n readonly corpus: string\n readonly trajId: string\n readonly image: string\n readonly derivedImage: string | null\n readonly cwd: string\n readonly cwdSource: string\n readonly k: number\n readonly stepCount: number\n readonly goldIncorrectSteps: readonly number[]\n /** Gold steps before k skipped because their action is the submit command. */\n readonly submitGoldsSkipped: number\n readonly recordedReturncodeAtK: number | null\n readonly signature: string | null\n readonly status: 'ok' | 'image-unavailable' | 'replay-error'\n readonly error: string | null\n readonly imagePulled: boolean\n readonly imageBuilt: boolean\n readonly prefixExecuted: number | null\n readonly prefixDivergences: number | null\n readonly prefixDivergencePct: number | null\n /** Prefix steps whose recorded returncode equalled the replayed exit. */\n readonly prefixConfirmed: number | null\n readonly prefixReturncodeMismatches: number | null\n /** Prefix steps the recording carries no returncode for: unverifiable, and\n * counted as divergences because agreement was never established. */\n readonly prefixUnknownExpectations: number | null\n readonly armAExit: number | null\n readonly armAReturncodeMatch: boolean\n readonly armASignatureMatch: boolean\n /** Headline predicate: prefix divergence within tolerance AND arm A\n * reproduced the recorded returncode at k. */\n readonly replayed: boolean\n readonly fix: ReplayBatchFixResult | null\n readonly wallMs: number\n}\n\nexport interface ReplayBatchReport {\n readonly generatedAt: string\n readonly corpora: readonly { name: string; labelsPath: string; preparedDir: string }[]\n readonly totals: {\n readonly labelEntries: number\n readonly replayable: number\n readonly executed: number\n readonly excludedByReason: Record<string, number>\n /** Per-corpus submit-gold accounting: cases dropped because every gold is\n * the submit command, and golds skipped inside still-replayable cases. */\n readonly submitGoldsByCorpus: Record<\n string,\n { submitOnlyCases: number; goldsSkippedWithinReplayable: number }\n >\n }\n readonly headline: {\n readonly replayabilityRate: { numerator: number; denominator: number; value: number | null }\n readonly signatureStrictRate: { numerator: number; denominator: number; value: number | null }\n /** Corpus-level replay fidelity over every executed prefix step. A corpus\n * whose recordings cannot adjudicate the replay lands here as\n * `unknownExpectations`, not as a clean replay. */\n readonly prefixFidelity: {\n readonly executedSteps: number\n readonly divergentSteps: number\n readonly returncodeMismatches: number\n readonly unknownExpectations: number\n /** Divergent over executed steps; null when no prefix step ran. */\n readonly divergencePct: number | null\n readonly tolerancePct: number\n readonly casesWithinTolerance: number\n readonly casesExecuted: number\n }\n readonly fixFlipRate: { numerator: number; denominator: number; value: number | null } | null\n /** Fix-flip restricted to cases whose recorded returncode at k is nonzero —\n * real recorded failures, where \"the failure vanished\" is not vacuous. */\n readonly fixFlipRateNonzeroRc: {\n numerator: number\n denominator: number\n value: number | null\n } | null\n /** Loop mode only: flips at attempt 1 over cases whose attempt 1 executed —\n * the number directly comparable to the one-shot fixFlipRate. */\n readonly fixFlipAttempt1: {\n numerator: number\n denominator: number\n value: number | null\n } | null\n /** Loop mode only: flip count keyed by the attempt number that flipped. */\n readonly flipsByAttempt: Record<string, number> | null\n }\n readonly llm: {\n readonly model: string\n readonly calls: number\n readonly failures: number\n readonly promptTokens: number\n readonly completionTokens: number\n /** Successful calls whose provider reported no usage. Their tokens are\n * absent from the two totals above, so a nonzero count here means the\n * totals are a lower bound, not a measurement. */\n readonly callsWithoutUsage: number\n } | null\n readonly excluded: readonly { corpus: string; trajId: string; reason: string; detail?: string }[]\n readonly pullFailures: readonly { corpus: string; trajId: string; image: string; error: string }[]\n readonly cases: readonly ReplayBatchCaseRow[]\n}\n\n/** Deterministic PRNG for the fix-case sample; the seed lands in the report. */\nfunction mulberry32(seed: number): () => number {\n let state = seed >>> 0\n return () => {\n state = (state + 0x6d2b79f5) >>> 0\n let t = state\n t = Math.imul(t ^ (t >>> 15), t | 1)\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61)\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296\n }\n}\n\nexport function seededSample<T>(items: readonly T[], size: number, seed: number): Set<T> {\n const pool = [...items]\n const random = mulberry32(seed)\n for (let i = pool.length - 1; i > 0; i--) {\n const j = Math.floor(random() * (i + 1))\n ;[pool[i], pool[j]] = [pool[j]!, pool[i]!]\n }\n return new Set(pool.slice(0, size))\n}\n\nfunction caseOutDirName(row: { corpus: string; trajId: string }): string {\n return `${row.corpus}--${row.trajId}`.replaceAll(/[^A-Za-z0-9._-]/g, '_').slice(0, 180)\n}\n\ninterface ArmBExecution {\n readonly exitCode: number\n readonly prefixExecuted: number\n readonly prefixDivergences: number\n readonly prefixDivergencePct: number\n readonly failureVanished: boolean\n readonly stdout: string\n readonly stderr: string\n}\n\n/**\n * Arm B standalone: fresh sandbox, prefix replay, corrected step k. Reuses\n * the same counterfactual scaffold as replayVerify without re-running arm A.\n */\nasync function executeArmB(\n replayCase: ReplayableCase,\n fixCommand: string,\n backend: ReplayExecBackend,\n signature: string | null,\n stepTimeoutMs: number,\n prefixLimit: number | undefined,\n onProgress?: (message: string) => void,\n): Promise<ArmBExecution> {\n const store = new InMemoryTraceStore()\n const { runId } = await ingestRecordedTrajectory(store, replayCase.steps, replayCase.trajId)\n const runner = new SandboxCounterfactualRunner(backend, {\n cwd: replayCase.cwd,\n stepTimeoutMs,\n prefixLimit,\n onProgress,\n })\n await runCounterfactual(\n store,\n runId,\n {\n kind: 'custom',\n at: replayCase.k - 1,\n describe: 'arm-B corrected step',\n apply: (step) => ({\n ...step,\n span: { ...(step.span as ToolSpan), args: { command: fixCommand } },\n }),\n },\n runner,\n )\n const exec = runner.lastArm\n if (!exec) throw new Error('arm B finished without executing the corrected step')\n const prefix: PrefixReplayResult | null = runner.lastPrefix\n if (!prefix) throw new Error('arm B reported no prefix replay result')\n const output = `${exec.stdout}\\n${exec.stderr}`\n return {\n exitCode: exec.exitCode,\n prefixExecuted: prefix.prefixExecuted,\n prefixDivergences: prefix.prefixDivergences.length,\n prefixDivergencePct: prefix.prefixDivergencePct,\n failureVanished: exec.exitCode === 0 && (signature ? !output.includes(signature) : true),\n stdout: exec.stdout,\n stderr: exec.stderr,\n }\n}\n\nfunction rate(numerator: number, denominator: number): number | null {\n return denominator > 0 ? numerator / denominator : null\n}\n\nexport async function runReplayBatch(options: ReplayBatchOptions): Promise<ReplayBatchReport> {\n const onProgress = options.onProgress ?? (() => {})\n const enumeration: EnumerationResult = enumerateReplayableCases(options.corpora)\n let selected = enumeration.replayable\n if (options.caseFilter) {\n selected = selected.filter((c) => c.trajId.includes(options.caseFilter!))\n }\n if (options.caseLimit !== undefined) selected = selected.slice(0, options.caseLimit)\n onProgress(\n `enumerated ${enumeration.labelEntryCount} label entries → ${enumeration.replayable.length} replayable, ` +\n `${enumeration.excluded.length} excluded; executing ${selected.length}`,\n )\n\n const preparer = options.preparer ?? dockerImagePreparer()\n const backendFactory = options.backendFactory\n\n mkdirSync(options.out, { recursive: true })\n const progressPath = join(options.out, 'cases.jsonl')\n const rows: ReplayBatchCaseRow[] = []\n const pullFailures: { corpus: string; trajId: string; image: string; error: string }[] = []\n\n // Phase 1 — arm A for every selected case, serially.\n const verdictByTraj = new Map<string, ReplayVerdict>()\n for (const [index, replayCase] of selected.entries()) {\n const caseStart = Date.now()\n const label = `[${index + 1}/${selected.length}] ${replayCase.corpus}/${replayCase.trajId}`\n onProgress(`${label}: preparing image ${replayCase.image}`)\n const preparation = await preparer.ensure(replayCase.image, replayCase.cwd)\n const base = {\n corpus: replayCase.corpus,\n trajId: replayCase.trajId,\n image: replayCase.image,\n cwd: replayCase.cwd,\n cwdSource: replayCase.cwdSource,\n k: replayCase.k,\n stepCount: replayCase.steps.length,\n goldIncorrectSteps: replayCase.goldIncorrectSteps,\n submitGoldsSkipped: replayCase.submitGoldsSkipped,\n recordedReturncodeAtK: replayCase.recordedReturncodeAtK,\n }\n if (!preparation.succeeded) {\n pullFailures.push({\n corpus: replayCase.corpus,\n trajId: replayCase.trajId,\n image: replayCase.image,\n error: preparation.error,\n })\n const row: ReplayBatchCaseRow = {\n ...base,\n derivedImage: null,\n signature: null,\n status: 'image-unavailable',\n error: preparation.error,\n imagePulled: false,\n imageBuilt: false,\n prefixExecuted: null,\n prefixDivergences: null,\n prefixDivergencePct: null,\n prefixConfirmed: null,\n prefixReturncodeMismatches: null,\n prefixUnknownExpectations: null,\n armAExit: null,\n armAReturncodeMatch: false,\n armASignatureMatch: false,\n replayed: false,\n fix: null,\n wallMs: Date.now() - caseStart,\n }\n rows.push(row)\n appendFileSync(progressPath, `${JSON.stringify(row)}\\n`)\n onProgress(`${label}: image unavailable — ${preparation.error}`)\n continue\n }\n const { derivedImage, pulled, built } = preparation.value\n const stepTimeoutMs = options.stepTimeoutMs ?? replayCase.recordedStepTimeoutMs ?? 120_000\n const caseOut = join(options.out, caseOutDirName(replayCase))\n onProgress(`${label}: arm A on ${derivedImage} (k=${replayCase.k}, timeout ${stepTimeoutMs}ms)`)\n try {\n const verdict = await replayVerify({\n stepsPath: replayCase.stepsPath,\n image: derivedImage,\n at: replayCase.k,\n cwd: replayCase.cwd,\n out: caseOut,\n caseId: replayCase.trajId,\n stepTimeoutMs,\n prefixLimit: options.prefixLimit,\n backend: backendFactory(derivedImage),\n onProgress: (message) => onProgress(`${label}: ${message}`),\n })\n verdictByTraj.set(replayCase.trajId, verdict)\n const returncodeMatch =\n verdict.recordedReturncode !== null && verdict.armA.exitCode === verdict.recordedReturncode\n const row: ReplayBatchCaseRow = {\n ...base,\n derivedImage,\n signature: verdict.signature,\n status: 'ok',\n error: null,\n imagePulled: pulled,\n imageBuilt: built,\n prefixExecuted: verdict.prefixExecuted,\n prefixDivergences: verdict.prefixDivergences.length,\n prefixDivergencePct: verdict.prefixDivergencePct,\n prefixConfirmed: verdict.prefixConfirmed,\n prefixReturncodeMismatches: verdict.prefixReturncodeMismatches,\n prefixUnknownExpectations: verdict.prefixUnknownExpectations,\n armAExit: verdict.armA.exitCode,\n armAReturncodeMatch: returncodeMatch,\n armASignatureMatch: verdict.armA.failureSignatureMatch,\n replayed: verdict.prefixWithinTolerance && returncodeMatch,\n fix: null,\n wallMs: Date.now() - caseStart,\n }\n rows.push(row)\n appendFileSync(progressPath, `${JSON.stringify(row)}\\n`)\n onProgress(\n `${label}: armA exit=${verdict.armA.exitCode} rcMatch=${returncodeMatch} ` +\n `divergences=${verdict.prefixDivergences.length}/${verdict.prefixExecuted} ` +\n `(${verdict.prefixDivergencePct}%, ${verdict.prefixUnknownExpectations} unknown-expectation)`,\n )\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n const row: ReplayBatchCaseRow = {\n ...base,\n derivedImage,\n signature: null,\n status: 'replay-error',\n error: message.slice(0, 500),\n imagePulled: pulled,\n imageBuilt: built,\n prefixExecuted: null,\n prefixDivergences: null,\n prefixDivergencePct: null,\n prefixConfirmed: null,\n prefixReturncodeMismatches: null,\n prefixUnknownExpectations: null,\n armAExit: null,\n armAReturncodeMatch: false,\n armASignatureMatch: false,\n replayed: false,\n fix: null,\n wallMs: Date.now() - caseStart,\n }\n rows.push(row)\n appendFileSync(progressPath, `${JSON.stringify(row)}\\n`)\n onProgress(`${label}: replay error — ${message.slice(0, 200)}`)\n }\n }\n\n // Phase 2 — counterfactual fixes for cases where arm A reproduced.\n let llm: ReplayBatchReport['llm'] = null\n if (options.fix !== 'none') {\n const caller = options.fixCaller\n if (!caller) throw new Error(`trajectory-replay: fix=${options.fix} requires a fixCaller`)\n const fixAttempts = options.fixAttempts ?? 3\n const maxFixCases = options.maxFixCases ?? 30\n const seed = options.seed ?? 17\n const eligible = rows.filter((r) => r.status === 'ok' && r.replayed)\n const sampled =\n eligible.length > maxFixCases ? seededSample(eligible, maxFixCases, seed) : new Set(eligible)\n if (eligible.length > maxFixCases) {\n onProgress(\n `fix phase: ${eligible.length} eligible > cap ${maxFixCases}; seeded sample (seed=${seed})`,\n )\n }\n let calls = 0\n let failures = 0\n let promptTokens = 0\n let completionTokens = 0\n let callsWithoutUsage = 0\n for (const row of eligible) {\n const index = rows.indexOf(row)\n if (!sampled.has(row)) {\n rows[index] = {\n ...row,\n fix: {\n attempted: false,\n sampledOut: true,\n command: null,\n llmError: null,\n usage: null,\n armBExit: null,\n armBPrefixExecuted: null,\n armBPrefixDivergences: null,\n armBPrefixDivergencePct: null,\n failureVanished: null,\n armBError: null,\n attempts: null,\n flippedAtAttempt: null,\n },\n }\n continue\n }\n const replayCase = selected.find((c) => c.trajId === row.trajId && c.corpus === row.corpus)!\n const label = `fix ${row.corpus}/${row.trajId}`\n const signature = verdictByTraj.get(row.trajId)?.signature ?? null\n const stepTimeoutMs = options.stepTimeoutMs ?? replayCase.recordedStepTimeoutMs ?? 120_000\n const promptInput = {\n taskStatement: replayCase.taskStatement,\n steps: replayCase.steps,\n k: replayCase.k,\n }\n const caseOut = join(options.out, caseOutDirName(row))\n\n if (options.fix === 'loop') {\n onProgress(`${label}: fix loop (budget ${fixAttempts} attempts)`)\n const result = await runFixLoop(\n caller,\n promptInput,\n async (command, attempt) => {\n onProgress(\n `${label}: attempt ${attempt} arm B — ${command.split('\\n')[0]!.slice(0, 120)}`,\n )\n const armB = await executeArmB(\n replayCase,\n command,\n backendFactory(row.derivedImage!),\n signature,\n stepTimeoutMs,\n options.prefixLimit,\n (message) => onProgress(`${label}: attempt ${attempt}: ${message}`),\n )\n mkdirSync(caseOut, { recursive: true })\n writeFileSync(\n join(caseOut, `armB-attempt${attempt}-result.json`),\n `${JSON.stringify({ command, ...armB }, null, 2)}\\n`,\n )\n // armB-result.json always holds the LAST executed attempt — the\n // flipped one when the loop flips (it stops there).\n writeFileSync(\n join(caseOut, 'armB-result.json'),\n `${JSON.stringify({ command, attempt, ...armB }, null, 2)}\\n`,\n )\n return armB\n },\n { maxAttempts: fixAttempts, onProgress: (message) => onProgress(`${label}: ${message}`) },\n )\n calls += result.llmCalls\n failures += result.llmFailures\n promptTokens += result.promptTokens\n completionTokens += result.completionTokens\n callsWithoutUsage += result.callsWithoutUsage\n const usage =\n result.promptTokens + result.completionTokens > 0\n ? { promptTokens: result.promptTokens, completionTokens: result.completionTokens }\n : null\n const flippedRecord =\n result.flippedAtAttempt !== null\n ? result.attempts.find((a) => a.attempt === result.flippedAtAttempt)!\n : null\n const summary =\n flippedRecord ?? [...result.attempts].reverse().find((a) => a.executed) ?? null\n const lastRecord = result.attempts.at(-1) ?? null\n rows[index] = {\n ...row,\n fix: summary\n ? {\n attempted: true,\n sampledOut: false,\n command: summary.command,\n llmError: null,\n usage,\n armBExit: summary.exitCode,\n armBPrefixExecuted: summary.prefixExecuted,\n armBPrefixDivergences: summary.prefixDivergences,\n armBPrefixDivergencePct: summary.prefixDivergencePct,\n failureVanished: summary.failureVanished,\n armBError: null,\n attempts: result.attempts,\n flippedAtAttempt: result.flippedAtAttempt,\n }\n : result.aborted\n ? {\n attempted: true,\n sampledOut: false,\n command: lastRecord?.command ?? null,\n llmError: null,\n usage,\n armBExit: null,\n armBPrefixExecuted: null,\n armBPrefixDivergences: null,\n armBPrefixDivergencePct: null,\n failureVanished: null,\n armBError: lastRecord?.armBError ?? 'sandbox error',\n attempts: result.attempts,\n flippedAtAttempt: null,\n }\n : {\n attempted: true,\n sampledOut: false,\n command: null,\n llmError: lastRecord?.llmError ?? 'no attempt produced a runnable fix',\n usage,\n armBExit: null,\n armBPrefixExecuted: null,\n armBPrefixDivergences: null,\n armBPrefixDivergencePct: null,\n failureVanished: null,\n armBError: null,\n attempts: result.attempts,\n flippedAtAttempt: null,\n },\n }\n onProgress(\n `${label}: loop done — flipped=${result.flipped}` +\n (result.flippedAtAttempt !== null ? ` at attempt ${result.flippedAtAttempt}` : '') +\n ` (${result.llmCalls} calls, ${result.attempts.filter((a) => a.executed).length} arms)`,\n )\n continue\n }\n\n onProgress(`${label}: generating corrected command`)\n calls += 1\n const generated = await generateFixCommand(caller, promptInput)\n if (!generated.succeeded) {\n failures += 1\n rows[index] = {\n ...row,\n fix: {\n attempted: true,\n sampledOut: false,\n command: null,\n llmError: generated.error,\n usage: null,\n armBExit: null,\n armBPrefixExecuted: null,\n armBPrefixDivergences: null,\n armBPrefixDivergencePct: null,\n failureVanished: null,\n armBError: null,\n attempts: null,\n flippedAtAttempt: null,\n },\n }\n onProgress(`${label}: LLM failed — ${generated.error.slice(0, 200)}`)\n continue\n }\n if (generated.value.usage === null || generated.value.usage === undefined) {\n callsWithoutUsage += 1\n }\n promptTokens += generated.value.usage?.promptTokens ?? 0\n completionTokens += generated.value.usage?.completionTokens ?? 0\n onProgress(`${label}: arm B — ${generated.value.command.split('\\n')[0]!.slice(0, 120)}`)\n try {\n const armB = await executeArmB(\n replayCase,\n generated.value.command,\n backendFactory(row.derivedImage!),\n signature,\n stepTimeoutMs,\n options.prefixLimit,\n (message) => onProgress(`${label}: ${message}`),\n )\n rows[index] = {\n ...row,\n fix: {\n attempted: true,\n sampledOut: false,\n command: generated.value.command,\n llmError: null,\n usage: generated.value.usage,\n armBExit: armB.exitCode,\n armBPrefixExecuted: armB.prefixExecuted,\n armBPrefixDivergences: armB.prefixDivergences,\n armBPrefixDivergencePct: armB.prefixDivergencePct,\n failureVanished: armB.failureVanished,\n armBError: null,\n attempts: null,\n flippedAtAttempt: armB.failureVanished ? 1 : null,\n },\n }\n mkdirSync(caseOut, { recursive: true })\n writeFileSync(\n join(caseOut, 'armB-result.json'),\n `${JSON.stringify({ command: generated.value.command, ...armB }, null, 2)}\\n`,\n )\n onProgress(`${label}: armB exit=${armB.exitCode} failureVanished=${armB.failureVanished}`)\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n rows[index] = {\n ...row,\n fix: {\n attempted: true,\n sampledOut: false,\n command: generated.value.command,\n llmError: null,\n usage: generated.value.usage,\n armBExit: null,\n armBPrefixExecuted: null,\n armBPrefixDivergences: null,\n armBPrefixDivergencePct: null,\n failureVanished: null,\n armBError: message.slice(0, 500),\n attempts: null,\n flippedAtAttempt: null,\n },\n }\n onProgress(`${label}: arm B error — ${message.slice(0, 200)}`)\n }\n }\n llm = {\n model: options.fixModelLabel ?? 'unknown',\n calls,\n failures,\n promptTokens,\n completionTokens,\n callsWithoutUsage,\n }\n }\n\n const executedRows = rows.filter((r) => r.status === 'ok')\n const replayed = executedRows.filter((r) => r.replayed)\n const sumOver = (pick: (row: ReplayBatchCaseRow) => number | null): number =>\n executedRows.reduce((total, row) => total + (pick(row) ?? 0), 0)\n const executedSteps = sumOver((r) => r.prefixExecuted)\n const divergentSteps = sumOver((r) => r.prefixDivergences)\n const prefixFidelity = {\n executedSteps,\n divergentSteps,\n returncodeMismatches: sumOver((r) => r.prefixReturncodeMismatches),\n unknownExpectations: sumOver((r) => r.prefixUnknownExpectations),\n divergencePct:\n executedSteps > 0 ? Number(((divergentSteps / executedSteps) * 100).toFixed(1)) : null,\n tolerancePct: PREFIX_DIVERGENCE_TOLERANCE_PCT,\n casesWithinTolerance: executedRows.filter(\n (r) =>\n r.prefixDivergencePct !== null && r.prefixDivergencePct <= PREFIX_DIVERGENCE_TOLERANCE_PCT,\n ).length,\n casesExecuted: executedRows.length,\n }\n const signatureStrict = executedRows.filter((r) => r.replayed && r.armASignatureMatch)\n const armBExecuted = rows.filter((r) => r.fix?.attempted && r.fix.failureVanished !== null)\n const flipped = armBExecuted.filter((r) => r.fix!.failureVanished === true)\n const armBNonzeroRc = armBExecuted.filter(\n (r) => r.recordedReturncodeAtK !== null && r.recordedReturncodeAtK !== 0,\n )\n const flippedNonzeroRc = armBNonzeroRc.filter((r) => r.fix!.failureVanished === true)\n const attempt1Executed = rows.filter(\n (r) => r.fix?.attempts?.find((a) => a.attempt === 1)?.executed === true,\n )\n const flippedAt1 = rows.filter((r) => r.fix?.flippedAtAttempt === 1)\n const flipsByAttempt: Record<string, number> = {}\n for (const row of rows) {\n const at = row.fix?.flippedAtAttempt\n if (typeof at === 'number') flipsByAttempt[String(at)] = (flipsByAttempt[String(at)] ?? 0) + 1\n }\n const excludedByReason: Record<string, number> = {}\n for (const excluded of enumeration.excluded) {\n excludedByReason[excluded.reason] = (excludedByReason[excluded.reason] ?? 0) + 1\n }\n const submitGoldsByCorpus: Record<\n string,\n { submitOnlyCases: number; goldsSkippedWithinReplayable: number }\n > = {}\n const submitEntry = (corpus: string) =>\n (submitGoldsByCorpus[corpus] ??= { submitOnlyCases: 0, goldsSkippedWithinReplayable: 0 })\n for (const excluded of enumeration.excluded) {\n if (excluded.reason === 'gold-only-submit-step')\n submitEntry(excluded.corpus).submitOnlyCases += 1\n }\n for (const replayCase of enumeration.replayable) {\n if (replayCase.submitGoldsSkipped > 0) {\n submitEntry(replayCase.corpus).goldsSkippedWithinReplayable += replayCase.submitGoldsSkipped\n }\n }\n\n const report: ReplayBatchReport = {\n generatedAt: new Date().toISOString(),\n corpora: options.corpora.map((c) => ({\n name: c.name,\n labelsPath: c.labelsPath,\n preparedDir: c.preparedDir,\n })),\n totals: {\n labelEntries: enumeration.labelEntryCount,\n replayable: enumeration.replayable.length,\n executed: selected.length,\n excludedByReason,\n submitGoldsByCorpus,\n },\n headline: {\n replayabilityRate: {\n numerator: replayed.length,\n denominator: selected.length,\n value: rate(replayed.length, selected.length),\n },\n signatureStrictRate: {\n numerator: signatureStrict.length,\n denominator: selected.length,\n value: rate(signatureStrict.length, selected.length),\n },\n prefixFidelity,\n fixFlipRate:\n options.fix !== 'none'\n ? {\n numerator: flipped.length,\n denominator: armBExecuted.length,\n value: rate(flipped.length, armBExecuted.length),\n }\n : null,\n fixFlipRateNonzeroRc:\n options.fix !== 'none'\n ? {\n numerator: flippedNonzeroRc.length,\n denominator: armBNonzeroRc.length,\n value: rate(flippedNonzeroRc.length, armBNonzeroRc.length),\n }\n : null,\n fixFlipAttempt1:\n options.fix === 'loop'\n ? {\n numerator: flippedAt1.length,\n denominator: attempt1Executed.length,\n value: rate(flippedAt1.length, attempt1Executed.length),\n }\n : null,\n flipsByAttempt: options.fix === 'loop' ? flipsByAttempt : null,\n },\n llm,\n excluded: enumeration.excluded,\n pullFailures,\n cases: rows,\n }\n writeFileSync(join(options.out, 'batch-report.json'), `${JSON.stringify(report, null, 2)}\\n`)\n writeFileSync(join(options.out, 'batch-report.md'), renderBatchReport(report))\n return report\n}\n\n// ── Report rendering ─────────────────────────────────────────────────\n\nfunction pct(value: number | null): string {\n return value === null ? '—' : `${(value * 100).toFixed(1)}%`\n}\n\nexport function renderBatchReport(report: ReplayBatchReport): string {\n const lines: string[] = []\n const { headline, totals } = report\n lines.push('# Replay-verify batch report')\n lines.push('')\n lines.push(`Generated ${report.generatedAt}.`)\n lines.push('')\n lines.push('## Headline')\n lines.push('')\n const fidelity = headline.prefixFidelity\n lines.push(\n `- **Replayability rate: ${pct(headline.replayabilityRate.value)}** ` +\n `(${headline.replayabilityRate.numerator}/${headline.replayabilityRate.denominator} replayable cases ` +\n `where the prefix replayed within ${fidelity.tolerancePct}% divergence AND arm A reproduced the recorded returncode at the gold step k).`,\n )\n lines.push(\n `- Signature-strict rate: ${pct(headline.signatureStrictRate.value)} ` +\n `(${headline.signatureStrictRate.numerator}/${headline.signatureStrictRate.denominator}; additionally requires the recorded error substring in arm A output).`,\n )\n lines.push(\n `- **Prefix divergence: ${fidelity.divergencePct === null ? '—' : `${fidelity.divergencePct}%`}** ` +\n `(${fidelity.divergentSteps}/${fidelity.executedSteps} executed prefix steps did not confirm the recording: ` +\n `${fidelity.returncodeMismatches} returncode mismatches, ${fidelity.unknownExpectations} with no recorded returncode to check). ` +\n `${fidelity.casesWithinTolerance}/${fidelity.casesExecuted} executed cases are within the ${fidelity.tolerancePct}% tolerance.`,\n )\n if (headline.fixFlipRate) {\n lines.push(\n `- **Fix-flip rate: ${pct(headline.fixFlipRate.value)}** ` +\n `(${headline.fixFlipRate.numerator}/${headline.fixFlipRate.denominator} arm-B-executed cases where the generated fix made the failure vanish).`,\n )\n }\n if (headline.fixFlipRateNonzeroRc) {\n lines.push(\n `- Fix-flip rate on recorded-rc≠0 cases: ${pct(headline.fixFlipRateNonzeroRc.value)} ` +\n `(${headline.fixFlipRateNonzeroRc.numerator}/${headline.fixFlipRateNonzeroRc.denominator}; real recorded failures — a gold step recorded with rc 0 flips vacuously).`,\n )\n }\n if (headline.fixFlipAttempt1) {\n lines.push(\n `- Fix-flip@1: ${pct(headline.fixFlipAttempt1.value)} ` +\n `(${headline.fixFlipAttempt1.numerator}/${headline.fixFlipAttempt1.denominator} cases whose attempt 1 executed — the one-shot-comparable number).`,\n )\n }\n if (headline.flipsByAttempt && Object.keys(headline.flipsByAttempt).length > 0) {\n const parts = Object.entries(headline.flipsByAttempt)\n .sort((a, b) => Number(a[0]) - Number(b[0]))\n .map(([attempt, count]) => `attempt ${attempt}: ${count}`)\n lines.push(`- Flips by attempt: ${parts.join(', ')}.`)\n }\n lines.push('')\n lines.push('## Enumeration')\n lines.push('')\n lines.push(\n `${totals.labelEntries} label entries across ${report.corpora.length} corpora → ` +\n `${totals.replayable} replayable (SWE-style docker image + ≥1 gold incorrect step), ${totals.executed} executed.`,\n )\n lines.push('')\n lines.push('| exclusion reason | count |')\n lines.push('| --- | --- |')\n for (const [reason, count] of Object.entries(totals.excludedByReason).sort(\n (a, b) => b[1] - a[1],\n )) {\n lines.push(`| ${reason} | ${count} |`)\n }\n const submitEntries = Object.entries(totals.submitGoldsByCorpus)\n if (submitEntries.length > 0) {\n lines.push('')\n lines.push(\n 'Submit-command golds are never counterfactual targets ' +\n '(a gold on the submit step marks a bad submit decision, not a failed command):',\n )\n lines.push('')\n lines.push(\n '| corpus | cases excluded (all golds = submit) | golds skipped within replayable cases |',\n )\n lines.push('| --- | --- | --- |')\n for (const [corpus, stats] of submitEntries.sort((a, b) => a[0].localeCompare(b[0]))) {\n lines.push(`| ${corpus} | ${stats.submitOnlyCases} | ${stats.goldsSkippedWithinReplayable} |`)\n }\n }\n if (report.pullFailures.length > 0) {\n lines.push('')\n lines.push('## Image pull/build failures')\n lines.push('')\n lines.push('| corpus | trajectory | image | error |')\n lines.push('| --- | --- | --- | --- |')\n for (const failure of report.pullFailures) {\n lines.push(\n `| ${failure.corpus} | ${failure.trajId} | \\`${failure.image}\\` | ${failure.error.replaceAll('|', '\\\\|')} |`,\n )\n }\n }\n lines.push('')\n lines.push('## Per-case results')\n lines.push('')\n lines.push(\n '| corpus | trajectory | k | rc@k | prefix | confirmed | rc mismatch | unknown rc | div | div% | armA exit | rc match | sig match | replayed | fix | armB exit | armB div% | vanished | wall s |',\n )\n lines.push(`| ${Array(19).fill('---').join(' | ')} |`)\n for (const row of report.cases) {\n const fix = row.fix\n const fixCell = !fix\n ? '—'\n : fix.sampledOut\n ? 'sampled-out'\n : fix.llmError\n ? 'llm-failed'\n : fix.armBError\n ? 'armB-error'\n : fix.attempts\n ? fix.flippedAtAttempt !== null\n ? `flip@${fix.flippedAtAttempt}`\n : `exhausted(${fix.attempts.length})`\n : 'generated'\n lines.push(\n [\n row.corpus,\n row.trajId.length > 48 ? `${row.trajId.slice(0, 45)}…` : row.trajId,\n row.k,\n row.recordedReturncodeAtK ?? 'null',\n row.prefixExecuted ?? '—',\n row.prefixConfirmed ?? '—',\n row.prefixReturncodeMismatches ?? '—',\n row.prefixUnknownExpectations ?? '—',\n row.prefixDivergences ?? '—',\n row.prefixDivergencePct ?? '—',\n row.status === 'ok' ? row.armAExit : row.status,\n row.armAReturncodeMatch ? 'yes' : 'no',\n row.armASignatureMatch ? 'yes' : 'no',\n row.replayed ? '**yes**' : 'no',\n fixCell,\n fix?.armBExit ?? '—',\n fix?.armBPrefixDivergencePct ?? '—',\n fix?.failureVanished === null || fix === null\n ? '—'\n : fix.failureVanished\n ? '**yes**'\n : 'no',\n (row.wallMs / 1000).toFixed(1),\n ].join(' | '),\n )\n }\n if (report.llm) {\n lines.push('')\n lines.push('## LLM fix generation')\n lines.push('')\n lines.push(\n `Model ${report.llm.model}: ${report.llm.calls} calls (${report.llm.failures} failed), ` +\n `${report.llm.promptTokens} prompt + ${report.llm.completionTokens} completion tokens.`,\n )\n }\n lines.push('')\n return lines.join('\\n')\n}\n","/**\n * Finding-to-replay wire: the entry point that turns a cited incorrect-steps\n * finding into an executed replay proof.\n *\n * An analyst finding over a labeled trajectory corpus names its trajectory and\n * carries a subject of the form\n * `incorrect-steps-<first>-<last>-<escaped|unescaped>-consequence-<step>`.\n * The wire maps that to a replay invocation: the executed step is the\n * finding's first incorrect step (which may differ from the gold label), the\n * image and cwd come from the trajectory's raw config, and — optionally — an\n * arm-B corrected command comes from the counterfactual fix generator.\n */\n\nimport { type CaseResources, type CorpusSpec, resolveCaseResources } from './corpus'\nimport type { ReplayExecBackendFactory } from './exec'\nimport { type ChatCompletionCaller, generateFixCommand } from './fix'\nimport { type ReplayVerdict, replayVerify } from './verify'\n\nexport interface IncorrectStepsSubject {\n readonly firstStep: number\n readonly lastStep: number\n readonly escapeStatus: 'escaped' | 'unescaped'\n readonly consequenceStep: number\n}\n\nconst SUBJECT_PATTERN = /^incorrect-steps-(\\d+)-(\\d+)-(escaped|unescaped)-consequence-(\\d+)$/\n\n/** Null when the subject is not an incorrect-steps finding subject. */\nexport function parseIncorrectStepsSubject(subject: string): IncorrectStepsSubject | null {\n const match = SUBJECT_PATTERN.exec(subject)\n if (!match) return null\n return {\n firstStep: Number(match[1]),\n lastStep: Number(match[2]),\n escapeStatus: match[3] as 'escaped' | 'unescaped',\n consequenceStep: Number(match[4]),\n }\n}\n\nexport interface AnalystReplayFinding {\n readonly trajId: string\n readonly subject: string\n}\n\nexport interface ResolvedReplayInvocation {\n readonly resources: CaseResources\n readonly subject: IncorrectStepsSubject\n /** 1-based step_id arm A executes: the finding's first incorrect step. */\n readonly at: number\n}\n\n/**\n * Maps a finding onto replay resources, searching the given corpora for the\n * trajectory. Throws with the precise reason when the finding cannot be\n * replayed (malformed subject, unknown trajectory, non-replayable case, step\n * out of range) — the caller surfaces that reason instead of a proof.\n */\nexport function resolveFindingInvocation(\n finding: AnalystReplayFinding,\n corpora: readonly CorpusSpec[],\n): ResolvedReplayInvocation {\n const subject = parseIncorrectStepsSubject(finding.subject)\n if (!subject) {\n throw new Error(\n `trajectory-replay: subject '${finding.subject}' is not incorrect-steps-<first>-<last>-<escaped|unescaped>-consequence-<step>`,\n )\n }\n const failures: string[] = []\n for (const corpus of corpora) {\n const resolution = resolveCaseResources(corpus, finding.trajId)\n if (resolution.resolved) {\n const at = subject.firstStep\n const step = resolution.resources.steps.find((s) => s.step_id === at)\n if (!step) {\n throw new Error(\n `trajectory-replay: finding step ${at} is outside ${finding.trajId} ` +\n `(${resolution.resources.steps.length} steps)`,\n )\n }\n return { resources: resolution.resources, subject, at }\n }\n failures.push(`${corpus.name}: ${resolution.reason}`)\n }\n throw new Error(\n `trajectory-replay: trajectory ${finding.trajId} is not replayable in any corpus — ${failures.join('; ')}`,\n )\n}\n\nexport interface ReplayFindingOptions {\n readonly corpora: readonly CorpusSpec[]\n readonly out: string\n /** Generates the arm-B corrected command; omit to run arm A only. */\n readonly fixCaller?: ChatCompletionCaller\n /** Pre-supplied arm-B command; mutually exclusive with fixCaller. */\n readonly fixCommand?: string\n readonly stepTimeoutMs?: number\n readonly prefixLimit?: number\n /** Builds the exec backend for the resolved trajectory image. */\n readonly backendFactory: ReplayExecBackendFactory\n readonly onProgress?: (message: string) => void\n}\n\nexport interface ReplayFindingResult {\n readonly invocation: ResolvedReplayInvocation\n readonly fixCommand: string | null\n readonly verdict: ReplayVerdict\n}\n\n/**\n * Finding in, executed proof out. The image comes from the corpus resources;\n * the backend factory receives it as-is, so a factory backed by infrastructure\n * that needs a derived image must run an `ImagePreparer` first.\n */\nexport async function replayVerifyFinding(\n finding: AnalystReplayFinding,\n options: ReplayFindingOptions,\n): Promise<ReplayFindingResult> {\n if (options.fixCaller && options.fixCommand !== undefined) {\n throw new Error('trajectory-replay: pass fixCaller or fixCommand, not both')\n }\n const invocation = resolveFindingInvocation(finding, options.corpora)\n let fixCommand: string | null = options.fixCommand ?? null\n if (options.fixCaller) {\n const generated = await generateFixCommand(options.fixCaller, {\n taskStatement: invocation.resources.taskStatement,\n steps: invocation.resources.steps,\n k: invocation.at,\n })\n if (!generated.succeeded) {\n throw new Error(`trajectory-replay: fix generation failed — ${generated.error}`)\n }\n fixCommand = generated.value.command\n }\n const verdict = await replayVerify({\n stepsPath: invocation.resources.stepsPath,\n image: invocation.resources.image,\n at: invocation.at,\n fixCommand: fixCommand ?? undefined,\n cwd: invocation.resources.cwd,\n out: options.out,\n caseId: invocation.resources.trajId,\n stepTimeoutMs: options.stepTimeoutMs ?? invocation.resources.recordedStepTimeoutMs ?? undefined,\n prefixLimit: options.prefixLimit,\n backend: options.backendFactory(invocation.resources.image),\n onProgress: options.onProgress,\n })\n return { invocation, fixCommand, verdict }\n}\n","/**\n * Proof-carrying findings: execute analyst findings as replays.\n *\n * An analyst finding is a cited claim (\"step 12 is where the run went\n * wrong\"). This module turns each finding into an executed verdict by\n * replaying the trajectory prefix and running the accused step (arm A),\n * optionally followed by a corrected step (arm B):\n *\n * `reproduced` arm A re-produced the recorded failure signature\n * (returncode + stable output substring).\n * `fix-flipped` arm A reproduced AND arm B's corrected command made the\n * failure vanish — the strongest per-finding proof.\n * `divergent` arm A executed but the recorded failure did NOT\n * reproduce; evidence against the finding (or against\n * replay fidelity — the receipt carries prefix\n * divergences so the reader can tell which).\n * `not-replayable` the finding could not be executed at all; the receipt\n * carries the precise reason (no step subject, unknown\n * trajectory, no recorded image, submit step, …).\n *\n * Verification is execution, not generation: no LLM is involved unless the\n * caller supplies a corrected command for arm B. A caller whose execution\n * environment must be reachable before proofs run passes `preflight`, which\n * fails loud instead of letting verification skip silently.\n *\n * Findings are matched by the shape the analyst product emits\n * (`AnalystFinding`): `subject` (`incorrect-step-<n>` or the wire's\n * `incorrect-steps-<f>-<l>-<escaped|unescaped>-consequence-<c>`),\n * `metadata.block_first_step`, and `trace://<traj>/…` evidence refs.\n */\n\nimport { mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { packageVersion } from '../package-version'\nimport { certificationEvidenceDigest, type DefaultVerdict } from '../verdict'\nimport { type CorpusSpec, resolveCaseResources } from './corpus'\nimport type { ReplayExecBackendFactory } from './exec'\nimport { dockerImagePreparer, type ImagePreparer } from './image-preparer'\nimport { isSubmitAction, parseRecordedReturncode, type RecordedTrajectoryStep } from './steps'\nimport { type ReplayVerdict, replayVerify } from './verify'\nimport { parseIncorrectStepsSubject } from './wire'\n\n// ── Finding shape (structural subset of the analyst's AnalystFinding) ─\n\nexport interface VerifiableFinding {\n readonly finding_id?: string\n readonly analyst_id?: string\n readonly subject?: string\n readonly area?: string\n readonly claim?: string\n readonly evidence_refs?: readonly {\n readonly kind?: string\n readonly uri?: string\n readonly excerpt?: string\n }[]\n readonly metadata?: Readonly<Record<string, unknown>>\n}\n\nconst SINGLE_STEP_SUBJECT = /^incorrect-step-(\\d+)$/\n\n/**\n * 1-based step the finding accuses, or null when the finding names none.\n * `metadata.block_first_step` wins over the subject: the analyst records the\n * block's first incorrect step there even when the subject names a later\n * step of the same block.\n */\nexport function findingReplayStep(finding: VerifiableFinding): number | null {\n const fromMetadata = finding.metadata?.block_first_step\n if (typeof fromMetadata === 'number' && Number.isInteger(fromMetadata) && fromMetadata >= 1) {\n return fromMetadata\n }\n const subject = finding.subject ?? ''\n const wire = parseIncorrectStepsSubject(subject)\n if (wire) return wire.firstStep\n const single = SINGLE_STEP_SUBJECT.exec(subject)\n if (single) return Number(single[1])\n return null\n}\n\nconst TRACE_EVIDENCE_URI = /^trace:\\/\\/([^/]+)\\//\n\n/** Trajectory id from the finding's `trace://<traj>/…` evidence refs, or null. */\nexport function findingTrajectoryId(finding: VerifiableFinding): string | null {\n for (const ref of finding.evidence_refs ?? []) {\n if (typeof ref.uri !== 'string') continue\n const match = TRACE_EVIDENCE_URI.exec(ref.uri)\n if (match) return match[1]!\n }\n return null\n}\n\n// ── Replay source ────────────────────────────────────────────────────\n\n/**\n * Where the executable trajectory lives.\n * `direct` — one trajectory's steps.json plus a replay-ready image; the\n * caller owns image preparation.\n * `corpus` — labeled trajectory corpora; each finding's trajectory is\n * resolved by its `trace://` evidence and the image is derived through\n * `preparer` (the docker uid-1000 preparer unless overridden; `null` when\n * the images are already replay-ready).\n */\nexport type FindingReplaySource =\n | {\n readonly kind: 'direct'\n readonly stepsPath: string\n readonly image: string\n readonly cwd: string\n readonly caseId?: string\n }\n | {\n readonly kind: 'corpus'\n readonly corpora: readonly CorpusSpec[]\n readonly preparer?: ImagePreparer | null\n }\n\nexport interface ResolvedFindingReplay {\n readonly caseId: string\n readonly stepsPath: string\n /** Raw image; corpus-mode execution derives the replay image from it. */\n readonly image: string\n readonly cwd: string\n /** 1-based step_id arm A executes. */\n readonly at: number\n readonly recordedReturncode: number\n readonly recordedStepTimeoutMs: number | null\n}\n\nexport type FindingReplayability =\n | { readonly replayable: true; readonly resolved: ResolvedFindingReplay }\n | { readonly replayable: false; readonly reason: string }\n\nfunction checkStep(\n steps: readonly RecordedTrajectoryStep[],\n at: number,\n):\n | { readonly ok: true; readonly recordedReturncode: number }\n | { readonly ok: false; readonly reason: string } {\n const step = steps.find((s) => s.step_id === at)\n if (!step) {\n return { ok: false, reason: `step ${at} is outside the trajectory (${steps.length} steps)` }\n }\n if (isSubmitAction(step.action)) {\n return {\n ok: false,\n reason: `step ${at} is the submit action — a submit decision has no executable failure to replay`,\n }\n }\n const recordedReturncode = parseRecordedReturncode(step.observation)\n if (recordedReturncode === null) {\n return {\n ok: false,\n reason: `step ${at} recorded no returncode — there is no executable failure signature to reproduce`,\n }\n }\n return { ok: true, recordedReturncode }\n}\n\n/**\n * Decides whether one finding can be executed against the source, and with\n * what invocation. Never throws for a finding-shaped problem — every dead end\n * becomes a `not-replayable` reason the receipt can carry verbatim.\n */\nexport function resolveFindingReplayability(\n finding: VerifiableFinding,\n source: FindingReplaySource,\n): FindingReplayability {\n const at = findingReplayStep(finding)\n if (at === null) {\n return {\n replayable: false,\n reason:\n `subject '${finding.subject ?? '(none)'}' names no trajectory step ` +\n '(expected incorrect-step-<n>, incorrect-steps-<f>-<l>-…, or metadata.block_first_step)',\n }\n }\n if (source.kind === 'direct') {\n const trajId = findingTrajectoryId(finding)\n if (trajId && source.caseId && trajId !== source.caseId) {\n return {\n replayable: false,\n reason: `finding cites trajectory '${trajId}' but the supplied steps are case '${source.caseId}'`,\n }\n }\n let steps: RecordedTrajectoryStep[]\n try {\n steps = JSON.parse(readFileSync(source.stepsPath, 'utf8')) as RecordedTrajectoryStep[]\n } catch (err) {\n throw new Error(\n `verify-findings: cannot read steps file ${source.stepsPath} — ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n if (!Array.isArray(steps) || steps.length === 0) {\n throw new Error(`verify-findings: ${source.stepsPath} is not a non-empty steps array`)\n }\n const step = checkStep(steps, at)\n if (!step.ok) return { replayable: false, reason: step.reason }\n return {\n replayable: true,\n resolved: {\n caseId: source.caseId ?? trajId ?? source.stepsPath,\n stepsPath: source.stepsPath,\n image: source.image,\n cwd: source.cwd,\n at,\n recordedReturncode: step.recordedReturncode,\n recordedStepTimeoutMs: null,\n },\n }\n }\n const trajId = findingTrajectoryId(finding)\n if (!trajId) {\n return {\n replayable: false,\n reason: 'finding carries no trace://<trajectory>/ evidence ref naming its trajectory',\n }\n }\n const failures: string[] = []\n for (const corpus of source.corpora) {\n const resolution = resolveCaseResources(corpus, trajId)\n if (!resolution.resolved) {\n failures.push(\n `${corpus.name}: ${resolution.reason}${resolution.detail ? ` (${resolution.detail})` : ''}`,\n )\n continue\n }\n const step = checkStep(resolution.resources.steps, at)\n if (!step.ok) return { replayable: false, reason: step.reason }\n return {\n replayable: true,\n resolved: {\n caseId: trajId,\n stepsPath: resolution.resources.stepsPath,\n image: resolution.resources.image,\n cwd: resolution.resources.cwd,\n at,\n recordedReturncode: step.recordedReturncode,\n recordedStepTimeoutMs: resolution.resources.recordedStepTimeoutMs,\n },\n }\n }\n return {\n replayable: false,\n reason: `trajectory ${trajId} is not replayable in any corpus — ${failures.join('; ')}`,\n }\n}\n\n// ── Verification run ─────────────────────────────────────────────────\n\nexport type FindingVerificationStatus =\n | 'reproduced'\n | 'fix-flipped'\n | 'not-replayable'\n | 'divergent'\n\nexport interface FindingVerification {\n readonly finding_id: string | null\n readonly subject: string | null\n readonly trajectory_id: string | null\n /** 1-based step the proof executed at; null when not replayable. */\n readonly step: number | null\n readonly verified: FindingVerificationStatus\n /** Present exactly when `verified` is `not-replayable`. */\n readonly reason: string | null\n /** Receipt directory: receipt.json plus, when executed, replay-verdict.json + report.md. */\n readonly receipt: string\n readonly verdict_path: string | null\n /** Receipt dir of the executed proof this finding shares (same case, step, and fix). */\n readonly deduplicated_with: string | null\n}\n\n/** Extends the substrate verdict spine over the whole batch: `score` =\n * verified findings (reproduced or fix-flipped) over MEASURABLE findings —\n * not-replayable rows leave the denominator, mirroring the completion\n * verifier's unmeasured rule — and `valid` = every finding was measured and\n * verified. Certification is present exactly when at least one proof\n * executed; a run that executed nothing certifies nothing. */\nexport interface VerifyFindingsRun extends DefaultVerdict {\n readonly out: string\n readonly verifications: readonly FindingVerification[]\n readonly counts: Readonly<Record<FindingVerificationStatus, number>>\n /** Executions actually performed (deduplicated proofs count once). */\n readonly executions: number\n}\n\nexport interface VerifyFindingsOptions {\n readonly source: FindingReplaySource\n /** Receipt root; one subdirectory per finding plus verifications.json. */\n readonly out: string\n /** Corrected command for arm B on every executed finding; omit for arm A only. */\n readonly fixCommand?: string\n readonly stepTimeoutMs?: number\n readonly prefixLimit?: number\n /** Builds the exec backend for a finding's replay image. */\n readonly backendFactory: ReplayExecBackendFactory\n /** Runs once before the first proof, only when some finding is replayable.\n * Throw to refuse execution against absent or degraded infrastructure. */\n readonly preflight?: () => Promise<void>\n readonly onProgress?: (message: string) => void\n}\n\n/**\n * Arm A reproduced on a prefix the recording confirmed → the fix flipping it\n * beats plain reproduction; anything else diverged. A proof standing on a\n * prefix outside the divergence tolerance is divergent no matter what arm A\n * did: the state it ran against is not the recorded state.\n */\nexport function classifyVerdict(verdict: ReplayVerdict): FindingVerificationStatus {\n if (!verdict.prefixWithinTolerance) return 'divergent'\n if (!verdict.armA.failureSignatureMatch) return 'divergent'\n if (verdict.armB?.failureVanished) return 'fix-flipped'\n return 'reproduced'\n}\n\ninterface ReceiptExecution {\n readonly image: string\n readonly cwd: string\n readonly recordedReturncode: number | null\n readonly signature: string | null\n readonly signatureBasis: string\n readonly armA: {\n readonly command: string\n readonly exitCode: number\n readonly wallMs: number\n readonly failureSignatureMatch: boolean\n }\n readonly armB: {\n readonly command: string\n readonly exitCode: number\n readonly wallMs: number\n readonly failureVanished: boolean\n } | null\n readonly prefixExecuted: number\n readonly prefixDivergences: number\n readonly prefixDivergencePct: number\n readonly prefixReturncodeMismatches: number\n readonly prefixUnknownExpectations: number\n readonly prefixWithinTolerance: boolean\n readonly totalMs: number\n}\n\nfunction receiptExecution(verdict: ReplayVerdict): ReceiptExecution {\n return {\n image: verdict.image,\n cwd: verdict.cwd,\n recordedReturncode: verdict.recordedReturncode,\n signature: verdict.signature,\n signatureBasis: verdict.signatureBasis,\n armA: {\n command: verdict.armA.command,\n exitCode: verdict.armA.exitCode,\n wallMs: verdict.armA.wallMs,\n failureSignatureMatch: verdict.armA.failureSignatureMatch,\n },\n armB: verdict.armB\n ? {\n command: verdict.armB.command,\n exitCode: verdict.armB.exitCode,\n wallMs: verdict.armB.wallMs,\n failureVanished: verdict.armB.failureVanished,\n }\n : null,\n prefixExecuted: verdict.prefixExecuted,\n prefixDivergences: verdict.prefixDivergences.length,\n prefixDivergencePct: verdict.prefixDivergencePct,\n prefixReturncodeMismatches: verdict.prefixReturncodeMismatches,\n prefixUnknownExpectations: verdict.prefixUnknownExpectations,\n prefixWithinTolerance: verdict.prefixWithinTolerance,\n totalMs: verdict.timings.totalMs,\n }\n}\n\nfunction writeReceipt(\n receiptDir: string,\n finding: VerifiableFinding,\n verification: FindingVerification,\n execution: ReceiptExecution | null,\n): void {\n const receipt = {\n schema_version: '1.0.0',\n produced_at: new Date().toISOString(),\n finding_id: verification.finding_id,\n analyst_id: finding.analyst_id ?? null,\n subject: verification.subject,\n claim: typeof finding.claim === 'string' ? finding.claim.slice(0, 600) : null,\n trajectory_id: verification.trajectory_id,\n step: verification.step,\n verified: verification.verified,\n reason: verification.reason,\n execution,\n verdict_path: verification.verdict_path,\n deduplicated_with: verification.deduplicated_with,\n }\n writeFileSync(join(receiptDir, 'receipt.json'), `${JSON.stringify(receipt, null, 2)}\\n`)\n}\n\nfunction receiptDirName(index: number, finding: VerifiableFinding): string {\n const id =\n typeof finding.finding_id === 'string' && finding.finding_id.length > 0\n ? finding.finding_id.replace(/[^A-Za-z0-9_-]/g, '_')\n : 'finding'\n return `${String(index + 1).padStart(3, '0')}-${id}`\n}\n\n/**\n * Verifies every finding against the source: resolves replayability, executes\n * one proof per distinct (case, step, fix) — findings accusing the same step\n * share the executed proof — and writes a receipt directory per finding plus a\n * run-level verifications.json.\n */\nexport async function verifyFindings(\n findings: readonly VerifiableFinding[],\n options: VerifyFindingsOptions,\n): Promise<VerifyFindingsRun> {\n if (findings.length === 0) throw new Error('verify-findings: no findings to verify')\n mkdirSync(options.out, { recursive: true })\n const resolutions = findings.map((finding) =>\n resolveFindingReplayability(finding, options.source),\n )\n if (resolutions.some((resolution) => resolution.replayable) && options.preflight) {\n await options.preflight()\n }\n\n // `null` is the caller asserting the corpus images are already replay-ready;\n // only an ABSENT field falls back to the docker preparer.\n const preparer =\n options.source.kind === 'corpus'\n ? options.source.preparer === undefined\n ? dockerImagePreparer()\n : options.source.preparer\n : null\n const preparedImages = new Map<\n string,\n | { readonly succeeded: true; readonly image: string }\n | { readonly succeeded: false; readonly error: string }\n >()\n const executedByKey = new Map<string, FindingVerification>()\n const verifications: FindingVerification[] = []\n let executions = 0\n\n for (let index = 0; index < findings.length; index++) {\n const finding = findings[index]!\n const resolution = resolutions[index]!\n const receiptDir = join(options.out, receiptDirName(index, finding))\n mkdirSync(receiptDir, { recursive: true })\n const identity = {\n finding_id: finding.finding_id ?? null,\n subject: finding.subject ?? null,\n trajectory_id: findingTrajectoryId(finding),\n }\n\n if (!resolution.replayable) {\n const verification: FindingVerification = {\n ...identity,\n step: findingReplayStep(finding),\n verified: 'not-replayable',\n reason: resolution.reason,\n receipt: receiptDir,\n verdict_path: null,\n deduplicated_with: null,\n }\n writeReceipt(receiptDir, finding, verification, null)\n verifications.push(verification)\n options.onProgress?.(\n `${identity.finding_id ?? `finding ${index + 1}`}: not-replayable — ${resolution.reason}`,\n )\n continue\n }\n\n const resolved = resolution.resolved\n const dedupeKey = `${resolved.caseId}::${resolved.at}::${options.fixCommand ?? ''}`\n const prior = executedByKey.get(dedupeKey)\n if (prior) {\n const verification: FindingVerification = {\n ...identity,\n step: resolved.at,\n verified: prior.verified,\n reason: prior.reason,\n receipt: receiptDir,\n verdict_path: prior.verdict_path,\n deduplicated_with: prior.receipt,\n }\n const priorVerdict = prior.verdict_path\n ? (JSON.parse(readFileSync(prior.verdict_path, 'utf8')) as ReplayVerdict)\n : null\n writeReceipt(\n receiptDir,\n finding,\n verification,\n priorVerdict ? receiptExecution(priorVerdict) : null,\n )\n verifications.push(verification)\n options.onProgress?.(\n `${identity.finding_id ?? `finding ${index + 1}`}: ${prior.verified} (shares proof with ${prior.finding_id ?? prior.receipt})`,\n )\n continue\n }\n\n let image = resolved.image\n if (preparer) {\n const preparationKey = `${resolved.image}::${resolved.cwd}`\n let preparation = preparedImages.get(preparationKey)\n if (!preparation) {\n const ensured = await preparer.ensure(resolved.image, resolved.cwd)\n preparation = ensured.succeeded\n ? { succeeded: true, image: ensured.value.derivedImage }\n : { succeeded: false, error: ensured.error }\n preparedImages.set(preparationKey, preparation)\n }\n if (!preparation.succeeded) {\n const verification: FindingVerification = {\n ...identity,\n step: resolved.at,\n verified: 'not-replayable',\n reason: `replay image could not be prepared — ${preparation.error}`,\n receipt: receiptDir,\n verdict_path: null,\n deduplicated_with: null,\n }\n writeReceipt(receiptDir, finding, verification, null)\n verifications.push(verification)\n options.onProgress?.(\n `${identity.finding_id ?? `finding ${index + 1}`}: not-replayable — image preparation failed`,\n )\n continue\n }\n image = preparation.image\n }\n\n options.onProgress?.(\n `${identity.finding_id ?? `finding ${index + 1}`}: executing arm A at step ${resolved.at} of ${resolved.caseId} on ${image}`,\n )\n const verdict = await replayVerify({\n stepsPath: resolved.stepsPath,\n image,\n at: resolved.at,\n fixCommand: options.fixCommand,\n cwd: resolved.cwd,\n out: receiptDir,\n caseId: resolved.caseId,\n stepTimeoutMs: options.stepTimeoutMs ?? resolved.recordedStepTimeoutMs ?? undefined,\n prefixLimit: options.prefixLimit,\n backend: options.backendFactory(image),\n onProgress: options.onProgress,\n })\n executions += 1\n const verification: FindingVerification = {\n ...identity,\n step: resolved.at,\n verified: classifyVerdict(verdict),\n reason: null,\n receipt: receiptDir,\n verdict_path: join(receiptDir, 'replay-verdict.json'),\n deduplicated_with: null,\n }\n executedByKey.set(dedupeKey, verification)\n writeReceipt(receiptDir, finding, verification, receiptExecution(verdict))\n verifications.push(verification)\n options.onProgress?.(\n `${identity.finding_id ?? `finding ${index + 1}`}: ${verification.verified}`,\n )\n }\n\n const counts: Record<FindingVerificationStatus, number> = {\n reproduced: 0,\n 'fix-flipped': 0,\n divergent: 0,\n 'not-replayable': 0,\n }\n for (const verification of verifications) counts[verification.verified] += 1\n const verified = counts.reproduced + counts['fix-flipped']\n const measurable = verifications.length - counts['not-replayable']\n const run: VerifyFindingsRun = {\n out: options.out,\n verifications,\n counts,\n executions,\n valid: measurable > 0 && verified === verifications.length,\n score: measurable > 0 ? verified / measurable : 0,\n // Status distribution over ALL findings (counts travel in `counts`).\n scores: {\n reproduced: counts.reproduced / verifications.length,\n fixFlipped: counts['fix-flipped'] / verifications.length,\n divergent: counts.divergent / verifications.length,\n notReplayable: counts['not-replayable'] / verifications.length,\n },\n notes:\n measurable === 0\n ? 'no finding was replayable — nothing measured'\n : `${verified}/${measurable} measurable finding(s) verified under execution (${counts['not-replayable']} not replayable)`,\n ...(executions > 0\n ? {\n certification: {\n strategy: 'replication',\n checker: { name: 'agent-eval:trajectory-replay', version: packageVersion() },\n assumptions:\n counts['not-replayable'] > 0\n ? [\n `${counts['not-replayable']} finding(s) were not replayable — excluded from the score's denominator, unverified either way`,\n ]\n : [],\n evidenceDigest: certificationEvidenceDigest(verifications),\n },\n }\n : {}),\n }\n writeFileSync(\n join(options.out, 'verifications.json'),\n `${JSON.stringify({ schema_version: '1.0.0', ...run }, null, 2)}\\n`,\n )\n return run\n}\n\n// ── Report rendering ─────────────────────────────────────────────────\n\nfunction verdictCell(verification: FindingVerification): string {\n switch (verification.verified) {\n case 'reproduced':\n return '**VERIFIED** — reproduced'\n case 'fix-flipped':\n return '**VERIFIED** — fix-flipped'\n case 'divergent':\n return 'DIVERGENT — recorded failure did not reproduce'\n case 'not-replayable':\n return `UNVERIFIABLE — ${verification.reason ?? 'no reason recorded'}`\n }\n}\n\n/** Markdown section an analysis report appends when finding verification ran. */\nexport function renderVerifiedFindingsSection(run: VerifyFindingsRun): string {\n const lines: string[] = ['## Verified findings (executed replay)', '']\n const total = run.verifications.length\n lines.push(\n `${total} finding(s) → ${run.counts.reproduced} reproduced, ${run.counts['fix-flipped']} fix-flipped, ` +\n `${run.counts.divergent} divergent, ${run.counts['not-replayable']} not replayable ` +\n `(${run.executions} execution(s); findings accusing the same step share one proof).`,\n )\n lines.push('')\n lines.push('| Finding | Subject | Step | Verdict | Receipt |')\n lines.push('|---|---|---:|---|---|')\n for (const verification of run.verifications) {\n const shared = verification.deduplicated_with ? ' (shared proof)' : ''\n lines.push(\n `| \\`${verification.finding_id ?? '—'}\\` | \\`${verification.subject ?? '—'}\\` | ` +\n `${verification.step ?? '—'} | ${verdictCell(verification)} | \\`${verification.receipt}\\`${shared} |`,\n )\n }\n lines.push('')\n lines.push(\n 'VERIFIED = the accused step was re-executed after replaying the trajectory prefix, and the recorded ' +\n 'failure signature reproduced (fix-flipped: a corrected command additionally made it vanish). Each receipt ' +\n 'directory carries receipt.json and, when executed, replay-verdict.json + report.md with real stdout/stderr.',\n )\n lines.push('')\n return lines.join('\\n')\n}\n\n// ── Findings file loading ────────────────────────────────────────────\n\n/**\n * Accepts the two shapes findings travel in: a bare JSON array of analyst\n * findings, or an object with a `findings` array (e.g. an extracted\n * `observations[n]` from a result.json).\n */\nexport function readFindingsFile(path: string): VerifiableFinding[] {\n const parsed: unknown = JSON.parse(readFileSync(path, 'utf8'))\n const array = Array.isArray(parsed)\n ? parsed\n : parsed &&\n typeof parsed === 'object' &&\n Array.isArray((parsed as { findings?: unknown }).findings)\n ? (parsed as { findings: unknown[] }).findings\n : null\n if (!array) {\n throw new Error(`${path} is neither a findings array nor an object with a findings array`)\n }\n for (const entry of array) {\n if (!entry || typeof entry !== 'object') {\n throw new Error(`${path}: every finding must be an object, got ${JSON.stringify(entry)}`)\n }\n }\n return array as VerifiableFinding[]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,gBAAgB,OAA2B;CACzD,MAAM,KAAK,MAAM,QAAQ,GAAG;CAC5B,IAAI,MAAM,GAAG,MAAM,IAAI,MAAM,oDAAoD,OAAO;CACxF,MAAM,OAAO,MAAM,MAAM,GAAG,EAAE;CAC9B,MAAM,OAAO,MAAM,MAAM,KAAK,CAAC;CAC/B,MAAM,MAAM,KAAK,QAAQ,IAAI;CAC7B,IAAI,OAAO,KAAK,QAAQ,KAAK,SAAS,GACpC,MAAM,IAAI,MAAM,oDAAoD,OAAO;CAE7E,OAAO;EAAE;EAAM,YAAY,KAAK,MAAM,GAAG,GAAG;EAAG,aAAa,KAAK,MAAM,MAAM,CAAC;CAAE;AAClF;AAqDA,SAAgB,iBAAiB,YAAkC;CACjE,MAAM,SAAkB,KAAK,MAAM,aAAa,YAAY,MAAM,CAAC;CACnE,IAAI,CAAC,MAAM,QAAQ,MAAM,GAAG,MAAM,IAAI,MAAM,GAAG,WAAW,sCAAsC;CAChG,KAAK,MAAM,SAAS,QAClB,IAAI,OAAQ,MAAqB,YAAY,UAC3C,MAAM,IAAI,MAAM,GAAG,WAAW,uCAAuC;CAGzE,OAAO;AACT;AAEA,SAAgB,mBAAmB,OAA6B;CAC9D,MAAM,sBAAM,IAAI,IAAY;CAC5B,KAAK,MAAM,SAAS,MAAM,oBAAoB,CAAC,GAC7C,KAAK,MAAM,MAAM,MAAM,sBAAsB,CAAC,GAAG,IAAI,IAAI,EAAE;CAE7D,OAAO,CAAC,GA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KACJ,GAAG,MAAM,gBAAgB,IAAI,OAAO,WAAW,eAAe,IAAI,OAAO,eAAe,gBACnF,IAAI,OAAO,UAAU,cAAc,IAAI,OAAO,kBAAkB,mBAC/D,IAAI,WAAW,iEACvB;CACA,MAAM,KAAK,EAAE;CACb,MAAM,KAAK,kDAAkD;CAC7D,MAAM,KAAK,wBAAwB;CACnC,KAAK,MAAM,gBAAgB,IAAI,eAAe;EAC5C,MAAM,SAAS,aAAa,oBAAoB,oBAAoB;EACpE,MAAM,KACJ,OAAO,aAAa,cAAc,IAAI,SAAS,aAAa,WAAW,IAAI,OACtE,aAAa,QAAQ,IAAI,KAAK,YAAY,YAAY,EAAE,OAAO,aAAa,QAAQ,IAAI,OAAO,GACtG;CACF;CACA,MAAM,KAAK,EAAE;CACb,MAAM,KACJ,2TAGF;CACA,MAAM,KAAK,EAAE;CACb,OAAO,MAAM,KAAK,IAAI;AACxB;;;;;;AASA,SAAgB,iBAAiB,MAAmC;CAClE,MAAM,SAAkB,KAAK,MAAM,aAAa,MAAM,MAAM,CAAC;CAC7D,MAAM,QAAQ,MAAM,QAAQ,MAAM,IAC9B,SACA,UACE,OAAO,WAAW,YAClB,MAAM,QAAS,OAAkC,QAAQ,IACxD,OAAmC,WACpC;CACN,IAAI,CAAC,OACH,MAAM,IAAI,MAAM,GAAG,KAAK,iEAAiE;CAE3F,KAAK,MAAM,SAAS,OAClB,IAAI,CAAC,SAAS,OAAO,UAAU,UAC7B,MAAM,IAAI,MAAM,GAAG,KAAK,yCAAyC,KAAK,UAAU,KAAK,GAAG;CAG5F,OAAO;AACT"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/trajectory-replay/corpus.ts","../../src/trajectory-replay/fix.ts","../../src/trajectory-replay/fix-loop.ts","../../src/trajectory-replay/image-preparer.ts","../../src/trajectory-replay/verify.ts","../../src/trajectory-replay/batch.ts","../../src/trajectory-replay/wire.ts","../../src/trajectory-replay/findings.ts"],"sourcesContent":["/**\n * Corpus enumeration for batch replay verification.\n *\n * A labeled trajectory corpus is a gold label file (array of trajectory\n * entries with `incorrect_stages[].incorrect_step_ids`) plus a prepared\n * directory:\n * <prepared>/normalized/<traj_id>/steps.json normalized steps\n * <prepared>/normalized/<traj_id>/task.md optional task statement\n * <prepared>/extracted/<traj_id>/swe_raw/** raw mini-SWE trajectory\n *\n * Only trajectories that record their environment are replayable: the raw\n * trajectory must carry `info.docker_config.base_image`. Every excluded case\n * is returned with a machine-readable reason — the batch report surfaces the\n * full exclusion table, never a silently shrunk denominator.\n */\n\nimport { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport {\n isSubmitAction,\n parseObservationOutput,\n parseRecordedReturncode,\n type RecordedTrajectoryStep,\n} from './steps'\n\nexport interface CorpusSpec {\n readonly name: string\n readonly labelsPath: string\n readonly preparedDir: string\n}\n\n/** Parses `name=<labelsPath>::<preparedDir>` (paths may contain `=`, not `::`). */\nexport function parseCorpusFlag(value: string): CorpusSpec {\n const eq = value.indexOf('=')\n if (eq <= 0) throw new Error(`--corpus must be name=<labels>::<prepared>, got: ${value}`)\n const name = value.slice(0, eq)\n const rest = value.slice(eq + 1)\n const sep = rest.indexOf('::')\n if (sep <= 0 || sep === rest.length - 2) {\n throw new Error(`--corpus must be name=<labels>::<prepared>, got: ${value}`)\n }\n return { name, labelsPath: rest.slice(0, sep), preparedDir: rest.slice(sep + 2) }\n}\n\nexport type ReplayExclusionReason =\n | 'no-swe-raw-trajectory'\n | 'ambiguous-swe-raw-trajectory'\n | 'unreadable-raw-trajectory'\n | 'no-docker-image'\n | 'no-gold-incorrect-step'\n | 'gold-only-submit-step'\n | 'missing-steps-json'\n | 'gold-step-outside-steps'\n | 'cwd-underivable'\n\nexport interface ExcludedCase {\n readonly corpus: string\n readonly trajId: string\n readonly reason: ReplayExclusionReason\n readonly detail?: string\n}\n\nexport type CwdSource = 'run-config' | 'docker-config' | 'pwd-observation'\n\n/** Everything needed to replay one trajectory. */\nexport interface CaseResources {\n readonly corpus: string\n readonly trajId: string\n readonly stepsPath: string\n readonly steps: readonly RecordedTrajectoryStep[]\n readonly taskStatement: string | null\n readonly image: string\n readonly cwd: string\n readonly cwdSource: CwdSource\n /** Per-step timeout the recorded run used, when the raw config carries one. */\n readonly recordedStepTimeoutMs: number | null\n}\n\nexport interface ReplayableCase extends CaseResources {\n /** 1-based gold incorrect step ids, ascending. */\n readonly goldIncorrectSteps: readonly number[]\n /** k — the first gold incorrect step that is a real mid-trajectory action;\n * submit-command golds are skipped (see SUBMIT_ACTION_SIGNATURE). */\n readonly k: number\n /** Gold steps before k skipped because their action is the submit command. */\n readonly submitGoldsSkipped: number\n /** Recorded returncode at k; null when the observation carries none. */\n readonly recordedReturncodeAtK: number | null\n}\n\ninterface LabelEntry {\n readonly traj_id: string\n readonly incorrect_stages?: readonly { readonly incorrect_step_ids?: readonly number[] }[]\n}\n\nexport function readLabelEntries(labelsPath: string): LabelEntry[] {\n const parsed: unknown = JSON.parse(readFileSync(labelsPath, 'utf8'))\n if (!Array.isArray(parsed)) throw new Error(`${labelsPath} is not a JSON array of label entries`)\n for (const entry of parsed) {\n if (typeof (entry as LabelEntry).traj_id !== 'string') {\n throw new Error(`${labelsPath} has an entry without a string traj_id`)\n }\n }\n return parsed as LabelEntry[]\n}\n\nexport function goldIncorrectSteps(entry: LabelEntry): number[] {\n const ids = new Set<number>()\n for (const stage of entry.incorrect_stages ?? []) {\n for (const id of stage.incorrect_step_ids ?? []) ids.add(id)\n }\n return [...ids].sort((a, b) => a - b)\n}\n\ninterface RawTrajInfo {\n readonly docker_config?: { readonly base_image?: unknown; readonly cwd?: unknown }\n readonly config?: {\n readonly environment?: { readonly cwd?: unknown; readonly timeout?: unknown }\n }\n}\n\ninterface RawTrajFile {\n readonly info?: RawTrajInfo\n readonly messages?: readonly { readonly role?: unknown; readonly content?: unknown }[]\n}\n\nfunction findRawTrajFiles(sweRawDir: string): string[] {\n if (!existsSync(sweRawDir)) return []\n const entries = readdirSync(sweRawDir, { recursive: true, encoding: 'utf8' })\n return entries\n .filter((relative) => relative.endsWith('.traj.json'))\n .map((relative) => join(sweRawDir, relative))\n .sort()\n}\n\n/** First non-empty output line of the trajectory's first bare `pwd` step. */\nfunction cwdFromPwdObservation(steps: readonly RecordedTrajectoryStep[]): string | null {\n for (const step of steps) {\n if (step.action.trim() !== 'pwd') continue\n const line = parseObservationOutput(step.observation)\n .split('\\n')\n .map((l) => l.trim())\n .find((l) => l.startsWith('/'))\n if (line) return line\n }\n return null\n}\n\nfunction taskStatementOf(preparedDir: string, trajId: string, raw: RawTrajFile): string | null {\n const taskPath = join(preparedDir, 'normalized', trajId, 'task.md')\n if (existsSync(taskPath)) {\n const text = readFileSync(taskPath, 'utf8').trim()\n if (text.length > 0) return text\n }\n const userMessage = raw.messages?.find((m) => m.role === 'user')\n if (typeof userMessage?.content === 'string' && userMessage.content.trim().length > 0) {\n return userMessage.content.trim()\n }\n return null\n}\n\nexport type ResourceResolution =\n | { readonly resolved: true; readonly resources: CaseResources }\n | { readonly resolved: false; readonly reason: ReplayExclusionReason; readonly detail?: string }\n\n/**\n * Resolves the replay resources for one trajectory, independent of gold\n * labels — the finding wire uses this with a finding-supplied step instead.\n */\nexport function resolveCaseResources(corpus: CorpusSpec, trajId: string): ResourceResolution {\n const sweRawDir = join(corpus.preparedDir, 'extracted', trajId, 'swe_raw')\n const rawFiles = findRawTrajFiles(sweRawDir)\n if (rawFiles.length === 0) {\n return { resolved: false, reason: 'no-swe-raw-trajectory', detail: sweRawDir }\n }\n if (rawFiles.length > 1) {\n return { resolved: false, reason: 'ambiguous-swe-raw-trajectory', detail: rawFiles.join(', ') }\n }\n let raw: RawTrajFile\n try {\n raw = JSON.parse(readFileSync(rawFiles[0]!, 'utf8')) as RawTrajFile\n } catch (err) {\n return {\n resolved: false,\n reason: 'unreadable-raw-trajectory',\n detail: `${rawFiles[0]}: ${err instanceof Error ? err.message : String(err)}`,\n }\n }\n const dockerConfig = raw.info?.docker_config\n const image = dockerConfig?.base_image\n if (typeof image !== 'string' || image.length === 0) {\n return { resolved: false, reason: 'no-docker-image', detail: rawFiles[0] }\n }\n const stepsPath = join(corpus.preparedDir, 'normalized', trajId, 'steps.json')\n if (!existsSync(stepsPath)) {\n return { resolved: false, reason: 'missing-steps-json', detail: stepsPath }\n }\n const steps = JSON.parse(readFileSync(stepsPath, 'utf8')) as RecordedTrajectoryStep[]\n\n const runConfigCwd = raw.info?.config?.environment?.cwd\n const dockerCwd = dockerConfig?.cwd\n let cwd: string\n let cwdSource: CwdSource\n if (typeof runConfigCwd === 'string' && runConfigCwd.length > 0) {\n cwd = runConfigCwd\n cwdSource = 'run-config'\n } else if (typeof dockerCwd === 'string' && dockerCwd.length > 0) {\n cwd = dockerCwd\n cwdSource = 'docker-config'\n } else {\n const observed = cwdFromPwdObservation(steps)\n if (!observed) return { resolved: false, reason: 'cwd-underivable' }\n cwd = observed\n cwdSource = 'pwd-observation'\n }\n\n const recordedTimeout = raw.info?.config?.environment?.timeout\n return {\n resolved: true,\n resources: {\n corpus: corpus.name,\n trajId,\n stepsPath,\n steps,\n taskStatement: taskStatementOf(corpus.preparedDir, trajId, raw),\n image,\n cwd,\n cwdSource,\n recordedStepTimeoutMs:\n typeof recordedTimeout === 'number' && recordedTimeout > 0 ? recordedTimeout * 1000 : null,\n },\n }\n}\n\nexport interface EnumerationResult {\n readonly replayable: ReplayableCase[]\n readonly excluded: ExcludedCase[]\n readonly labelEntryCount: number\n}\n\n/**\n * Replayable = a raw trajectory with a recorded image AND at least one gold\n * incorrect step that is a real mid-trajectory action. Gold steps whose action\n * is the submit command are skipped when choosing k (counted per case); a case\n * whose golds are ALL submit steps is excluded as gold-only-submit-step.\n * Exclusion reasons are reported in resolution order:\n * raw trajectory → image → gold labels → steps.json → k range → cwd.\n */\nexport function enumerateReplayableCases(corpora: readonly CorpusSpec[]): EnumerationResult {\n const replayable: ReplayableCase[] = []\n const excluded: ExcludedCase[] = []\n let labelEntryCount = 0\n for (const corpus of corpora) {\n for (const entry of readLabelEntries(corpus.labelsPath)) {\n labelEntryCount += 1\n const trajId = entry.traj_id\n const resolution = resolveCaseResources(corpus, trajId)\n if (!resolution.resolved) {\n excluded.push({\n corpus: corpus.name,\n trajId,\n reason: resolution.reason,\n detail: resolution.detail,\n })\n continue\n }\n const gold = goldIncorrectSteps(entry)\n if (gold.length === 0) {\n excluded.push({ corpus: corpus.name, trajId, reason: 'no-gold-incorrect-step' })\n continue\n }\n const resources = resolution.resources\n let submitGoldsSkipped = 0\n let target: RecordedTrajectoryStep | null = null\n let missingGoldId: number | null = null\n for (const goldId of gold) {\n const step = resources.steps.find((s) => s.step_id === goldId)\n if (!step) {\n missingGoldId = goldId\n break\n }\n if (isSubmitAction(step.action)) {\n submitGoldsSkipped += 1\n continue\n }\n target = step\n break\n }\n if (missingGoldId !== null) {\n excluded.push({\n corpus: corpus.name,\n trajId,\n reason: 'gold-step-outside-steps',\n detail: `k=${missingGoldId}, steps=${resources.steps.length}`,\n })\n continue\n }\n if (!target) {\n excluded.push({\n corpus: corpus.name,\n trajId,\n reason: 'gold-only-submit-step',\n detail: `${submitGoldsSkipped} gold step(s), all submit commands`,\n })\n continue\n }\n replayable.push({\n ...resources,\n goldIncorrectSteps: gold,\n k: target.step_id,\n submitGoldsSkipped,\n recordedReturncodeAtK: parseRecordedReturncode(target.observation),\n })\n }\n }\n return { replayable, excluded, labelEntryCount }\n}\n","/**\n * Counterfactual patch synthesis: turn a recorded incorrect step into a\n * corrected shell command for replay arm B.\n *\n * The caller is a typed outcome boundary ({ succeeded, value, error }) so a\n * provider failure is a per-case report row, never a thrown batch abort and\n * never a silent empty fix. Concrete chat transports live with the consumer;\n * this module only builds prompts and reads replies.\n */\n\nimport {\n parseObservationOutput,\n parseRecordedReturncode,\n type RecordedTrajectoryStep,\n} from './steps'\n\nexport interface ChatUsage {\n readonly promptTokens: number\n readonly completionTokens: number\n}\n\nexport type ChatOutcome =\n | { readonly succeeded: true; readonly value: { content: string; usage: ChatUsage | null } }\n | { readonly succeeded: false; readonly error: string }\n\nexport interface ChatCompletionCaller {\n complete(system: string, user: string): Promise<ChatOutcome>\n}\n\nexport interface FixPromptInput {\n readonly taskStatement: string | null\n readonly steps: readonly RecordedTrajectoryStep[]\n /** 1-based step_id of the incorrect step. */\n readonly k: number\n /** Steps of context on each side of k (default 3). */\n readonly contextRadius?: number\n}\n\n/** Head+tail excerpt with an elision marker; identity below the limit. */\nexport function clipText(text: string, limit: number): string {\n if (text.length <= limit) return text\n const half = Math.floor(limit / 2)\n return `${text.slice(0, half)}\\n… [${text.length - limit} chars elided] …\\n${text.slice(-half)}`\n}\n\nfunction renderStep(step: RecordedTrajectoryStep, marker: string): string {\n const rc = parseRecordedReturncode(step.observation)\n const output = clipText(parseObservationOutput(step.observation).trim(), 1600)\n return [\n `### step ${step.step_id}${marker}`,\n '```sh',\n clipText(step.action, 2000),\n '```',\n `returncode: ${rc ?? 'none recorded'}`,\n output.length > 0 ? `output:\\n\\`\\`\\`\\n${output}\\n\\`\\`\\`` : 'output: (empty)',\n ].join('\\n')\n}\n\n/** Shared user-prompt sections: task statement, ±radius context, failing step. */\nfunction promptBody(input: FixPromptInput): string[] {\n const radius = input.contextRadius ?? 3\n const target = input.steps.find((s) => s.step_id === input.k)\n if (!target) throw new Error(`trajectory-replay: no step with step_id ${input.k}`)\n const context = input.steps.filter(\n (s) => s.step_id !== input.k && Math.abs(s.step_id - input.k) <= radius,\n )\n return [\n '## Task the agent was solving',\n input.taskStatement ? clipText(input.taskStatement, 4000) : '(no task statement recorded)',\n '',\n '## Surrounding steps',\n ...context.map((s) => renderStep(s, '')),\n '',\n '## Failing step to correct',\n renderStep(target, ' (INCORRECT — correct this one)'),\n ]\n}\n\nexport function buildFixPrompt(input: FixPromptInput): { system: string; user: string } {\n const system = [\n 'You repair one failed shell command from a recorded coding-agent trajectory.',\n 'The trajectory replays inside the original docker image; every command runs as a fresh /bin/sh subshell from a fixed working directory.',\n 'You are given the failing step, its recorded output, surrounding steps, and the task statement.',\n 'Reply with exactly ONE corrected shell command (compound commands with && or pipes are fine) inside a single ```sh fenced block.',\n \"The corrected command must accomplish the failing step's intent and exit 0. No prose outside the fenced block.\",\n ].join('\\n')\n const user = [\n ...promptBody(input),\n '',\n 'Output the single corrected replacement for the failing step now.',\n ].join('\\n')\n return { system, user }\n}\n\n/** One prior attempt of the fix loop, rendered into the retry prompt. */\nexport interface FailedFixAttempt {\n readonly attempt: number\n /** Null when the model call itself failed before producing a command. */\n readonly command: string | null\n readonly exitCode: number | null\n readonly stdoutTail: string | null\n readonly stderrTail: string | null\n readonly llmError: string | null\n}\n\nfunction renderFailedAttempt(prior: FailedFixAttempt): string {\n if (prior.command === null) {\n return [\n `### attempt ${prior.attempt}`,\n `model call failed before producing a command: ${prior.llmError ?? 'unknown error'}`,\n ].join('\\n')\n }\n const stdout = (prior.stdoutTail ?? '').trim()\n const stderr = (prior.stderrTail ?? '').trim()\n return [\n `### attempt ${prior.attempt}`,\n '```sh',\n clipText(prior.command, 2000),\n '```',\n `exit code: ${prior.exitCode ?? 'not executed'}`,\n stdout.length > 0 ? `stdout:\\n\\`\\`\\`\\n${stdout}\\n\\`\\`\\`` : 'stdout: (empty)',\n stderr.length > 0 ? `stderr:\\n\\`\\`\\`\\n${stderr}\\n\\`\\`\\`` : 'stderr: (empty)',\n ].join('\\n')\n}\n\n/**\n * Retry prompt for fix-loop attempts ≥2: the original context plus every prior\n * attempt with its REAL executed output, and permission to answer with a short\n * script (the block still executes as one /bin/sh unit).\n */\nexport function buildRetryFixPrompt(\n input: FixPromptInput,\n priorAttempts: readonly FailedFixAttempt[],\n maxScriptCommands = 5,\n): { system: string; user: string } {\n if (priorAttempts.length === 0) {\n throw new Error('trajectory-replay: buildRetryFixPrompt requires at least one prior attempt')\n }\n const system = [\n 'You repair one failed shell command from a recorded coding-agent trajectory.',\n 'The trajectory replays inside the original docker image; every command runs as a fresh /bin/sh subshell from a fixed working directory.',\n 'Earlier corrected commands were executed for real and failed; their actual output is included below.',\n `Reply with a corrected fix inside a single \\`\\`\\`sh fenced block: either one command, or a short script of at most ${maxScriptCommands} commands (one per line).`,\n 'The whole block executes as ONE /bin/sh unit from the fixed working directory and must exit 0.',\n 'Do not repeat a command that already failed. Keep reasoning brief. No prose outside the fenced block.',\n ].join('\\n')\n const user = [\n ...promptBody(input),\n '',\n '## Previous fix attempts (executed for real — all failed)',\n ...priorAttempts.map((prior) => renderFailedAttempt(prior)),\n '',\n `Output a corrected fix now — one \\`\\`\\`sh block, at most ${maxScriptCommands} commands.`,\n ].join('\\n')\n return { system, user }\n}\n\n/** Non-empty, non-comment lines of a fix script — the loop's script-size cap. */\nexport function countScriptCommands(script: string): number {\n return script.split('\\n').filter((line) => line.trim().length > 0 && !line.trim().startsWith('#'))\n .length\n}\n\n/** Last fenced code block, else the whole trimmed content; null when empty. */\nexport function extractFixCommand(content: string): string | null {\n const blocks = [...content.matchAll(/```(?:sh|bash|shell)?\\n([\\s\\S]*?)```/g)]\n const candidate = blocks.length > 0 ? blocks[blocks.length - 1]![1]! : content\n const command = candidate.trim()\n if (command.length === 0 || command.includes('```')) return null\n return command\n}\n\nexport type FixGenerationOutcome =\n | { readonly succeeded: true; readonly value: { command: string; usage: ChatUsage | null } }\n | { readonly succeeded: false; readonly error: string }\n\nexport async function generateFixCommand(\n caller: ChatCompletionCaller,\n input: FixPromptInput,\n): Promise<FixGenerationOutcome> {\n const { system, user } = buildFixPrompt(input)\n const outcome = await caller.complete(system, user)\n if (!outcome.succeeded) return outcome\n const command = extractFixCommand(outcome.value.content)\n if (command === null) {\n return {\n succeeded: false,\n error: `completion carried no usable command: ${clipText(outcome.value.content, 300)}`,\n }\n }\n return { succeeded: true, value: { command, usage: outcome.value.usage } }\n}\n","/**\n * Iterative counterfactual fix loop.\n *\n * Attempt 1 is exactly the one-shot generator (same prompt, same caller), so\n * flip@1 stays comparable to one-shot fix mode. When an attempt does not flip\n * the failure — nonzero exit, signature still present, or the model call\n * itself failed — the next attempt's prompt carries every prior command and\n * its REAL executed stdout/stderr, up to a fixed attempt budget.\n *\n * Isolation invariant: every attempt executes through the injected executor,\n * which must provide a FRESH sandbox with the same replayed prefix. A used\n * sandbox is never mutated mid-arm; a flip therefore always proves the\n * corrected step against the recorded prefix state, not against debris from\n * an earlier attempt.\n */\n\nimport {\n buildFixPrompt,\n buildRetryFixPrompt,\n type ChatCompletionCaller,\n clipText,\n countScriptCommands,\n extractFixCommand,\n type FailedFixAttempt,\n type FixPromptInput,\n} from './fix'\n\n/** Result of executing one corrected command as a full arm. */\nexport interface FixArmExecution {\n readonly exitCode: number\n readonly prefixExecuted: number\n readonly prefixDivergences: number\n /** Divergent prefix steps over executed ones, in percent. */\n readonly prefixDivergencePct: number\n readonly failureVanished: boolean\n readonly stdout: string\n readonly stderr: string\n}\n\n/** Runs one corrected command as a full arm: fresh sandbox + prefix replay. */\nexport type FixArmExecutor = (command: string, attempt: number) => Promise<FixArmExecution>\n\nexport interface FixLoopOptions {\n /** Total LLM attempts per case (≥1); 1 degenerates to the one-shot path. */\n readonly maxAttempts: number\n /** Command-line cap on retry scripts (default 5). */\n readonly maxScriptCommands?: number\n /** Chars kept per stdout/stderr tail in records and retry prompts. */\n readonly outputTailChars?: number\n readonly onProgress?: (message: string) => void\n}\n\nexport interface FixLoopAttemptRecord {\n readonly attempt: number\n readonly command: string | null\n readonly llmError: string | null\n readonly usage: { readonly promptTokens: number; readonly completionTokens: number } | null\n readonly executed: boolean\n readonly exitCode: number | null\n readonly prefixExecuted: number | null\n readonly prefixDivergences: number | null\n readonly prefixDivergencePct: number | null\n readonly failureVanished: boolean | null\n readonly stdoutTail: string | null\n readonly stderrTail: string | null\n readonly armBError: string | null\n readonly wallMs: number\n}\n\nexport interface FixLoopResult {\n readonly flipped: boolean\n readonly flippedAtAttempt: number | null\n readonly attempts: readonly FixLoopAttemptRecord[]\n /** True when a sandbox error ended the loop before the attempt budget. */\n readonly aborted: boolean\n readonly llmCalls: number\n /** Calls that produced no runnable fix: transport errors, empty replies,\n * and retry scripts over the command cap. */\n readonly llmFailures: number\n readonly promptTokens: number\n readonly completionTokens: number\n /** Successful calls whose provider reported no usage. Their tokens are absent\n * from the two totals above, so a nonzero count makes those totals a lower\n * bound rather than a measurement. */\n readonly callsWithoutUsage: number\n}\n\nfunction toFailedAttempt(record: FixLoopAttemptRecord): FailedFixAttempt {\n return {\n attempt: record.attempt,\n command: record.command,\n exitCode: record.exitCode,\n stdoutTail: record.stdoutTail,\n stderrTail: record.stderrTail,\n llmError: record.llmError ?? record.armBError,\n }\n}\n\nexport async function runFixLoop(\n caller: ChatCompletionCaller,\n input: FixPromptInput,\n executor: FixArmExecutor,\n options: FixLoopOptions,\n): Promise<FixLoopResult> {\n if (!Number.isInteger(options.maxAttempts) || options.maxAttempts < 1) {\n throw new Error(\n `trajectory-replay: maxAttempts must be a positive integer, got ${options.maxAttempts}`,\n )\n }\n const scriptCap = options.maxScriptCommands ?? 5\n const tailChars = options.outputTailChars ?? 1600\n const attempts: FixLoopAttemptRecord[] = []\n let llmCalls = 0\n let llmFailures = 0\n let promptTokens = 0\n let completionTokens = 0\n let callsWithoutUsage = 0\n\n const unexecuted = (\n attempt: number,\n llmError: string,\n usage: FixLoopAttemptRecord['usage'],\n command: string | null,\n started: number,\n ): FixLoopAttemptRecord => ({\n attempt,\n command,\n llmError,\n usage,\n executed: false,\n exitCode: null,\n prefixExecuted: null,\n prefixDivergences: null,\n prefixDivergencePct: null,\n failureVanished: null,\n stdoutTail: null,\n stderrTail: null,\n armBError: null,\n wallMs: Date.now() - started,\n })\n\n for (let attempt = 1; attempt <= options.maxAttempts; attempt++) {\n const started = Date.now()\n const prompt =\n attempt === 1\n ? buildFixPrompt(input)\n : buildRetryFixPrompt(input, attempts.map(toFailedAttempt), scriptCap)\n llmCalls += 1\n const outcome = await caller.complete(prompt.system, prompt.user)\n if (!outcome.succeeded) {\n llmFailures += 1\n attempts.push(unexecuted(attempt, outcome.error, null, null, started))\n options.onProgress?.(\n `fix-loop attempt ${attempt}: LLM failed — ${outcome.error.slice(0, 160)}`,\n )\n continue\n }\n const usage = outcome.value.usage\n if (usage === null || usage === undefined) callsWithoutUsage += 1\n promptTokens += usage?.promptTokens ?? 0\n completionTokens += usage?.completionTokens ?? 0\n const command = extractFixCommand(outcome.value.content)\n if (command === null) {\n llmFailures += 1\n attempts.push(\n unexecuted(\n attempt,\n `completion carried no usable command: ${clipText(outcome.value.content, 300)}`,\n usage,\n null,\n started,\n ),\n )\n continue\n }\n // Attempt 1 mirrors one-shot exactly, so only retries enforce the cap.\n if (attempt > 1) {\n const commandLines = countScriptCommands(command)\n if (commandLines > scriptCap) {\n llmFailures += 1\n attempts.push(\n unexecuted(\n attempt,\n `script exceeds ${scriptCap} command lines (${commandLines})`,\n usage,\n null,\n started,\n ),\n )\n options.onProgress?.(\n `fix-loop attempt ${attempt}: rejected script with ${commandLines} command lines`,\n )\n continue\n }\n }\n let execution: FixArmExecution\n try {\n execution = await executor(command, attempt)\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n attempts.push({\n ...unexecuted(attempt, '', usage, command, started),\n llmError: null,\n armBError: message.slice(0, 500),\n })\n options.onProgress?.(`fix-loop attempt ${attempt}: sandbox error — ${message.slice(0, 160)}`)\n return {\n flipped: false,\n flippedAtAttempt: null,\n attempts,\n aborted: true,\n llmCalls,\n llmFailures,\n promptTokens,\n completionTokens,\n callsWithoutUsage,\n }\n }\n attempts.push({\n attempt,\n command,\n llmError: null,\n usage,\n executed: true,\n exitCode: execution.exitCode,\n prefixExecuted: execution.prefixExecuted,\n prefixDivergences: execution.prefixDivergences,\n prefixDivergencePct: execution.prefixDivergencePct,\n failureVanished: execution.failureVanished,\n stdoutTail: clipText(execution.stdout, tailChars),\n stderrTail: clipText(execution.stderr, tailChars),\n armBError: null,\n wallMs: Date.now() - started,\n })\n options.onProgress?.(\n `fix-loop attempt ${attempt}: exit=${execution.exitCode} failureVanished=${execution.failureVanished}`,\n )\n if (execution.failureVanished) {\n return {\n flipped: true,\n flippedAtAttempt: attempt,\n attempts,\n aborted: false,\n llmCalls,\n llmFailures,\n promptTokens,\n completionTokens,\n callsWithoutUsage,\n }\n }\n }\n return {\n flipped: false,\n flippedAtAttempt: null,\n attempts,\n aborted: false,\n llmCalls,\n llmFailures,\n promptTokens,\n completionTokens,\n callsWithoutUsage,\n }\n}\n","/**\n * Replay-ready image derivation.\n *\n * A recorded trajectory names the image it ran in, but the image is not always\n * runnable as-is: sandbox platforms pin customer commands to a non-root\n * identity, so a root-owned working tree must be chowned before the replay can\n * write to it. `ImagePreparer` is that step, injectable so a consumer whose\n * images are already replay-ready supplies its own no-op or none at all.\n */\n\nimport { execFile } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport { mkdtempSync, writeFileSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport { promisify } from 'node:util'\n\nconst execFileAsync = promisify(execFile)\n\nexport type ImagePreparation =\n | {\n readonly succeeded: true\n readonly value: { derivedImage: string; pulled: boolean; built: boolean }\n }\n | { readonly succeeded: false; readonly error: string }\n\nexport interface ImagePreparer {\n ensure(image: string, cwd: string): Promise<ImagePreparation>\n}\n\nexport interface DockerImagePreparerOptions {\n readonly pullTimeoutMs?: number\n readonly buildTimeoutMs?: number\n}\n\nexport function derivedImageTag(image: string, cwd: string): string {\n const digest = createHash('sha256').update(`${image}\\n${cwd}`).digest('hex').slice(0, 12)\n return `ctb-replay:${digest}-uid1000`\n}\n\n/**\n * Pulls the base image when absent and builds `FROM <base>; RUN chown -R\n * 1000:1000 <cwd>` tagged by content hash, so repeated batches reuse both\n * the pull and the build. cwd `/` skips the chown (never chown -R /) and\n * replays on the base image directly.\n */\nexport function dockerImagePreparer(options: DockerImagePreparerOptions = {}): ImagePreparer {\n const pullTimeoutMs = options.pullTimeoutMs ?? 1_200_000\n const buildTimeoutMs = options.buildTimeoutMs ?? 900_000\n const imageExists = async (tag: string): Promise<boolean> => {\n try {\n await execFileAsync('docker', ['image', 'inspect', tag], { maxBuffer: 8 * 1024 * 1024 })\n return true\n } catch {\n return false\n }\n }\n const errorTail = (err: unknown): string => {\n const raw =\n err &&\n typeof err === 'object' &&\n 'stderr' in err &&\n typeof err.stderr === 'string' &&\n err.stderr.length > 0\n ? err.stderr\n : err instanceof Error\n ? err.message\n : String(err)\n return raw.trim().split('\\n').slice(-3).join(' | ').slice(0, 400)\n }\n return {\n async ensure(image: string, cwd: string): Promise<ImagePreparation> {\n if (cwd === '/') {\n if (await imageExists(image)) {\n return { succeeded: true, value: { derivedImage: image, pulled: false, built: false } }\n }\n try {\n await execFileAsync('docker', ['pull', image], {\n timeout: pullTimeoutMs,\n maxBuffer: 32 * 1024 * 1024,\n })\n } catch (err) {\n return { succeeded: false, error: `pull ${image}: ${errorTail(err)}` }\n }\n return { succeeded: true, value: { derivedImage: image, pulled: true, built: false } }\n }\n const derived = derivedImageTag(image, cwd)\n if (await imageExists(derived)) {\n return { succeeded: true, value: { derivedImage: derived, pulled: false, built: false } }\n }\n let pulled = false\n if (!(await imageExists(image))) {\n try {\n await execFileAsync('docker', ['pull', image], {\n timeout: pullTimeoutMs,\n maxBuffer: 32 * 1024 * 1024,\n })\n pulled = true\n } catch (err) {\n return { succeeded: false, error: `pull ${image}: ${errorTail(err)}` }\n }\n }\n const contextDir = mkdtempSync(join(tmpdir(), 'ctb-replay-image-'))\n const quotedCwd = `'${cwd.replaceAll(\"'\", `'\\\\''`)}'`\n writeFileSync(\n join(contextDir, 'Dockerfile'),\n `FROM ${image}\\nRUN chown -R 1000:1000 ${quotedCwd}\\n`,\n )\n try {\n await execFileAsync('docker', ['build', '-t', derived, contextDir], {\n timeout: buildTimeoutMs,\n maxBuffer: 32 * 1024 * 1024,\n })\n } catch (err) {\n return { succeeded: false, error: `build ${derived} from ${image}: ${errorTail(err)}` }\n }\n return { succeeded: true, value: { derivedImage: derived, pulled, built: true } }\n },\n }\n}\n","/**\n * Execution-replay verification for recorded shell trajectories.\n *\n * Turns a cited claim (\"step k is the error-critical step\") into an executed\n * proof: replay steps 1..k-1 inside the trajectory's own image, then\n * arm A — run the recorded step k and check the recorded failure signature\n * reproduces (returncode + a stable output substring), and\n * arm B — run a corrected step k and check the failure vanishes.\n *\n * Built on the counterfactual scaffold: the trajectory is ingested into a\n * TraceStore, each arm is a `runCounterfactual` meta-run, and the\n * `SandboxCounterfactualRunner` here supplies the `executeFrom` callback that\n * scaffold deliberately leaves to consumers.\n *\n * Honest limits:\n * - Only trajectories that record their image can be replayed; tasks whose\n * environment needs external compose peers cannot be replayed this way.\n * - Each arm replays the prefix in its own fresh session, so a backend\n * without copy-on-write forks pays the prefix twice.\n * - Prefix divergence is recorded per step and surfaced in the verdict, never\n * hidden: a high divergence rate is a finding about replayability, not an\n * error of the harness.\n *\n * Agreement requires positive evidence. A prefix step counts as confirmed only\n * when the recording carries a returncode AND the replayed exit equals it. A\n * step the recording cannot adjudicate is a divergence of its own kind\n * (`unknown-expectation`), never silent agreement — otherwise a replay that\n * fails on every step reports a perfect prefix and every downstream verdict\n * built on it is meaningless.\n */\n\nimport { mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport {\n type CounterfactualContext,\n type CounterfactualRunner,\n runCounterfactual,\n} from '../counterfactual'\nimport { packageVersion } from '../package-version'\nimport { TraceEmitter } from '../trace/emitter'\nimport type { ToolSpan } from '../trace/schema'\nimport { InMemoryTraceStore, type TraceStore } from '../trace/store'\nimport { certificationEvidenceDigest, type DefaultVerdict } from '../verdict'\nimport type { ReplayExecBackend } from './exec'\nimport { wrapActionForExec } from './exec'\nimport {\n deriveFailureSignature,\n parseObservationOutput,\n parseRecordedReturncode,\n type RecordedTrajectoryStep,\n} from './steps'\n\n// ── Ingest: recorded steps → a trace run ─────────────────────────────\n\nexport interface IngestedTrajectory {\n runId: string\n stepCount: number\n}\n\n/**\n * Emit one tool span per trajectory step, in order, with a monotonic\n * injected clock so `buildTrajectory` ordering is deterministic even when\n * two spans would share a Date.now() millisecond.\n */\nexport async function ingestRecordedTrajectory(\n store: TraceStore,\n steps: readonly RecordedTrajectoryStep[],\n caseId: string,\n): Promise<IngestedTrajectory> {\n let tick = 0\n const emitter = new TraceEmitter(store, { now: () => ++tick })\n await emitter.startRun({\n scenarioId: caseId,\n tags: { source: 'trajectory-replay', caseId },\n })\n for (const step of steps) {\n if (typeof step.action !== 'string' || step.action.length === 0) {\n throw new Error(`trajectory-replay: step ${step.step_id} has no action`)\n }\n const handle = await emitter.tool({\n name: `step:${step.step_id}`,\n toolName: 'shell',\n args: { command: step.action },\n result: {\n returncode: parseRecordedReturncode(step.observation),\n observation: step.observation,\n },\n })\n await handle.end()\n }\n await emitter.endRun({ pass: true, notes: 'recorded trajectory (ingested for replay)' })\n return { runId: emitter.runId, stepCount: steps.length }\n}\n\n// ── Counterfactual runner over an exec backend ───────────────────────\n\n/** Why a replayed prefix step failed to confirm the recording. */\nexport type PrefixDivergenceKind =\n /** The recording carries a returncode and the replayed exit differs from it. */\n | 'returncode-mismatch'\n /** The recording carries no returncode, so agreement cannot be established. */\n | 'unknown-expectation'\n\nexport interface PrefixDivergence {\n step: number\n kind: PrefixDivergenceKind\n /** null exactly when `kind` is `unknown-expectation`. */\n expectedReturncode: number | null\n actualExit: number\n}\n\nexport interface PrefixReplayResult {\n prefixExecuted: number\n /** Every step that did not confirm the recording, of both kinds. */\n prefixDivergences: PrefixDivergence[]\n /** Steps whose recorded returncode equalled the replayed exit. */\n prefixConfirmed: number\n prefixReturncodeMismatches: number\n prefixUnknownExpectations: number\n /** Divergent steps over executed steps, in percent, one decimal.\n * 0 for an empty prefix: no step ran, so none diverged. */\n prefixDivergencePct: number\n /** `prefixDivergencePct` within `PREFIX_DIVERGENCE_TOLERANCE_PCT`. */\n prefixWithinTolerance: boolean\n wallMs: number\n}\n\n/** Admission tolerance: a prefix replay is faithful enough to build a verdict\n * on when at most this percentage of its executed steps diverged. */\nexport const PREFIX_DIVERGENCE_TOLERANCE_PCT = 10\n\n/**\n * Compare one replayed prefix step against its recording. Returns null only\n * when the recording positively confirms the replay.\n */\nexport function classifyPrefixStep(\n step: number,\n expectedReturncode: number | null,\n actualExit: number,\n): PrefixDivergence | null {\n if (expectedReturncode === null) {\n return { step, kind: 'unknown-expectation', expectedReturncode: null, actualExit }\n }\n if (expectedReturncode !== actualExit) {\n return { step, kind: 'returncode-mismatch', expectedReturncode, actualExit }\n }\n return null\n}\n\n/** Roll per-step classifications up into the rate the admission pre-pass gates on. */\nexport function summarizePrefixReplay(\n prefixExecuted: number,\n prefixDivergences: PrefixDivergence[],\n wallMs: number,\n): PrefixReplayResult {\n if (prefixDivergences.length > prefixExecuted) {\n throw new Error(\n `trajectory-replay: ${prefixDivergences.length} divergences over ${prefixExecuted} executed prefix steps`,\n )\n }\n const pct =\n prefixExecuted === 0\n ? 0\n : Number(((prefixDivergences.length / prefixExecuted) * 100).toFixed(1))\n return {\n prefixExecuted,\n prefixDivergences,\n prefixConfirmed: prefixExecuted - prefixDivergences.length,\n prefixReturncodeMismatches: prefixDivergences.filter((d) => d.kind === 'returncode-mismatch')\n .length,\n prefixUnknownExpectations: prefixDivergences.filter((d) => d.kind === 'unknown-expectation')\n .length,\n prefixDivergencePct: pct,\n prefixWithinTolerance: pct <= PREFIX_DIVERGENCE_TOLERANCE_PCT,\n wallMs,\n }\n}\n\nexport interface ArmExecutionResult {\n command: string\n exitCode: number\n stdout: string\n stderr: string\n wallMs: number\n}\n\nexport interface SandboxCounterfactualRunnerOptions {\n cwd: string\n stepTimeoutMs: number\n /** Execute at most this many prefix steps (from the start). Fast-iteration\n * knob; a truncated prefix weakens state fidelity and the verdict says so. */\n prefixLimit?: number\n onProgress?: (message: string) => void\n}\n\nfunction toolCommand(span: ToolSpan): string {\n const args = span.args as { command?: unknown } | null\n if (!args || typeof args.command !== 'string') {\n throw new Error(`trajectory-replay: span ${span.name} carries no command`)\n }\n return args.command\n}\n\nfunction recordedReturncodeOf(span: ToolSpan): number | null {\n const result = span.result as { returncode?: unknown } | null\n return typeof result?.returncode === 'number' ? result.returncode : null\n}\n\n/**\n * Replays `ctx.prefix` in a fresh session, then executes the mutated step.\n * Divergences are recorded and never abort the replay. Results land on\n * `lastPrefix` / `lastArm` for the caller; spans for every exec land in the\n * counterfactual meta-run.\n */\nexport class SandboxCounterfactualRunner implements CounterfactualRunner {\n lastPrefix: PrefixReplayResult | null = null\n lastArm: ArmExecutionResult | null = null\n\n constructor(\n private readonly backend: ReplayExecBackend,\n private readonly options: SandboxCounterfactualRunnerOptions,\n ) {}\n\n async executeFrom(ctx: CounterfactualContext, emitter: TraceEmitter): Promise<void> {\n const { cwd, stepTimeoutMs, prefixLimit, onProgress } = this.options\n const session = await this.backend.open()\n try {\n const toolSteps = ctx.prefix.filter(\n (s): s is typeof s & { span: ToolSpan } => s.span.kind === 'tool',\n )\n const toExecute = prefixLimit !== undefined ? toolSteps.slice(0, prefixLimit) : toolSteps\n const divergences: PrefixDivergence[] = []\n const prefixStart = Date.now()\n for (const step of toExecute) {\n const command = toolCommand(step.span)\n const expected = recordedReturncodeOf(step.span)\n const started = Date.now()\n const result = await session.exec(wrapActionForExec(command, cwd), stepTimeoutMs)\n const handle = await emitter.sandbox({\n name: step.span.name,\n command,\n exitCode: result.exitCode,\n wallMs: Date.now() - started,\n })\n await handle.end()\n const divergence = classifyPrefixStep(step.index + 1, expected, result.exitCode)\n if (divergence) divergences.push(divergence)\n onProgress?.(\n `prefix ${step.span.name}: exit=${result.exitCode}` +\n (divergence\n ? ` (${divergence.kind}${expected === null ? '' : `, recorded ${expected}`})`\n : ''),\n )\n }\n this.lastPrefix = summarizePrefixReplay(\n toExecute.length,\n divergences,\n Date.now() - prefixStart,\n )\n\n if (ctx.mutatedStep.span.kind !== 'tool') {\n throw new Error('trajectory-replay: mutation target is not a tool span')\n }\n const armCommand = toolCommand(ctx.mutatedStep.span as ToolSpan)\n const armStart = Date.now()\n const armResult = await session.exec(wrapActionForExec(armCommand, cwd), stepTimeoutMs)\n const armWallMs = Date.now() - armStart\n const armHandle = await emitter.sandbox({\n name: `candidate:${ctx.mutatedStep.span.name}`,\n command: armCommand,\n exitCode: armResult.exitCode,\n wallMs: armWallMs,\n })\n await armHandle.end()\n this.lastArm = {\n command: armCommand,\n exitCode: armResult.exitCode,\n stdout: armResult.stdout,\n stderr: armResult.stderr,\n wallMs: armWallMs,\n }\n onProgress?.(`candidate step: exit=${armResult.exitCode} in ${armWallMs}ms`)\n await emitter.endRun({\n pass: armResult.exitCode === 0,\n notes:\n `prefix ${toExecute.length} steps, ${divergences.length} divergences ` +\n `(${this.lastPrefix.prefixDivergencePct}%)`,\n })\n } finally {\n await session.close()\n }\n }\n}\n\n// ── Verdict assembly ─────────────────────────────────────────────────\n\nexport interface ReplayVerifyOptions {\n stepsPath: string\n image: string\n /** 1-based step_id of the error-critical step. */\n at: number\n /** Corrected command for arm B. Omit to run arm A only. */\n fixCommand?: string\n cwd: string\n out: string\n caseId?: string\n /** Override the auto-derived failure signature substring. */\n signature?: string\n stepTimeoutMs?: number\n prefixLimit?: number\n /** Label of the driver backing the exec backend (reported, not probed). */\n driverLabel?: string\n /** Execution environment for both arms; each arm opens its own session. */\n backend: ReplayExecBackend\n onProgress?: (message: string) => void\n}\n\nexport interface ReplayArmVerdict {\n command: string\n exitCode: number\n wallMs: number\n prefix: PrefixReplayResult\n}\n\n/** Extends the substrate verdict spine: `valid` = the claim the caller asked\n * to verify held under execution — arm A reproduced the recorded failure on\n * an in-tolerance prefix, and, when arm B ran, the corrected step made the\n * failure vanish. `score` is the same bit as a number; the sub-measurements\n * live in `scores`. Certified as `'replication'`: a re-execution from the\n * pinned image, deterministic given the pins. */\nexport interface ReplayVerdict extends DefaultVerdict {\n case: string\n image: string\n driver: string\n k: number\n cwd: string\n recordedReturncode: number | null\n signature: string | null\n signatureBasis: 'returncode+output-substring' | 'returncode-only'\n prefixExecuted: number\n prefixDivergences: PrefixDivergence[]\n /** Arm A's prefix divergence rate — the number admission gates on. */\n prefixDivergencePct: number\n prefixConfirmed: number\n prefixReturncodeMismatches: number\n prefixUnknownExpectations: number\n prefixWithinTolerance: boolean\n armA: ReplayArmVerdict & { failureSignatureMatch: boolean }\n armB: (ReplayArmVerdict & { failureVanished: boolean }) | null\n timings: { armAMs: number; armBMs: number | null; totalMs: number }\n runIds: { original: string; armA: string; armB: string | null }\n}\n\nfunction excerpt(text: string, limit = 2400): string {\n if (text.length <= limit) return text\n const head = text.slice(0, limit / 2)\n const tail = text.slice(-limit / 2)\n return `${head}\\n… [${text.length - limit} chars elided] …\\n${tail}`\n}\n\nexport async function replayVerify(options: ReplayVerifyOptions): Promise<ReplayVerdict> {\n const totalStart = Date.now()\n const steps = JSON.parse(readFileSync(options.stepsPath, 'utf8')) as RecordedTrajectoryStep[]\n if (!Array.isArray(steps) || steps.length === 0) {\n throw new Error(`trajectory-replay: ${options.stepsPath} is not a non-empty steps array`)\n }\n const index = options.at - 1\n if (index < 0 || index >= steps.length) {\n throw new Error(`trajectory-replay: at ${options.at} out of range [1, ${steps.length}]`)\n }\n const target = steps[index]!\n if (target.step_id !== options.at) {\n throw new Error(\n `trajectory-replay: steps[${index}].step_id=${target.step_id} != at ${options.at}; ` +\n 'steps.json must be ordered with 1-based contiguous step_ids',\n )\n }\n const caseId = options.caseId ?? options.stepsPath\n const recordedReturncode = parseRecordedReturncode(target.observation)\n const signature = options.signature ?? deriveFailureSignature(target.observation)\n const signatureBasis: ReplayVerdict['signatureBasis'] = signature\n ? 'returncode+output-substring'\n : 'returncode-only'\n\n const runnerOptions: SandboxCounterfactualRunnerOptions = {\n cwd: options.cwd,\n stepTimeoutMs: options.stepTimeoutMs ?? 300_000,\n prefixLimit: options.prefixLimit,\n onProgress: options.onProgress,\n }\n\n const store = new InMemoryTraceStore()\n const { runId } = await ingestRecordedTrajectory(store, steps, caseId)\n\n options.onProgress?.(`arm A: replaying ${index} prefix steps then recorded step ${options.at}`)\n const armARunner = new SandboxCounterfactualRunner(options.backend, runnerOptions)\n const armAStart = Date.now()\n const armAResult = await runCounterfactual(\n store,\n runId,\n { kind: 'custom', at: index, describe: 'arm-A identity replay', apply: (s) => s },\n armARunner,\n )\n const armAMs = Date.now() - armAStart\n const armAExec = requireExec(armARunner, 'arm A')\n const armAOutput = `${armAExec.stdout}\\n${armAExec.stderr}`\n const failureSignatureMatch =\n recordedReturncode !== null &&\n armAExec.exitCode === recordedReturncode &&\n (signature ? armAOutput.includes(signature) : true)\n\n let armBRunner: SandboxCounterfactualRunner | null = null\n let armBExec: ArmExecutionResult | null = null\n let armBRunId: string | null = null\n let armBMs: number | null = null\n if (options.fixCommand) {\n const fixCommand = options.fixCommand\n options.onProgress?.('arm B: replaying prefix then corrected step')\n armBRunner = new SandboxCounterfactualRunner(options.backend, runnerOptions)\n const armBStart = Date.now()\n const armBResult = await runCounterfactual(\n store,\n runId,\n {\n kind: 'custom',\n at: index,\n describe: 'arm-B corrected step',\n apply: (step) => ({\n ...step,\n span: { ...(step.span as ToolSpan), args: { command: fixCommand } },\n }),\n },\n armBRunner,\n )\n armBMs = Date.now() - armBStart\n armBRunId = armBResult.counterfactualRunId\n armBExec = requireExec(armBRunner, 'arm B')\n }\n\n const armBOutput = armBExec ? `${armBExec.stdout}\\n${armBExec.stderr}` : null\n const armAPrefix = requirePrefix(armARunner, 'arm A')\n const core = {\n case: caseId,\n image: options.image,\n driver: options.driverLabel ?? 'docker',\n k: options.at,\n cwd: options.cwd,\n recordedReturncode,\n signature,\n signatureBasis,\n prefixExecuted: armAPrefix.prefixExecuted,\n prefixDivergences: armAPrefix.prefixDivergences,\n prefixDivergencePct: armAPrefix.prefixDivergencePct,\n prefixConfirmed: armAPrefix.prefixConfirmed,\n prefixReturncodeMismatches: armAPrefix.prefixReturncodeMismatches,\n prefixUnknownExpectations: armAPrefix.prefixUnknownExpectations,\n prefixWithinTolerance: armAPrefix.prefixWithinTolerance,\n armA: {\n command: armAExec.command,\n exitCode: armAExec.exitCode,\n wallMs: armAExec.wallMs,\n prefix: armAPrefix,\n failureSignatureMatch,\n },\n armB:\n armBExec && armBRunner\n ? {\n command: armBExec.command,\n exitCode: armBExec.exitCode,\n wallMs: armBExec.wallMs,\n prefix: requirePrefix(armBRunner, 'arm B'),\n failureVanished:\n armBExec.exitCode === 0 &&\n (signature && armBOutput ? !armBOutput.includes(signature) : true),\n }\n : null,\n timings: { armAMs, armBMs, totalMs: Date.now() - totalStart },\n runIds: {\n original: runId,\n armA: armAResult.counterfactualRunId,\n armB: armBRunId,\n },\n }\n\n // Steps the certificate rests on unverified: prefix steps the recording\n // cannot adjudicate, a caller-truncated prefix, and a signature derived\n // from the returncode alone.\n const assumptions: string[] = []\n if (armAPrefix.prefixUnknownExpectations > 0) {\n assumptions.push(\n `${armAPrefix.prefixUnknownExpectations} prefix step(s) carry no recorded returncode — agreement with the recording is unestablished there`,\n )\n }\n if (options.prefixLimit !== undefined && options.prefixLimit < index) {\n assumptions.push(\n `prefix truncated at ${options.prefixLimit} of ${index} recorded steps — state fidelity at k is weakened`,\n )\n }\n if (signatureBasis === 'returncode-only') {\n assumptions.push(\n 'no output substring derived from the recording — reproduction rests on the returncode alone',\n )\n }\n const valid =\n core.prefixWithinTolerance &&\n failureSignatureMatch &&\n (core.armB === null || core.armB.failureVanished)\n const verdict: ReplayVerdict = {\n ...core,\n valid,\n score: valid ? 1 : 0,\n scores: {\n prefixFidelity: 1 - core.prefixDivergencePct / 100,\n armAReproduced: failureSignatureMatch ? 1 : 0,\n ...(core.armB === null ? {} : { armBFailureVanished: core.armB.failureVanished ? 1 : 0 }),\n },\n certification: {\n strategy: 'replication',\n checker: {\n name: 'agent-eval:trajectory-replay',\n version: packageVersion(),\n pins: { image: options.image },\n },\n assumptions,\n evidenceDigest: certificationEvidenceDigest(core),\n },\n }\n\n mkdirSync(options.out, { recursive: true })\n writeFileSync(join(options.out, 'replay-verdict.json'), `${JSON.stringify(verdict, null, 2)}\\n`)\n writeFileSync(join(options.out, 'report.md'), renderReport(verdict, target, armAExec, armBExec))\n return verdict\n}\n\nfunction requireExec(runner: SandboxCounterfactualRunner, arm: string): ArmExecutionResult {\n if (!runner.lastArm) {\n throw new Error(`trajectory-replay: ${arm} finished without executing step k`)\n }\n return runner.lastArm\n}\n\nfunction requirePrefix(runner: SandboxCounterfactualRunner, arm: string): PrefixReplayResult {\n if (!runner.lastPrefix) {\n throw new Error(`trajectory-replay: ${arm} reported no prefix replay result`)\n }\n return runner.lastPrefix\n}\n\nfunction renderReport(\n verdict: ReplayVerdict,\n target: RecordedTrajectoryStep,\n armA: ArmExecutionResult,\n armB: ArmExecutionResult | null,\n): string {\n const lines: string[] = []\n lines.push(`# Replay verification — ${verdict.case}`)\n lines.push('')\n lines.push(`- image: \\`${verdict.image}\\` (driver: ${verdict.driver})`)\n lines.push(`- error-critical step k = ${verdict.k}, cwd \\`${verdict.cwd}\\``)\n lines.push(`- recorded returncode at k: ${verdict.recordedReturncode ?? 'none recorded'}`)\n lines.push(\n `- failure signature (${verdict.signatureBasis}): ${\n verdict.signature ? `\\`${verdict.signature}\\`` : '—'\n }`,\n )\n lines.push('')\n lines.push(`## Prefix replay (steps 1..${verdict.k - 1})`)\n lines.push('')\n lines.push(\n `Executed ${verdict.prefixExecuted} steps; ${verdict.prefixConfirmed} confirmed against the ` +\n `recording, ${verdict.prefixDivergences.length} divergent (${verdict.prefixDivergencePct}%) — ` +\n `${verdict.prefixReturncodeMismatches} returncode mismatches, ` +\n `${verdict.prefixUnknownExpectations} with no recorded returncode to check.`,\n )\n lines.push('')\n lines.push(\n `Within the ${PREFIX_DIVERGENCE_TOLERANCE_PCT}% admission tolerance: **${verdict.prefixWithinTolerance}**.`,\n )\n if (verdict.prefixDivergences.length > 0) {\n lines.push('')\n lines.push('| step | kind | recorded rc | replayed exit |')\n lines.push('| --- | --- | --- | --- |')\n for (const d of verdict.prefixDivergences) {\n lines.push(\n `| ${d.step} | ${d.kind} | ${d.expectedReturncode ?? 'none recorded'} | ${d.actualExit} |`,\n )\n }\n }\n lines.push('')\n lines.push('## Arm A — recorded step k, replayed')\n lines.push('')\n lines.push('```sh')\n lines.push(armA.command)\n lines.push('```')\n lines.push('')\n lines.push(\n `Exit ${armA.exitCode} in ${armA.wallMs}ms — failureSignatureMatch: **${verdict.armA.failureSignatureMatch}**`,\n )\n lines.push('')\n lines.push('Recorded observation excerpt:')\n lines.push('')\n lines.push('```')\n lines.push(excerpt(parseObservationOutput(target.observation)))\n lines.push('```')\n lines.push('')\n lines.push('Replayed stdout+stderr excerpt:')\n lines.push('')\n lines.push('```')\n lines.push(excerpt(`${armA.stdout}\\n${armA.stderr}`.trim()))\n lines.push('```')\n if (armB && verdict.armB) {\n lines.push('')\n lines.push('## Arm B — corrected step k')\n lines.push('')\n lines.push('```sh')\n lines.push(armB.command)\n lines.push('```')\n lines.push('')\n lines.push(\n `Exit ${armB.exitCode} in ${armB.wallMs}ms — failureVanished: **${verdict.armB.failureVanished}** ` +\n `(prefix re-replayed in a fresh session: ${verdict.armB.prefix.prefixExecuted} steps, ` +\n `${verdict.armB.prefix.prefixDivergences.length} divergences, ` +\n `${verdict.armB.prefix.prefixDivergencePct}%)`,\n )\n lines.push('')\n lines.push('Replayed stdout+stderr excerpt:')\n lines.push('')\n lines.push('```')\n lines.push(excerpt(`${armB.stdout}\\n${armB.stderr}`.trim()))\n lines.push('```')\n }\n lines.push('')\n lines.push('## Timings')\n lines.push('')\n lines.push(\n `arm A ${verdict.timings.armAMs}ms, arm B ${verdict.timings.armBMs ?? '—'}ms, total ${verdict.timings.totalMs}ms.`,\n )\n lines.push('')\n return lines.join('\\n')\n}\n","/**\n * Batch replay verification across gold-labeled trajectory corpora.\n *\n * For every replayable case (a raw trajectory with a recorded image AND at\n * least one gold incorrect step) the batch:\n * 1. derives the replay-ready image through the injected `ImagePreparer`,\n * 2. replays the prefix and runs arm A — the recorded gold step k, and\n * 3. optionally generates a corrected command with one LLM call and runs\n * arm B in its own fresh session.\n *\n * Headline metrics:\n * replayability rate — fraction of replayable cases where the prefix\n * replays within the divergence tolerance AND arm A reproduces the\n * recorded returncode at k;\n * prefix fidelity — executed prefix steps and the share of them that did\n * not confirm the recording, split by kind. A corpus whose recordings\n * carry no returncodes shows up here as unknown-expectation steps, never\n * as a clean replay;\n * fix-flip rate — fraction of arm-B-executed cases where the failure\n * vanished (exit 0, signature absent).\n *\n * Image pulls and execs run strictly serially: pulls contend on disk and\n * registry bandwidth, and serial cases keep wall-time attribution per case\n * honest. Pull failures are report rows, never silent skips.\n */\n\nimport { appendFileSync, mkdirSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { runCounterfactual } from '../counterfactual'\nimport { mulberry32 } from '../statistics/random'\nimport type { ToolSpan } from '../trace/schema'\nimport { InMemoryTraceStore } from '../trace/store'\nimport {\n type CorpusSpec,\n type EnumerationResult,\n enumerateReplayableCases,\n type ReplayableCase,\n} from './corpus'\nimport type { ReplayExecBackend, ReplayExecBackendFactory } from './exec'\nimport { type ChatCompletionCaller, type ChatUsage, generateFixCommand } from './fix'\nimport { type FixLoopAttemptRecord, runFixLoop } from './fix-loop'\nimport { dockerImagePreparer, type ImagePreparer } from './image-preparer'\nimport {\n ingestRecordedTrajectory,\n PREFIX_DIVERGENCE_TOLERANCE_PCT,\n type PrefixReplayResult,\n type ReplayVerdict,\n replayVerify,\n SandboxCounterfactualRunner,\n} from './verify'\n\n// ── Batch execution ──────────────────────────────────────────────────\n\nexport interface ReplayBatchOptions {\n readonly corpora: readonly CorpusSpec[]\n readonly out: string\n /** 'generate' = one LLM call per arm-A-reproduced case, then arm B.\n * 'loop' = iterative: failed arms feed their real output into up to\n * `fixAttempts` prompts, each executed in its own fresh session. */\n readonly fix: 'none' | 'generate' | 'loop'\n /** Attempt budget per case in loop mode (default 3). */\n readonly fixAttempts?: number\n readonly fixCaller?: ChatCompletionCaller\n readonly fixModelLabel?: string\n /** Cap on LLM fix calls; eligible cases beyond it are seeded-sampled out. */\n readonly maxFixCases?: number\n readonly seed?: number\n /** Overrides the per-case recorded step timeout. */\n readonly stepTimeoutMs?: number\n readonly prefixLimit?: number\n /** Run only cases whose trajId contains this substring (smoke knob). */\n readonly caseFilter?: string\n /** Run only the first N replayable cases (smoke knob). */\n readonly caseLimit?: number\n /** Derives the replay-ready image per case. Defaults to the docker preparer. */\n readonly preparer?: ImagePreparer\n /** Builds the exec backend for a case's derived image. */\n readonly backendFactory: ReplayExecBackendFactory\n readonly onProgress?: (message: string) => void\n}\n\nexport interface ReplayBatchFixResult {\n /** false when the case was eligible but seeded-sampled out of the cap. */\n readonly attempted: boolean\n readonly sampledOut: boolean\n readonly command: string | null\n readonly llmError: string | null\n /** Loop mode: token totals summed across every attempt (null when the\n * provider reported no usage). */\n readonly usage: ChatUsage | null\n readonly armBExit: number | null\n readonly armBPrefixExecuted: number | null\n readonly armBPrefixDivergences: number | null\n readonly armBPrefixDivergencePct: number | null\n readonly failureVanished: boolean | null\n readonly armBError: string | null\n /** Loop mode only: the full per-attempt trail. Null in generate mode. */\n readonly attempts: readonly FixLoopAttemptRecord[] | null\n /** 1-based attempt that flipped the failure; null when none did.\n * Generate mode: 1 when the single attempt flipped. */\n readonly flippedAtAttempt: number | null\n}\n\nexport interface ReplayBatchCaseRow {\n readonly corpus: string\n readonly trajId: string\n readonly image: string\n readonly derivedImage: string | null\n readonly cwd: string\n readonly cwdSource: string\n readonly k: number\n readonly stepCount: number\n readonly goldIncorrectSteps: readonly number[]\n /** Gold steps before k skipped because their action is the submit command. */\n readonly submitGoldsSkipped: number\n readonly recordedReturncodeAtK: number | null\n readonly signature: string | null\n readonly status: 'ok' | 'image-unavailable' | 'replay-error'\n readonly error: string | null\n readonly imagePulled: boolean\n readonly imageBuilt: boolean\n readonly prefixExecuted: number | null\n readonly prefixDivergences: number | null\n readonly prefixDivergencePct: number | null\n /** Prefix steps whose recorded returncode equalled the replayed exit. */\n readonly prefixConfirmed: number | null\n readonly prefixReturncodeMismatches: number | null\n /** Prefix steps the recording carries no returncode for: unverifiable, and\n * counted as divergences because agreement was never established. */\n readonly prefixUnknownExpectations: number | null\n readonly armAExit: number | null\n readonly armAReturncodeMatch: boolean\n readonly armASignatureMatch: boolean\n /** Headline predicate: prefix divergence within tolerance AND arm A\n * reproduced the recorded returncode at k. */\n readonly replayed: boolean\n readonly fix: ReplayBatchFixResult | null\n readonly wallMs: number\n}\n\nexport interface ReplayBatchReport {\n readonly generatedAt: string\n readonly corpora: readonly { name: string; labelsPath: string; preparedDir: string }[]\n readonly totals: {\n readonly labelEntries: number\n readonly replayable: number\n readonly executed: number\n readonly excludedByReason: Record<string, number>\n /** Per-corpus submit-gold accounting: cases dropped because every gold is\n * the submit command, and golds skipped inside still-replayable cases. */\n readonly submitGoldsByCorpus: Record<\n string,\n { submitOnlyCases: number; goldsSkippedWithinReplayable: number }\n >\n }\n readonly headline: {\n readonly replayabilityRate: { numerator: number; denominator: number; value: number | null }\n readonly signatureStrictRate: { numerator: number; denominator: number; value: number | null }\n /** Corpus-level replay fidelity over every executed prefix step. A corpus\n * whose recordings cannot adjudicate the replay lands here as\n * `unknownExpectations`, not as a clean replay. */\n readonly prefixFidelity: {\n readonly executedSteps: number\n readonly divergentSteps: number\n readonly returncodeMismatches: number\n readonly unknownExpectations: number\n /** Divergent over executed steps; null when no prefix step ran. */\n readonly divergencePct: number | null\n readonly tolerancePct: number\n readonly casesWithinTolerance: number\n readonly casesExecuted: number\n }\n readonly fixFlipRate: { numerator: number; denominator: number; value: number | null } | null\n /** Fix-flip restricted to cases whose recorded returncode at k is nonzero —\n * real recorded failures, where \"the failure vanished\" is not vacuous. */\n readonly fixFlipRateNonzeroRc: {\n numerator: number\n denominator: number\n value: number | null\n } | null\n /** Loop mode only: flips at attempt 1 over cases whose attempt 1 executed —\n * the number directly comparable to the one-shot fixFlipRate. */\n readonly fixFlipAttempt1: {\n numerator: number\n denominator: number\n value: number | null\n } | null\n /** Loop mode only: flip count keyed by the attempt number that flipped. */\n readonly flipsByAttempt: Record<string, number> | null\n }\n readonly llm: {\n readonly model: string\n readonly calls: number\n readonly failures: number\n readonly promptTokens: number\n readonly completionTokens: number\n /** Successful calls whose provider reported no usage. Their tokens are\n * absent from the two totals above, so a nonzero count here means the\n * totals are a lower bound, not a measurement. */\n readonly callsWithoutUsage: number\n } | null\n readonly excluded: readonly { corpus: string; trajId: string; reason: string; detail?: string }[]\n readonly pullFailures: readonly { corpus: string; trajId: string; image: string; error: string }[]\n readonly cases: readonly ReplayBatchCaseRow[]\n}\n\nexport function seededSample<T>(items: readonly T[], size: number, seed: number): Set<T> {\n const pool = [...items]\n const random = mulberry32(seed)\n for (let i = pool.length - 1; i > 0; i--) {\n const j = Math.floor(random() * (i + 1))\n ;[pool[i], pool[j]] = [pool[j]!, pool[i]!]\n }\n return new Set(pool.slice(0, size))\n}\n\nfunction caseOutDirName(row: { corpus: string; trajId: string }): string {\n return `${row.corpus}--${row.trajId}`.replaceAll(/[^A-Za-z0-9._-]/g, '_').slice(0, 180)\n}\n\ninterface ArmBExecution {\n readonly exitCode: number\n readonly prefixExecuted: number\n readonly prefixDivergences: number\n readonly prefixDivergencePct: number\n readonly failureVanished: boolean\n readonly stdout: string\n readonly stderr: string\n}\n\n/**\n * Arm B standalone: fresh sandbox, prefix replay, corrected step k. Reuses\n * the same counterfactual scaffold as replayVerify without re-running arm A.\n */\nasync function executeArmB(\n replayCase: ReplayableCase,\n fixCommand: string,\n backend: ReplayExecBackend,\n signature: string | null,\n stepTimeoutMs: number,\n prefixLimit: number | undefined,\n onProgress?: (message: string) => void,\n): Promise<ArmBExecution> {\n const store = new InMemoryTraceStore()\n const { runId } = await ingestRecordedTrajectory(store, replayCase.steps, replayCase.trajId)\n const runner = new SandboxCounterfactualRunner(backend, {\n cwd: replayCase.cwd,\n stepTimeoutMs,\n prefixLimit,\n onProgress,\n })\n await runCounterfactual(\n store,\n runId,\n {\n kind: 'custom',\n at: replayCase.k - 1,\n describe: 'arm-B corrected step',\n apply: (step) => ({\n ...step,\n span: { ...(step.span as ToolSpan), args: { command: fixCommand } },\n }),\n },\n runner,\n )\n const exec = runner.lastArm\n if (!exec) throw new Error('arm B finished without executing the corrected step')\n const prefix: PrefixReplayResult | null = runner.lastPrefix\n if (!prefix) throw new Error('arm B reported no prefix replay result')\n const output = `${exec.stdout}\\n${exec.stderr}`\n return {\n exitCode: exec.exitCode,\n prefixExecuted: prefix.prefixExecuted,\n prefixDivergences: prefix.prefixDivergences.length,\n prefixDivergencePct: prefix.prefixDivergencePct,\n failureVanished: exec.exitCode === 0 && (signature ? !output.includes(signature) : true),\n stdout: exec.stdout,\n stderr: exec.stderr,\n }\n}\n\nfunction rate(numerator: number, denominator: number): number | null {\n return denominator > 0 ? numerator / denominator : null\n}\n\nexport async function runReplayBatch(options: ReplayBatchOptions): Promise<ReplayBatchReport> {\n const onProgress = options.onProgress ?? (() => {})\n const enumeration: EnumerationResult = enumerateReplayableCases(options.corpora)\n let selected = enumeration.replayable\n if (options.caseFilter) {\n selected = selected.filter((c) => c.trajId.includes(options.caseFilter!))\n }\n if (options.caseLimit !== undefined) selected = selected.slice(0, options.caseLimit)\n onProgress(\n `enumerated ${enumeration.labelEntryCount} label entries → ${enumeration.replayable.length} replayable, ` +\n `${enumeration.excluded.length} excluded; executing ${selected.length}`,\n )\n\n const preparer = options.preparer ?? dockerImagePreparer()\n const backendFactory = options.backendFactory\n\n mkdirSync(options.out, { recursive: true })\n const progressPath = join(options.out, 'cases.jsonl')\n const rows: ReplayBatchCaseRow[] = []\n const pullFailures: { corpus: string; trajId: string; image: string; error: string }[] = []\n\n // Phase 1 — arm A for every selected case, serially.\n const verdictByTraj = new Map<string, ReplayVerdict>()\n for (const [index, replayCase] of selected.entries()) {\n const caseStart = Date.now()\n const label = `[${index + 1}/${selected.length}] ${replayCase.corpus}/${replayCase.trajId}`\n onProgress(`${label}: preparing image ${replayCase.image}`)\n const preparation = await preparer.ensure(replayCase.image, replayCase.cwd)\n const base = {\n corpus: replayCase.corpus,\n trajId: replayCase.trajId,\n image: replayCase.image,\n cwd: replayCase.cwd,\n cwdSource: replayCase.cwdSource,\n k: replayCase.k,\n stepCount: replayCase.steps.length,\n goldIncorrectSteps: replayCase.goldIncorrectSteps,\n submitGoldsSkipped: replayCase.submitGoldsSkipped,\n recordedReturncodeAtK: replayCase.recordedReturncodeAtK,\n }\n if (!preparation.succeeded) {\n pullFailures.push({\n corpus: replayCase.corpus,\n trajId: replayCase.trajId,\n image: replayCase.image,\n error: preparation.error,\n })\n const row: ReplayBatchCaseRow = {\n ...base,\n derivedImage: null,\n signature: null,\n status: 'image-unavailable',\n error: preparation.error,\n imagePulled: false,\n imageBuilt: false,\n prefixExecuted: null,\n prefixDivergences: null,\n prefixDivergencePct: null,\n prefixConfirmed: null,\n prefixReturncodeMismatches: null,\n prefixUnknownExpectations: null,\n armAExit: null,\n armAReturncodeMatch: false,\n armASignatureMatch: false,\n replayed: false,\n fix: null,\n wallMs: Date.now() - caseStart,\n }\n rows.push(row)\n appendFileSync(progressPath, `${JSON.stringify(row)}\\n`)\n onProgress(`${label}: image unavailable — ${preparation.error}`)\n continue\n }\n const { derivedImage, pulled, built } = preparation.value\n const stepTimeoutMs = options.stepTimeoutMs ?? replayCase.recordedStepTimeoutMs ?? 120_000\n const caseOut = join(options.out, caseOutDirName(replayCase))\n onProgress(`${label}: arm A on ${derivedImage} (k=${replayCase.k}, timeout ${stepTimeoutMs}ms)`)\n try {\n const verdict = await replayVerify({\n stepsPath: replayCase.stepsPath,\n image: derivedImage,\n at: replayCase.k,\n cwd: replayCase.cwd,\n out: caseOut,\n caseId: replayCase.trajId,\n stepTimeoutMs,\n prefixLimit: options.prefixLimit,\n backend: backendFactory(derivedImage),\n onProgress: (message) => onProgress(`${label}: ${message}`),\n })\n verdictByTraj.set(replayCase.trajId, verdict)\n const returncodeMatch =\n verdict.recordedReturncode !== null && verdict.armA.exitCode === verdict.recordedReturncode\n const row: ReplayBatchCaseRow = {\n ...base,\n derivedImage,\n signature: verdict.signature,\n status: 'ok',\n error: null,\n imagePulled: pulled,\n imageBuilt: built,\n prefixExecuted: verdict.prefixExecuted,\n prefixDivergences: verdict.prefixDivergences.length,\n prefixDivergencePct: verdict.prefixDivergencePct,\n prefixConfirmed: verdict.prefixConfirmed,\n prefixReturncodeMismatches: verdict.prefixReturncodeMismatches,\n prefixUnknownExpectations: verdict.prefixUnknownExpectations,\n armAExit: verdict.armA.exitCode,\n armAReturncodeMatch: returncodeMatch,\n armASignatureMatch: verdict.armA.failureSignatureMatch,\n replayed: verdict.prefixWithinTolerance && returncodeMatch,\n fix: null,\n wallMs: Date.now() - caseStart,\n }\n rows.push(row)\n appendFileSync(progressPath, `${JSON.stringify(row)}\\n`)\n onProgress(\n `${label}: armA exit=${verdict.armA.exitCode} rcMatch=${returncodeMatch} ` +\n `divergences=${verdict.prefixDivergences.length}/${verdict.prefixExecuted} ` +\n `(${verdict.prefixDivergencePct}%, ${verdict.prefixUnknownExpectations} unknown-expectation)`,\n )\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n const row: ReplayBatchCaseRow = {\n ...base,\n derivedImage,\n signature: null,\n status: 'replay-error',\n error: message.slice(0, 500),\n imagePulled: pulled,\n imageBuilt: built,\n prefixExecuted: null,\n prefixDivergences: null,\n prefixDivergencePct: null,\n prefixConfirmed: null,\n prefixReturncodeMismatches: null,\n prefixUnknownExpectations: null,\n armAExit: null,\n armAReturncodeMatch: false,\n armASignatureMatch: false,\n replayed: false,\n fix: null,\n wallMs: Date.now() - caseStart,\n }\n rows.push(row)\n appendFileSync(progressPath, `${JSON.stringify(row)}\\n`)\n onProgress(`${label}: replay error — ${message.slice(0, 200)}`)\n }\n }\n\n // Phase 2 — counterfactual fixes for cases where arm A reproduced.\n let llm: ReplayBatchReport['llm'] = null\n if (options.fix !== 'none') {\n const caller = options.fixCaller\n if (!caller) throw new Error(`trajectory-replay: fix=${options.fix} requires a fixCaller`)\n const fixAttempts = options.fixAttempts ?? 3\n const maxFixCases = options.maxFixCases ?? 30\n const seed = options.seed ?? 17\n const eligible = rows.filter((r) => r.status === 'ok' && r.replayed)\n const sampled =\n eligible.length > maxFixCases ? seededSample(eligible, maxFixCases, seed) : new Set(eligible)\n if (eligible.length > maxFixCases) {\n onProgress(\n `fix phase: ${eligible.length} eligible > cap ${maxFixCases}; seeded sample (seed=${seed})`,\n )\n }\n let calls = 0\n let failures = 0\n let promptTokens = 0\n let completionTokens = 0\n let callsWithoutUsage = 0\n for (const row of eligible) {\n const index = rows.indexOf(row)\n if (!sampled.has(row)) {\n rows[index] = {\n ...row,\n fix: {\n attempted: false,\n sampledOut: true,\n command: null,\n llmError: null,\n usage: null,\n armBExit: null,\n armBPrefixExecuted: null,\n armBPrefixDivergences: null,\n armBPrefixDivergencePct: null,\n failureVanished: null,\n armBError: null,\n attempts: null,\n flippedAtAttempt: null,\n },\n }\n continue\n }\n const replayCase = selected.find((c) => c.trajId === row.trajId && c.corpus === row.corpus)!\n const label = `fix ${row.corpus}/${row.trajId}`\n const signature = verdictByTraj.get(row.trajId)?.signature ?? null\n const stepTimeoutMs = options.stepTimeoutMs ?? replayCase.recordedStepTimeoutMs ?? 120_000\n const promptInput = {\n taskStatement: replayCase.taskStatement,\n steps: replayCase.steps,\n k: replayCase.k,\n }\n const caseOut = join(options.out, caseOutDirName(row))\n\n if (options.fix === 'loop') {\n onProgress(`${label}: fix loop (budget ${fixAttempts} attempts)`)\n const result = await runFixLoop(\n caller,\n promptInput,\n async (command, attempt) => {\n onProgress(\n `${label}: attempt ${attempt} arm B — ${command.split('\\n')[0]!.slice(0, 120)}`,\n )\n const armB = await executeArmB(\n replayCase,\n command,\n backendFactory(row.derivedImage!),\n signature,\n stepTimeoutMs,\n options.prefixLimit,\n (message) => onProgress(`${label}: attempt ${attempt}: ${message}`),\n )\n mkdirSync(caseOut, { recursive: true })\n writeFileSync(\n join(caseOut, `armB-attempt${attempt}-result.json`),\n `${JSON.stringify({ command, ...armB }, null, 2)}\\n`,\n )\n // armB-result.json always holds the LAST executed attempt — the\n // flipped one when the loop flips (it stops there).\n writeFileSync(\n join(caseOut, 'armB-result.json'),\n `${JSON.stringify({ command, attempt, ...armB }, null, 2)}\\n`,\n )\n return armB\n },\n { maxAttempts: fixAttempts, onProgress: (message) => onProgress(`${label}: ${message}`) },\n )\n calls += result.llmCalls\n failures += result.llmFailures\n promptTokens += result.promptTokens\n completionTokens += result.completionTokens\n callsWithoutUsage += result.callsWithoutUsage\n const usage =\n result.promptTokens + result.completionTokens > 0\n ? { promptTokens: result.promptTokens, completionTokens: result.completionTokens }\n : null\n const flippedRecord =\n result.flippedAtAttempt !== null\n ? result.attempts.find((a) => a.attempt === result.flippedAtAttempt)!\n : null\n const summary =\n flippedRecord ?? [...result.attempts].reverse().find((a) => a.executed) ?? null\n const lastRecord = result.attempts.at(-1) ?? null\n rows[index] = {\n ...row,\n fix: summary\n ? {\n attempted: true,\n sampledOut: false,\n command: summary.command,\n llmError: null,\n usage,\n armBExit: summary.exitCode,\n armBPrefixExecuted: summary.prefixExecuted,\n armBPrefixDivergences: summary.prefixDivergences,\n armBPrefixDivergencePct: summary.prefixDivergencePct,\n failureVanished: summary.failureVanished,\n armBError: null,\n attempts: result.attempts,\n flippedAtAttempt: result.flippedAtAttempt,\n }\n : result.aborted\n ? {\n attempted: true,\n sampledOut: false,\n command: lastRecord?.command ?? null,\n llmError: null,\n usage,\n armBExit: null,\n armBPrefixExecuted: null,\n armBPrefixDivergences: null,\n armBPrefixDivergencePct: null,\n failureVanished: null,\n armBError: lastRecord?.armBError ?? 'sandbox error',\n attempts: result.attempts,\n flippedAtAttempt: null,\n }\n : {\n attempted: true,\n sampledOut: false,\n command: null,\n llmError: lastRecord?.llmError ?? 'no attempt produced a runnable fix',\n usage,\n armBExit: null,\n armBPrefixExecuted: null,\n armBPrefixDivergences: null,\n armBPrefixDivergencePct: null,\n failureVanished: null,\n armBError: null,\n attempts: result.attempts,\n flippedAtAttempt: null,\n },\n }\n onProgress(\n `${label}: loop done — flipped=${result.flipped}` +\n (result.flippedAtAttempt !== null ? ` at attempt ${result.flippedAtAttempt}` : '') +\n ` (${result.llmCalls} calls, ${result.attempts.filter((a) => a.executed).length} arms)`,\n )\n continue\n }\n\n onProgress(`${label}: generating corrected command`)\n calls += 1\n const generated = await generateFixCommand(caller, promptInput)\n if (!generated.succeeded) {\n failures += 1\n rows[index] = {\n ...row,\n fix: {\n attempted: true,\n sampledOut: false,\n command: null,\n llmError: generated.error,\n usage: null,\n armBExit: null,\n armBPrefixExecuted: null,\n armBPrefixDivergences: null,\n armBPrefixDivergencePct: null,\n failureVanished: null,\n armBError: null,\n attempts: null,\n flippedAtAttempt: null,\n },\n }\n onProgress(`${label}: LLM failed — ${generated.error.slice(0, 200)}`)\n continue\n }\n if (generated.value.usage === null || generated.value.usage === undefined) {\n callsWithoutUsage += 1\n }\n promptTokens += generated.value.usage?.promptTokens ?? 0\n completionTokens += generated.value.usage?.completionTokens ?? 0\n onProgress(`${label}: arm B — ${generated.value.command.split('\\n')[0]!.slice(0, 120)}`)\n try {\n const armB = await executeArmB(\n replayCase,\n generated.value.command,\n backendFactory(row.derivedImage!),\n signature,\n stepTimeoutMs,\n options.prefixLimit,\n (message) => onProgress(`${label}: ${message}`),\n )\n rows[index] = {\n ...row,\n fix: {\n attempted: true,\n sampledOut: false,\n command: generated.value.command,\n llmError: null,\n usage: generated.value.usage,\n armBExit: armB.exitCode,\n armBPrefixExecuted: armB.prefixExecuted,\n armBPrefixDivergences: armB.prefixDivergences,\n armBPrefixDivergencePct: armB.prefixDivergencePct,\n failureVanished: armB.failureVanished,\n armBError: null,\n attempts: null,\n flippedAtAttempt: armB.failureVanished ? 1 : null,\n },\n }\n mkdirSync(caseOut, { recursive: true })\n writeFileSync(\n join(caseOut, 'armB-result.json'),\n `${JSON.stringify({ command: generated.value.command, ...armB }, null, 2)}\\n`,\n )\n onProgress(`${label}: armB exit=${armB.exitCode} failureVanished=${armB.failureVanished}`)\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n rows[index] = {\n ...row,\n fix: {\n attempted: true,\n sampledOut: false,\n command: generated.value.command,\n llmError: null,\n usage: generated.value.usage,\n armBExit: null,\n armBPrefixExecuted: null,\n armBPrefixDivergences: null,\n armBPrefixDivergencePct: null,\n failureVanished: null,\n armBError: message.slice(0, 500),\n attempts: null,\n flippedAtAttempt: null,\n },\n }\n onProgress(`${label}: arm B error — ${message.slice(0, 200)}`)\n }\n }\n llm = {\n model: options.fixModelLabel ?? 'unknown',\n calls,\n failures,\n promptTokens,\n completionTokens,\n callsWithoutUsage,\n }\n }\n\n const executedRows = rows.filter((r) => r.status === 'ok')\n const replayed = executedRows.filter((r) => r.replayed)\n const sumOver = (pick: (row: ReplayBatchCaseRow) => number | null): number =>\n executedRows.reduce((total, row) => total + (pick(row) ?? 0), 0)\n const executedSteps = sumOver((r) => r.prefixExecuted)\n const divergentSteps = sumOver((r) => r.prefixDivergences)\n const prefixFidelity = {\n executedSteps,\n divergentSteps,\n returncodeMismatches: sumOver((r) => r.prefixReturncodeMismatches),\n unknownExpectations: sumOver((r) => r.prefixUnknownExpectations),\n divergencePct:\n executedSteps > 0 ? Number(((divergentSteps / executedSteps) * 100).toFixed(1)) : null,\n tolerancePct: PREFIX_DIVERGENCE_TOLERANCE_PCT,\n casesWithinTolerance: executedRows.filter(\n (r) =>\n r.prefixDivergencePct !== null && r.prefixDivergencePct <= PREFIX_DIVERGENCE_TOLERANCE_PCT,\n ).length,\n casesExecuted: executedRows.length,\n }\n const signatureStrict = executedRows.filter((r) => r.replayed && r.armASignatureMatch)\n const armBExecuted = rows.filter((r) => r.fix?.attempted && r.fix.failureVanished !== null)\n const flipped = armBExecuted.filter((r) => r.fix!.failureVanished === true)\n const armBNonzeroRc = armBExecuted.filter(\n (r) => r.recordedReturncodeAtK !== null && r.recordedReturncodeAtK !== 0,\n )\n const flippedNonzeroRc = armBNonzeroRc.filter((r) => r.fix!.failureVanished === true)\n const attempt1Executed = rows.filter(\n (r) => r.fix?.attempts?.find((a) => a.attempt === 1)?.executed === true,\n )\n const flippedAt1 = rows.filter((r) => r.fix?.flippedAtAttempt === 1)\n const flipsByAttempt: Record<string, number> = {}\n for (const row of rows) {\n const at = row.fix?.flippedAtAttempt\n if (typeof at === 'number') flipsByAttempt[String(at)] = (flipsByAttempt[String(at)] ?? 0) + 1\n }\n const excludedByReason: Record<string, number> = {}\n for (const excluded of enumeration.excluded) {\n excludedByReason[excluded.reason] = (excludedByReason[excluded.reason] ?? 0) + 1\n }\n const submitGoldsByCorpus: Record<\n string,\n { submitOnlyCases: number; goldsSkippedWithinReplayable: number }\n > = {}\n const submitEntry = (corpus: string) =>\n (submitGoldsByCorpus[corpus] ??= { submitOnlyCases: 0, goldsSkippedWithinReplayable: 0 })\n for (const excluded of enumeration.excluded) {\n if (excluded.reason === 'gold-only-submit-step')\n submitEntry(excluded.corpus).submitOnlyCases += 1\n }\n for (const replayCase of enumeration.replayable) {\n if (replayCase.submitGoldsSkipped > 0) {\n submitEntry(replayCase.corpus).goldsSkippedWithinReplayable += replayCase.submitGoldsSkipped\n }\n }\n\n const report: ReplayBatchReport = {\n generatedAt: new Date().toISOString(),\n corpora: options.corpora.map((c) => ({\n name: c.name,\n labelsPath: c.labelsPath,\n preparedDir: c.preparedDir,\n })),\n totals: {\n labelEntries: enumeration.labelEntryCount,\n replayable: enumeration.replayable.length,\n executed: selected.length,\n excludedByReason,\n submitGoldsByCorpus,\n },\n headline: {\n replayabilityRate: {\n numerator: replayed.length,\n denominator: selected.length,\n value: rate(replayed.length, selected.length),\n },\n signatureStrictRate: {\n numerator: signatureStrict.length,\n denominator: selected.length,\n value: rate(signatureStrict.length, selected.length),\n },\n prefixFidelity,\n fixFlipRate:\n options.fix !== 'none'\n ? {\n numerator: flipped.length,\n denominator: armBExecuted.length,\n value: rate(flipped.length, armBExecuted.length),\n }\n : null,\n fixFlipRateNonzeroRc:\n options.fix !== 'none'\n ? {\n numerator: flippedNonzeroRc.length,\n denominator: armBNonzeroRc.length,\n value: rate(flippedNonzeroRc.length, armBNonzeroRc.length),\n }\n : null,\n fixFlipAttempt1:\n options.fix === 'loop'\n ? {\n numerator: flippedAt1.length,\n denominator: attempt1Executed.length,\n value: rate(flippedAt1.length, attempt1Executed.length),\n }\n : null,\n flipsByAttempt: options.fix === 'loop' ? flipsByAttempt : null,\n },\n llm,\n excluded: enumeration.excluded,\n pullFailures,\n cases: rows,\n }\n writeFileSync(join(options.out, 'batch-report.json'), `${JSON.stringify(report, null, 2)}\\n`)\n writeFileSync(join(options.out, 'batch-report.md'), renderBatchReport(report))\n return report\n}\n\n// ── Report rendering ─────────────────────────────────────────────────\n\nfunction pct(value: number | null): string {\n return value === null ? '—' : `${(value * 100).toFixed(1)}%`\n}\n\nexport function renderBatchReport(report: ReplayBatchReport): string {\n const lines: string[] = []\n const { headline, totals } = report\n lines.push('# Replay-verify batch report')\n lines.push('')\n lines.push(`Generated ${report.generatedAt}.`)\n lines.push('')\n lines.push('## Headline')\n lines.push('')\n const fidelity = headline.prefixFidelity\n lines.push(\n `- **Replayability rate: ${pct(headline.replayabilityRate.value)}** ` +\n `(${headline.replayabilityRate.numerator}/${headline.replayabilityRate.denominator} replayable cases ` +\n `where the prefix replayed within ${fidelity.tolerancePct}% divergence AND arm A reproduced the recorded returncode at the gold step k).`,\n )\n lines.push(\n `- Signature-strict rate: ${pct(headline.signatureStrictRate.value)} ` +\n `(${headline.signatureStrictRate.numerator}/${headline.signatureStrictRate.denominator}; additionally requires the recorded error substring in arm A output).`,\n )\n lines.push(\n `- **Prefix divergence: ${fidelity.divergencePct === null ? '—' : `${fidelity.divergencePct}%`}** ` +\n `(${fidelity.divergentSteps}/${fidelity.executedSteps} executed prefix steps did not confirm the recording: ` +\n `${fidelity.returncodeMismatches} returncode mismatches, ${fidelity.unknownExpectations} with no recorded returncode to check). ` +\n `${fidelity.casesWithinTolerance}/${fidelity.casesExecuted} executed cases are within the ${fidelity.tolerancePct}% tolerance.`,\n )\n if (headline.fixFlipRate) {\n lines.push(\n `- **Fix-flip rate: ${pct(headline.fixFlipRate.value)}** ` +\n `(${headline.fixFlipRate.numerator}/${headline.fixFlipRate.denominator} arm-B-executed cases where the generated fix made the failure vanish).`,\n )\n }\n if (headline.fixFlipRateNonzeroRc) {\n lines.push(\n `- Fix-flip rate on recorded-rc≠0 cases: ${pct(headline.fixFlipRateNonzeroRc.value)} ` +\n `(${headline.fixFlipRateNonzeroRc.numerator}/${headline.fixFlipRateNonzeroRc.denominator}; real recorded failures — a gold step recorded with rc 0 flips vacuously).`,\n )\n }\n if (headline.fixFlipAttempt1) {\n lines.push(\n `- Fix-flip@1: ${pct(headline.fixFlipAttempt1.value)} ` +\n `(${headline.fixFlipAttempt1.numerator}/${headline.fixFlipAttempt1.denominator} cases whose attempt 1 executed — the one-shot-comparable number).`,\n )\n }\n if (headline.flipsByAttempt && Object.keys(headline.flipsByAttempt).length > 0) {\n const parts = Object.entries(headline.flipsByAttempt)\n .sort((a, b) => Number(a[0]) - Number(b[0]))\n .map(([attempt, count]) => `attempt ${attempt}: ${count}`)\n lines.push(`- Flips by attempt: ${parts.join(', ')}.`)\n }\n lines.push('')\n lines.push('## Enumeration')\n lines.push('')\n lines.push(\n `${totals.labelEntries} label entries across ${report.corpora.length} corpora → ` +\n `${totals.replayable} replayable (SWE-style docker image + ≥1 gold incorrect step), ${totals.executed} executed.`,\n )\n lines.push('')\n lines.push('| exclusion reason | count |')\n lines.push('| --- | --- |')\n for (const [reason, count] of Object.entries(totals.excludedByReason).sort(\n (a, b) => b[1] - a[1],\n )) {\n lines.push(`| ${reason} | ${count} |`)\n }\n const submitEntries = Object.entries(totals.submitGoldsByCorpus)\n if (submitEntries.length > 0) {\n lines.push('')\n lines.push(\n 'Submit-command golds are never counterfactual targets ' +\n '(a gold on the submit step marks a bad submit decision, not a failed command):',\n )\n lines.push('')\n lines.push(\n '| corpus | cases excluded (all golds = submit) | golds skipped within replayable cases |',\n )\n lines.push('| --- | --- | --- |')\n for (const [corpus, stats] of submitEntries.sort((a, b) => a[0].localeCompare(b[0]))) {\n lines.push(`| ${corpus} | ${stats.submitOnlyCases} | ${stats.goldsSkippedWithinReplayable} |`)\n }\n }\n if (report.pullFailures.length > 0) {\n lines.push('')\n lines.push('## Image pull/build failures')\n lines.push('')\n lines.push('| corpus | trajectory | image | error |')\n lines.push('| --- | --- | --- | --- |')\n for (const failure of report.pullFailures) {\n lines.push(\n `| ${failure.corpus} | ${failure.trajId} | \\`${failure.image}\\` | ${failure.error.replaceAll('|', '\\\\|')} |`,\n )\n }\n }\n lines.push('')\n lines.push('## Per-case results')\n lines.push('')\n lines.push(\n '| corpus | trajectory | k | rc@k | prefix | confirmed | rc mismatch | unknown rc | div | div% | armA exit | rc match | sig match | replayed | fix | armB exit | armB div% | vanished | wall s |',\n )\n lines.push(`| ${Array(19).fill('---').join(' | ')} |`)\n for (const row of report.cases) {\n const fix = row.fix\n const fixCell = !fix\n ? '—'\n : fix.sampledOut\n ? 'sampled-out'\n : fix.llmError\n ? 'llm-failed'\n : fix.armBError\n ? 'armB-error'\n : fix.attempts\n ? fix.flippedAtAttempt !== null\n ? `flip@${fix.flippedAtAttempt}`\n : `exhausted(${fix.attempts.length})`\n : 'generated'\n lines.push(\n [\n row.corpus,\n row.trajId.length > 48 ? `${row.trajId.slice(0, 45)}…` : row.trajId,\n row.k,\n row.recordedReturncodeAtK ?? 'null',\n row.prefixExecuted ?? '—',\n row.prefixConfirmed ?? '—',\n row.prefixReturncodeMismatches ?? '—',\n row.prefixUnknownExpectations ?? '—',\n row.prefixDivergences ?? '—',\n row.prefixDivergencePct ?? '—',\n row.status === 'ok' ? row.armAExit : row.status,\n row.armAReturncodeMatch ? 'yes' : 'no',\n row.armASignatureMatch ? 'yes' : 'no',\n row.replayed ? '**yes**' : 'no',\n fixCell,\n fix?.armBExit ?? '—',\n fix?.armBPrefixDivergencePct ?? '—',\n fix?.failureVanished === null || fix === null\n ? '—'\n : fix.failureVanished\n ? '**yes**'\n : 'no',\n (row.wallMs / 1000).toFixed(1),\n ].join(' | '),\n )\n }\n if (report.llm) {\n lines.push('')\n lines.push('## LLM fix generation')\n lines.push('')\n lines.push(\n `Model ${report.llm.model}: ${report.llm.calls} calls (${report.llm.failures} failed), ` +\n `${report.llm.promptTokens} prompt + ${report.llm.completionTokens} completion tokens.`,\n )\n }\n lines.push('')\n return lines.join('\\n')\n}\n","/**\n * Finding-to-replay wire: the entry point that turns a cited incorrect-steps\n * finding into an executed replay proof.\n *\n * An analyst finding over a labeled trajectory corpus names its trajectory and\n * carries a subject of the form\n * `incorrect-steps-<first>-<last>-<escaped|unescaped>-consequence-<step>`.\n * The wire maps that to a replay invocation: the executed step is the\n * finding's first incorrect step (which may differ from the gold label), the\n * image and cwd come from the trajectory's raw config, and — optionally — an\n * arm-B corrected command comes from the counterfactual fix generator.\n */\n\nimport { type CaseResources, type CorpusSpec, resolveCaseResources } from './corpus'\nimport type { ReplayExecBackendFactory } from './exec'\nimport { type ChatCompletionCaller, generateFixCommand } from './fix'\nimport { type ReplayVerdict, replayVerify } from './verify'\n\nexport interface IncorrectStepsSubject {\n readonly firstStep: number\n readonly lastStep: number\n readonly escapeStatus: 'escaped' | 'unescaped'\n readonly consequenceStep: number\n}\n\nconst SUBJECT_PATTERN = /^incorrect-steps-(\\d+)-(\\d+)-(escaped|unescaped)-consequence-(\\d+)$/\n\n/** Null when the subject is not an incorrect-steps finding subject. */\nexport function parseIncorrectStepsSubject(subject: string): IncorrectStepsSubject | null {\n const match = SUBJECT_PATTERN.exec(subject)\n if (!match) return null\n return {\n firstStep: Number(match[1]),\n lastStep: Number(match[2]),\n escapeStatus: match[3] as 'escaped' | 'unescaped',\n consequenceStep: Number(match[4]),\n }\n}\n\nexport interface AnalystReplayFinding {\n readonly trajId: string\n readonly subject: string\n}\n\nexport interface ResolvedReplayInvocation {\n readonly resources: CaseResources\n readonly subject: IncorrectStepsSubject\n /** 1-based step_id arm A executes: the finding's first incorrect step. */\n readonly at: number\n}\n\n/**\n * Maps a finding onto replay resources, searching the given corpora for the\n * trajectory. Throws with the precise reason when the finding cannot be\n * replayed (malformed subject, unknown trajectory, non-replayable case, step\n * out of range) — the caller surfaces that reason instead of a proof.\n */\nexport function resolveFindingInvocation(\n finding: AnalystReplayFinding,\n corpora: readonly CorpusSpec[],\n): ResolvedReplayInvocation {\n const subject = parseIncorrectStepsSubject(finding.subject)\n if (!subject) {\n throw new Error(\n `trajectory-replay: subject '${finding.subject}' is not incorrect-steps-<first>-<last>-<escaped|unescaped>-consequence-<step>`,\n )\n }\n const failures: string[] = []\n for (const corpus of corpora) {\n const resolution = resolveCaseResources(corpus, finding.trajId)\n if (resolution.resolved) {\n const at = subject.firstStep\n const step = resolution.resources.steps.find((s) => s.step_id === at)\n if (!step) {\n throw new Error(\n `trajectory-replay: finding step ${at} is outside ${finding.trajId} ` +\n `(${resolution.resources.steps.length} steps)`,\n )\n }\n return { resources: resolution.resources, subject, at }\n }\n failures.push(`${corpus.name}: ${resolution.reason}`)\n }\n throw new Error(\n `trajectory-replay: trajectory ${finding.trajId} is not replayable in any corpus — ${failures.join('; ')}`,\n )\n}\n\nexport interface ReplayFindingOptions {\n readonly corpora: readonly CorpusSpec[]\n readonly out: string\n /** Generates the arm-B corrected command; omit to run arm A only. */\n readonly fixCaller?: ChatCompletionCaller\n /** Pre-supplied arm-B command; mutually exclusive with fixCaller. */\n readonly fixCommand?: string\n readonly stepTimeoutMs?: number\n readonly prefixLimit?: number\n /** Builds the exec backend for the resolved trajectory image. */\n readonly backendFactory: ReplayExecBackendFactory\n readonly onProgress?: (message: string) => void\n}\n\nexport interface ReplayFindingResult {\n readonly invocation: ResolvedReplayInvocation\n readonly fixCommand: string | null\n readonly verdict: ReplayVerdict\n}\n\n/**\n * Finding in, executed proof out. The image comes from the corpus resources;\n * the backend factory receives it as-is, so a factory backed by infrastructure\n * that needs a derived image must run an `ImagePreparer` first.\n */\nexport async function replayVerifyFinding(\n finding: AnalystReplayFinding,\n options: ReplayFindingOptions,\n): Promise<ReplayFindingResult> {\n if (options.fixCaller && options.fixCommand !== undefined) {\n throw new Error('trajectory-replay: pass fixCaller or fixCommand, not both')\n }\n const invocation = resolveFindingInvocation(finding, options.corpora)\n let fixCommand: string | null = options.fixCommand ?? null\n if (options.fixCaller) {\n const generated = await generateFixCommand(options.fixCaller, {\n taskStatement: invocation.resources.taskStatement,\n steps: invocation.resources.steps,\n k: invocation.at,\n })\n if (!generated.succeeded) {\n throw new Error(`trajectory-replay: fix generation failed — ${generated.error}`)\n }\n fixCommand = generated.value.command\n }\n const verdict = await replayVerify({\n stepsPath: invocation.resources.stepsPath,\n image: invocation.resources.image,\n at: invocation.at,\n fixCommand: fixCommand ?? undefined,\n cwd: invocation.resources.cwd,\n out: options.out,\n caseId: invocation.resources.trajId,\n stepTimeoutMs: options.stepTimeoutMs ?? invocation.resources.recordedStepTimeoutMs ?? undefined,\n prefixLimit: options.prefixLimit,\n backend: options.backendFactory(invocation.resources.image),\n onProgress: options.onProgress,\n })\n return { invocation, fixCommand, verdict }\n}\n","/**\n * Proof-carrying findings: execute analyst findings as replays.\n *\n * An analyst finding is a cited claim (\"step 12 is where the run went\n * wrong\"). This module turns each finding into an executed verdict by\n * replaying the trajectory prefix and running the accused step (arm A),\n * optionally followed by a corrected step (arm B):\n *\n * `reproduced` arm A re-produced the recorded failure signature\n * (returncode + stable output substring).\n * `fix-flipped` arm A reproduced AND arm B's corrected command made the\n * failure vanish — the strongest per-finding proof.\n * `divergent` arm A executed but the recorded failure did NOT\n * reproduce; evidence against the finding (or against\n * replay fidelity — the receipt carries prefix\n * divergences so the reader can tell which).\n * `not-replayable` the finding could not be executed at all; the receipt\n * carries the precise reason (no step subject, unknown\n * trajectory, no recorded image, submit step, …).\n *\n * Verification is execution, not generation: no LLM is involved unless the\n * caller supplies a corrected command for arm B. A caller whose execution\n * environment must be reachable before proofs run passes `preflight`, which\n * fails loud instead of letting verification skip silently.\n *\n * Findings are matched by the shape the analyst product emits\n * (`AnalystFinding`): `subject` (`incorrect-step-<n>` or the wire's\n * `incorrect-steps-<f>-<l>-<escaped|unescaped>-consequence-<c>`),\n * `metadata.block_first_step`, and `trace://<traj>/…` evidence refs.\n */\n\nimport { mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { packageVersion } from '../package-version'\nimport { certificationEvidenceDigest, type DefaultVerdict } from '../verdict'\nimport { type CorpusSpec, resolveCaseResources } from './corpus'\nimport type { ReplayExecBackendFactory } from './exec'\nimport { dockerImagePreparer, type ImagePreparer } from './image-preparer'\nimport { isSubmitAction, parseRecordedReturncode, type RecordedTrajectoryStep } from './steps'\nimport { type ReplayVerdict, replayVerify } from './verify'\nimport { parseIncorrectStepsSubject } from './wire'\n\n// ── Finding shape (structural subset of the analyst's AnalystFinding) ─\n\nexport interface VerifiableFinding {\n readonly finding_id?: string\n readonly analyst_id?: string\n readonly subject?: string\n readonly area?: string\n readonly claim?: string\n readonly evidence_refs?: readonly {\n readonly kind?: string\n readonly uri?: string\n readonly excerpt?: string\n }[]\n readonly metadata?: Readonly<Record<string, unknown>>\n}\n\nconst SINGLE_STEP_SUBJECT = /^incorrect-step-(\\d+)$/\n\n/**\n * 1-based step the finding accuses, or null when the finding names none.\n * `metadata.block_first_step` wins over the subject: the analyst records the\n * block's first incorrect step there even when the subject names a later\n * step of the same block.\n */\nexport function findingReplayStep(finding: VerifiableFinding): number | null {\n const fromMetadata = finding.metadata?.block_first_step\n if (typeof fromMetadata === 'number' && Number.isInteger(fromMetadata) && fromMetadata >= 1) {\n return fromMetadata\n }\n const subject = finding.subject ?? ''\n const wire = parseIncorrectStepsSubject(subject)\n if (wire) return wire.firstStep\n const single = SINGLE_STEP_SUBJECT.exec(subject)\n if (single) return Number(single[1])\n return null\n}\n\nconst TRACE_EVIDENCE_URI = /^trace:\\/\\/([^/]+)\\//\n\n/** Trajectory id from the finding's `trace://<traj>/…` evidence refs, or null. */\nexport function findingTrajectoryId(finding: VerifiableFinding): string | null {\n for (const ref of finding.evidence_refs ?? []) {\n if (typeof ref.uri !== 'string') continue\n const match = TRACE_EVIDENCE_URI.exec(ref.uri)\n if (match) return match[1]!\n }\n return null\n}\n\n// ── Replay source ────────────────────────────────────────────────────\n\n/**\n * Where the executable trajectory lives.\n * `direct` — one trajectory's steps.json plus a replay-ready image; the\n * caller owns image preparation.\n * `corpus` — labeled trajectory corpora; each finding's trajectory is\n * resolved by its `trace://` evidence and the image is derived through\n * `preparer` (the docker uid-1000 preparer unless overridden; `null` when\n * the images are already replay-ready).\n */\nexport type FindingReplaySource =\n | {\n readonly kind: 'direct'\n readonly stepsPath: string\n readonly image: string\n readonly cwd: string\n readonly caseId?: string\n }\n | {\n readonly kind: 'corpus'\n readonly corpora: readonly CorpusSpec[]\n readonly preparer?: ImagePreparer | null\n }\n\nexport interface ResolvedFindingReplay {\n readonly caseId: string\n readonly stepsPath: string\n /** Raw image; corpus-mode execution derives the replay image from it. */\n readonly image: string\n readonly cwd: string\n /** 1-based step_id arm A executes. */\n readonly at: number\n readonly recordedReturncode: number\n readonly recordedStepTimeoutMs: number | null\n}\n\nexport type FindingReplayability =\n | { readonly replayable: true; readonly resolved: ResolvedFindingReplay }\n | { readonly replayable: false; readonly reason: string }\n\nfunction checkStep(\n steps: readonly RecordedTrajectoryStep[],\n at: number,\n):\n | { readonly ok: true; readonly recordedReturncode: number }\n | { readonly ok: false; readonly reason: string } {\n const step = steps.find((s) => s.step_id === at)\n if (!step) {\n return { ok: false, reason: `step ${at} is outside the trajectory (${steps.length} steps)` }\n }\n if (isSubmitAction(step.action)) {\n return {\n ok: false,\n reason: `step ${at} is the submit action — a submit decision has no executable failure to replay`,\n }\n }\n const recordedReturncode = parseRecordedReturncode(step.observation)\n if (recordedReturncode === null) {\n return {\n ok: false,\n reason: `step ${at} recorded no returncode — there is no executable failure signature to reproduce`,\n }\n }\n return { ok: true, recordedReturncode }\n}\n\n/**\n * Decides whether one finding can be executed against the source, and with\n * what invocation. Never throws for a finding-shaped problem — every dead end\n * becomes a `not-replayable` reason the receipt can carry verbatim.\n */\nexport function resolveFindingReplayability(\n finding: VerifiableFinding,\n source: FindingReplaySource,\n): FindingReplayability {\n const at = findingReplayStep(finding)\n if (at === null) {\n return {\n replayable: false,\n reason:\n `subject '${finding.subject ?? '(none)'}' names no trajectory step ` +\n '(expected incorrect-step-<n>, incorrect-steps-<f>-<l>-…, or metadata.block_first_step)',\n }\n }\n if (source.kind === 'direct') {\n const trajId = findingTrajectoryId(finding)\n if (trajId && source.caseId && trajId !== source.caseId) {\n return {\n replayable: false,\n reason: `finding cites trajectory '${trajId}' but the supplied steps are case '${source.caseId}'`,\n }\n }\n let steps: RecordedTrajectoryStep[]\n try {\n steps = JSON.parse(readFileSync(source.stepsPath, 'utf8')) as RecordedTrajectoryStep[]\n } catch (err) {\n throw new Error(\n `verify-findings: cannot read steps file ${source.stepsPath} — ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n if (!Array.isArray(steps) || steps.length === 0) {\n throw new Error(`verify-findings: ${source.stepsPath} is not a non-empty steps array`)\n }\n const step = checkStep(steps, at)\n if (!step.ok) return { replayable: false, reason: step.reason }\n return {\n replayable: true,\n resolved: {\n caseId: source.caseId ?? trajId ?? source.stepsPath,\n stepsPath: source.stepsPath,\n image: source.image,\n cwd: source.cwd,\n at,\n recordedReturncode: step.recordedReturncode,\n recordedStepTimeoutMs: null,\n },\n }\n }\n const trajId = findingTrajectoryId(finding)\n if (!trajId) {\n return {\n replayable: false,\n reason: 'finding carries no trace://<trajectory>/ evidence ref naming its trajectory',\n }\n }\n const failures: string[] = []\n for (const corpus of source.corpora) {\n const resolution = resolveCaseResources(corpus, trajId)\n if (!resolution.resolved) {\n failures.push(\n `${corpus.name}: ${resolution.reason}${resolution.detail ? ` (${resolution.detail})` : ''}`,\n )\n continue\n }\n const step = checkStep(resolution.resources.steps, at)\n if (!step.ok) return { replayable: false, reason: step.reason }\n return {\n replayable: true,\n resolved: {\n caseId: trajId,\n stepsPath: resolution.resources.stepsPath,\n image: resolution.resources.image,\n cwd: resolution.resources.cwd,\n at,\n recordedReturncode: step.recordedReturncode,\n recordedStepTimeoutMs: resolution.resources.recordedStepTimeoutMs,\n },\n }\n }\n return {\n replayable: false,\n reason: `trajectory ${trajId} is not replayable in any corpus — ${failures.join('; ')}`,\n }\n}\n\n// ── Verification run ─────────────────────────────────────────────────\n\nexport type FindingVerificationStatus =\n | 'reproduced'\n | 'fix-flipped'\n | 'not-replayable'\n | 'divergent'\n\nexport interface FindingVerification {\n readonly finding_id: string | null\n readonly subject: string | null\n readonly trajectory_id: string | null\n /** 1-based step the proof executed at; null when not replayable. */\n readonly step: number | null\n readonly verified: FindingVerificationStatus\n /** Present exactly when `verified` is `not-replayable`. */\n readonly reason: string | null\n /** Receipt directory: receipt.json plus, when executed, replay-verdict.json + report.md. */\n readonly receipt: string\n readonly verdict_path: string | null\n /** Receipt dir of the executed proof this finding shares (same case, step, and fix). */\n readonly deduplicated_with: string | null\n}\n\n/** Extends the substrate verdict spine over the whole batch: `score` =\n * verified findings (reproduced or fix-flipped) over MEASURABLE findings —\n * not-replayable rows leave the denominator, mirroring the completion\n * verifier's unmeasured rule — and `valid` = every finding was measured and\n * verified. Certification is present exactly when at least one proof\n * executed; a run that executed nothing certifies nothing. */\nexport interface VerifyFindingsRun extends DefaultVerdict {\n readonly out: string\n readonly verifications: readonly FindingVerification[]\n readonly counts: Readonly<Record<FindingVerificationStatus, number>>\n /** Executions actually performed (deduplicated proofs count once). */\n readonly executions: number\n}\n\nexport interface VerifyFindingsOptions {\n readonly source: FindingReplaySource\n /** Receipt root; one subdirectory per finding plus verifications.json. */\n readonly out: string\n /** Corrected command for arm B on every executed finding; omit for arm A only. */\n readonly fixCommand?: string\n readonly stepTimeoutMs?: number\n readonly prefixLimit?: number\n /** Builds the exec backend for a finding's replay image. */\n readonly backendFactory: ReplayExecBackendFactory\n /** Runs once before the first proof, only when some finding is replayable.\n * Throw to refuse execution against absent or degraded infrastructure. */\n readonly preflight?: () => Promise<void>\n readonly onProgress?: (message: string) => void\n}\n\n/**\n * Arm A reproduced on a prefix the recording confirmed → the fix flipping it\n * beats plain reproduction; anything else diverged. A proof standing on a\n * prefix outside the divergence tolerance is divergent no matter what arm A\n * did: the state it ran against is not the recorded state.\n */\nexport function classifyVerdict(verdict: ReplayVerdict): FindingVerificationStatus {\n if (!verdict.prefixWithinTolerance) return 'divergent'\n if (!verdict.armA.failureSignatureMatch) return 'divergent'\n if (verdict.armB?.failureVanished) return 'fix-flipped'\n return 'reproduced'\n}\n\ninterface ReceiptExecution {\n readonly image: string\n readonly cwd: string\n readonly recordedReturncode: number | null\n readonly signature: string | null\n readonly signatureBasis: string\n readonly armA: {\n readonly command: string\n readonly exitCode: number\n readonly wallMs: number\n readonly failureSignatureMatch: boolean\n }\n readonly armB: {\n readonly command: string\n readonly exitCode: number\n readonly wallMs: number\n readonly failureVanished: boolean\n } | null\n readonly prefixExecuted: number\n readonly prefixDivergences: number\n readonly prefixDivergencePct: number\n readonly prefixReturncodeMismatches: number\n readonly prefixUnknownExpectations: number\n readonly prefixWithinTolerance: boolean\n readonly totalMs: number\n}\n\nfunction receiptExecution(verdict: ReplayVerdict): ReceiptExecution {\n return {\n image: verdict.image,\n cwd: verdict.cwd,\n recordedReturncode: verdict.recordedReturncode,\n signature: verdict.signature,\n signatureBasis: verdict.signatureBasis,\n armA: {\n command: verdict.armA.command,\n exitCode: verdict.armA.exitCode,\n wallMs: verdict.armA.wallMs,\n failureSignatureMatch: verdict.armA.failureSignatureMatch,\n },\n armB: verdict.armB\n ? {\n command: verdict.armB.command,\n exitCode: verdict.armB.exitCode,\n wallMs: verdict.armB.wallMs,\n failureVanished: verdict.armB.failureVanished,\n }\n : null,\n prefixExecuted: verdict.prefixExecuted,\n prefixDivergences: verdict.prefixDivergences.length,\n prefixDivergencePct: verdict.prefixDivergencePct,\n prefixReturncodeMismatches: verdict.prefixReturncodeMismatches,\n prefixUnknownExpectations: verdict.prefixUnknownExpectations,\n prefixWithinTolerance: verdict.prefixWithinTolerance,\n totalMs: verdict.timings.totalMs,\n }\n}\n\nfunction writeReceipt(\n receiptDir: string,\n finding: VerifiableFinding,\n verification: FindingVerification,\n execution: ReceiptExecution | null,\n): void {\n const receipt = {\n schema_version: '1.0.0',\n produced_at: new Date().toISOString(),\n finding_id: verification.finding_id,\n analyst_id: finding.analyst_id ?? null,\n subject: verification.subject,\n claim: typeof finding.claim === 'string' ? finding.claim.slice(0, 600) : null,\n trajectory_id: verification.trajectory_id,\n step: verification.step,\n verified: verification.verified,\n reason: verification.reason,\n execution,\n verdict_path: verification.verdict_path,\n deduplicated_with: verification.deduplicated_with,\n }\n writeFileSync(join(receiptDir, 'receipt.json'), `${JSON.stringify(receipt, null, 2)}\\n`)\n}\n\nfunction receiptDirName(index: number, finding: VerifiableFinding): string {\n const id =\n typeof finding.finding_id === 'string' && finding.finding_id.length > 0\n ? finding.finding_id.replace(/[^A-Za-z0-9_-]/g, '_')\n : 'finding'\n return `${String(index + 1).padStart(3, '0')}-${id}`\n}\n\n/**\n * Verifies every finding against the source: resolves replayability, executes\n * one proof per distinct (case, step, fix) — findings accusing the same step\n * share the executed proof — and writes a receipt directory per finding plus a\n * run-level verifications.json.\n */\nexport async function verifyFindings(\n findings: readonly VerifiableFinding[],\n options: VerifyFindingsOptions,\n): Promise<VerifyFindingsRun> {\n if (findings.length === 0) throw new Error('verify-findings: no findings to verify')\n mkdirSync(options.out, { recursive: true })\n const resolutions = findings.map((finding) =>\n resolveFindingReplayability(finding, options.source),\n )\n if (resolutions.some((resolution) => resolution.replayable) && options.preflight) {\n await options.preflight()\n }\n\n // `null` is the caller asserting the corpus images are already replay-ready;\n // only an ABSENT field falls back to the docker preparer.\n const preparer =\n options.source.kind === 'corpus'\n ? options.source.preparer === undefined\n ? dockerImagePreparer()\n : options.source.preparer\n : null\n const preparedImages = new Map<\n string,\n | { readonly succeeded: true; readonly image: string }\n | { readonly succeeded: false; readonly error: string }\n >()\n const executedByKey = new Map<string, FindingVerification>()\n const verifications: FindingVerification[] = []\n let executions = 0\n\n for (let index = 0; index < findings.length; index++) {\n const finding = findings[index]!\n const resolution = resolutions[index]!\n const receiptDir = join(options.out, receiptDirName(index, finding))\n mkdirSync(receiptDir, { recursive: true })\n const identity = {\n finding_id: finding.finding_id ?? null,\n subject: finding.subject ?? null,\n trajectory_id: findingTrajectoryId(finding),\n }\n\n if (!resolution.replayable) {\n const verification: FindingVerification = {\n ...identity,\n step: findingReplayStep(finding),\n verified: 'not-replayable',\n reason: resolution.reason,\n receipt: receiptDir,\n verdict_path: null,\n deduplicated_with: null,\n }\n writeReceipt(receiptDir, finding, verification, null)\n verifications.push(verification)\n options.onProgress?.(\n `${identity.finding_id ?? `finding ${index + 1}`}: not-replayable — ${resolution.reason}`,\n )\n continue\n }\n\n const resolved = resolution.resolved\n const dedupeKey = `${resolved.caseId}::${resolved.at}::${options.fixCommand ?? ''}`\n const prior = executedByKey.get(dedupeKey)\n if (prior) {\n const verification: FindingVerification = {\n ...identity,\n step: resolved.at,\n verified: prior.verified,\n reason: prior.reason,\n receipt: receiptDir,\n verdict_path: prior.verdict_path,\n deduplicated_with: prior.receipt,\n }\n const priorVerdict = prior.verdict_path\n ? (JSON.parse(readFileSync(prior.verdict_path, 'utf8')) as ReplayVerdict)\n : null\n writeReceipt(\n receiptDir,\n finding,\n verification,\n priorVerdict ? receiptExecution(priorVerdict) : null,\n )\n verifications.push(verification)\n options.onProgress?.(\n `${identity.finding_id ?? `finding ${index + 1}`}: ${prior.verified} (shares proof with ${prior.finding_id ?? prior.receipt})`,\n )\n continue\n }\n\n let image = resolved.image\n if (preparer) {\n const preparationKey = `${resolved.image}::${resolved.cwd}`\n let preparation = preparedImages.get(preparationKey)\n if (!preparation) {\n const ensured = await preparer.ensure(resolved.image, resolved.cwd)\n preparation = ensured.succeeded\n ? { succeeded: true, image: ensured.value.derivedImage }\n : { succeeded: false, error: ensured.error }\n preparedImages.set(preparationKey, preparation)\n }\n if (!preparation.succeeded) {\n const verification: FindingVerification = {\n ...identity,\n step: resolved.at,\n verified: 'not-replayable',\n reason: `replay image could not be prepared — ${preparation.error}`,\n receipt: receiptDir,\n verdict_path: null,\n deduplicated_with: null,\n }\n writeReceipt(receiptDir, finding, verification, null)\n verifications.push(verification)\n options.onProgress?.(\n `${identity.finding_id ?? `finding ${index + 1}`}: not-replayable — image preparation failed`,\n )\n continue\n }\n image = preparation.image\n }\n\n options.onProgress?.(\n `${identity.finding_id ?? `finding ${index + 1}`}: executing arm A at step ${resolved.at} of ${resolved.caseId} on ${image}`,\n )\n const verdict = await replayVerify({\n stepsPath: resolved.stepsPath,\n image,\n at: resolved.at,\n fixCommand: options.fixCommand,\n cwd: resolved.cwd,\n out: receiptDir,\n caseId: resolved.caseId,\n stepTimeoutMs: options.stepTimeoutMs ?? resolved.recordedStepTimeoutMs ?? undefined,\n prefixLimit: options.prefixLimit,\n backend: options.backendFactory(image),\n onProgress: options.onProgress,\n })\n executions += 1\n const verification: FindingVerification = {\n ...identity,\n step: resolved.at,\n verified: classifyVerdict(verdict),\n reason: null,\n receipt: receiptDir,\n verdict_path: join(receiptDir, 'replay-verdict.json'),\n deduplicated_with: null,\n }\n executedByKey.set(dedupeKey, verification)\n writeReceipt(receiptDir, finding, verification, receiptExecution(verdict))\n verifications.push(verification)\n options.onProgress?.(\n `${identity.finding_id ?? `finding ${index + 1}`}: ${verification.verified}`,\n )\n }\n\n const counts: Record<FindingVerificationStatus, number> = {\n reproduced: 0,\n 'fix-flipped': 0,\n divergent: 0,\n 'not-replayable': 0,\n }\n for (const verification of verifications) counts[verification.verified] += 1\n const verified = counts.reproduced + counts['fix-flipped']\n const measurable = verifications.length - counts['not-replayable']\n const run: VerifyFindingsRun = {\n out: options.out,\n verifications,\n counts,\n executions,\n valid: measurable > 0 && verified === verifications.length,\n score: measurable > 0 ? verified / measurable : 0,\n // Status distribution over ALL findings (counts travel in `counts`).\n scores: {\n reproduced: counts.reproduced / verifications.length,\n fixFlipped: counts['fix-flipped'] / verifications.length,\n divergent: counts.divergent / verifications.length,\n notReplayable: counts['not-replayable'] / verifications.length,\n },\n notes:\n measurable === 0\n ? 'no finding was replayable — nothing measured'\n : `${verified}/${measurable} measurable finding(s) verified under execution (${counts['not-replayable']} not replayable)`,\n ...(executions > 0\n ? {\n certification: {\n strategy: 'replication',\n checker: { name: 'agent-eval:trajectory-replay', version: packageVersion() },\n assumptions:\n counts['not-replayable'] > 0\n ? [\n `${counts['not-replayable']} finding(s) were not replayable — excluded from the score's denominator, unverified either way`,\n ]\n : [],\n evidenceDigest: certificationEvidenceDigest(verifications),\n },\n }\n : {}),\n }\n writeFileSync(\n join(options.out, 'verifications.json'),\n `${JSON.stringify({ schema_version: '1.0.0', ...run }, null, 2)}\\n`,\n )\n return run\n}\n\n// ── Report rendering ─────────────────────────────────────────────────\n\nfunction verdictCell(verification: FindingVerification): string {\n switch (verification.verified) {\n case 'reproduced':\n return '**VERIFIED** — reproduced'\n case 'fix-flipped':\n return '**VERIFIED** — fix-flipped'\n case 'divergent':\n return 'DIVERGENT — recorded failure did not reproduce'\n case 'not-replayable':\n return `UNVERIFIABLE — ${verification.reason ?? 'no reason recorded'}`\n }\n}\n\n/** Markdown section an analysis report appends when finding verification ran. */\nexport function renderVerifiedFindingsSection(run: VerifyFindingsRun): string {\n const lines: string[] = ['## Verified findings (executed replay)', '']\n const total = run.verifications.length\n lines.push(\n `${total} finding(s) → ${run.counts.reproduced} reproduced, ${run.counts['fix-flipped']} fix-flipped, ` +\n `${run.counts.divergent} divergent, ${run.counts['not-replayable']} not replayable ` +\n `(${run.executions} execution(s); findings accusing the same step share one proof).`,\n )\n lines.push('')\n lines.push('| Finding | Subject | Step | Verdict | Receipt |')\n lines.push('|---|---|---:|---|---|')\n for (const verification of run.verifications) {\n const shared = verification.deduplicated_with ? ' (shared proof)' : ''\n lines.push(\n `| \\`${verification.finding_id ?? '—'}\\` | \\`${verification.subject ?? '—'}\\` | ` +\n `${verification.step ?? '—'} | ${verdictCell(verification)} | \\`${verification.receipt}\\`${shared} |`,\n )\n }\n lines.push('')\n lines.push(\n 'VERIFIED = the accused step was re-executed after replaying the trajectory prefix, and the recorded ' +\n 'failure signature reproduced (fix-flipped: a corrected command additionally made it vanish). Each receipt ' +\n 'directory carries receipt.json and, when executed, replay-verdict.json + report.md with real stdout/stderr.',\n )\n lines.push('')\n return lines.join('\\n')\n}\n\n// ── Findings file loading ────────────────────────────────────────────\n\n/**\n * Accepts the two shapes findings travel in: a bare JSON array of analyst\n * findings, or an object with a `findings` array (e.g. an extracted\n * `observations[n]` from a result.json).\n */\nexport function readFindingsFile(path: string): VerifiableFinding[] {\n const parsed: unknown = JSON.parse(readFileSync(path, 'utf8'))\n const array = Array.isArray(parsed)\n ? parsed\n : parsed &&\n typeof parsed === 'object' &&\n Array.isArray((parsed as { findings?: unknown }).findings)\n ? (parsed as { findings: unknown[] }).findings\n : null\n if (!array) {\n throw new Error(`${path} is neither a findings array nor an object with a findings array`)\n }\n for (const entry of array) {\n if (!entry || typeof entry !== 'object') {\n throw new Error(`${path}: every finding must be an object, got ${JSON.stringify(entry)}`)\n }\n }\n return array as VerifiableFinding[]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,gBAAgB,OAA2B;CACzD,MAAM,KAAK,MAAM,QAAQ,GAAG;CAC5B,IAAI,MAAM,GAAG,MAAM,IAAI,MAAM,oDAAoD,OAAO;CACxF,MAAM,OAAO,MAAM,MAAM,GAAG,EAAE;CAC9B,MAAM,OAAO,MAAM,MAAM,KAAK,CAAC;CAC/B,MAAM,MAAM,KAAK,QAAQ,IAAI;CAC7B,IAAI,OAAO,KAAK,QAAQ,KAAK,SAAS,GACpC,MAAM,IAAI,MAAM,oDAAoD,OAAO;CAE7E,OAAO;EAAE;EAAM,YAAY,KAAK,MAAM,GAAG,GAAG;EAAG,aAAa,KAAK,MAAM,MAAM,CAAC;CAAE;AAClF;AAqDA,SAAgB,iBAAiB,YAAkC;CACjE,MAAM,SAAkB,KAAK,MAAM,aAAa,YAAY,MAAM,CAAC;CACnE,IAAI,CAAC,MAAM,QAAQ,MAAM,GAAG,MAAM,IAAI,M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