@tangle-network/agent-eval 0.150.2 → 0.161.1
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.
- package/CHANGELOG.md +158 -1
- package/README.md +7 -3
- package/dist/{active-curriculum-C4mk67HP.js → active-curriculum-CD5TU2yW.js} +3 -13
- package/dist/active-curriculum-CD5TU2yW.js.map +1 -0
- package/dist/{agent-profile-cell-BkcRDikH.d.ts → agent-profile-cell-CTOZJUuE.d.ts} +4 -2
- package/dist/agent-profile-cell-CTOZJUuE.d.ts.map +1 -0
- package/dist/analyst/index.d.ts +19 -36
- package/dist/analyst/index.d.ts.map +1 -1
- package/dist/analyst/index.js +8 -8
- package/dist/analyst/index.js.map +1 -1
- package/dist/{backend-integrity-DOCa_QrR.d.ts → backend-integrity-DxuQCu_A.d.ts} +4 -3
- package/dist/backend-integrity-DxuQCu_A.d.ts.map +1 -0
- package/dist/{benchmark-BtAWA8nT.d.ts → benchmark-CGPp-kDC.d.ts} +3 -3
- package/dist/{benchmark-BtAWA8nT.d.ts.map → benchmark-CGPp-kDC.d.ts.map} +1 -1
- package/dist/{benchmark-command-BU1Las59.js → benchmark-command-BDC3Gocz.js} +26 -31
- package/dist/benchmark-command-BDC3Gocz.js.map +1 -0
- package/dist/benchmarks/index.d.ts +6 -19
- package/dist/benchmarks/index.d.ts.map +1 -1
- package/dist/benchmarks/index.js +4 -4
- package/dist/benchmarks/index.js.map +1 -1
- package/dist/builder-eval/index.d.ts +3 -3
- package/dist/builder-eval/index.js +2 -2
- package/dist/campaign/index.d.ts +9 -9
- package/dist/campaign/index.js +7 -7
- package/dist/{campaign-la-gEYNz.js → campaign-BSmOwskD.js} +77 -795
- package/dist/campaign-BSmOwskD.js.map +1 -0
- package/dist/{canonical-D-XsTQ6_.js → canonical-IL-Bu-14.js} +26 -2
- package/dist/canonical-IL-Bu-14.js.map +1 -0
- package/dist/{capture-fetch-BBVFzhkk.d.ts → capture-fetch-CqwsJkkG.d.ts} +3 -3
- package/dist/{capture-fetch-BBVFzhkk.d.ts.map → capture-fetch-CqwsJkkG.d.ts.map} +1 -1
- package/dist/{chat-client-Bvmxedyv.js → chat-client-DlMlAeYI.js} +5 -55
- package/dist/{chat-client-Bvmxedyv.js.map → chat-client-DlMlAeYI.js.map} +1 -1
- package/dist/chat-json-call-6g5sJobJ.js +53 -0
- package/dist/chat-json-call-6g5sJobJ.js.map +1 -0
- package/dist/cli.js +54 -19
- package/dist/cli.js.map +1 -1
- package/dist/{client-LIuo-KPv.js → client-CX7KqIdB.js} +3 -3
- package/dist/client-CX7KqIdB.js.map +1 -0
- package/dist/{client-kPQYT_56.d.ts → client-L9VVPkim.d.ts} +4 -4
- package/dist/{client-kPQYT_56.d.ts.map → client-L9VVPkim.d.ts.map} +1 -1
- package/dist/contract/index.d.ts +13 -27
- package/dist/contract/index.d.ts.map +1 -1
- package/dist/contract/index.js +14 -17
- package/dist/contract/index.js.map +1 -1
- package/dist/{counterfactual--bpysZF0.d.ts → counterfactual-BaFUWK3H.d.ts} +4 -4
- package/dist/{counterfactual--bpysZF0.d.ts.map → counterfactual-BaFUWK3H.d.ts.map} +1 -1
- package/dist/{counterfactual-lDfCx0Uz.js → counterfactual-D_VWavVm.js} +2 -2
- package/dist/{counterfactual-lDfCx0Uz.js.map → counterfactual-D_VWavVm.js.map} +1 -1
- package/dist/{dataset-CJjKqQfA.d.ts → dataset-DQqhOCPt.d.ts} +5 -4
- package/dist/{dataset-CJjKqQfA.d.ts.map → dataset-DQqhOCPt.d.ts.map} +1 -1
- package/dist/{default-registry-Cw0Ohdoj.d.ts → default-registry-G9CKMNkc.d.ts} +7 -8
- package/dist/{default-registry-Cw0Ohdoj.d.ts.map → default-registry-G9CKMNkc.d.ts.map} +1 -1
- package/dist/{define-agent-eval-CEQWL9Hy.d.ts → define-agent-eval-Dx1JnPEa.d.ts} +26 -6
- package/dist/define-agent-eval-Dx1JnPEa.d.ts.map +1 -0
- package/dist/{define-agent-eval-C8V8sMqP.js → define-agent-eval-h-s-sI-v.js} +15 -9
- package/dist/define-agent-eval-h-s-sI-v.js.map +1 -0
- package/dist/{dspy-rlm-engine-CBYlPvNy.js → dspy-rlm-engine-DptEII26.js} +95 -15
- package/dist/dspy-rlm-engine-DptEII26.js.map +1 -0
- package/dist/{emitter-CPBAhxum.js → emitter-BpYFQPj4.js} +2 -18
- package/dist/emitter-BpYFQPj4.js.map +1 -0
- package/dist/{emitter-DGQGoLyj.d.ts → emitter-D_jYSGRd.d.ts} +4 -20
- package/dist/{emitter-DGQGoLyj.d.ts.map → emitter-D_jYSGRd.d.ts.map} +1 -1
- package/dist/{engine-BLzhNzoY.d.ts → engine-Cu5qD5Fc.d.ts} +9 -11
- package/dist/{engine-BLzhNzoY.d.ts.map → engine-Cu5qD5Fc.d.ts.map} +1 -1
- package/dist/{eval-campaign-CQuZrLR_.js → eval-campaign-BsXWL2-2.js} +17 -28
- package/dist/eval-campaign-BsXWL2-2.js.map +1 -0
- package/dist/{exact-types-ccQAyut1.d.ts → exact-types-qnexxJ1Z.d.ts} +2 -2
- package/dist/{exact-types-ccQAyut1.d.ts.map → exact-types-qnexxJ1Z.d.ts.map} +1 -1
- package/dist/{exec-y-DCLqK7.js → exec-D9WpA2p-.js} +2 -2
- package/dist/exec-D9WpA2p-.js.map +1 -0
- package/dist/experiment/index.d.ts +45 -11
- package/dist/experiment/index.d.ts.map +1 -1
- package/dist/experiment/index.js +30 -11
- package/dist/experiment/index.js.map +1 -1
- package/dist/{experiment-tracker-0MhuPArU.d.ts → experiment-tracker-DCO6Cz4s.d.ts} +2 -2
- package/dist/{experiment-tracker-0MhuPArU.d.ts.map → experiment-tracker-DCO6Cz4s.d.ts.map} +1 -1
- package/dist/{exporters-q9iL-2Jf.js → exporters-Df7TgHFv.js} +3 -3
- package/dist/exporters-Df7TgHFv.js.map +1 -0
- package/dist/{external-optimizer-contracts-DbLsm4Po.d.ts → external-optimizer-contracts-szBJ_1vh.d.ts} +2 -2
- package/dist/{external-optimizer-contracts-DbLsm4Po.d.ts.map → external-optimizer-contracts-szBJ_1vh.d.ts.map} +1 -1
- package/dist/{external-optimizer-process-x9oEXKsU.js → external-optimizer-process-WosTBChy.js} +4 -4
- package/dist/{external-optimizer-process-x9oEXKsU.js.map → external-optimizer-process-WosTBChy.js.map} +1 -1
- package/dist/{external-optimizer-subprocess-CKNb42oM.js → external-optimizer-subprocess-BIWbHpgD.js} +4 -4
- package/dist/{external-optimizer-subprocess-CKNb42oM.js.map → external-optimizer-subprocess-BIWbHpgD.js.map} +1 -1
- package/dist/{failure-cluster-BLURuWG4.d.ts → failure-cluster-CXL8NbEw.d.ts} +3 -3
- package/dist/{failure-cluster-BLURuWG4.d.ts.map → failure-cluster-CXL8NbEw.d.ts.map} +1 -1
- package/dist/{feedback-trajectory-DpTTjo0q.d.ts → feedback-trajectory-B3ZHaHV_.d.ts} +7 -7
- package/dist/{feedback-trajectory-DpTTjo0q.d.ts.map → feedback-trajectory-B3ZHaHV_.d.ts.map} +1 -1
- package/dist/fuzz.js +1 -1
- package/dist/{hf-dataset-XggBupCr.js → hf-dataset-D8_RNIis.js} +4 -4
- package/dist/{hf-dataset-XggBupCr.js.map → hf-dataset-D8_RNIis.js.map} +1 -1
- package/dist/hosted/index.d.ts +3 -14
- package/dist/hosted/index.d.ts.map +1 -1
- package/dist/hosted/index.js +2 -2
- package/dist/{index-Aj3WO3_a.d.ts → index-CGtH1piv.d.ts} +48 -26
- package/dist/index-CGtH1piv.d.ts.map +1 -0
- package/dist/{index-BNPtkBPf.d.ts → index-D-IiQIBB.d.ts} +5 -10
- package/dist/index-D-IiQIBB.d.ts.map +1 -0
- package/dist/{index-IQccV3Ou.d.ts → index-D-V8gCs_.d.ts} +13 -90
- package/dist/index-D-V8gCs_.d.ts.map +1 -0
- package/dist/{index-B8Ui1mr1.d.ts → index-lfaSeKSD.d.ts} +18 -2
- package/dist/index-lfaSeKSD.d.ts.map +1 -0
- package/dist/index-vrJugRal.d.ts +1 -0
- package/dist/index.d.ts +68 -56
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +59 -110
- package/dist/index.js.map +1 -1
- package/dist/{insight-report-BeT8KCgI.d.ts → insight-report-DRe8LB6d.d.ts} +4 -4
- package/dist/{insight-report-BeT8KCgI.d.ts.map → insight-report-DRe8LB6d.d.ts.map} +1 -1
- package/dist/{integrity-DL91tucI.js → integrity-CyWSSoQS.js} +2 -2
- package/dist/{integrity-DL91tucI.js.map → integrity-CyWSSoQS.js.map} +1 -1
- package/dist/{integrity-B0dZ96EO.d.ts → integrity-DUNX9Fao.d.ts} +3 -3
- package/dist/{integrity-B0dZ96EO.d.ts.map → integrity-DUNX9Fao.d.ts.map} +1 -1
- package/dist/{kind-factory-DmAa0h3K.js → kind-factory-DY8FdoXf.js} +3 -71
- package/dist/kind-factory-DY8FdoXf.js.map +1 -0
- package/dist/ledger-core/index.d.ts +2 -2
- package/dist/ledger-core/index.js +3 -3
- package/dist/{ledger-core-DTae9rv_.js → ledger-core-BOzlRygb.js} +2 -2
- package/dist/{ledger-core-DTae9rv_.js.map → ledger-core-BOzlRygb.js.map} +1 -1
- package/dist/{llm-client-Bg32RW0j.js → llm-client-hgDieDNN.js} +53 -98
- package/dist/llm-client-hgDieDNN.js.map +1 -0
- package/dist/{llm-judge-BqqMS8t7.js → llm-judge-BhasIPFT.js} +1135 -77
- package/dist/llm-judge-BhasIPFT.js.map +1 -0
- package/dist/{matrix-DrVnRp4G.d.ts → matrix-eXKRMHnL.d.ts} +74 -72
- package/dist/matrix-eXKRMHnL.d.ts.map +1 -0
- package/dist/meta-eval/index.d.ts +8 -6
- package/dist/meta-eval/index.d.ts.map +1 -1
- package/dist/meta-eval/index.js +8 -6
- package/dist/meta-eval/index.js.map +1 -1
- package/dist/{mint-BV6tLVWl.js → mint-DfODW1KW.js} +3 -3
- package/dist/{mint-BV6tLVWl.js.map → mint-DfODW1KW.js.map} +1 -1
- package/dist/multishot/golden/index.d.ts +2 -8
- package/dist/multishot/golden/index.d.ts.map +1 -1
- package/dist/multishot/golden/index.js +56 -86
- package/dist/multishot/golden/index.js.map +1 -1
- package/dist/multishot/index.d.ts +11 -46
- package/dist/multishot/index.d.ts.map +1 -1
- package/dist/multishot/index.js +30 -83
- package/dist/multishot/index.js.map +1 -1
- package/dist/openapi.json +1 -1
- package/dist/{opencode-sqlite-DJWAXLms.js → opencode-sqlite-eK6HW6dr.js} +2 -6
- package/dist/{opencode-sqlite-DJWAXLms.js.map → opencode-sqlite-eK6HW6dr.js.map} +1 -1
- package/dist/pipelines/index.d.ts +5 -5
- package/dist/pipelines/index.js +3 -3
- package/dist/{pre-registration-zFSLEiFU.d.ts → pre-registration-CzFCcwYk.d.ts} +55 -40
- package/dist/pre-registration-CzFCcwYk.d.ts.map +1 -0
- package/dist/pre-registration-KN9jkh58.js +110 -0
- package/dist/pre-registration-KN9jkh58.js.map +1 -0
- package/dist/{produced-state-Bnq4FaDO.js → produced-state-DZ89riy5.js} +8 -8
- package/dist/produced-state-DZ89riy5.js.map +1 -0
- package/dist/profile-cell.d.ts +1 -1
- package/dist/profile-cell.js +31 -5
- package/dist/profile-cell.js.map +1 -1
- package/dist/{promotion-policy-DLOUkYhI.d.ts → promotion-policy-DtnOIZvk.d.ts} +2 -2
- package/dist/{promotion-policy-DLOUkYhI.d.ts.map → promotion-policy-DtnOIZvk.d.ts.map} +1 -1
- package/dist/{query-Di7eEQ79.js → query-CHmMP42p.js} +20 -11
- package/dist/query-CHmMP42p.js.map +1 -0
- package/dist/{query-CJ_DX8vl.d.ts → query-DxPYqpmT.d.ts} +10 -4
- package/dist/query-DxPYqpmT.d.ts.map +1 -0
- package/dist/raw-provider-sink-BU29Sh8h.d.ts +134 -0
- package/dist/raw-provider-sink-BU29Sh8h.d.ts.map +1 -0
- package/dist/{registry-BQwrSYpC.d.ts → registry-8You7OK1.d.ts} +5 -7
- package/dist/{registry-BQwrSYpC.d.ts.map → registry-8You7OK1.d.ts.map} +1 -1
- package/dist/{release-confidence-BknrpBnO.js → release-confidence-DKfD2RYU.js} +28 -14
- package/dist/release-confidence-DKfD2RYU.js.map +1 -0
- package/dist/{release-confidence-4XrqlpFD.d.ts → release-confidence-Dqt0NFep.d.ts} +7 -6
- package/dist/release-confidence-Dqt0NFep.d.ts.map +1 -0
- package/dist/reporting.d.ts +3 -3
- package/dist/reporting.js +3 -3
- package/dist/{researcher-DJnoUE8c.d.ts → researcher-Cz565b7D.d.ts} +34 -21
- package/dist/researcher-Cz565b7D.d.ts.map +1 -0
- package/dist/{reward-hacking-62tojkQd.d.ts → reward-hacking-MBf7qpSB.d.ts} +2 -2
- package/dist/{reward-hacking-62tojkQd.d.ts.map → reward-hacking-MBf7qpSB.d.ts.map} +1 -1
- package/dist/{reward-hacking-C0x0xihA.js → reward-hacking-t4lB1yt8.js} +2 -2
- package/dist/{reward-hacking-C0x0xihA.js.map → reward-hacking-t4lB1yt8.js.map} +1 -1
- package/dist/rl.d.ts +11 -42
- package/dist/rl.d.ts.map +1 -1
- package/dist/rl.js +41 -24
- package/dist/rl.js.map +1 -1
- package/dist/rollout/index.d.ts +3 -3
- package/dist/rollout/index.js +7 -7
- package/dist/{rollout-ytVQ7WT8.js → rollout-Dm2tSdiQ.js} +6 -6
- package/dist/{rollout-ytVQ7WT8.js.map → rollout-Dm2tSdiQ.js.map} +1 -1
- package/dist/{rubric-predictive-validity-CzxLoZge.js → rubric-predictive-validity-CK8SCOg-.js} +5 -15
- package/dist/rubric-predictive-validity-CK8SCOg-.js.map +1 -0
- package/dist/{rubric-predictive-validity-C7LnNvF2.d.ts → rubric-predictive-validity-CxycqzX5.d.ts} +4 -3
- package/dist/rubric-predictive-validity-CxycqzX5.d.ts.map +1 -0
- package/dist/{run-record-D2lDdSAz.js → run-record-BC0ebuRP.js} +2 -2
- package/dist/{run-record-D2lDdSAz.js.map → run-record-BC0ebuRP.js.map} +1 -1
- package/dist/{run-record-DVV82Gwh.d.ts → run-record-VVy4T9OW.d.ts} +3 -3
- package/dist/{run-record-DVV82Gwh.d.ts.map → run-record-VVy4T9OW.d.ts.map} +1 -1
- package/dist/{schema-BtVldJ3T.d.ts → schema-Bjgdsn73.d.ts} +2 -4
- package/dist/{schema-BtVldJ3T.d.ts.map → schema-Bjgdsn73.d.ts.map} +1 -1
- package/dist/{schema-Cef2cFmb.d.ts → schema-BzWDXhOR.d.ts} +2 -5
- package/dist/schema-BzWDXhOR.d.ts.map +1 -0
- package/dist/{schema-C6DW4ZHR.js → schema-C1aaAxTf.js} +2 -2
- package/dist/schema-C1aaAxTf.js.map +1 -0
- package/dist/{schema-CRhEY1SO.js → schema-k6ZBftVv.js} +2 -8
- package/dist/{schema-CRhEY1SO.js.map → schema-k6ZBftVv.js.map} +1 -1
- package/dist/{semantic-concept-judge-laMCnTLn.js → semantic-concept-judge-BSkKKHeq.js} +14 -38
- package/dist/semantic-concept-judge-BSkKKHeq.js.map +1 -0
- package/dist/{sequential-eprocess-CbUt2htw.js → sequential-eprocess-D1jKoihe.js} +49 -2
- package/dist/sequential-eprocess-D1jKoihe.js.map +1 -0
- package/dist/{sequential-C458DXNf.js → sequential-rYW-Ophm.js} +41 -16
- package/dist/sequential-rYW-Ophm.js.map +1 -0
- package/dist/{series-convergence-BxKEgBwA.d.ts → series-convergence-D9WgpXGi.d.ts} +2 -2
- package/dist/{series-convergence-BxKEgBwA.d.ts.map → series-convergence-D9WgpXGi.d.ts.map} +1 -1
- package/dist/{server-dIWwF3j_.js → server-BtFd4uzB.js} +19 -42
- package/dist/server-BtFd4uzB.js.map +1 -0
- package/dist/{skillopt-optimization-method-CPBlTcj5.js → skillopt-optimization-method-DbaekMcn.js} +794 -8
- package/dist/skillopt-optimization-method-DbaekMcn.js.map +1 -0
- package/dist/{skillopt-optimization-method-BDD_o1xE.d.ts → skillopt-optimization-method-x7TTF23P.d.ts} +20 -7
- package/dist/{skillopt-optimization-method-BDD_o1xE.d.ts.map → skillopt-optimization-method-x7TTF23P.d.ts.map} +1 -1
- package/dist/{statistical-heldout-_woZ9q9j.d.ts → statistical-heldout-Cy3EhjlC.d.ts} +21 -8
- package/dist/statistical-heldout-Cy3EhjlC.d.ts.map +1 -0
- package/dist/{steps-AmkT-GIM.d.ts → steps-CiNVJry_.d.ts} +2 -17
- package/dist/steps-CiNVJry_.d.ts.map +1 -0
- package/dist/{store-CT9YIIve.d.ts → store-B06JdC56.d.ts} +2 -2
- package/dist/{store-CT9YIIve.d.ts.map → store-B06JdC56.d.ts.map} +1 -1
- package/dist/{store-otlp-CDYWW_8N.js → store-otlp-C_Rq5I4D.js} +2 -2
- package/dist/{store-otlp-CDYWW_8N.js.map → store-otlp-C_Rq5I4D.js.map} +1 -1
- package/dist/{store-tool-spans-Br2_IUhm.d.ts → store-tool-spans-DPUG7UUY.d.ts} +6 -6
- package/dist/{store-tool-spans-Br2_IUhm.d.ts.map → store-tool-spans-DPUG7UUY.d.ts.map} +1 -1
- package/dist/{store-tool-spans-CykkbOlv.js → store-tool-spans-Dlh9vkFK.js} +3 -3
- package/dist/{store-tool-spans-CykkbOlv.js.map → store-tool-spans-Dlh9vkFK.js.map} +1 -1
- package/dist/storyboard/index.d.ts +1 -1
- package/dist/{summary-report-DW2bEpdB.js → summary-report-BI5hUtvK.js} +6 -16
- package/dist/summary-report-BI5hUtvK.js.map +1 -0
- package/dist/{summary-report-B__Y5ub3.d.ts → summary-report-CC07PhEL.d.ts} +6 -5
- package/dist/summary-report-CC07PhEL.d.ts.map +1 -0
- package/dist/supervisor-run/index.d.ts +3 -16
- package/dist/supervisor-run/index.d.ts.map +1 -1
- package/dist/supervisor-run/index.js +3 -3
- package/dist/supervisor-run/index.js.map +1 -1
- package/dist/{task-failure-attributes--ZTP3tYO.js → task-failure-attributes-DTl-7-Kw.js} +3 -3
- package/dist/{task-failure-attributes--ZTP3tYO.js.map → task-failure-attributes-DTl-7-Kw.js.map} +1 -1
- package/dist/{tool-groups-B4tqh8jB.d.ts → tool-groups-Ci8i9ErB.d.ts} +3 -3
- package/dist/tool-groups-Ci8i9ErB.d.ts.map +1 -0
- package/dist/{tool-waste-C-VHSRwF.js → tool-waste-BqzmVdJk.js} +2 -2
- package/dist/{tool-waste-C-VHSRwF.js.map → tool-waste-BqzmVdJk.js.map} +1 -1
- package/dist/{tool-waste-DjRDEsuI.d.ts → tool-waste-Dro0gJi3.d.ts} +4 -4
- package/dist/{tool-waste-DjRDEsuI.d.ts.map → tool-waste-Dro0gJi3.d.ts.map} +1 -1
- package/dist/trace-repair/index.d.ts +4 -77
- package/dist/trace-repair/index.d.ts.map +1 -1
- package/dist/trace-repair/index.js +5 -15
- package/dist/trace-repair/index.js.map +1 -1
- package/dist/traces.d.ts +13 -23
- package/dist/traces.d.ts.map +1 -1
- package/dist/traces.js +9 -20
- package/dist/traces.js.map +1 -1
- package/dist/{trajectory-YC15QDYQ.d.ts → trajectory-Bi157Gun.d.ts} +3 -3
- package/dist/{trajectory-YC15QDYQ.d.ts.map → trajectory-Bi157Gun.d.ts.map} +1 -1
- package/dist/trajectory-replay/index.d.ts +5 -5
- package/dist/trajectory-replay/index.js +5 -5
- package/dist/{provenance-oA4-zUqm.d.ts → transient-failure-DKF5Mofa.d.ts} +468 -13
- package/dist/transient-failure-DKF5Mofa.d.ts.map +1 -0
- package/dist/types-B3jzCp0p.js.map +1 -1
- package/dist/{types-CLAwnY-L.d.ts → types-BPb2Kf_C2.d.ts} +3 -3
- package/dist/types-BPb2Kf_C2.d.ts.map +1 -0
- package/dist/types-Bfk0uxRj.d.ts +443 -0
- package/dist/types-Bfk0uxRj.d.ts.map +1 -0
- package/dist/{types-DdFNuyxQ.d.ts → types-D4s7Z6nq.d.ts} +30 -6
- package/dist/types-D4s7Z6nq.d.ts.map +1 -0
- package/dist/{types-B2NsbrNy.d.ts → types-D9ssmxKL.d.ts} +3 -3
- package/dist/{types-B2NsbrNy.d.ts.map → types-D9ssmxKL.d.ts.map} +1 -1
- package/dist/{types-I5WwVzQ7.d.ts → types-DeIUdzNd.d.ts} +2 -2
- package/dist/{types-I5WwVzQ7.d.ts.map → types-DeIUdzNd.d.ts.map} +1 -1
- package/dist/{verdict-BndeTAh_.js → verdict-B0xltqu6.js} +2 -2
- package/dist/{verdict-BndeTAh_.js.map → verdict-B0xltqu6.js.map} +1 -1
- package/dist/verdict-cache-CdVVTVmn.js +88 -0
- package/dist/verdict-cache-CdVVTVmn.js.map +1 -0
- package/dist/wire/index.d.ts +21 -111
- package/dist/wire/index.d.ts.map +1 -1
- package/dist/wire/index.js +2 -2
- package/docs/building-doctrine.md +3 -3
- package/docs/campaign-proposers.md +41 -10
- package/docs/design/statistics-decisions.md +89 -1
- package/docs/eval-surface-map.md +14 -0
- package/docs/experiment.md +19 -2
- package/docs/feedback-trajectories.md +1 -1
- package/docs/multishot-golden-records.md +4 -4
- package/docs/public-api.md +1616 -0
- package/docs/research-report-methodology.md +1 -1
- package/docs/search-history-receipts.md +39 -1
- package/docs/trace-analysis.md +1 -1
- package/docs/trace-repair-admission.md +1 -1
- package/docs/trace-repair-continuation.md +1 -1
- package/docs/verdicts.md +24 -0
- package/package.json +7 -3
- package/dist/active-curriculum-C4mk67HP.js.map +0 -1
- package/dist/agent-profile-cell-BkcRDikH.d.ts.map +0 -1
- package/dist/backend-integrity-DOCa_QrR.d.ts.map +0 -1
- package/dist/benchmark-command-BU1Las59.js.map +0 -1
- package/dist/campaign-la-gEYNz.js.map +0 -1
- package/dist/canonical-D-XsTQ6_.js.map +0 -1
- package/dist/client-LIuo-KPv.js.map +0 -1
- package/dist/define-agent-eval-C8V8sMqP.js.map +0 -1
- package/dist/define-agent-eval-CEQWL9Hy.d.ts.map +0 -1
- package/dist/dspy-rlm-engine-CBYlPvNy.js.map +0 -1
- package/dist/emitter-CPBAhxum.js.map +0 -1
- package/dist/eval-campaign-CQuZrLR_.js.map +0 -1
- package/dist/exec-y-DCLqK7.js.map +0 -1
- package/dist/exporters-q9iL-2Jf.js.map +0 -1
- package/dist/index-Aj3WO3_a.d.ts.map +0 -1
- package/dist/index-B8Ui1mr1.d.ts.map +0 -1
- package/dist/index-BNPtkBPf.d.ts.map +0 -1
- package/dist/index-C1ravkGA.d.ts +0 -1
- package/dist/index-IQccV3Ou.d.ts.map +0 -1
- package/dist/kind-factory-DmAa0h3K.js.map +0 -1
- package/dist/llm-client-Bg32RW0j.js.map +0 -1
- package/dist/llm-judge-BqqMS8t7.js.map +0 -1
- package/dist/matrix-DrVnRp4G.d.ts.map +0 -1
- package/dist/pre-registration-DakwTRXk.js +0 -96
- package/dist/pre-registration-DakwTRXk.js.map +0 -1
- package/dist/pre-registration-zFSLEiFU.d.ts.map +0 -1
- package/dist/produced-state-Bnq4FaDO.js.map +0 -1
- package/dist/provenance-oA4-zUqm.d.ts.map +0 -1
- package/dist/query-CJ_DX8vl.d.ts.map +0 -1
- package/dist/query-Di7eEQ79.js.map +0 -1
- package/dist/release-confidence-4XrqlpFD.d.ts.map +0 -1
- package/dist/release-confidence-BknrpBnO.js.map +0 -1
- package/dist/researcher-DJnoUE8c.d.ts.map +0 -1
- package/dist/rubric-predictive-validity-C7LnNvF2.d.ts.map +0 -1
- package/dist/rubric-predictive-validity-CzxLoZge.js.map +0 -1
- package/dist/schema-C6DW4ZHR.js.map +0 -1
- package/dist/schema-Cef2cFmb.d.ts.map +0 -1
- package/dist/semantic-concept-judge-laMCnTLn.js.map +0 -1
- package/dist/sequential-C458DXNf.js.map +0 -1
- package/dist/sequential-eprocess-CbUt2htw.js.map +0 -1
- package/dist/server-dIWwF3j_.js.map +0 -1
- package/dist/skillopt-optimization-method-CPBlTcj5.js.map +0 -1
- package/dist/statistical-heldout-_woZ9q9j.d.ts.map +0 -1
- package/dist/steps-AmkT-GIM.d.ts.map +0 -1
- package/dist/summary-report-B__Y5ub3.d.ts.map +0 -1
- package/dist/summary-report-DW2bEpdB.js.map +0 -1
- package/dist/tool-groups-B4tqh8jB.d.ts.map +0 -1
- package/dist/types-CLAwnY-L.d.ts.map +0 -1
- package/dist/types-DdFNuyxQ.d.ts.map +0 -1
- package/dist/types-jUBXJ7Iz.d.ts +0 -884
- package/dist/types-jUBXJ7Iz.d.ts.map +0 -1
- package/dist/verdict-cache-mZf5FEiY.js +0 -107
- package/dist/verdict-cache-mZf5FEiY.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["requirePositiveInteger","admitRow","describe","describe"],"sources":["../../src/trace-repair/mini-swe-scaffold.ts","../../src/trace-repair/action-budget.ts","../../src/trace-repair/admission-records.ts","../../src/trace-repair/continuation-policy.ts","../../src/trace-repair/control-policy.ts","../../src/trace-repair/admission.ts","../../src/trace-repair/admission-contract.ts","../../src/trace-repair/admission-report.ts","../../src/trace-repair/blinding.ts","../../src/trace-repair/repair-prompt.ts","../../src/trace-repair/analyst-arm.ts","../../src/trace-repair/analyst-response.ts","../../src/trace-repair/arm-completion.ts","../../src/trace-repair/arm-dspy.ts","../../src/trace-repair/continuation-records.ts","../../src/trace-repair/degenerate-strategies.ts","../../src/trace-repair/funnel.ts","../../src/trace-repair/delta-repair.ts","../../src/trace-repair/docker-environment.ts","../../src/trace-repair/grade.ts","../../src/trace-repair/oracle-determinism.ts","../../src/trace-repair/test-oracle.ts"],"sourcesContent":["/**\n * The mini-swe-agent scaffold as the Terminal-Bench-2 trajectory corpus\n * recorded it: one bash block per turn, one observation per command, and a\n * sentinel command that ends the run.\n *\n * Every template here is byte-verified against\n * `yoonholee/terminalbench-trajectories` (agent = `mini-swe-agent`, 6663 rows,\n * one distinct system prompt across all of them). A continuation that renders\n * different bytes puts the model in a different distribution than the prefix\n * it inherits, so these strings are pinned, not configurable.\n *\n * The markers a reader matches on live in `trajectory-replay/steps`, which owns\n * the recorded grammar. This module writes with them so a rendered observation\n * and a recorded one classify the same way.\n */\n\nimport {\n FORMAT_ERROR_OBSERVATION_PREFIX,\n SUBMIT_ACTION_SIGNATURE,\n TIMEOUT_OBSERVATION_MARKER,\n} from '../trajectory-replay/steps'\n\nexport { isRecordedTimeout } from '../trajectory-replay/steps'\n\n/** Whole-line marker that ends a run. The first output line must equal it and the command must exit 0. */\nexport const SUBMIT_SENTINEL = SUBMIT_ACTION_SIGNATURE\n\n/** Outputs at or above this length are elided head+tail instead of shown whole. */\nexport const OUTPUT_ELISION_THRESHOLD = 10_000\n\n/** Characters kept from each end of an elided output. */\nexport const OUTPUT_ELISION_WINDOW = 5_000\n\nexport const MINI_SWE_SYSTEM_MESSAGE = `You are a helpful assistant that can interact with a computer.\n\nYour response must contain exactly ONE bash code block with ONE command (or commands connected with && or ||).\nInclude a THOUGHT section before your command where you explain your reasoning process.\nFormat your response as shown in <format_example>.\n\n<format_example>\nYour reasoning and analysis here. Explain why you want to perform the action.\n\n\\`\\`\\`bash\nyour_command_here\n\\`\\`\\`\n</format_example>\n\nFailure to follow these rules will cause your response to be rejected.\n`\n\nexport interface InstanceMessageInput {\n /** The task statement, substituted verbatim. */\n task: string\n /**\n * `uname`-style line the recorded runs rendered from the host running the\n * scaffold, e.g. `Linux 6.8.0-86-generic #87-Ubuntu SMP ... x86_64`.\n */\n systemInformation: string\n}\n\n/** The second message of every recorded run: task plus workflow rules. */\nexport function renderInstanceMessage(input: InstanceMessageInput): string {\n return `Please solve this issue: ${input.task}\n\nYou can execute bash commands and edit files to implement the necessary changes.\n\n## Recommended Workflow\n\nThis workflows should be done step-by-step so that you can iterate on your changes and any possible problems.\n\n1. Analyze the codebase by finding and reading relevant files\n2. Create a script to reproduce the issue\n3. Edit the source code to resolve the issue\n4. Verify your fix works by running your script again\n5. Test edge cases to ensure your fix is robust\n6. Submit your changes and finish your work by issuing the following command: \\`echo ${SUBMIT_SENTINEL}\\`.\n Do not combine it with any other command. <important>After this command, you cannot continue working on this task.</important>\n\n## Important Rules\n\n1. Every response must contain exactly one action\n2. The action must be enclosed in triple backticks\n3. Directory or environment variable changes are not persistent. Every action is executed in a new subshell.\n However, you can prefix any action with \\`MY_ENV_VAR=MY_VALUE cd /path/to/working/dir && ...\\` or write/load environment variables from files\n\n<system_information>\n${input.systemInformation}\n</system_information>\n\n## Formatting your response\n\nHere is an example of a correct response:\n\n<example_response>\nTHOUGHT: I need to understand the structure of the repository first. Let me check what files are in the current directory to get a better understanding of the codebase.\n\n\\`\\`\\`bash\nls -la\n\\`\\`\\`\n</example_response>\n\n## Useful command examples\n\n### Create a new file:\n\n\\`\\`\\`bash\ncat <<'EOF' > newfile.py\nimport numpy as np\nhello = \"world\"\nprint(hello)\nEOF\n\\`\\`\\`\n\n### Edit files with sed:\\`\\`\\`bash\n# Replace all occurrences\nsed -i 's/old_string/new_string/g' filename.py\n\n# Replace only first occurrence\nsed -i 's/old_string/new_string/' filename.py\n\n# Replace first occurrence on line 1\nsed -i '1s/old_string/new_string/' filename.py\n\n# Replace all occurrences in lines 1-10\nsed -i '1,10s/old_string/new_string/g' filename.py\n\\`\\`\\`\n\n### View file content:\n\n\\`\\`\\`bash\n# View specific lines with numbers\nnl -ba filename.py | sed -n '10,20p'\n\\`\\`\\`\n\n### Any other command you want to run\n\n\\`\\`\\`bash\nanything\n\\`\\`\\`\n`\n}\n\nexport type ParsedAction =\n | { kind: 'action'; command: string }\n | { kind: 'format-error'; actionCount: number }\n\nconst BASH_BLOCK = /```bash\\n(.*?)\\n```/gs\n\n/**\n * Exactly one fenced bash block is an action; zero or many is a format error.\n * The scaffold trims the command, so a block padded with blank lines executes\n * the same command as an unpadded one.\n */\nexport function parseAction(assistantMessage: string): ParsedAction {\n const blocks = [...assistantMessage.matchAll(BASH_BLOCK)].map((match) => match[1] ?? '')\n if (blocks.length !== 1) return { kind: 'format-error', actionCount: blocks.length }\n return { kind: 'action', command: (blocks[0] ?? '').trim() }\n}\n\nexport interface CommandOutput {\n returncode: number\n output: string\n /** Set when the environment itself failed rather than the command. */\n exceptionInfo?: string\n}\n\n/**\n * The observation the agent reads after a command. Short outputs are shown\n * whole; long ones keep the first and last `OUTPUT_ELISION_WINDOW` characters\n * with the dropped count between them.\n */\nexport function renderObservation(output: CommandOutput): string {\n const head = output.exceptionInfo ? `<exception>${output.exceptionInfo}</exception>\\n` : ''\n const returncode = `<returncode>${output.returncode}</returncode>\\n`\n if (output.output.length < OUTPUT_ELISION_THRESHOLD) {\n return `${head}${returncode}<output>\\n${output.output}</output>`\n }\n const elided = output.output.length - OUTPUT_ELISION_THRESHOLD\n return (\n `${head}${returncode}<warning>\\n` +\n 'The output of your last command was too long.\\n' +\n 'Please try a different command that produces less output.\\n' +\n \"If you're looking at a file you can try use head, tail or sed to view a smaller number of lines selectively.\\n\" +\n \"If you're using grep or find and it produced too much output, you can use a more selective search pattern.\\n\" +\n \"If you really need to see something from the full command's output, you can redirect output to a file and then search in that file.\\n\" +\n '</warning>' +\n `<output_head>\\n${output.output.slice(0, OUTPUT_ELISION_WINDOW)}\\n</output_head>\\n` +\n `<elided_chars>\\n${elided} characters elided\\n</elided_chars>\\n` +\n `<output_tail>\\n${output.output.slice(-OUTPUT_ELISION_WINDOW)}\\n</output_tail>`\n )\n}\n\n/** The observation after the environment killed a command for exceeding its timeout. */\nexport function renderTimeoutObservation(command: string, partialOutput: string): string {\n return (\n `The last command <command>${command}</command> ${TIMEOUT_OBSERVATION_MARKER}.\\n` +\n `The output of the command was:\\n <output>\\n${partialOutput}\\n</output>\\n` +\n 'Please try another command and make sure to avoid those requiring interactive input.'\n )\n}\n\n/** The observation after a turn that did not contain exactly one bash block. */\nexport function renderFormatErrorObservation(actionCount: number): string {\n return (\n `${FORMAT_ERROR_OBSERVATION_PREFIX}${actionCount} actions.\\n` +\n `If you want to end the task, please issue the following command: \\`echo ${SUBMIT_SENTINEL}\\`\\n` +\n 'without any other command.\\n' +\n 'Else, please format your response exactly as follows:\\n' +\n '\\n' +\n '<response_example>\\n' +\n 'Here are some thoughts about why you want to perform the action.\\n' +\n '\\n' +\n '```bash\\n' +\n '<action>\\n' +\n '```\\n' +\n '</response_example>\\n' +\n '\\n' +\n 'Note: In rare cases, if you need to reference a similar format in your command, you might have\\n' +\n 'to proceed in two steps, first writing TRIPLEBACKTICKSBASH, then replacing them with ```bash.'\n )\n}\n\n/**\n * The submission text when this output ends the run, `null` otherwise.\n * A non-zero exit does not submit even when the sentinel is echoed, so an\n * agent cannot end the run through a command that failed.\n */\nexport function submissionOf(output: CommandOutput): string | null {\n if (output.returncode !== 0) return null\n const lines = output.output.replace(/^\\s+/, '').split(/(?<=\\n)/)\n const first = lines[0]\n if (first === undefined || first.trim() !== SUBMIT_SENTINEL) return null\n return lines.slice(1).join('')\n}\n","/**\n * The action budget an intervention must fit inside.\n *\n * The analyst answers with one action, applied at step k, drawn from the same\n * action space the scaffold had: one shell command or one edit, at most 4 KB.\n * An answer that buys a bigger action than the scaffold could take is not a\n * counterfactual about the recorded run, so the budget is enforced before any\n * container is opened and a violation never reaches the reproduction gate.\n *\n * \"One action\" is decided by counting top-level statements, not lines. A\n * command list joined by `&&`, `||` or a pipe is one statement, because that\n * is one thing the shell runs and one thing the scaffold could have typed.\n * Two statements separated by a newline or `;` are two actions and are\n * rejected. Heredoc bodies, comments and compound blocks (`if`, `for`,\n * `while`, `until`, `case`, `{ … }`) are inside a statement, never separators.\n */\n\nimport { ValidationError } from '../errors'\nimport { SUBMIT_SENTINEL } from './mini-swe-scaffold'\n\n/**\n * Payload shape of an action.\n *\n * `edit` authors file content inline through a heredoc; `shell` runs a\n * command. The split matters because the two carry different amounts of\n * information for the same byte count, and a report that pools them hides it.\n */\nexport type ActionPayloadKind = 'shell' | 'edit'\n\nexport interface InterventionBudget {\n /** Hard cap on the UTF-8 byte length of the action. */\n readonly maxBytes: number\n /** Top-level statements the action may contain. One means one action. */\n readonly maxStatements: number\n /** Heredoc redirections an `edit` may contain. One means one file. */\n readonly maxHeredocs: number\n}\n\n/** The scaffold's own per-action budget, pre-registered for the campaign. */\nexport const SCAFFOLD_INTERVENTION_BUDGET: InterventionBudget = Object.freeze({\n maxBytes: 4096,\n maxStatements: 1,\n maxHeredocs: 1,\n})\n\n/**\n * Actions whose only effect is to consume a turn. They are rejected before a\n * container opens: an intervention that changes nothing is measurably\n * identical to the no-op control, and paying rollouts to rediscover that\n * wastes the corpus.\n */\nexport const NO_OP_ACTIONS: readonly string[] = Object.freeze([\n ':',\n 'true',\n '/bin/true',\n 'exit',\n 'exit 0',\n])\n\ninterface HeredocMark {\n delimiter: string\n stripTabs: boolean\n quoted: boolean\n}\n\ninterface ScanState {\n statements: string[]\n current: string\n heredocs: number\n}\n\nconst BLOCK_OPENERS = new Set(['if', 'for', 'while', 'until', 'case', 'select', 'do', 'then'])\nconst BLOCK_CLOSERS = new Set(['fi', 'done', 'esac'])\n\n/**\n * Split a shell script into top-level statements and count its heredocs.\n *\n * The scan tracks quoting, escapes, command substitution, brace and paren\n * grouping, comments, compound-block keywords, and heredoc bodies. Anything\n * it cannot resolve stays inside the current statement, so an unparseable\n * action reads as one oversized statement and is rejected on bytes rather\n * than silently accepted as one clean action.\n */\nexport function scanShellAction(script: string): { statements: string[]; heredocs: number } {\n const state: ScanState = { statements: [], current: '', heredocs: 0 }\n let index = 0\n let parenDepth = 0\n let braceDepth = 0\n let blockDepth = 0\n let inSingle = false\n let inDouble = false\n let inBacktick = false\n let pendingHeredocs: HeredocMark[] = []\n let word = ''\n let atStatementStart = true\n\n const flushWord = (): void => {\n if (word.length === 0) return\n if (BLOCK_OPENERS.has(word)) blockDepth += 1\n else if (BLOCK_CLOSERS.has(word)) blockDepth = Math.max(0, blockDepth - 1)\n word = ''\n }\n\n const endStatement = (): void => {\n flushWord()\n const text = state.current.trim()\n // A comment runs no command, so a comment-only chunk is not a statement.\n if (text.length > 0 && !isCommentOnly(text)) state.statements.push(text)\n state.current = ''\n atStatementStart = true\n }\n\n while (index < script.length) {\n const char = script[index]!\n\n if (inSingle) {\n state.current += char\n if (char === \"'\") inSingle = false\n index += 1\n continue\n }\n\n if (char === '\\\\' && index + 1 < script.length) {\n const next = script[index + 1]!\n if (next === '\\n' && !inDouble) {\n // Line continuation: the statement carries on.\n state.current += char + next\n index += 2\n continue\n }\n state.current += char + next\n index += 2\n continue\n }\n\n if (inDouble) {\n state.current += char\n if (char === '\"') inDouble = false\n index += 1\n continue\n }\n\n if (char === \"'\") {\n flushWord()\n inSingle = true\n state.current += char\n index += 1\n atStatementStart = false\n continue\n }\n\n if (char === '\"') {\n flushWord()\n inDouble = true\n state.current += char\n index += 1\n atStatementStart = false\n continue\n }\n\n if (char === '`') {\n inBacktick = !inBacktick\n state.current += char\n index += 1\n atStatementStart = false\n continue\n }\n\n if (char === '#' && (atStatementStart || /\\s/.test(script[index - 1] ?? ' '))) {\n const end = script.indexOf('\\n', index)\n const stop = end === -1 ? script.length : end\n state.current += script.slice(index, stop)\n index = stop\n continue\n }\n\n // Heredoc introducer: `<<WORD`, `<<-WORD`, `<<'WORD'`. A run of three `<`\n // is a herestring, so neither of its `<<` pairs may open a heredoc.\n if (\n char === '<' &&\n script[index + 1] === '<' &&\n script[index + 2] !== '<' &&\n script[index - 1] !== '<'\n ) {\n const mark = readHeredocMark(script, index)\n if (mark) {\n pendingHeredocs.push(mark.mark)\n state.heredocs += 1\n state.current += script.slice(index, mark.nextIndex)\n index = mark.nextIndex\n atStatementStart = false\n continue\n }\n }\n\n if (char === '(') {\n flushWord()\n parenDepth += 1\n state.current += char\n index += 1\n atStatementStart = true\n continue\n }\n if (char === ')') {\n flushWord()\n parenDepth = Math.max(0, parenDepth - 1)\n state.current += char\n index += 1\n atStatementStart = false\n continue\n }\n if (char === '{') {\n flushWord()\n braceDepth += 1\n state.current += char\n index += 1\n atStatementStart = true\n continue\n }\n if (char === '}') {\n flushWord()\n braceDepth = Math.max(0, braceDepth - 1)\n state.current += char\n index += 1\n atStatementStart = false\n continue\n }\n\n if (char === '\\n') {\n flushWord()\n if (pendingHeredocs.length > 0) {\n const consumed = consumeHeredocBodies(script, index + 1, pendingHeredocs)\n state.current += script.slice(index, consumed)\n pendingHeredocs = []\n index = consumed\n continue\n }\n if (\n parenDepth > 0 ||\n braceDepth > 0 ||\n blockDepth > 0 ||\n inBacktick ||\n endsWithContinuation(state.current)\n ) {\n state.current += char\n index += 1\n atStatementStart = true\n continue\n }\n endStatement()\n index += 1\n continue\n }\n\n if (char === ';') {\n flushWord()\n if (parenDepth > 0 || braceDepth > 0 || blockDepth > 0 || inBacktick) {\n state.current += char\n index += 1\n atStatementStart = true\n continue\n }\n endStatement()\n index += 1\n continue\n }\n\n if (/\\s/.test(char)) {\n flushWord()\n state.current += char\n index += 1\n continue\n }\n\n if (char === '&' || char === '|') {\n flushWord()\n state.current += char\n index += 1\n atStatementStart = true\n continue\n }\n\n word += char\n state.current += char\n atStatementStart = false\n index += 1\n }\n\n endStatement()\n return { statements: state.statements, heredocs: state.heredocs }\n}\n\nfunction isCommentOnly(text: string): boolean {\n return text.split('\\n').every((line) => line.trim().length === 0 || line.trim().startsWith('#'))\n}\n\nfunction endsWithContinuation(current: string): boolean {\n const trimmed = current.trimEnd()\n return /(&&|\\|\\||\\||&|\\\\)$/.test(trimmed)\n}\n\nfunction readHeredocMark(\n script: string,\n index: number,\n): { mark: HeredocMark; nextIndex: number } | null {\n let cursor = index + 2\n let stripTabs = false\n if (script[cursor] === '-') {\n stripTabs = true\n cursor += 1\n }\n while (script[cursor] === ' ' || script[cursor] === '\\t') cursor += 1\n const quote = script[cursor]\n if (quote === \"'\" || quote === '\"') {\n const close = script.indexOf(quote, cursor + 1)\n if (close === -1) return null\n return {\n mark: { delimiter: script.slice(cursor + 1, close), stripTabs, quoted: true },\n nextIndex: close + 1,\n }\n }\n const match = /^[A-Za-z_][A-Za-z0-9_]*/.exec(script.slice(cursor))\n if (!match) return null\n return {\n mark: { delimiter: match[0], stripTabs, quoted: false },\n nextIndex: cursor + match[0].length,\n }\n}\n\n/** Consume every pending heredoc body; returns the offset just past the last\n * terminator, or the end of the script when a terminator never arrives. */\nfunction consumeHeredocBodies(script: string, from: number, marks: HeredocMark[]): number {\n let cursor = from\n for (const mark of marks) {\n let closed = false\n while (cursor < script.length) {\n const lineEnd = script.indexOf('\\n', cursor)\n const stop = lineEnd === -1 ? script.length : lineEnd\n const line = script.slice(cursor, stop)\n const candidate = mark.stripTabs ? line.replace(/^\\t+/, '') : line\n cursor = lineEnd === -1 ? script.length : lineEnd + 1\n if (candidate === mark.delimiter) {\n closed = true\n break\n }\n }\n if (!closed) return script.length\n }\n return cursor\n}\n\n/** Payload shape of an action: `edit` when it authors file content through a\n * heredoc, `shell` otherwise. */\nexport function classifyActionPayload(action: string): ActionPayloadKind {\n return scanShellAction(action).heredocs > 0 ? 'edit' : 'shell'\n}\n\n/** Why an action fails the budget. Every value is a rejection the report\n * counts by name; none of them is a scoring judgement. */\nexport type BudgetViolation =\n | 'empty'\n | 'over-byte-cap'\n | 'multiple-statements'\n | 'multiple-heredocs'\n | 'no-op-action'\n | 'submit-instead-of-repair'\n\nexport interface BudgetMeasurement {\n bytes: number\n statements: number\n heredocs: number\n /** What the action IS, measured from its text. */\n payload: ActionPayloadKind\n /** What the analyst SAID it was. Recorded, never a rejection. */\n declared: ActionPayloadKind\n}\n\nexport type BudgetCheck =\n | { readonly admissible: true; readonly measurement: BudgetMeasurement }\n | {\n readonly admissible: false\n readonly violation: BudgetViolation\n readonly detail: string\n readonly measurement: BudgetMeasurement\n }\n\n/** Re-exported so budget callers read the sentinel from the module that\n * measures actions. Submitting is how the recorded agent ended a run that the\n * tests then failed, so it can never be the repair. */\nexport { SUBMIT_SENTINEL } from './mini-swe-scaffold'\n\n/**\n * Measure an action against the budget.\n *\n * The budget bounds what the scaffold can execute: one top-level statement,\n * one authored file, a byte cap, and neither a no-op nor a submit. Every\n * rejection here is one of those.\n *\n * `declaredKind` is what the analyst called its own action. It is recorded\n * beside the measured payload and never rejected on, because the scaffold runs\n * the action identically either way — so rejecting the label scores an arm on\n * how it described a repair rather than on the repair. A reader who wants the\n * mismatch counts `declared` against `payload`.\n */\nexport function checkInterventionBudget(\n action: string,\n declaredKind: ActionPayloadKind,\n budget: InterventionBudget = SCAFFOLD_INTERVENTION_BUDGET,\n): BudgetCheck {\n assertBudget(budget)\n const scan = scanShellAction(action)\n const payload: ActionPayloadKind = scan.heredocs > 0 ? 'edit' : 'shell'\n const measurement: BudgetMeasurement = {\n bytes: Buffer.byteLength(action, 'utf8'),\n statements: scan.statements.length,\n heredocs: scan.heredocs,\n payload,\n declared: declaredKind,\n }\n const reject = (violation: BudgetViolation, detail: string): BudgetCheck => ({\n admissible: false,\n violation,\n detail,\n measurement,\n })\n\n if (action.trim().length === 0) return reject('empty', 'the intervention is empty')\n if (measurement.bytes > budget.maxBytes) {\n return reject(\n 'over-byte-cap',\n `${measurement.bytes} bytes exceeds the ${budget.maxBytes}-byte action budget`,\n )\n }\n if (measurement.statements > budget.maxStatements) {\n return reject(\n 'multiple-statements',\n `${measurement.statements} top-level statements exceeds the ${budget.maxStatements} the scaffold takes per action`,\n )\n }\n if (measurement.heredocs > budget.maxHeredocs) {\n return reject(\n 'multiple-heredocs',\n `${measurement.heredocs} heredocs exceeds the ${budget.maxHeredocs} one edit may author`,\n )\n }\n if (action.includes(SUBMIT_SENTINEL)) {\n return reject('submit-instead-of-repair', 'the action submits the run instead of repairing it')\n }\n if (NO_OP_ACTIONS.includes(action.trim())) {\n return reject('no-op-action', `\"${action.trim()}\" changes nothing`)\n }\n return { admissible: true, measurement }\n}\n\nfunction assertBudget(budget: InterventionBudget): void {\n for (const field of ['maxBytes', 'maxStatements', 'maxHeredocs'] as const) {\n const value = budget[field]\n if (!Number.isInteger(value) || value <= 0) {\n throw new ValidationError(\n `intervention budget ${field} must be a positive integer, got ${value}`,\n )\n }\n }\n}\n\n/**\n * Whitespace-insensitive comparison used to reject an intervention that is\n * the recorded action again. Trailing whitespace and blank lines are the only\n * differences a re-proposal can carry without changing what runs.\n */\nexport function normalizeActionForComparison(action: string): string {\n return action\n .split('\\n')\n .map((line) => line.trimEnd())\n .filter((line, index, lines) => line.length > 0 || (index > 0 && index < lines.length - 1))\n .join('\\n')\n .trim()\n}\n","/**\n * The vocabulary of the TB-Repair admission pre-pass: what a corpus row is,\n * which failure population it belongs to, why it can leave the funnel, and the\n * denominator chain those exclusions add up to.\n *\n * Pure data and pure functions. The gate that spends containers on these types\n * lives in `admission.ts`, and the artifact that publishes them lives in\n * `admission-report.ts`.\n */\n\nimport { CaptureIntegrityError } from '../errors'\nimport type { ContinuationRollout } from './continuation-records'\nimport type { ControlScreening } from './control-policy'\n\n/** A campaign scored rows the pre-pass did not admit, or dropped rows it did. */\nexport class AdmissionDenominatorError extends CaptureIntegrityError {}\n\n/** A row handed to the pre-pass carried a field only an analyst could produce. */\nexport class AdmissionIndependenceError extends CaptureIntegrityError {}\n\n// ── Rows ─────────────────────────────────────────────────────────────\n\n/**\n * One corpus row, described by what the recording holds and nothing else.\n *\n * The field list is closed on purpose: `assertAnalystIndependent` rejects any\n * extra key, which is what stops a finding, a step index, or a proposed\n * intervention from reaching the gate that fixes the denominator.\n */\nexport interface AdmissionRow {\n /** Stable identifier for the recorded trajectory. Duplicates are rejected. */\n rowId: string\n /** Terminal-Bench-2 task the trajectory ran. */\n taskName: string\n /** Model that produced the recorded trajectory. */\n recordedModel: string\n /**\n * Recorded shell commands. An action can be substituted at any one of them,\n * and a replay must execute all of them to reach the recorded end state.\n */\n recordedCommands: number\n /**\n * Return code of the trajectory's last recorded observation. Negative values\n * are signal kills and are real. `null` means the recording did not parse,\n * which excludes the row instead of defaulting it.\n */\n finalReturncode: number | null\n}\n\nexport const ADMISSION_ROW_KEYS: readonly string[] = [\n 'rowId',\n 'taskName',\n 'recordedModel',\n 'recordedCommands',\n 'finalReturncode',\n]\n\n/**\n * Reject rows that carry anything beyond the recording.\n *\n * The check is a closed key list rather than a list of known analyst field\n * names, because the failure to catch is \"some new analyst output leaked into\n * the gate\", and only a closed shape catches the fields nobody thought of.\n */\nexport function assertAnalystIndependent(rows: readonly AdmissionRow[]): void {\n const allowed = new Set(ADMISSION_ROW_KEYS)\n for (const row of rows) {\n const extra = Object.keys(row).filter((key) => !allowed.has(key))\n if (extra.length > 0) {\n throw new AdmissionIndependenceError(\n `admission row ${String(row.rowId)} carries analyst-side fields: ${extra.sort().join(', ')}`,\n )\n }\n }\n}\n\n// ── Strata ───────────────────────────────────────────────────────────\n\n/**\n * Failure population a row belongs to.\n *\n * - `clean-exit` — the last command exited 0 and the tests still fail, so the\n * agent stopped believing it was done. The assay measured 87.13% of admitted\n * failures here.\n * - `command-error` — the last command exited non-zero.\n * - `signal-kill` — the last command was killed by a signal, recorded as a\n * negative return code. Substituting one command does not address a timeout,\n * so this population stays separate from the other two.\n */\nexport type AdmissionStratum = 'clean-exit' | 'command-error' | 'signal-kill'\n\nexport const ADMISSION_STRATA: readonly AdmissionStratum[] = [\n 'clean-exit',\n 'command-error',\n 'signal-kill',\n]\n\n/** `null` when the recording holds no parseable final return code. */\nexport function stratumOf(finalReturncode: number | null): AdmissionStratum | null {\n if (finalReturncode === null || !Number.isInteger(finalReturncode)) return null\n if (finalReturncode === 0) return 'clean-exit'\n return finalReturncode < 0 ? 'signal-kill' : 'command-error'\n}\n\n// ── Exclusion reasons ────────────────────────────────────────────────\n\n/**\n * Why a row left the funnel.\n *\n * `ADMISSION_EXCLUSION_ORDER` is the order the gate applies the checks, and it\n * is cost-ordered: everything decidable from the recording runs before the\n * first container, and the control rollouts run last.\n */\nexport type AdmissionExclusionReason =\n | 'no-recorded-commands'\n | 'unparseable-final-returncode'\n | 'stratum-not-admitted'\n | 'task-oracle-uncertified'\n | 'task-oracle-nondeterministic'\n | 'prefix-replay-error'\n | 'prefix-replay-empty'\n | 'prefix-replay-truncated'\n | 'prefix-divergence-above-threshold'\n | 'end-state-oracle-error'\n | 'end-state-tests-pass'\n | 'no-fix-control-error'\n | 'no-fix-control-rescued'\n | 'no-op-control-error'\n | 'no-op-control-rescued'\n\nexport const ADMISSION_EXCLUSION_ORDER: readonly AdmissionExclusionReason[] = [\n 'no-recorded-commands',\n 'unparseable-final-returncode',\n 'stratum-not-admitted',\n 'task-oracle-uncertified',\n 'task-oracle-nondeterministic',\n 'prefix-replay-error',\n 'prefix-replay-empty',\n 'prefix-replay-truncated',\n 'prefix-divergence-above-threshold',\n 'end-state-oracle-error',\n 'end-state-tests-pass',\n 'no-fix-control-error',\n 'no-fix-control-rescued',\n 'no-op-control-error',\n 'no-op-control-rescued',\n]\n\n/** Reasons decided from the recording alone, before a row can be stratified. */\nconst PRE_STRATUM_REASONS: readonly AdmissionExclusionReason[] = [\n 'no-recorded-commands',\n 'unparseable-final-returncode',\n]\n\nexport function isPreStratumReason(reason: AdmissionExclusionReason): boolean {\n return PRE_STRATUM_REASONS.includes(reason)\n}\n\n/** One line of prose per reason, for the rendered chain. */\nexport const ADMISSION_EXCLUSION_MEANING: Readonly<Record<AdmissionExclusionReason, string>> =\n Object.freeze({\n 'no-recorded-commands': 'the recording holds no command to substitute',\n 'unparseable-final-returncode': 'the last observation carries no return code',\n 'stratum-not-admitted': 'the row belongs to a population this campaign excluded',\n 'task-oracle-uncertified': 'the task grader has no determinism certification on file',\n 'task-oracle-nondeterministic':\n 'the task grader returns different verdicts on byte-identical state',\n 'prefix-replay-error': 'the replay boundary failed, so divergence is unmeasured',\n 'prefix-replay-empty': 'the replay executed no recorded step',\n 'prefix-replay-truncated': 'the replay stopped short of the recorded end state',\n 'prefix-divergence-above-threshold': 'replaying the prefix did not reproduce the recording',\n 'end-state-oracle-error': 'the task grader failed, so the end state is unjudged',\n 'end-state-tests-pass': 'the task tests pass on the recorded end state, so nothing failed',\n 'no-fix-control-error': 'a no-fix rollout failed to run, so the control is unmeasured',\n 'no-fix-control-rescued': 'the continuation policy passes the task with no intervention',\n 'no-op-control-error': 'a no-op rollout failed to run, so the control is unmeasured',\n 'no-op-control-rescued': 'an inert action plus continuation passes the task',\n })\n\n// ── Per-row verdict ──────────────────────────────────────────────────\n\nexport type AdmissionControlArm = 'no-fix-control' | 'no-op-control'\n\n/** The inert action the no-op control substitutes, and where it goes. */\nexport interface AdmissionNoOpInjection {\n /** 1-based recorded command the inert action replaces. */\n step: number\n action: string\n}\n\nexport type AdmissionCheckRecord =\n | { check: 'stratum'; stratum: AdmissionStratum }\n | {\n check: 'prefix-replay'\n prefixExecuted: number\n divergences: number\n divergenceRatio: number\n }\n | { check: 'task-oracle'; stable: boolean; flipRate: number; replicates: number }\n | { check: 'end-state-tests'; passed: boolean; reward: number | null }\n | {\n check: 'control'\n arm: AdmissionControlArm\n rolloutsRun: number\n passes: number\n injections: AdmissionNoOpInjection[]\n }\n\n/** What one control rollout did, small enough to serialize for every row. */\nexport interface AdmissionRolloutSummary {\n arm: AdmissionControlArm\n index: number\n seed: number\n policyDigest: string\n exitStatus: ContinuationRollout['exitStatus']\n testsPassed: boolean\n /** `null` when the rollout carried an unpriced model call. */\n costUsd: number | null\n}\n\nexport interface AdmissionRowVerdict {\n rowId: string\n taskName: string\n recordedModel: string\n recordedCommands: number\n finalReturncode: number | null\n /** `null` only together with a pre-stratum exclusion reason. */\n stratum: AdmissionStratum | null\n /** The control this row was screened under, and how a control pass reads.\n * Recorded on every verdict, including rows excluded before a control ran,\n * so a reader never has to open the runner's source to learn what screened\n * the row. */\n controlPolicyDigest: string\n controlScreening: ControlScreening\n /** The task's certified oracle flip rate. Zero on a certified-stable task,\n * `null` when the task carried no certification. */\n oracleFlipRate: number | null\n admitted: boolean\n /** `null` when the row is admitted. */\n excludedBy: AdmissionExclusionReason | null\n /** Message from the boundary that failed, on the four `*-error` reasons. */\n errorDetail: string | null\n /** Checks that ran, in order. A check never reached is absent, not zero. */\n checks: AdmissionCheckRecord[]\n rollouts: AdmissionRolloutSummary[]\n}\n\n// ── Denominator chain ────────────────────────────────────────────────\n\nexport interface DenominatorStage {\n reason: AdmissionExclusionReason\n entering: number\n excluded: number\n remaining: number\n}\n\nexport interface DenominatorChain {\n /** `all` counts every input row; a stratum chain starts after stratification. */\n scope: 'all' | AdmissionStratum\n input: number\n stages: DenominatorStage[]\n admitted: number\n}\n\nexport interface DenominatorChainArtifact {\n version: 1\n overall: DenominatorChain\n byStratum: DenominatorChain[]\n reasonTotals: Record<AdmissionExclusionReason, number>\n /** Rows excluded before a stratum could be assigned. */\n unstratified: number\n /** Strata this run admitted. Others can only reach `stratum-not-admitted`. */\n admitStrata: readonly AdmissionStratum[]\n}\n\n/**\n * Build the funnel every campaign report publishes.\n *\n * Each stage names the reason, the rows that reached it, the rows it removed,\n * and the rows that survived, so `input = admitted + sum(excluded)` can be read\n * off the table instead of trusted.\n */\nexport function buildDenominatorChain(\n verdicts: readonly AdmissionRowVerdict[],\n admitStrata: readonly AdmissionStratum[],\n): DenominatorChainArtifact {\n const reasonTotals = emptyReasonTotals()\n for (const verdict of verdicts) {\n if (verdict.excludedBy !== null) reasonTotals[verdict.excludedBy] += 1\n }\n const stratumReasons = ADMISSION_EXCLUSION_ORDER.filter((reason) => !isPreStratumReason(reason))\n const artifact: DenominatorChainArtifact = {\n version: 1,\n overall: chainOf('all', verdicts, ADMISSION_EXCLUSION_ORDER),\n byStratum: ADMISSION_STRATA.filter((stratum) =>\n verdicts.some((verdict) => verdict.stratum === stratum),\n ).map((stratum) =>\n chainOf(\n stratum,\n verdicts.filter((verdict) => verdict.stratum === stratum),\n stratumReasons,\n ),\n ),\n reasonTotals,\n unstratified: verdicts.filter((verdict) => verdict.stratum === null).length,\n admitStrata: [...admitStrata],\n }\n assertChainReconciles(artifact)\n return artifact\n}\n\nfunction chainOf(\n scope: 'all' | AdmissionStratum,\n verdicts: readonly AdmissionRowVerdict[],\n reasons: readonly AdmissionExclusionReason[],\n): DenominatorChain {\n let remaining = verdicts.length\n const stages: DenominatorStage[] = []\n for (const reason of reasons) {\n const excluded = verdicts.filter((verdict) => verdict.excludedBy === reason).length\n const entering = remaining\n remaining -= excluded\n stages.push({ reason, entering, excluded, remaining })\n }\n return {\n scope,\n input: verdicts.length,\n stages,\n admitted: verdicts.filter((verdict) => verdict.admitted).length,\n }\n}\n\nfunction emptyReasonTotals(): Record<AdmissionExclusionReason, number> {\n const totals = {} as Record<AdmissionExclusionReason, number>\n for (const reason of ADMISSION_EXCLUSION_ORDER) totals[reason] = 0\n return totals\n}\n\n/** A chain that does not add up is a broken denominator, so this throws. */\nexport function assertChainReconciles(artifact: DenominatorChainArtifact): void {\n for (const chain of [artifact.overall, ...artifact.byStratum]) {\n const excluded = chain.stages.reduce((total, stage) => total + stage.excluded, 0)\n if (chain.input !== chain.admitted + excluded) {\n throw new AdmissionDenominatorError(\n `denominator chain (${chain.scope}) does not reconcile: input ${chain.input} != admitted ${chain.admitted} + excluded ${excluded}`,\n )\n }\n const last = chain.stages[chain.stages.length - 1]\n if (last && last.remaining !== chain.admitted) {\n throw new AdmissionDenominatorError(\n `denominator chain (${chain.scope}) ends at ${last.remaining} rows but reports ${chain.admitted} admitted`,\n )\n }\n }\n const stratumInputs = artifact.byStratum.reduce((total, chain) => total + chain.input, 0)\n if (stratumInputs + artifact.unstratified !== artifact.overall.input) {\n throw new AdmissionDenominatorError(\n `stratum inputs ${stratumInputs} plus ${artifact.unstratified} unstratified do not cover ${artifact.overall.input} input rows`,\n )\n }\n}\n","/**\n * The pinned continuation policy: given a container restored to the state\n * after step k, run the mini-swe-agent scaffold forward under one frozen\n * configuration and record everything it did.\n *\n * `Delta-repair = P(tests pass | intervention) - P(tests pass | no-fix control)`\n * only measures the intervention if the continuation is identical across arms.\n * That symmetry is structural here: arms differ by the container state handed\n * in, never by the policy. One code path serves all three, the arm is a label,\n * the seed derivation cannot see it, and `policyDigest` is recorded on every\n * rollout so a mismatch is caught in the data rather than argued about.\n */\n\nimport type { CostProvenance } from '../cost-ledger'\nimport { CaptureIntegrityError, ValidationError } from '../errors'\nimport type { RunTokenUsage } from '../run-record'\nimport { contentHash } from '../verdict-cache'\nimport type {\n ContinuationArm,\n ContinuationEnvironmentDescription,\n ContinuationExitStatus,\n ContinuationMessage,\n ContinuationModelCall,\n ContinuationRollout,\n ContinuationStepRecord,\n ContinuationUsageTotals,\n} from './continuation-records'\nimport {\n MINI_SWE_SYSTEM_MESSAGE,\n parseAction,\n renderFormatErrorObservation,\n renderInstanceMessage,\n renderObservation,\n renderTimeoutObservation,\n submissionOf,\n} from './mini-swe-scaffold'\n\n/** A rollout ran outside the pinned policy, so its evidence cannot be used. */\nexport class ContinuationPolicyViolationError extends CaptureIntegrityError {}\n\n/** Two arms did not run the same policy, so their difference is not the intervention. */\nexport class ContinuationSymmetryError extends CaptureIntegrityError {}\n\nexport interface PinnedContinuationPolicy {\n /** Stable name for the frozen configuration, recorded on every rollout. */\n readonly id: string\n /** Requested model id. The served id is recorded per call and can differ. */\n readonly model: string\n /** Seed root. Per-rollout seeds derive from it and never from the arm. */\n readonly seed: number\n /** Model calls allowed per rollout. */\n readonly stepBudget: number\n readonly temperature: number\n readonly maxTokens: number\n /** Per-command wall-clock limit inside the container. */\n readonly commandTimeoutSeconds: number\n /** Consecutive unparseable turns that end a rollout. */\n readonly maxConsecutiveFormatErrors: number\n /** The only admissible container network mode. */\n readonly networkMode: 'none'\n readonly scaffold: 'mini-swe-agent'\n}\n\n/**\n * Everything the policy fixes except the two a campaign must choose.\n *\n * `commandTimeoutSeconds` is 30 because the recorded runs used the scaffold's\n * own 30-second environment timeout; a longer limit would let the continuation\n * finish commands the recorded agent could not.\n */\nexport const CONTINUATION_POLICY_DEFAULTS = {\n id: 'tb-repair-continuation-v1',\n stepBudget: 20,\n temperature: 0,\n maxTokens: 4096,\n commandTimeoutSeconds: 30,\n maxConsecutiveFormatErrors: 3,\n networkMode: 'none',\n scaffold: 'mini-swe-agent',\n} as const satisfies Omit<PinnedContinuationPolicy, 'model' | 'seed'>\n\nexport interface DefineContinuationPolicyInput\n extends Partial<Omit<PinnedContinuationPolicy, 'networkMode' | 'scaffold'>> {\n /** Required: a campaign pins one model, and no default can stand in for it. */\n model: string\n /** Required: a default seed would make two campaigns silently share a draw. */\n seed: number\n}\n\nexport function definePinnedContinuationPolicy(\n input: DefineContinuationPolicyInput,\n): PinnedContinuationPolicy {\n const policy: PinnedContinuationPolicy = { ...CONTINUATION_POLICY_DEFAULTS, ...input }\n if (!policy.model.trim()) throw new ValidationError('continuation policy requires a model id')\n if (!Number.isInteger(policy.seed)) {\n throw new ValidationError(`continuation policy seed must be an integer, got ${policy.seed}`)\n }\n requirePositiveInteger(policy.stepBudget, 'stepBudget')\n requirePositiveInteger(policy.maxTokens, 'maxTokens')\n requirePositiveInteger(policy.commandTimeoutSeconds, 'commandTimeoutSeconds')\n requirePositiveInteger(policy.maxConsecutiveFormatErrors, 'maxConsecutiveFormatErrors')\n if (!Number.isFinite(policy.temperature) || policy.temperature < 0) {\n throw new ValidationError(\n `continuation policy temperature must be a non-negative number, got ${policy.temperature}`,\n )\n }\n return Object.freeze(policy)\n}\n\nfunction requirePositiveInteger(value: number, field: string): void {\n if (!Number.isInteger(value) || value <= 0) {\n throw new ValidationError(\n `continuation policy ${field} must be a positive integer, got ${value}`,\n )\n }\n}\n\n/**\n * Hash over the policy and the scaffold text it renders. A changed template\n * changes the digest, so rollouts recorded before and after an edit cannot be\n * pooled by accident.\n */\nexport function continuationPolicyDigest(policy: PinnedContinuationPolicy): string {\n return contentHash({\n policy: { ...policy },\n systemMessage: MINI_SWE_SYSTEM_MESSAGE,\n instanceMessage: renderInstanceMessage({ task: '<task>', systemInformation: '<system>' }),\n formatErrorObservation: renderFormatErrorObservation(0),\n timeoutObservation: renderTimeoutObservation('<command>', '<output>'),\n observation: renderObservation({ returncode: 0, output: '' }),\n })\n}\n\n/**\n * Per-rollout seed. It reads the policy seed, the row, and the rollout index —\n * deliberately not the arm, so paired rollouts across arms draw identically.\n */\nexport function continuationSeed(policySeed: number, rowId: string, rolloutIndex: number): number {\n const input = `${policySeed}:${rowId}:${rolloutIndex}`\n let hash = 0x811c9dc5\n for (let i = 0; i < input.length; i += 1) {\n hash ^= input.charCodeAt(i)\n hash = Math.imul(hash, 0x01000193) >>> 0\n }\n return hash >>> 1\n}\n\nexport interface ContinuationModelRequest {\n model: string\n messages: ContinuationMessage[]\n seed: number\n temperature: number\n maxTokens: number\n}\n\nexport interface ContinuationModelResponse {\n content: string\n /** Model id the provider reported serving. */\n servedModel: string\n /** `null` when the provider omitted usage. Callers must not substitute zeros. */\n usage: RunTokenUsage | null\n /** `null` when no amount is available from the provider or local pricing. */\n costUsd: number | null\n finishReason?: string | null\n}\n\nexport type ContinuationModel = (\n request: ContinuationModelRequest,\n) => Promise<ContinuationModelResponse>\n\nexport interface ContinuationExecResult {\n output: string\n returncode: number\n /** True when the environment killed the command at the policy timeout. */\n timedOut: boolean\n /** Set when the environment itself failed rather than the command. */\n exceptionInfo?: string\n}\n\nexport interface ContinuationEnvironment {\n /** Container id or equivalent handle, recorded for provenance. */\n containerRef: string\n describe(): Promise<ContinuationEnvironmentDescription>\n exec(command: string, options: { timeoutSeconds: number }): Promise<ContinuationExecResult>\n dispose(): Promise<void>\n}\n\nexport interface ContinuationEnvironmentRequest {\n rowId: string\n arm: ContinuationArm\n rolloutIndex: number\n}\n\nexport interface ContinuationEnvironmentFactory {\n id: string\n /**\n * A container restored to the post-step-k state for one rollout. The arm is\n * passed because the state under test differs by arm; the policy applied to\n * that state does not.\n */\n create(request: ContinuationEnvironmentRequest): Promise<ContinuationEnvironment>\n}\n\nexport interface RunContinuationOptions {\n policy: PinnedContinuationPolicy\n arm: ContinuationArm\n /** Corpus row under repair. Pairs rollouts across arms. */\n rowId: string\n /**\n * Messages through step k, as the replay layer rebuilt them: the pinned\n * system and task messages, then every replayed turn with the observation\n * the replay itself produced.\n */\n prefix: readonly ContinuationMessage[]\n /** Rollouts to run for this arm. */\n rollouts: number\n /**\n * Global index of the first rollout this invocation produces. The per-rollout\n * seed derives from the global index, so a campaign that adds rollouts in\n * later passes must shift this base — an index that repeats is a rollout\n * that repeats. Defaults to 0.\n */\n rolloutBase?: number\n model: ContinuationModel\n environments: ContinuationEnvironmentFactory\n /** Epoch milliseconds. Injected so tests can assert on records without wall-clock noise. */\n clock?: () => number\n}\n\n/**\n * Run the scaffold forward for `rollouts` independent continuations.\n *\n * Each rollout gets its own environment from the factory, because a rollout\n * mutates the container it runs in and the next one must start from the same\n * state, not from the previous rollout's leftovers.\n */\nexport async function runContinuation(\n options: RunContinuationOptions,\n): Promise<ContinuationRollout[]> {\n const { policy, arm, rowId, prefix, rollouts, model, environments } = options\n const clock = options.clock ?? Date.now\n const rolloutBase = options.rolloutBase ?? 0\n requirePositiveInteger(rollouts, 'rollouts')\n if (!Number.isInteger(rolloutBase) || rolloutBase < 0) {\n throw new ValidationError(\n `continuation policy rolloutBase must be a non-negative integer, got ${rolloutBase}`,\n )\n }\n assertPrefix(prefix)\n const policyDigest = continuationPolicyDigest(policy)\n\n const records: ContinuationRollout[] = []\n for (let offset = 0; offset < rollouts; offset += 1) {\n records.push(\n await runOneRollout({\n policy,\n policyDigest,\n arm,\n rowId,\n index: rolloutBase + offset,\n prefix,\n model,\n environments,\n clock,\n }),\n )\n }\n return records\n}\n\nfunction assertPrefix(prefix: readonly ContinuationMessage[]): void {\n if (prefix.length < 2) {\n throw new ValidationError('continuation prefix needs the system and task messages')\n }\n if (prefix[0]?.role !== 'system' || prefix[1]?.role !== 'user') {\n throw new ValidationError('continuation prefix must start with a system then a user message')\n }\n if (prefix[prefix.length - 1]?.role !== 'user') {\n throw new ValidationError(\n 'continuation prefix must end on a user message; an assistant turn with no observation means the replay left an action unanswered',\n )\n }\n}\n\ninterface RolloutInput {\n policy: PinnedContinuationPolicy\n policyDigest: string\n arm: ContinuationArm\n rowId: string\n index: number\n prefix: readonly ContinuationMessage[]\n model: ContinuationModel\n environments: ContinuationEnvironmentFactory\n clock: () => number\n}\n\nasync function runOneRollout(input: RolloutInput): Promise<ContinuationRollout> {\n const { policy, arm, rowId, index, clock } = input\n const seed = continuationSeed(policy.seed, rowId, index)\n const startedMs = clock()\n const environment = await input.environments.create({ rowId, arm, rolloutIndex: index })\n try {\n const description = await environment.describe()\n if (description.networkMode !== policy.networkMode) {\n throw new ContinuationPolicyViolationError(\n `continuation requires network mode \"${policy.networkMode}\", container ${environment.containerRef} reports \"${description.networkMode}\"`,\n )\n }\n\n const messages: ContinuationMessage[] = [...input.prefix]\n const steps: ContinuationStepRecord[] = []\n let exitStatus: ContinuationExitStatus = 'step-budget-exhausted'\n let submission: string | null = null\n let terminalError: string | undefined\n let consecutiveFormatErrors = 0\n\n for (let step = 1; step <= policy.stepBudget; step += 1) {\n const callStartedMs = clock()\n let response: ContinuationModelResponse\n try {\n response = await input.model({\n model: policy.model,\n messages: [...messages],\n seed,\n temperature: policy.temperature,\n maxTokens: policy.maxTokens,\n })\n } catch (error) {\n exitStatus = 'model-error'\n terminalError = errorMessage(error)\n break\n }\n const call: ContinuationModelCall = {\n servedModel: response.servedModel,\n seed,\n latencyMs: clock() - callStartedMs,\n usage: response.usage,\n costUsd: response.costUsd,\n finishReason: response.finishReason ?? null,\n contentChars: response.content.length,\n }\n messages.push({ role: 'assistant', content: response.content })\n\n const parsed = parseAction(response.content)\n if (parsed.kind === 'format-error') {\n consecutiveFormatErrors += 1\n const observation = renderFormatErrorObservation(parsed.actionCount)\n messages.push({ role: 'user', content: observation })\n steps.push({\n step,\n assistantMessage: response.content,\n action: null,\n observation,\n execution: null,\n model: call,\n })\n if (consecutiveFormatErrors >= policy.maxConsecutiveFormatErrors) {\n exitStatus = 'repeated-format-error'\n break\n }\n continue\n }\n\n consecutiveFormatErrors = 0\n const execStartedMs = clock()\n let execution: ContinuationExecResult\n try {\n execution = await environment.exec(parsed.command, {\n timeoutSeconds: policy.commandTimeoutSeconds,\n })\n } catch (error) {\n exitStatus = 'environment-error'\n terminalError = errorMessage(error)\n steps.push({\n step,\n assistantMessage: response.content,\n action: parsed.command,\n observation: null,\n execution: null,\n model: call,\n error: errorMessage(error),\n })\n break\n }\n const execRecord = {\n command: parsed.command,\n returncode: execution.returncode,\n timedOut: execution.timedOut,\n outputChars: execution.output.length,\n durationMs: clock() - execStartedMs,\n }\n\n if (execution.timedOut) {\n const observation = renderTimeoutObservation(parsed.command, execution.output)\n messages.push({ role: 'user', content: observation })\n steps.push({\n step,\n assistantMessage: response.content,\n action: parsed.command,\n observation,\n execution: execRecord,\n model: call,\n })\n continue\n }\n\n const submitted = submissionOf(execution)\n if (submitted !== null) {\n exitStatus = 'submitted'\n submission = submitted\n // The recorded runs end here: the sentinel command gets no observation.\n steps.push({\n step,\n assistantMessage: response.content,\n action: parsed.command,\n observation: null,\n execution: execRecord,\n model: call,\n })\n break\n }\n\n const observation = renderObservation(execution)\n messages.push({ role: 'user', content: observation })\n steps.push({\n step,\n assistantMessage: response.content,\n action: parsed.command,\n observation,\n execution: execRecord,\n model: call,\n })\n }\n\n const endedMs = clock()\n const rollout: ContinuationRollout = {\n rolloutId: `${rowId}:${arm}:${index}`,\n arm,\n rowId,\n index,\n seed,\n policyDigest: input.policyDigest,\n environmentId: input.environments.id,\n containerRef: environment.containerRef,\n environment: description,\n steps,\n exitStatus,\n submission,\n usage: totalUsage(steps),\n costProvenance: totalCost(steps),\n wallMs: endedMs - startedMs,\n startedAt: new Date(startedMs).toISOString(),\n endedAt: new Date(endedMs).toISOString(),\n }\n return terminalError === undefined ? rollout : { ...rollout, terminalError }\n } finally {\n await environment.dispose()\n }\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/**\n * Sum only what the provider reported. A call with no usage raises\n * `callsWithUsage` short of `calls` and clears `captured`, so a partially\n * reported rollout can never read as a fully measured one.\n */\nexport function totalUsage(steps: readonly ContinuationStepRecord[]): ContinuationUsageTotals {\n let input = 0\n let output = 0\n let reasoning = 0\n let cached = 0\n let cacheWrite = 0\n let sawReasoning = false\n let sawCached = false\n let sawCacheWrite = false\n let callsWithUsage = 0\n for (const step of steps) {\n const usage = step.model.usage\n if (!usage) continue\n callsWithUsage += 1\n input += usage.input\n output += usage.output\n if (usage.reasoning !== undefined) {\n reasoning += usage.reasoning\n sawReasoning = true\n }\n if (usage.cached !== undefined) {\n cached += usage.cached\n sawCached = true\n }\n if (usage.cacheWrite !== undefined) {\n cacheWrite += usage.cacheWrite\n sawCacheWrite = true\n }\n }\n const totals: ContinuationUsageTotals = {\n calls: steps.length,\n callsWithUsage,\n captured: steps.length > 0 && callsWithUsage === steps.length,\n input,\n output,\n }\n if (sawReasoning) totals.reasoning = reasoning\n if (sawCached) totals.cached = cached\n if (sawCacheWrite) totals.cacheWrite = cacheWrite\n return totals\n}\n\n/**\n * One unpriced call makes the rollout's cost unknown. Summing the rest would\n * report a number smaller than what was spent.\n */\nexport function totalCost(steps: readonly ContinuationStepRecord[]): CostProvenance {\n if (steps.length === 0) return { kind: 'uncaptured', usd: null }\n let usd = 0\n for (const step of steps) {\n if (step.model.costUsd === null) return { kind: 'uncaptured', usd: null }\n usd += step.model.costUsd\n }\n return { kind: 'observed', usd }\n}\n\n/**\n * Prove the arms ran the same policy. Rollouts paired by row and index must\n * carry the same policy digest and the same seed; anything else means the\n * measured difference includes a policy change, not only the intervention.\n */\nexport function assertArmSymmetry(rollouts: readonly ContinuationRollout[]): void {\n const digests = new Set(rollouts.map((rollout) => rollout.policyDigest))\n if (digests.size > 1) {\n throw new ContinuationSymmetryError(\n `arms ran different policies: ${[...digests].sort().join(', ')}`,\n )\n }\n const seeds = new Map<string, { seed: number; arm: ContinuationArm }>()\n for (const rollout of rollouts) {\n const key = `${rollout.rowId}:${rollout.index}`\n const seen = seeds.get(key)\n if (!seen) {\n seeds.set(key, { seed: rollout.seed, arm: rollout.arm })\n continue\n }\n if (seen.seed !== rollout.seed) {\n throw new ContinuationSymmetryError(\n `paired rollouts ${key} drew different seeds: ${seen.arm}=${seen.seed}, ${rollout.arm}=${rollout.seed}`,\n )\n }\n }\n}\n","/**\n * The control policy admission screens under, declared rather than assumed.\n *\n * Admission conditions 3 and 4 ask whether a row is rescued by continuing from\n * the recorded end state with no intervention, and by continuing after an\n * action that changes nothing. Both are questions about a policy, and neither\n * is answerable without knowing what that policy is allowed to do.\n *\n * One number decides whether the question can be answered at all. Condition 2\n * has already graded the recorded end state and found it failing. A control\n * rollout that makes no model call executes no command, so the container it\n * grades holds those same bytes — the ones already graded as failing. Under\n * such a policy a control pass is not a rescue; it is the task's own grader\n * answering differently about identical state. The condition cannot fire for\n * the reason it exists, and every row walks through it.\n *\n * So the policy is a required, hashed parameter that lands on every admission\n * decision, and a configuration whose control cannot reach the outcome it\n * screens for is refused where it is configured rather than passed silently.\n */\n\nimport { CaptureIntegrityError, ValidationError } from '../errors'\nimport { contentHash } from '../verdict-cache'\n\n/** The declared control cannot produce the outcome the criteria screen for. */\nexport class UncalibratedControlError extends CaptureIntegrityError {}\n\n/**\n * What the criteria expect of the control.\n *\n * - `enforced` — conditions 3 and 4 decide admission, so the control must be\n * able to rescue a row.\n * - `declared-inert` — the campaign has pinned a control that cannot rescue\n * anything (a calibration run comparing arms at equal depth, for instance).\n * Conditions 3 and 4 still run, but a pass then means the task's grader\n * disagreed with itself about identical state, and the row leaves as that.\n */\nexport type ControlScreening = 'enforced' | 'declared-inert'\n\nexport const CONTROL_SCREENING_MODES: readonly ControlScreening[] = ['enforced', 'declared-inert']\n\nexport interface ControlPolicyInput {\n /** Stable name for the frozen configuration. */\n readonly id: string\n /** Model calls one control rollout may make after the arm's own treatment. */\n readonly stepBudget: number\n /** Scaffold the rollout runs under. */\n readonly scaffold: string\n /** Requested model id, or `null` when the budget calls no model. */\n readonly model: string | null\n /** Per-command wall-clock limit inside the container. */\n readonly commandTimeoutSeconds: number\n}\n\n/**\n * The part of a control the calibration rule reads.\n *\n * Both admission paths declare a control in their own vocabulary — the pure\n * contract takes a `ControlPolicy`, the executing pre-pass runs a pinned\n * continuation policy — and both are checked by one rule against this shape,\n * so the two cannot drift into disagreeing about what a usable control is.\n */\nexport interface ControlCapability {\n readonly id: string\n readonly digest: string\n /** Model calls one control rollout may make after the arm's own treatment. */\n readonly stepBudget: number\n}\n\nexport interface ControlPolicy extends ControlPolicyInput, ControlCapability {\n /** Hash over the whole declaration. A hand-written label cannot stand in for\n * it, so two runs cannot share a digest while differing in step budget. */\n readonly digest: string\n /**\n * Whether a rollout under this policy can reach a state the recorded end\n * state was not already in. False at a zero step budget: no model call means\n * no command, which means the graded bytes are the ones condition 2 read.\n */\n readonly canRescue: boolean\n}\n\n/**\n * A control rollout changes the graded state only by executing something, and\n * it executes only what a model call asks for. At a zero budget it grades the\n * bytes it was handed.\n */\nexport function controlCanRescue(stepBudget: number): boolean {\n return stepBudget > 0\n}\n\nexport function defineControlPolicy(input: ControlPolicyInput): ControlPolicy {\n if (!input.id.trim()) throw new ValidationError('control policy requires an id')\n if (!input.scaffold.trim()) throw new ValidationError('control policy requires a scaffold name')\n if (!Number.isInteger(input.stepBudget) || input.stepBudget < 0) {\n throw new ValidationError(\n `control policy stepBudget must be a non-negative integer, got ${input.stepBudget}`,\n )\n }\n if (!Number.isInteger(input.commandTimeoutSeconds) || input.commandTimeoutSeconds <= 0) {\n throw new ValidationError(\n `control policy commandTimeoutSeconds must be a positive integer, got ${input.commandTimeoutSeconds}`,\n )\n }\n // The model is the other half of \"which control screened this row\". A budget\n // that calls a model without naming one, or names one it will never call,\n // makes the recorded policy unreadable either way.\n if (input.stepBudget === 0 && input.model !== null) {\n throw new ValidationError(\n `control policy ${input.id} declares model ${input.model} at a zero step budget; ` +\n 'a policy that makes no model call must record model: null',\n )\n }\n if (input.stepBudget > 0 && !input.model?.trim()) {\n throw new ValidationError(\n `control policy ${input.id} allows ${input.stepBudget} model call(s) but names no model`,\n )\n }\n const declaration: ControlPolicyInput = {\n id: input.id,\n stepBudget: input.stepBudget,\n scaffold: input.scaffold,\n model: input.model,\n commandTimeoutSeconds: input.commandTimeoutSeconds,\n }\n return Object.freeze({\n ...declaration,\n digest: contentHash(declaration),\n canRescue: controlCanRescue(input.stepBudget),\n })\n}\n\n/**\n * Refuse a configuration whose control and screening mode contradict.\n *\n * Both directions are faults, and both are silent without this. A screening\n * control that cannot act passes every row through a condition it can never\n * fire. A control declared inert that can in fact act hides a real screen\n * behind a label that says nothing was screened.\n */\nexport function assertControlCalibrated(\n policy: ControlCapability,\n screening: ControlScreening,\n): void {\n if (!CONTROL_SCREENING_MODES.includes(screening)) {\n throw new ValidationError(`unknown control screening mode: ${screening}`)\n }\n const canRescue = controlCanRescue(policy.stepBudget)\n if (screening === 'enforced' && !canRescue) {\n throw new UncalibratedControlError(\n `control policy ${policy.id} (digest ${policy.digest}) allows ${policy.stepBudget} model ` +\n 'call(s) per rollout, so a control rollout executes no command and grades the same bytes ' +\n 'the end-state check already graded as failing. Under it conditions 3 and 4 can only fire ' +\n 'on a grader that disagrees with itself, so they screen nothing. Give the control a step ' +\n \"budget of at least 1, or set controlScreening to 'declared-inert' and read a control pass \" +\n 'as the oracle flip it is.',\n )\n }\n if (screening === 'declared-inert' && canRescue) {\n throw new UncalibratedControlError(\n `control policy ${policy.id} (digest ${policy.digest}) allows ${policy.stepBudget} model ` +\n 'call(s) per rollout, so it can rescue a row, but the criteria declare it inert. Set ' +\n \"controlScreening to 'enforced' so a control pass is recorded as a rescue.\",\n )\n }\n}\n","/**\n * The TB-Repair admission pre-pass: decide which corpus rows may enter a\n * campaign, before any analyst reads one.\n *\n * A repair benchmark reports `Delta-repair = P(pass | intervention) - P(pass |\n * no-fix control)`. That number is only honest if the row set it averages over\n * was fixed by something the analyst cannot influence. An analyst that declines\n * the rows it cannot solve shrinks its own denominator and raises its own\n * score, so admission runs first, records every row it saw, and publishes the\n * reason each excluded row left.\n *\n * A row is admitted only when all four conditions hold:\n *\n * 1. the recorded prefix replays with divergence at or below the threshold,\n * 2. the task's held-out tests fail on the recorded end state,\n * 3. the no-fix control fails every rollout under the pinned policy,\n * 4. the no-op control fails every rollout under the pinned policy.\n *\n * Conditions 3 and 4 delete rows the continuation policy rescues on its own and\n * rows whose task grades flakily. Both would otherwise be counted as repair.\n *\n * Rows are stratified before anything samples them, and the report exposes\n * admitted rows per stratum only: pooling a population a single command can\n * repair with one it cannot requires an explicit concatenation at the call\n * site.\n *\n * The three external boundaries — prefix replay, the task's test oracle, and\n * the control rollouts — are injected. Each carries an `id` that lands in the\n * artifact, so a report produced against fakes cannot be read as one produced\n * against real containers.\n */\n\nimport type { CostProvenance } from '../cost-ledger'\nimport { ValidationError } from '../errors'\nimport { contentHash } from '../verdict-cache'\nimport {\n ADMISSION_STRATA,\n type AdmissionCheckRecord,\n type AdmissionControlArm,\n AdmissionDenominatorError,\n type AdmissionExclusionReason,\n type AdmissionNoOpInjection,\n type AdmissionRolloutSummary,\n type AdmissionRow,\n type AdmissionRowVerdict,\n type AdmissionStratum,\n assertAnalystIndependent,\n buildDenominatorChain,\n type DenominatorChainArtifact,\n stratumOf,\n} from './admission-records'\nimport {\n assertArmSymmetry,\n continuationPolicyDigest,\n type PinnedContinuationPolicy,\n} from './continuation-policy'\nimport type { ContinuationRollout } from './continuation-records'\nimport {\n assertControlCalibrated,\n CONTROL_SCREENING_MODES,\n type ControlScreening,\n} from './control-policy'\nimport type { TaskOracleRegistry } from './oracle-determinism'\n\n// ── Injected boundaries ──────────────────────────────────────────────\n\n/**\n * Result of an external call. Callers read `succeeded` before `value`: a\n * boundary failure is an exclusion with its own reason, never a false verdict.\n */\nexport type AdmissionOutcome<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; error: string }\n\nexport interface AdmissionDivergence {\n /** 1-based recorded step. */\n step: number\n expectedReturncode: number | null\n actualExit: number\n}\n\nexport interface AdmissionPrefixReplay {\n /** Recorded steps the replay actually executed. */\n prefixExecuted: number\n /** Steps whose replayed exit differs from the recorded return code. */\n prefixDivergences: readonly AdmissionDivergence[]\n}\n\nexport interface AdmissionPrefixReplayer {\n /** Lands in the artifact. A fake and a container replayer must not share one. */\n id: string\n /** Replay the recorded prefix in the task's pinned image and report divergence. */\n replay(row: AdmissionRow): Promise<AdmissionOutcome<AdmissionPrefixReplay>>\n}\n\nexport interface AdmissionTestVerdict {\n passed: boolean\n /** Reward the task's own grader reported. `null` when it reported none. */\n reward: number | null\n}\n\nexport interface AdmissionEndStateOracle {\n id: string\n /** Run the task's held-out tests against the recorded end state. */\n grade(row: AdmissionRow): Promise<AdmissionOutcome<AdmissionTestVerdict>>\n}\n\nexport interface AdmissionControlRequest {\n row: AdmissionRow\n arm: AdmissionControlArm\n /** 0-based rollout index within the arm. */\n rolloutIndex: number\n /** Present for `no-op-control` only; `null` for `no-fix-control`. */\n injection: AdmissionNoOpInjection | null\n}\n\nexport interface AdmissionControlObservation {\n /** The task's held-out tests, run after the continuation stopped. */\n tests: AdmissionTestVerdict\n /** The rollout the pinned policy produced. Its digest and seed prove symmetry. */\n rollout: ContinuationRollout\n}\n\nexport interface AdmissionControlRunner {\n id: string\n /**\n * Restore the row's post-trajectory state, apply the arm's treatment, run the\n * pinned continuation policy forward, then grade the container it left.\n */\n run(request: AdmissionControlRequest): Promise<AdmissionOutcome<AdmissionControlObservation>>\n}\n\n// ── Configuration ────────────────────────────────────────────────────\n\nexport interface AdmissionConfigInput {\n /** Share of replayed prefix steps allowed to diverge. Default 0.10. */\n maxPrefixDivergence?: number\n /** Rollouts each control arm must fail. Default 3. */\n controlRollouts?: number\n /**\n * Strata a campaign accepts. The default omits `signal-kill`, because\n * substituting one command does not address a timeout. The excluded count\n * stays visible in the chain instead of disappearing.\n */\n admitStrata?: readonly AdmissionStratum[]\n /** Shell action the no-op control substitutes. Default `true`. */\n inertAction?: string\n /**\n * How a control pass is read. Default `enforced`, which requires a control\n * that can act; `resolveAdmissionConfig` refuses the pairing that cannot.\n */\n controlScreening?: ControlScreening\n /** Rows processed at once. Output order always follows input order. Default 1. */\n concurrency?: number\n}\n\nexport interface AdmissionConfig {\n readonly maxPrefixDivergence: number\n readonly controlRollouts: number\n readonly admitStrata: readonly AdmissionStratum[]\n readonly inertAction: string\n readonly controlScreening: ControlScreening\n readonly concurrency: number\n}\n\nexport const ADMISSION_CONFIG_DEFAULTS: AdmissionConfig = Object.freeze({\n maxPrefixDivergence: 0.1,\n controlRollouts: 3,\n admitStrata: Object.freeze(['clean-exit', 'command-error']) as readonly AdmissionStratum[],\n inertAction: 'true',\n controlScreening: 'enforced' as ControlScreening,\n concurrency: 1,\n})\n\nexport function resolveAdmissionConfig(input: AdmissionConfigInput = {}): AdmissionConfig {\n const config: AdmissionConfig = { ...ADMISSION_CONFIG_DEFAULTS, ...input }\n if (!Number.isFinite(config.maxPrefixDivergence)) {\n throw new ValidationError(\n `admission maxPrefixDivergence must be a number, got ${config.maxPrefixDivergence}`,\n )\n }\n if (config.maxPrefixDivergence < 0 || config.maxPrefixDivergence > 1) {\n throw new ValidationError(\n `admission maxPrefixDivergence must be a share between 0 and 1, got ${config.maxPrefixDivergence}`,\n )\n }\n requirePositiveInteger(config.controlRollouts, 'controlRollouts')\n requirePositiveInteger(config.concurrency, 'concurrency')\n if (config.admitStrata.length === 0) {\n throw new ValidationError('admission admitStrata must name at least one stratum')\n }\n for (const stratum of config.admitStrata) {\n if (!ADMISSION_STRATA.includes(stratum)) {\n throw new ValidationError(`admission admitStrata holds an unknown stratum: ${stratum}`)\n }\n }\n if (config.inertAction.trim().length === 0) {\n throw new ValidationError('admission inertAction must be a non-empty command')\n }\n if (!CONTROL_SCREENING_MODES.includes(config.controlScreening)) {\n throw new ValidationError(\n `admission controlScreening must be one of ${CONTROL_SCREENING_MODES.join(', ')}, got ${config.controlScreening}`,\n )\n }\n return Object.freeze({ ...config, admitStrata: Object.freeze([...config.admitStrata]) })\n}\n\nfunction requirePositiveInteger(value: number, field: string): void {\n if (!Number.isInteger(value) || value <= 0) {\n throw new ValidationError(`admission ${field} must be a positive integer, got ${value}`)\n }\n}\n\n/**\n * The recorded command the no-op control replaces, drawn per rollout.\n *\n * The draw reads the policy seed, the row, and the rollout index, so it is\n * reproducible from the artifact and cannot depend on when the pre-pass ran.\n */\nexport function noOpInjectionStep(\n policySeed: number,\n rowId: string,\n rolloutIndex: number,\n recordedCommands: number,\n): number {\n requirePositiveInteger(recordedCommands, 'recordedCommands')\n const input = `no-op:${policySeed}:${rowId}:${rolloutIndex}`\n let hash = 0x811c9dc5\n for (let i = 0; i < input.length; i += 1) {\n hash ^= input.charCodeAt(i)\n hash = Math.imul(hash, 0x01000193) >>> 0\n }\n return ((hash >>> 1) % recordedCommands) + 1\n}\n\n// ── Report ───────────────────────────────────────────────────────────\n\nexport interface AdmissionProvenance {\n replayerId: string\n oracleId: string\n controlRunnerId: string\n policyId: string\n policyModel: string\n policySeed: number\n policyDigest: string\n /** Model calls a control rollout may make. Zero cannot screen anything, and\n * `resolveAdmissionConfig` refuses that pairing before a container opens. */\n policyStepBudget: number\n controlScreening: ControlScreening\n /** Tasks whose oracle carried a determinism certification, and their\n * measured flip rates. */\n certifiedTasks: Readonly<Record<string, number>>\n}\n\nexport interface AdmissionReport {\n config: AdmissionConfig\n provenance: AdmissionProvenance\n /** Every input row, in input order, admitted or not. */\n rows: readonly AdmissionRowVerdict[]\n /** Admitted row ids per stratum. There is no pooled list; pooling is explicit. */\n strata: Readonly<Record<AdmissionStratum, readonly string[]>>\n chain: DenominatorChainArtifact\n /** Model cost of the control rollouts. One unpriced rollout makes it uncaptured. */\n controlCost: CostProvenance\n /** Hash over the admitted ids, the config, and the provenance. */\n digest: string\n generatedAt: string\n}\n\nexport interface RunAdmissionOptions {\n rows: readonly AdmissionRow[]\n /** The policy the campaign's arms run under. Its seed drives the no-op draw. */\n policy: PinnedContinuationPolicy\n replayer: AdmissionPrefixReplayer\n oracle: AdmissionEndStateOracle\n controls: AdmissionControlRunner\n /**\n * Determinism certifications by task name. Required: every check below reads\n * the task's own suite, so a suite whose verdict is not a function of the\n * state makes each of them a coin flip. A task with no entry is excluded as\n * uncertified rather than assumed stable.\n */\n taskOracles: TaskOracleRegistry\n config?: AdmissionConfigInput\n /** Epoch milliseconds. Injected so a report can be compared exactly in a test. */\n clock?: () => number\n}\n\n/**\n * Run the pre-pass over every row and publish the denominator it produced.\n *\n * Nothing here reads an analyst output. The report is frozen, and a campaign\n * proves it measured this denominator by passing the report back to\n * `assertDenominatorIntact`.\n */\nexport async function runAdmission(options: RunAdmissionOptions): Promise<AdmissionReport> {\n const { rows, policy, replayer, oracle, controls, taskOracles } = options\n const config = resolveAdmissionConfig(options.config)\n const clock = options.clock ?? Date.now\n assertAnalystIndependent(rows)\n assertUniqueRowIds(rows)\n const policyDigest = continuationPolicyDigest(policy)\n // Both admission paths check the same rule against the same shape, so the\n // pure contract and this pre-pass cannot drift about what a control that can\n // screen looks like.\n assertControlCalibrated(\n { id: policy.id, digest: policyDigest, stepBudget: policy.stepBudget },\n config.controlScreening,\n )\n\n const verdicts = await mapOrdered(rows, config.concurrency, (row) =>\n admitRow({ row, policy, policyDigest, replayer, oracle, controls, taskOracles, config }),\n )\n\n const strata = groupAdmittedByStratum(verdicts)\n const provenance: AdmissionProvenance = {\n replayerId: replayer.id,\n oracleId: oracle.id,\n controlRunnerId: controls.id,\n policyId: policy.id,\n policyModel: policy.model,\n policySeed: policy.seed,\n policyDigest,\n policyStepBudget: policy.stepBudget,\n controlScreening: config.controlScreening,\n certifiedTasks: Object.freeze(\n Object.fromEntries([...taskOracles].map(([task, verdict]) => [task, verdict.flipRate])),\n ),\n }\n return Object.freeze({\n config,\n provenance,\n rows: Object.freeze(verdicts),\n strata,\n chain: buildDenominatorChain(verdicts, config.admitStrata),\n controlCost: summarizeControlCost(verdicts),\n digest: contentHash({\n config,\n provenance,\n admitted: ADMISSION_STRATA.map((stratum) => ({ stratum, rowIds: strata[stratum] })),\n }),\n generatedAt: new Date(clock()).toISOString(),\n })\n}\n\nfunction assertUniqueRowIds(rows: readonly AdmissionRow[]): void {\n const seen = new Set<string>()\n for (const row of rows) {\n if (typeof row.rowId !== 'string' || row.rowId.length === 0) {\n throw new ValidationError('admission row requires a non-empty rowId')\n }\n if (seen.has(row.rowId)) {\n throw new ValidationError(`admission received rowId ${row.rowId} twice`)\n }\n seen.add(row.rowId)\n }\n}\n\ninterface AdmitRowInput {\n row: AdmissionRow\n policy: PinnedContinuationPolicy\n policyDigest: string\n replayer: AdmissionPrefixReplayer\n oracle: AdmissionEndStateOracle\n controls: AdmissionControlRunner\n taskOracles: TaskOracleRegistry\n config: AdmissionConfig\n}\n\nasync function admitRow(input: AdmitRowInput): Promise<AdmissionRowVerdict> {\n const { row, config } = input\n const checks: AdmissionCheckRecord[] = []\n const rollouts: ContinuationRollout[] = []\n const summaries: AdmissionRolloutSummary[] = []\n const certification = input.taskOracles.get(row.taskName) ?? null\n const base = {\n rowId: row.rowId,\n taskName: row.taskName,\n recordedModel: row.recordedModel,\n recordedCommands: row.recordedCommands,\n finalReturncode: row.finalReturncode,\n controlPolicyDigest: input.policyDigest,\n controlScreening: config.controlScreening,\n oracleFlipRate: certification === null ? null : certification.flipRate,\n }\n const finish = (\n stratum: AdmissionStratum | null,\n reason: AdmissionExclusionReason | null,\n errorDetail: string | null = null,\n ): AdmissionRowVerdict => ({\n ...base,\n stratum,\n admitted: reason === null,\n excludedBy: reason,\n errorDetail,\n checks,\n rollouts: summaries,\n })\n\n if (!Number.isInteger(row.recordedCommands) || row.recordedCommands < 1) {\n return finish(null, 'no-recorded-commands')\n }\n const stratum = stratumOf(row.finalReturncode)\n if (stratum === null) return finish(null, 'unparseable-final-returncode')\n checks.push({ check: 'stratum', stratum })\n if (!config.admitStrata.includes(stratum)) return finish(stratum, 'stratum-not-admitted')\n\n // Ahead of the first container: every check below reads this task's suite, so\n // a suite that answers differently about identical bytes turns each of them\n // into a draw. An absent certification is its own reason — the check has not\n // run, which is not the same as having run and failed.\n if (certification === null) return finish(stratum, 'task-oracle-uncertified')\n checks.push({\n check: 'task-oracle',\n stable: certification.stable,\n flipRate: certification.flipRate,\n replicates: certification.replicates,\n })\n if (!certification.stable) {\n return finish(stratum, 'task-oracle-nondeterministic', certification.detail)\n }\n\n const replay = await input.replayer.replay(row)\n if (!replay.succeeded) return finish(stratum, 'prefix-replay-error', replay.error)\n const { prefixExecuted, prefixDivergences } = replay.value\n if (!Number.isInteger(prefixExecuted) || prefixExecuted < 1) {\n return finish(stratum, 'prefix-replay-empty')\n }\n // A replay that stopped early would compute divergence over the steps it did\n // reach, so a truncated run could report a low ratio and admit a row that\n // never reproduced its end state.\n if (prefixExecuted < row.recordedCommands) return finish(stratum, 'prefix-replay-truncated')\n const divergenceRatio = prefixDivergences.length / prefixExecuted\n checks.push({\n check: 'prefix-replay',\n prefixExecuted,\n divergences: prefixDivergences.length,\n divergenceRatio,\n })\n if (divergenceRatio > config.maxPrefixDivergence) {\n return finish(stratum, 'prefix-divergence-above-threshold')\n }\n\n const endState = await input.oracle.grade(row)\n if (!endState.succeeded) return finish(stratum, 'end-state-oracle-error', endState.error)\n checks.push({\n check: 'end-state-tests',\n passed: endState.value.passed,\n reward: endState.value.reward,\n })\n if (endState.value.passed) return finish(stratum, 'end-state-tests-pass')\n\n for (const arm of CONTROL_ARMS) {\n const control = await runControlArm({ ...input, arm })\n checks.push(control.record)\n rollouts.push(...control.rollouts)\n summaries.push(...control.summaries)\n if (control.outcome === 'error') {\n return finish(stratum, CONTROL_EXCLUSIONS[arm].error, control.error)\n }\n if (control.outcome === 'rescued') return finish(stratum, CONTROL_EXCLUSIONS[arm].rescued)\n }\n\n // Both arms ran the full rollout count, so a policy or seed that differs\n // between them is a wiring fault in the runner, not a property of the row.\n assertArmSymmetry(rollouts)\n return finish(stratum, null)\n}\n\nconst CONTROL_ARMS: readonly AdmissionControlArm[] = ['no-fix-control', 'no-op-control']\n\nconst CONTROL_EXCLUSIONS: Readonly<\n Record<\n AdmissionControlArm,\n { error: AdmissionExclusionReason; rescued: AdmissionExclusionReason }\n >\n> = Object.freeze({\n 'no-fix-control': { error: 'no-fix-control-error', rescued: 'no-fix-control-rescued' },\n 'no-op-control': { error: 'no-op-control-error', rescued: 'no-op-control-rescued' },\n})\n\ninterface ControlArmResult {\n outcome: 'failed-every-rollout' | 'rescued' | 'error'\n error: string | null\n record: AdmissionCheckRecord\n /** Kept whole for the symmetry assertion; the verdict stores the summaries. */\n rollouts: ContinuationRollout[]\n summaries: AdmissionRolloutSummary[]\n}\n\n/**\n * Run one control arm until it is decided.\n *\n * A rollout that passes decides the arm at once, so the remaining rollouts go\n * unpaid. A boundary failure decides it too, and as an error: counting an\n * unmeasured rollout as a failure would admit a row nobody verified.\n */\nasync function runControlArm(\n input: AdmitRowInput & { arm: AdmissionControlArm },\n): Promise<ControlArmResult> {\n const { row, arm, config, policy } = input\n const rollouts: ContinuationRollout[] = []\n const summaries: AdmissionRolloutSummary[] = []\n const injections: AdmissionNoOpInjection[] = []\n let passes = 0\n let error: string | null = null\n\n for (let index = 0; index < config.controlRollouts; index += 1) {\n const injection =\n arm === 'no-op-control'\n ? {\n step: noOpInjectionStep(policy.seed, row.rowId, index, row.recordedCommands),\n action: config.inertAction,\n }\n : null\n if (injection) injections.push(injection)\n const result = await input.controls.run({ row, arm, rolloutIndex: index, injection })\n if (!result.succeeded) {\n error = result.error\n break\n }\n const { rollout, tests } = result.value\n assertRolloutMatchesRequest(rollout, { row, arm, index })\n rollouts.push(rollout)\n summaries.push({\n arm,\n index: rollout.index,\n seed: rollout.seed,\n policyDigest: rollout.policyDigest,\n exitStatus: rollout.exitStatus,\n testsPassed: tests.passed,\n costUsd: rollout.costProvenance.usd,\n })\n if (tests.passed) {\n passes += 1\n break\n }\n }\n\n const record: AdmissionCheckRecord = {\n check: 'control',\n arm,\n rolloutsRun: rollouts.length,\n passes,\n injections,\n }\n if (error !== null) return { outcome: 'error', error, record, rollouts, summaries }\n if (passes > 0) return { outcome: 'rescued', error: null, record, rollouts, summaries }\n return { outcome: 'failed-every-rollout', error: null, record, rollouts, summaries }\n}\n\nfunction assertRolloutMatchesRequest(\n rollout: ContinuationRollout,\n request: { row: AdmissionRow; arm: AdmissionControlArm; index: number },\n): void {\n if (rollout.arm !== request.arm) {\n throw new AdmissionDenominatorError(\n `control runner returned a ${rollout.arm} rollout for the ${request.arm} arm`,\n )\n }\n if (rollout.rowId !== request.row.rowId) {\n throw new AdmissionDenominatorError(\n `control runner returned a rollout for row ${rollout.rowId} while deciding ${request.row.rowId}`,\n )\n }\n if (rollout.index !== request.index) {\n throw new AdmissionDenominatorError(\n `control runner returned rollout index ${rollout.index} for requested index ${request.index}`,\n )\n }\n}\n\n/**\n * Model cost of every control rollout that ran.\n *\n * One unpriced rollout makes the total uncaptured, because summing the priced\n * ones reports less than the pre-pass spent. Zero rollouts is an observed zero:\n * nothing ran, so nothing is missing.\n */\nfunction summarizeControlCost(verdicts: readonly AdmissionRowVerdict[]): CostProvenance {\n let usd = 0\n for (const verdict of verdicts) {\n for (const rollout of verdict.rollouts) {\n if (rollout.costUsd === null) return { kind: 'uncaptured', usd: null }\n usd += rollout.costUsd\n }\n }\n return { kind: 'observed', usd }\n}\n\nfunction groupAdmittedByStratum(\n verdicts: readonly AdmissionRowVerdict[],\n): Readonly<Record<AdmissionStratum, readonly string[]>> {\n const grouped: Record<AdmissionStratum, string[]> = {\n 'clean-exit': [],\n 'command-error': [],\n 'signal-kill': [],\n }\n for (const verdict of verdicts) {\n if (!verdict.admitted || verdict.stratum === null) continue\n grouped[verdict.stratum].push(verdict.rowId)\n }\n return Object.freeze({\n 'clean-exit': Object.freeze(grouped['clean-exit']),\n 'command-error': Object.freeze(grouped['command-error']),\n 'signal-kill': Object.freeze(grouped['signal-kill']),\n })\n}\n\n/** Bounded worker pool that keeps results in input order. */\nasync function mapOrdered<T, R>(\n items: readonly T[],\n concurrency: number,\n fn: (item: T) => Promise<R>,\n): Promise<R[]> {\n const results = new Array<R>(items.length)\n let next = 0\n const workerCount = Math.max(1, Math.min(concurrency, items.length))\n const workers = Array.from({ length: workerCount }, async () => {\n for (;;) {\n const index = next\n next += 1\n if (index >= items.length) return\n const item = items[index]\n if (item === undefined) return\n results[index] = await fn(item)\n }\n })\n await Promise.all(workers)\n return results\n}\n\n// ── Reading the report ───────────────────────────────────────────────\n\n/** Admitted row ids in one stratum. No call returns them pooled. */\nexport function admittedRowIds(\n report: AdmissionReport,\n stratum: AdmissionStratum,\n): readonly string[] {\n return report.strata[stratum]\n}\n\nexport function admittedCount(report: AdmissionReport): number {\n return ADMISSION_STRATA.reduce((total, stratum) => total + report.strata[stratum].length, 0)\n}\n\nexport interface DenominatorIntactInput {\n report: AdmissionReport\n /** Strata the campaign drew from. Rows outside them are not expected. */\n strata: readonly AdmissionStratum[]\n /** Rows the campaign sampled from the admitted set. */\n sampled: readonly string[]\n /** Rows the campaign produced an outcome for, including `no-decisive-failure`. */\n scored: readonly string[]\n}\n\n/**\n * Prove a campaign measured the denominator admission published.\n *\n * Three ways a denominator moves after the fact, each rejected here: scoring a\n * row that was never admitted, scoring a row that was never sampled, and\n * dropping a sampled row instead of scoring it. The third is the one an analyst\n * can cause on its own — declining a row it cannot solve — so a sampled row\n * with no outcome is an error, not a smaller `n`.\n */\nexport function assertDenominatorIntact(input: DenominatorIntactInput): void {\n const { report, strata, sampled, scored } = input\n for (const stratum of strata) {\n if (!ADMISSION_STRATA.includes(stratum)) {\n throw new ValidationError(`unknown stratum in denominator check: ${stratum}`)\n }\n }\n assertNoDuplicates(sampled, 'sampled')\n assertNoDuplicates(scored, 'scored')\n const eligible = new Set(strata.flatMap((stratum) => [...report.strata[stratum]]))\n const notAdmitted = sampled.filter((rowId) => !eligible.has(rowId))\n if (notAdmitted.length > 0) {\n throw new AdmissionDenominatorError(\n `${notAdmitted.length} sampled row(s) are not admitted in strata ${strata.join(', ')}: ${preview(notAdmitted)}`,\n )\n }\n const sampledSet = new Set(sampled)\n const unsampled = scored.filter((rowId) => !sampledSet.has(rowId))\n if (unsampled.length > 0) {\n throw new AdmissionDenominatorError(\n `${unsampled.length} scored row(s) were never sampled: ${preview(unsampled)}`,\n )\n }\n const scoredSet = new Set(scored)\n const dropped = sampled.filter((rowId) => !scoredSet.has(rowId))\n if (dropped.length > 0) {\n throw new AdmissionDenominatorError(\n `denominator shrank by ${dropped.length} row(s): sampled but never scored: ${preview(dropped)}`,\n )\n }\n}\n\n/** A row counted twice raises `n` without measuring anything twice. */\nfunction assertNoDuplicates(rowIds: readonly string[], field: string): void {\n const seen = new Set<string>()\n const duplicates = rowIds.filter((rowId) => {\n if (seen.has(rowId)) return true\n seen.add(rowId)\n return false\n })\n if (duplicates.length > 0) {\n throw new AdmissionDenominatorError(\n `${field} lists ${duplicates.length} duplicate row id(s): ${preview([...new Set(duplicates)])}`,\n )\n }\n}\n\nfunction preview(rowIds: readonly string[]): string {\n const shown = rowIds.slice(0, 5).join(', ')\n return rowIds.length > 5 ? `${shown}, +${rowIds.length - 5} more` : shown\n}\n","/**\n * Admission: the executed checks a row must pass before an analyst is allowed\n * to see it, and the brand that proves it did.\n *\n * Every check is analyst-independent. None of them reads a finding, a label,\n * or a k, and all of them are anchored at the recorded end state — the point\n * the agent actually stopped at — so the same evidence admits a row no matter\n * which step an analyst later blames:\n *\n * oracle-determinism the task's own suite returns one verdict on identical\n * bytes, so its answer is about the state\n * prefix-fidelity the recorded trajectory replays with at most 10 % of\n * its steps diverging from their recorded returncode\n * end-state-fails the held-out suite fails on the recorded end state\n * no-fix-control 3 of 3 continuations from the end state fail\n * no-op-control 3 of 3 continuations from the end state, after an\n * action that changes nothing, fail\n *\n * The two controls are what make `Delta-repair` a difference rather than a\n * rate, and what stops a row where the agent was one free step from success\n * from counting as a repair the analyst caused. They only do that under a\n * control that can act: `control-policy.ts` holds the declaration, and the\n * criteria name which reading of a control pass applies.\n *\n * The determinism check sits in front of all of it. Every downstream check\n * reads the same suite, so a suite whose verdict is not a function of the state\n * makes each of them a coin flip rather than a measurement.\n *\n * This module owns the CONTRACT, not the execution. `runAdmission` in\n * `./admission` executes the checks against real containers and hands the\n * measured evidence to `admitRow`, which decides and brands. Splitting it that\n * way keeps the decision auditable from the recorded numbers alone: a reviewer\n * can re-derive every admission from the evidence file without re-running a\n * container.\n */\n\nimport { ValidationError } from '../errors'\nimport type { RecordedTrajectoryStep } from '../trajectory-replay/steps'\nimport {\n assertControlCalibrated,\n type ControlPolicy,\n type ControlScreening,\n} from './control-policy'\nimport type { OracleDeterminismVerdict } from './oracle-determinism'\n\n/** Pre-registered admission thresholds. */\nexport interface AdmissionCriteria {\n /** Share of replayed prefix steps allowed to diverge from their recorded\n * returncode. Above it the container state under test is not the recorded\n * one, so nothing measured on it is about the recorded run. */\n readonly maxPrefixDivergenceRatio: number\n /** Control rollouts each control arm must run. */\n readonly controlRollouts: number\n /** How a control pass is read. `enforced` requires a control that can act. */\n readonly controlScreening: ControlScreening\n}\n\nexport const TB_REPAIR_ADMISSION_CRITERIA: AdmissionCriteria = Object.freeze({\n maxPrefixDivergenceRatio: 0.1,\n controlRollouts: 3,\n controlScreening: 'enforced' as ControlScreening,\n})\n\nexport interface PrefixFidelityEvidence {\n /** Recorded steps that were replayed. */\n readonly stepsReplayed: number\n /** Replayed steps whose exit code differed from the recorded returncode. */\n readonly divergences: number\n}\n\nexport interface ControlArmEvidence {\n readonly rollouts: number\n /** Rollouts whose held-out suite passed. Admission requires zero. */\n readonly passes: number\n /** Policy digest every rollout reported. An arm that ran something other\n * than the declared control is not the control the criteria describe. */\n readonly policyDigest: string\n}\n\nexport interface AdmissionEvidence {\n readonly rowId: string\n /** Terminal-Bench-2 task the trajectory ran. It selects the certification\n * below, and a certification for another task is refused rather than read. */\n readonly taskName: string\n /** Published image the trajectory was recorded against. */\n readonly image: string\n /** Working directory the scaffold ran every action from. */\n readonly cwd: string\n /** Task statement handed to the recorded agent. */\n readonly taskStatement: string\n readonly steps: readonly RecordedTrajectoryStep[]\n /**\n * The task's certified oracle determinism. Required: a campaign that has not\n * measured whether its ground truth is a function of the state cannot\n * construct evidence, which is where that omission should stop.\n */\n readonly oracleDeterminism: OracleDeterminismVerdict\n /** The control both arms ran, declared and hashed. */\n readonly controlPolicy: ControlPolicy\n readonly prefixFidelity: PrefixFidelityEvidence\n /** Held-out suite result on the recorded end state. Admission requires a fail. */\n readonly endStatePassed: boolean\n /** Digest of the suite that produced every result above. */\n readonly suiteDigest: string\n readonly noFixControl: ControlArmEvidence\n readonly noOpControl: ControlArmEvidence\n}\n\n/** Which pre-registered check refused the row. */\nexport type AdmissionRejection =\n | 'task-oracle-nondeterministic'\n | 'prefix-divergence-too-high'\n | 'end-state-already-passes'\n | 'no-fix-control-passed'\n | 'no-op-control-passed'\n | 'control-passed-on-identical-state'\n | 'control-rollouts-short'\n | 'control-policy-mismatch'\n | 'empty-trajectory'\n\ndeclare const ADMITTED: unique symbol\n\n/**\n * A row that passed every admission check.\n *\n * The brand is a phantom: it exists in the type and never in the value, and\n * the symbol that names it is not exported, so `AdmittedRow` cannot be\n * constructed anywhere but here. Both `blindTrajectory` and `gradeRepairRow`\n * require one. That is the structural form of \"admission runs before any\n * analyst sees a row\": there is no signature that accepts an unadmitted row.\n */\nexport interface AdmittedRow {\n readonly [ADMITTED]: true\n readonly rowId: string\n readonly taskName: string\n readonly image: string\n readonly cwd: string\n readonly taskStatement: string\n readonly steps: readonly RecordedTrajectoryStep[]\n readonly criteria: AdmissionCriteria\n readonly prefixDivergenceRatio: number\n readonly suiteDigest: string\n /** The control the row was screened under, carried whole so a later reader\n * never has to open the runner's source to learn what screened it. */\n readonly controlPolicy: ControlPolicy\n readonly controlScreening: ControlScreening\n /** Policy digest both controls ran under. Every intervention rollout must\n * report the same one or the arms are not comparable. */\n readonly policyDigest: string\n /** Control rate the paired delta subtracts. Zero by admission, carried\n * explicitly so the estimator never hardcodes it. */\n readonly controlRate: number\n readonly controlRollouts: number\n}\n\n/** Carried by every decision, admitted or not, so an artifact answers \"which\n * control screened this row\" without reading the runner's source. */\nexport interface AdmissionScreeningRecord {\n readonly controlPolicy: ControlPolicy\n readonly controlScreening: ControlScreening\n readonly controlPolicyDigest: string\n readonly taskName: string\n readonly oracleStable: boolean\n readonly oracleFlipRate: number\n}\n\nexport type AdmissionDecision =\n | {\n readonly admitted: true\n readonly screening: AdmissionScreeningRecord\n readonly row: AdmittedRow\n }\n | {\n readonly admitted: false\n readonly rowId: string\n readonly screening: AdmissionScreeningRecord\n readonly rejection: AdmissionRejection\n readonly detail: string\n }\n\n/**\n * Decide admission from executed evidence.\n *\n * Pure: it opens no container and calls no model. Every threshold it applies\n * is in `criteria`, and every number it reads is in `evidence`, so an\n * admission decision is reproducible from the recorded evidence alone.\n *\n * It throws, rather than rejecting, when the criteria and the declared control\n * contradict. A contradiction there is a property of the configuration and not\n * of the row, so it must stop the run instead of producing one verdict per row\n * that reads as if a check had been applied.\n */\nexport function admitRow(\n evidence: AdmissionEvidence,\n criteria: AdmissionCriteria = TB_REPAIR_ADMISSION_CRITERIA,\n): AdmissionDecision {\n assertCriteria(criteria)\n assertControlCalibrated(evidence.controlPolicy, criteria.controlScreening)\n // A certification measured on another task says nothing about this one, and\n // reading it as if it did is the same corruption the certification exists to\n // prevent. It is a wiring fault, so it stops the run.\n if (evidence.oracleDeterminism.taskName !== evidence.taskName) {\n throw new ValidationError(\n `row ${evidence.rowId} is from task ${evidence.taskName} but carries the oracle ` +\n `certification for ${evidence.oracleDeterminism.taskName}`,\n )\n }\n\n const screening: AdmissionScreeningRecord = {\n controlPolicy: evidence.controlPolicy,\n controlScreening: criteria.controlScreening,\n controlPolicyDigest: evidence.controlPolicy.digest,\n taskName: evidence.oracleDeterminism.taskName,\n oracleStable: evidence.oracleDeterminism.stable,\n oracleFlipRate: evidence.oracleDeterminism.flipRate,\n }\n const reject = (rejection: AdmissionRejection, detail: string): AdmissionDecision => ({\n admitted: false,\n rowId: evidence.rowId,\n screening,\n rejection,\n detail,\n })\n\n const oracle = evidence.oracleDeterminism\n if (!oracle.stable) {\n return reject(\n 'task-oracle-nondeterministic',\n `task ${oracle.taskName} graded byte-identical state inconsistently: flip rate ` +\n `${(oracle.flipRate * 100).toFixed(1)} % over ${oracle.replicates} replicates ` +\n `(${oracle.detail}). Every check below reads that suite, so none of them measures state.`,\n )\n }\n\n if (evidence.steps.length === 0) {\n return reject('empty-trajectory', 'the row records no steps')\n }\n const { stepsReplayed, divergences } = evidence.prefixFidelity\n if (stepsReplayed <= 0) {\n return reject('empty-trajectory', 'no recorded step was replayed')\n }\n const prefixDivergenceRatio = divergences / stepsReplayed\n if (prefixDivergenceRatio > criteria.maxPrefixDivergenceRatio) {\n return reject(\n 'prefix-divergence-too-high',\n `${divergences}/${stepsReplayed} replayed steps diverged (${(prefixDivergenceRatio * 100).toFixed(1)} %), ` +\n `above the ${(criteria.maxPrefixDivergenceRatio * 100).toFixed(1)} % ceiling`,\n )\n }\n if (evidence.endStatePassed) {\n return reject(\n 'end-state-already-passes',\n 'the held-out suite passes on the recorded end state, so the row records no failure to repair',\n )\n }\n for (const [name, arm, rescued] of [\n ['no-fix control', evidence.noFixControl, 'no-fix-control-passed'],\n ['no-op control', evidence.noOpControl, 'no-op-control-passed'],\n ] as const) {\n if (arm.rollouts !== criteria.controlRollouts) {\n return reject(\n 'control-rollouts-short',\n `${name} ran ${arm.rollouts} rollouts, the criteria pre-register ${criteria.controlRollouts}`,\n )\n }\n if (arm.policyDigest !== evidence.controlPolicy.digest) {\n return reject(\n 'control-policy-mismatch',\n `${name} reported policy ${arm.policyDigest} but the criteria screen under ` +\n `${evidence.controlPolicy.id} (${evidence.controlPolicy.digest}); the arm did not run the declared control`,\n )\n }\n if (arm.passes !== 0) {\n // Under a control that cannot act, the arm graded the same bytes the\n // end-state check read as failing. That is the task's grader answering\n // twice about one state, so it is recorded as the flip and never as a\n // rescue the control performed.\n return criteria.controlScreening === 'enforced'\n ? reject(\n rescued,\n `${name} passed ${arm.passes}/${arm.rollouts}; the row is repairable by continuing alone`,\n )\n : reject(\n 'control-passed-on-identical-state',\n `${name} passed ${arm.passes}/${arm.rollouts} under ${evidence.controlPolicy.id}, which ` +\n 'executes no command, so it graded the same bytes the end-state check graded as failing. ' +\n `The task's certification reports flip rate ${(oracle.flipRate * 100).toFixed(1)} %; this row ` +\n 'is a further flip, not a rescue.',\n )\n }\n }\n\n return {\n admitted: true,\n screening,\n // The brand is type-level only, so the branded value carries no phantom\n // property a consumer could copy to forge one.\n row: {\n rowId: evidence.rowId,\n taskName: evidence.taskName,\n image: evidence.image,\n cwd: evidence.cwd,\n taskStatement: evidence.taskStatement,\n steps: evidence.steps,\n criteria,\n prefixDivergenceRatio,\n suiteDigest: evidence.suiteDigest,\n controlPolicy: evidence.controlPolicy,\n controlScreening: criteria.controlScreening,\n policyDigest: evidence.controlPolicy.digest,\n controlRate: evidence.noFixControl.passes / evidence.noFixControl.rollouts,\n controlRollouts: evidence.noFixControl.rollouts,\n } as unknown as AdmittedRow,\n }\n}\n\nfunction assertCriteria(criteria: AdmissionCriteria): void {\n const { maxPrefixDivergenceRatio, controlRollouts } = criteria\n if (!(maxPrefixDivergenceRatio >= 0 && maxPrefixDivergenceRatio <= 1)) {\n throw new ValidationError(\n `admission maxPrefixDivergenceRatio must be within [0,1], got ${maxPrefixDivergenceRatio}`,\n )\n }\n if (!Number.isInteger(controlRollouts) || controlRollouts <= 0) {\n throw new ValidationError(\n `admission controlRollouts must be a positive integer, got ${controlRollouts}`,\n )\n }\n}\n","/**\n * The published form of an admission run: a JSON artifact a later process can\n * check the campaign against, and the Markdown a reader can audit.\n *\n * A benchmark whose denominator is not auditable is not a benchmark, so both\n * carry the same numbers: every exclusion reason with its count, the funnel per\n * stratum, and the provenance of the three boundaries that decided it.\n */\n\nimport type { AdmissionConfig, AdmissionProvenance, AdmissionReport } from './admission'\nimport {\n ADMISSION_EXCLUSION_MEANING,\n ADMISSION_EXCLUSION_ORDER,\n ADMISSION_STRATA,\n type AdmissionExclusionReason,\n type AdmissionRowVerdict,\n type AdmissionStratum,\n assertChainReconciles,\n type DenominatorChain,\n type DenominatorChainArtifact,\n} from './admission-records'\n\nexport interface AdmissionArtifact {\n version: 1\n kind: 'tb-repair-admission'\n generatedAt: string\n /** Hash over the admitted ids, the config, and the provenance. */\n digest: string\n config: AdmissionConfig\n provenance: AdmissionProvenance\n chain: DenominatorChainArtifact\n /** Admitted row ids per stratum, the only form the campaign may sample from. */\n admitted: Record<AdmissionStratum, readonly string[]>\n controlCost: { kind: string; usd: number | null }\n /** Every input row, admitted or not, with the stratum and reason it carried. */\n rows: readonly AdmissionRowVerdict[]\n}\n\n/** Plain JSON. `JSON.stringify` of this object is the machine-readable artifact. */\nexport function admissionArtifact(report: AdmissionReport): AdmissionArtifact {\n assertChainReconciles(report.chain)\n return {\n version: 1,\n kind: 'tb-repair-admission',\n generatedAt: report.generatedAt,\n digest: report.digest,\n config: report.config,\n provenance: report.provenance,\n chain: report.chain,\n admitted: {\n 'clean-exit': report.strata['clean-exit'],\n 'command-error': report.strata['command-error'],\n 'signal-kill': report.strata['signal-kill'],\n },\n controlCost: { kind: report.controlCost.kind, usd: report.controlCost.usd },\n rows: report.rows,\n }\n}\n\nexport interface RenderAdmissionOptions {\n /** Rows listed in the per-row appendix. Default 0, which omits the appendix. */\n rowLimit?: number\n}\n\n/** Markdown for the campaign report. Every number here is also in the artifact. */\nexport function renderAdmissionReport(\n artifact: AdmissionArtifact,\n options: RenderAdmissionOptions = {},\n): string {\n const lines: string[] = []\n lines.push('# TB-Repair admission', '')\n lines.push(\n `${artifact.chain.overall.admitted} of ${artifact.chain.overall.input} rows admitted. Digest \\`${artifact.digest}\\`.`,\n '',\n )\n lines.push(...provenanceSection(artifact))\n lines.push(...chainSection(artifact.chain.overall, 'Denominator chain'))\n for (const chain of artifact.chain.byStratum) {\n lines.push(...chainSection(chain, `Denominator chain — ${chain.scope}`))\n }\n lines.push(...stratumSection(artifact))\n lines.push(...reasonSection(artifact.chain.reasonTotals))\n const rowLimit = options.rowLimit ?? 0\n if (rowLimit > 0) lines.push(...rowSection(artifact.rows, rowLimit))\n return `${lines.join('\\n').trimEnd()}\\n`\n}\n\nfunction provenanceSection(artifact: AdmissionArtifact): string[] {\n const { provenance, config, controlCost } = artifact\n const cost = controlCost.usd === null ? 'uncaptured' : `$${controlCost.usd.toFixed(4)}`\n return [\n '## Provenance',\n '',\n '| field | value |',\n '| --- | --- |',\n `| generated | ${artifact.generatedAt} |`,\n `| prefix replayer | \\`${provenance.replayerId}\\` |`,\n `| end-state oracle | \\`${provenance.oracleId}\\` |`,\n `| control runner | \\`${provenance.controlRunnerId}\\` |`,\n `| continuation policy | \\`${provenance.policyId}\\` |`,\n `| policy model | \\`${provenance.policyModel}\\` |`,\n `| policy seed | ${provenance.policySeed} |`,\n `| policy digest | \\`${provenance.policyDigest}\\` |`,\n `| policy step budget | ${provenance.policyStepBudget} model call(s) per control rollout |`,\n `| control screening | \\`${provenance.controlScreening}\\` |`,\n `| certified task oracles | ${formatCertifiedTasks(provenance.certifiedTasks)} |`,\n `| max prefix divergence | ${formatShare(config.maxPrefixDivergence)} |`,\n `| control rollouts per arm | ${config.controlRollouts} |`,\n `| inert action | \\`${config.inertAction}\\` |`,\n `| strata admitted | ${config.admitStrata.join(', ')} |`,\n `| control model cost | ${cost} (${controlCost.kind}) |`,\n '',\n ]\n}\n\nfunction formatCertifiedTasks(certified: Readonly<Record<string, number>>): string {\n const entries = Object.entries(certified).sort(([a], [b]) => a.localeCompare(b))\n if (entries.length === 0) return 'none'\n return entries.map(([task, flipRate]) => `${task} (flip ${formatShare(flipRate)})`).join(', ')\n}\n\nfunction chainSection(chain: DenominatorChain, heading: string): string[] {\n const lines = [\n `## ${heading}`,\n '',\n '| stage | exclusion reason | entering | excluded | remaining |',\n '| --- | --- | --- | --- | --- |',\n ]\n chain.stages.forEach((stage, index) => {\n lines.push(\n `| ${index + 1} | \\`${stage.reason}\\` | ${stage.entering} | ${stage.excluded} | ${stage.remaining} |`,\n )\n })\n const excluded = chain.input - chain.admitted\n lines.push(\n '',\n `Input ${chain.input} = admitted ${chain.admitted} + excluded ${excluded}. Admission rate ${formatShare(rate(chain.admitted, chain.input))}.`,\n '',\n )\n return lines\n}\n\nfunction stratumSection(artifact: AdmissionArtifact): string[] {\n const lines = [\n '## Strata',\n '',\n '| stratum | admitted rows | in this campaign |',\n '| --- | --- | --- |',\n ]\n for (const stratum of ADMISSION_STRATA) {\n const admitted = artifact.admitted[stratum].length\n const eligible = artifact.chain.admitStrata.includes(stratum) ? 'yes' : 'no'\n lines.push(`| ${stratum} | ${admitted} | ${eligible} |`)\n }\n lines.push(\n '',\n 'Sample within a stratum. A command-level repair cannot address a signal kill, so pooling that population with the others averages an addressable class with an unaddressable one.',\n '',\n )\n return lines\n}\n\nfunction reasonSection(totals: Record<AdmissionExclusionReason, number>): string[] {\n const lines = ['## Exclusions', '', '| reason | rows | what it means |', '| --- | --- | --- |']\n for (const reason of ADMISSION_EXCLUSION_ORDER) {\n lines.push(`| \\`${reason}\\` | ${totals[reason]} | ${ADMISSION_EXCLUSION_MEANING[reason]} |`)\n }\n lines.push('')\n return lines\n}\n\nfunction rowSection(rows: readonly AdmissionRowVerdict[], limit: number): string[] {\n const lines = [\n '## Rows',\n '',\n '| row | task | stratum | final rc | admitted | excluded by |',\n '| --- | --- | --- | --- | --- | --- |',\n ]\n for (const row of rows.slice(0, limit)) {\n lines.push(\n `| \\`${row.rowId}\\` | ${row.taskName} | ${row.stratum ?? '—'} | ${row.finalReturncode ?? '—'} | ${row.admitted ? 'yes' : 'no'} | ${row.excludedBy === null ? '—' : `\\`${row.excludedBy}\\``} |`,\n )\n }\n if (rows.length > limit) lines.push('', `${rows.length - limit} further rows in the artifact.`)\n lines.push('')\n return lines\n}\n\nfunction rate(part: number, total: number): number {\n return total === 0 ? 0 : part / total\n}\n\nfunction formatShare(share: number): string {\n return `${(share * 100).toFixed(2)}%`\n}\n","/**\n * What the analyst is shown.\n *\n * A blinded trajectory prefix: the task the agent was given and the actions\n * and observations it produced, and nothing about how the run was judged. No\n * held-out suite, no suite digest, no control rates, no end-state result, no\n * label.\n *\n * The blinding is by construction rather than by redaction. The returned\n * object is assembled field by field from an admitted row, so a field added to\n * `AdmittedRow` later cannot leak into an analyst prompt by default — it has\n * to be copied here on purpose.\n *\n * Requiring an `AdmittedRow` is the other half of the guarantee: a row cannot\n * be shown to an analyst before the four admission checks have executed and\n * passed.\n */\n\nimport { ValidationError } from '../errors'\nimport type { AdmittedRow } from './admission-contract'\n\nexport interface BlindedStep {\n readonly step_id: number\n readonly action: string\n readonly observation: string | null\n}\n\nexport interface BlindedTrajectoryPrefix {\n readonly rowId: string\n /** The task statement the recorded agent was given. */\n readonly taskStatement: string\n readonly steps: readonly BlindedStep[]\n /** Steps the recording holds. Equal to `steps.length` unless the prefix was\n * deliberately truncated. */\n readonly recordedSteps: number\n /** Largest k the analyst may name for this prefix. */\n readonly maxK: number\n}\n\nexport interface BlindTrajectoryOptions {\n /** Truncate the prefix after this 1-based step. Defaults to the whole\n * recording, which is what the recorded agent itself saw before it stopped. */\n readonly throughStep?: number\n}\n\nexport function blindTrajectory(\n row: AdmittedRow,\n options: BlindTrajectoryOptions = {},\n): BlindedTrajectoryPrefix {\n const through = options.throughStep ?? row.steps.length\n if (!Number.isInteger(through) || through < 1 || through > row.steps.length) {\n throw new ValidationError(\n `blindTrajectory throughStep must be within [1, ${row.steps.length}], got ${through}`,\n )\n }\n const steps = row.steps.slice(0, through).map((step) => ({\n step_id: step.step_id,\n action: step.action,\n observation: step.observation,\n }))\n return {\n rowId: row.rowId,\n taskStatement: row.taskStatement,\n steps,\n recordedSteps: row.steps.length,\n maxK: through,\n }\n}\n\n/**\n * Fields an analyst prompt must never carry. Exported so a consumer that\n * builds its own prompt can assert against the same list this module honours.\n */\nexport const BLINDED_FIELDS: readonly string[] = Object.freeze([\n 'criteria',\n 'controlPolicy',\n 'controlRate',\n 'controlRollouts',\n 'controlScreening',\n 'suiteDigest',\n 'policyDigest',\n 'prefixDivergenceRatio',\n 'image',\n 'cwd',\n])\n","/**\n * The one question every repair arm answers.\n *\n * Arms differ in what EXECUTES the question — a single chat completion, an\n * agent harness, a DSPy program — and in nothing else. One prompt module is\n * what makes a comparison between them an ablation of the execution path\n * rather than a comparison of two prompts.\n *\n * The execution environment is stated, not hinted. The recorded scaffold runs\n * every action in a fresh `/bin/sh` and takes exactly one top-level statement,\n * so an arm that is not told that writes bash-only syntax and dies at\n * execution for a reason that has nothing to do with whether it localized the\n * failure. Stating the shell leaks no label: the held-out suite, the control\n * rates and the end-state verdict all stay out, and the prompt is built from a\n * `BlindedTrajectoryPrefix`, which cannot carry them.\n *\n * The action caps in the prose are read from the budget the grader enforces,\n * so the instruction and the rejection can never drift apart.\n */\n\nimport { createHash } from 'node:crypto'\nimport { type InterventionBudget, SCAFFOLD_INTERVENTION_BUDGET } from './action-budget'\nimport type { BlindedTrajectoryPrefix } from './blinding'\n\nexport const REPAIR_QUESTION =\n 'This coding agent ran and did not finish the task. Name the ONE recorded step whose action you would replace, and give the single shell action to run instead of it.'\n\n/**\n * The task definition. Parameterised by the budget so the stated caps are the\n * enforced caps.\n */\nexport function repairTaskPolicy(\n budget: InterventionBudget = SCAFFOLD_INTERVENTION_BUDGET,\n): readonly string[] {\n return Object.freeze([\n 'You are given a task statement and the complete recorded trajectory of an agent that attempted it and failed.',\n \"Your answer is executed. The action you return is run inside the real task container, at the point in the trajectory you name, and the task's held-out test suite is then run against the resulting state. You are scored on whether the suite passes, never on how your explanation reads.\",\n '',\n 'HOW YOUR ACTION IS EXECUTED — read this before writing it:',\n '- The action runs in a FRESH `/bin/sh`, which is dash on this image, not bash. C-style `for ((i=0;i<n;i++))`, `[[ ]]`, arrays, and `local` are bash-only and will fail with a syntax error.',\n `- The scaffold accepts exactly ${budget.maxStatements === 1 ? 'ONE top-level statement' : `${budget.maxStatements} top-level statements`}. Wrap multiple commands in a single \\`{ ...; }\\` block or chain them with \\`&&\\`.`,\n `- The action is at most ${budget.maxBytes} bytes, and must not be a no-op such as \\`true\\`, \\`:\\` or an empty string.`,\n '- It runs from the task working directory, as root, with the network available.',\n '- Prefer writing a complete correct file with a heredoc over patching in place; you cannot see the result of your own action, so it must work on the first attempt.',\n 'Name the step whose action you would replace as `k`, using the step_id shown in the trajectory. Choosing the last step means \"instead of the last thing the agent did, do this\". You are not repairing the agent\\'s reasoning; you are producing the state the suite requires.',\n 'Return no finding only when no single replacement action could plausibly make the suite pass.',\n ])\n}\n\n/** The reply grammar, stated to an arm that answers in one JSON object. */\nexport const REPAIR_CONTRACT_LINES: readonly string[] = Object.freeze([\n 'OUTPUT CONTRACT — reply with ONE fenced JSON object and nothing else:',\n '```json',\n '{\"answer\": \"<one sentence on what went wrong>\", \"findings\": [{\"k\": <int>, \"failure_claim\": \"<what went wrong at step k>\", \"intervention\": {\"kind\": \"shell\", \"action\": \"<the single shell action to run instead>\"}}]}',\n '```',\n 'Rules:',\n '- `findings` carries AT MOST ONE object. Never more.',\n '- `k` is an integer step_id present in the trajectory below.',\n '- `failure_claim` is a non-empty string. It is recorded and never scored, so spend your effort on the action.',\n '- `intervention.kind` is the string \"shell\", or \"edit\" when the action authors a file with a heredoc.',\n '- `intervention.action` is the exact shell text to execute. It is not a description and not a diff.',\n '- Return `\"findings\": []` only to say that no single action could repair this run.',\n])\n\n/** The same grammar restated for the bounded repair turn, which never carries\n * the trajectory again. */\nexport const REPAIR_REPAIR_CONTRACT_LINES: readonly string[] = Object.freeze([\n 'Your previous reply did not satisfy the output contract. Resend the answer, and nothing else, as ONE fenced JSON object:',\n '```json',\n '{\"answer\": \"<one sentence>\", \"findings\": [{\"k\": <int>, \"failure_claim\": \"<string>\", \"intervention\": {\"kind\": \"shell\", \"action\": \"<shell text>\"}}]}',\n '```',\n '`findings` carries at most one object. Do not restate the trajectory.',\n])\n\n/** The trajectory as an arm sees it: actions, observations, nothing about grading. */\nexport function renderRepairTrajectory(prefix: BlindedTrajectoryPrefix): string {\n return prefix.steps\n .map((step) =>\n [\n `--- step_id ${step.step_id} ---`,\n 'ACTION:',\n step.action,\n 'OBSERVATION:',\n step.observation === null ? '(no observation recorded)' : step.observation,\n ].join('\\n'),\n )\n .join('\\n\\n')\n}\n\nexport function repairTrajectoryHeader(prefix: BlindedTrajectoryPrefix): string {\n return `RECORDED TRAJECTORY (${prefix.steps.length} steps; valid k is any step_id below, the last is ${prefix.maxK}):`\n}\n\n/** The task definition an arm receives: the policy plus the statement the\n * recorded agent was given. */\nexport function repairTaskDefinition(\n prefix: BlindedTrajectoryPrefix,\n budget: InterventionBudget = SCAFFOLD_INTERVENTION_BUDGET,\n): string {\n return [\n ...repairTaskPolicy(budget),\n '',\n 'TASK STATEMENT GIVEN TO THE AGENT:',\n prefix.taskStatement,\n ].join('\\n')\n}\n\n/**\n * Digest of the question and task policy every arm shares.\n *\n * This is the part of the prompt that is equal by construction across arms:\n * the question, the execution rules, and the budget the caps are read from.\n * An arm's own contract text — its output grammar, its typed-signature\n * instructions — is deliberately outside it, because arms differ there.\n */\nexport function repairQuestionSha256(\n budget: InterventionBudget = SCAFFOLD_INTERVENTION_BUDGET,\n): string {\n return createHash('sha256')\n .update(\n JSON.stringify({\n kind: 'tb-repair-analyst-question',\n question: REPAIR_QUESTION,\n taskPolicy: repairTaskPolicy(budget),\n budget,\n }),\n )\n .digest('hex')\n}\n\n/**\n * Digest of the composed question one arm answered.\n *\n * Covers the shared question and the arm's own declared contract text, so two\n * arms that ask materially different composed questions — a JSON grammar\n * versus a typed SUBMIT signature — stamp different digests, and two arms\n * that ask the identical composed question share one.\n */\nexport function repairArmPromptSha256(\n budget: InterventionBudget,\n contract: readonly string[],\n): string {\n return createHash('sha256')\n .update(\n JSON.stringify({\n kind: 'tb-repair-analyst-prompt',\n question: REPAIR_QUESTION,\n taskPolicy: repairTaskPolicy(budget),\n budget,\n contract,\n }),\n )\n .digest('hex')\n}\n","/**\n * What an analyst arm is, and what every arm owes the comparison.\n *\n * An arm is one way of EXECUTING the repair question: a single chat\n * completion, an agent harness, a DSPy program. The question, the reply\n * grammar, the action budget and the bounded repair turn belong to the\n * comparison, not to the arm — so they live here and every arm inherits them.\n *\n * Three rules this module makes structural rather than customary:\n *\n * one contract an arm returns `RepairFinding` or an honest decline,\n * and nothing else parses. An arm that produced neither\n * fails loud with a typed reason; nothing is defaulted.\n * one budget `askRepairArm` measures every action against the\n * scaffold budget and records the measurement. The grader\n * remains the single authority that rejects, so a\n * violation is reported here and refused there — never\n * silently trimmed to fit.\n * one repair turn arms declare how many bounded retries a malformed reply\n * earns. `repairArmAsymmetries` refuses a set whose arms\n * disagree, because a second attempt is a second sample\n * the other arms never got.\n *\n * What arms are ALLOWED to differ in is declared, not hidden: `affordances`\n * names what an arm can do that another cannot — read the trajectory through\n * a code interpreter, take internal turns — and `repairArmAsymmetries` renders\n * those differences so a reader sees them beside the result instead of having\n * to infer them from two runners' source.\n */\n\nimport { assertEqualDeclarativeTerms } from '../analyst/equal-terms'\nimport { ValidationError } from '../errors'\nimport {\n type BudgetMeasurement,\n type BudgetViolation,\n checkInterventionBudget,\n type InterventionBudget,\n} from './action-budget'\nimport type { AdmittedRow } from './admission-contract'\nimport type { AnalystResponse, RepairFinding, RepairIntervention } from './analyst-response'\nimport { type BlindedTrajectoryPrefix, blindTrajectory } from './blinding'\nimport { repairArmPromptSha256, repairQuestionSha256 } from './repair-prompt'\n\n/**\n * Something an arm can do that another arm cannot.\n *\n * Declared per arm and reported beside the result. This list is the vocabulary\n * of admissible difference: an arm whose advantage is not nameable here is not\n * comparable to the others, and that is a design decision to take deliberately\n * rather than a field to widen.\n */\nexport type RepairArmAffordance =\n /** The whole trajectory arrives in the prompt text. */\n | 'inline-trajectory'\n /** The trajectory is read through bounded tools instead of the prompt. */\n | 'trajectory-tools'\n /** The arm may run code while it reasons. */\n | 'code-interpreter'\n /** The arm takes internal turns of its own before answering. */\n | 'agent-loop'\n\n/**\n * Whether the arm's instruction text carries a certification, and from where.\n *\n * On the repair task nothing is certified: the one certified analyst artifact\n * this repository holds was earned on a different benchmark under a different\n * output contract. `kind: 'none'` with a reason is therefore the expected\n * value, and it is recorded rather than omitted so a reader never has to\n * assume.\n */\nexport type RepairArmCertification =\n | { readonly kind: 'none'; readonly reason: string }\n | {\n readonly kind: 'certified'\n /** The artifact whose text this arm runs. */\n readonly artifact: string\n /** The benchmark the certification was earned on. */\n readonly benchmark: string\n /** The output contract it was certified for. */\n readonly contract: string\n }\n\nexport interface RepairArmDeclaration {\n readonly id: string\n /** What actually answers, in one plain sentence. Recorded so a report never\n * has to infer the execution path from the runner's source. */\n readonly execution: string\n readonly certification: RepairArmCertification\n /** The action budget the arm's answers are measured against. */\n readonly budget: InterventionBudget\n /** Bounded retries a structurally malformed reply earns. */\n readonly repairTurns: number\n readonly affordances: readonly RepairArmAffordance[]\n /** The arm's own instruction and output-grammar text, exactly as the arm\n * composes it into the question. It enters the per-arm prompt digest, so a\n * contract change — a reworded grammar, a new signature version — changes\n * the digest of every answer the arm stamps. */\n readonly promptContract: readonly string[]\n}\n\n/** What an arm is handed. The type carries only the blinded prefix, so a\n * grading field is unreachable rather than merely unread: the admitted row\n * stays with `askRepairArm`, which does the blinding and the bookkeeping. */\nexport interface RepairArmRequest {\n readonly prefix: BlindedTrajectoryPrefix\n readonly signal?: AbortSignal\n}\n\n/** Token accounting exactly as the execution path reported it. A side nobody\n * measured stays null rather than becoming a zero. */\nexport interface RepairArmUsage {\n readonly calls: number | null\n readonly inputTokens: number | null\n readonly outputTokens: number | null\n readonly costUsd: number | null\n}\n\nexport interface RepairArmRepairTurn {\n readonly attempted: boolean\n /** Null when no repair turn ran, or when it never returned a reply. */\n readonly succeeded: boolean | null\n}\n\n/** A row an arm reported and the pipeline refused, counted by reason. */\nexport interface RepairArmRejectedRow {\n readonly index: number\n readonly reason: string\n}\n\n/**\n * What an arm hands back.\n *\n * `finding` and `declined` are the two answers the grader consumes. `failed`\n * is everything else, and it always carries a reason: an arm that could not\n * answer must say so rather than return an empty finding that grades as a\n * decline it never made.\n */\nexport type RepairArmReply =\n | {\n readonly status: 'finding'\n readonly k: number\n readonly failureClaim: string\n readonly intervention: RepairIntervention\n readonly answer: string | null\n readonly reportedRows: number\n readonly rejectedRows: readonly RepairArmRejectedRow[]\n readonly repair: RepairArmRepairTurn\n readonly usage: RepairArmUsage\n }\n | {\n readonly status: 'declined'\n readonly answer: string | null\n readonly reportedRows: number\n readonly rejectedRows: readonly RepairArmRejectedRow[]\n readonly repair: RepairArmRepairTurn\n readonly usage: RepairArmUsage\n }\n | {\n readonly status: 'failed'\n readonly failure: string\n readonly answer: string | null\n readonly rejectedRows: readonly RepairArmRejectedRow[]\n readonly repair: RepairArmRepairTurn\n readonly usage: RepairArmUsage\n }\n\nexport interface RepairArm {\n readonly declaration: RepairArmDeclaration\n ask(request: RepairArmRequest): Promise<RepairArmReply>\n}\n\n/**\n * The budget verdict on an arm's action, measured before any container opens.\n *\n * Recorded, never enforced here: `gradeRepairRow` refuses an inadmissible\n * action, and one authority is the point. Measuring it at answer time is what\n * lets a report say what an arm spent its bytes on without paying for a\n * rollout to find out.\n */\nexport type RepairArmBudgetRecord =\n | { readonly admissible: true; readonly measurement: BudgetMeasurement }\n | {\n readonly admissible: false\n readonly violation: BudgetViolation\n readonly detail: string\n readonly measurement: BudgetMeasurement\n }\n\nexport interface RepairArmAnswer {\n readonly rowId: string\n readonly armId: string\n /** Digest of the composed question the arm answered. */\n readonly promptSha256: string\n readonly reply: RepairArmReply\n /** Present only for a finding. */\n readonly budget: RepairArmBudgetRecord | null\n readonly wallMs: number\n}\n\nexport interface AskRepairArmOptions {\n readonly arm: RepairArm\n readonly row: AdmittedRow\n /** Truncate the prefix after this 1-based step. Defaults to the whole recording. */\n readonly throughStep?: number\n readonly signal?: AbortSignal\n /** Injectable clock so a test can assert a recorded duration. */\n readonly now?: () => number\n}\n\n/**\n * Ask one arm about one admitted row.\n *\n * Blinding, prompt identity and budget measurement happen here, once, for\n * every arm. An arm that wants a different question does not get one.\n */\nexport async function askRepairArm(options: AskRepairArmOptions): Promise<RepairArmAnswer> {\n const { arm, row } = options\n assertDeclaration(arm.declaration)\n const now = options.now ?? Date.now\n const startedMs = now()\n const prefix = blindTrajectory(\n row,\n options.throughStep === undefined ? {} : { throughStep: options.throughStep },\n )\n const reply = await arm.ask({\n prefix,\n ...(options.signal ? { signal: options.signal } : {}),\n })\n assertReplyWithinDeclaration(arm.declaration, reply)\n const budget =\n reply.status === 'finding'\n ? checkInterventionBudget(\n reply.intervention.action,\n reply.intervention.kind,\n arm.declaration.budget,\n )\n : null\n return {\n rowId: row.rowId,\n armId: arm.declaration.id,\n promptSha256: repairArmPromptSha256(arm.declaration.budget, arm.declaration.promptContract),\n reply,\n budget,\n wallMs: now() - startedMs,\n }\n}\n\n/**\n * The answer in the grammar the grader consumes.\n *\n * Null for a failure: a run that could not answer has no answer to grade, and\n * turning it into a decline would credit an arm with an honest null it never\n * produced.\n */\nexport function repairArmResponse(answer: RepairArmAnswer): AnalystResponse | null {\n const { reply } = answer\n if (reply.status === 'declined') return { kind: 'no-decisive-failure' }\n if (reply.status === 'failed') return null\n const finding: RepairFinding = {\n kind: 'finding',\n k: reply.k,\n failureClaim: reply.failureClaim,\n intervention: reply.intervention,\n }\n return finding\n}\n\n/** One arm's difference from the set, as a report renders it. */\nexport interface RepairArmAsymmetry {\n readonly armId: string\n /** Affordances this arm has that at least one other arm lacks. */\n readonly extraAffordances: readonly RepairArmAffordance[]\n /** Affordances at least one other arm has and this one lacks. */\n readonly missingAffordances: readonly RepairArmAffordance[]\n readonly certification: RepairArmCertification\n /** Digest of the composed question this arm answers: the shared question\n * plus the arm's own contract text. Two arms with the same digest asked the\n * identical composed question; two arms with different digests did not. */\n readonly promptSha256: string\n}\n\nexport interface RepairArmAsymmetryReport {\n readonly armIds: readonly string[]\n /** Affordances every arm has. Not an asymmetry; recorded so a reader can see\n * the floor the comparison runs on. */\n readonly sharedAffordances: readonly RepairArmAffordance[]\n readonly asymmetries: readonly RepairArmAsymmetry[]\n /** True when no arm carries a certification. The honest state on a task\n * whose graders are newer than every certified artifact. */\n readonly noArmCertified: boolean\n readonly budget: InterventionBudget\n readonly repairTurns: number\n /** Digest of the question and task policy every arm shares. Per-arm\n * composed-question digests live on each asymmetry entry. */\n readonly questionSha256: string\n}\n\n/**\n * Refuse a set of arms that cannot be compared, and describe what still\n * differs between the ones that can.\n *\n * Two properties are hard: the arms measure actions against the same budget,\n * and a malformed reply earns the same number of retries everywhere. Both are\n * things that would move a score without moving the thing being measured.\n *\n * Certification is the third: a set where some arms run certified text and\n * others do not is refused outright. An optimisation applies to every arm or\n * to none — a mixed set measures the optimisation, then reports it as the\n * harness.\n */\nexport function repairArmAsymmetries(\n arms: readonly RepairArm[],\n options: { readonly budget?: InterventionBudget } = {},\n): RepairArmAsymmetryReport {\n if (arms.length === 0) {\n throw new ValidationError('a repair-arm comparison needs at least one arm')\n }\n const declarations = arms.map((arm) => arm.declaration)\n for (const declaration of declarations) assertDeclaration(declaration)\n\n const { ids, repairTurns } = assertEqualDeclarativeTerms(\n 'repair arm',\n declarations.map((declaration) => ({\n id: declaration.id,\n repairTurns: declaration.repairTurns,\n })),\n )\n\n const budget = options.budget ?? declarations[0]!.budget\n const mismatched = declarations.find((declaration) => !sameBudget(declaration.budget, budget))\n if (mismatched) {\n throw new ValidationError(\n `arm '${mismatched.id}' measures actions against ${JSON.stringify(mismatched.budget)}, ` +\n `the comparison runs ${JSON.stringify(budget)}; one arm buying a bigger action than ` +\n 'another is a difference in what was asked, not in what answered',\n )\n }\n\n const certified = declarations.filter(\n (declaration) => declaration.certification.kind === 'certified',\n )\n if (certified.length > 0 && certified.length !== declarations.length) {\n throw new ValidationError(\n `${certified.length}/${declarations.length} arms run certified text ` +\n `(${certified.map((declaration) => declaration.id).join(', ')}); an optimisation applies ` +\n 'to every arm or to none',\n )\n }\n\n const shared = ALL_AFFORDANCES.filter((affordance) =>\n declarations.every((declaration) => declaration.affordances.includes(affordance)),\n )\n const asymmetries = declarations.map((declaration) => ({\n armId: declaration.id,\n extraAffordances: ALL_AFFORDANCES.filter(\n (affordance) =>\n declaration.affordances.includes(affordance) &&\n declarations.some((other) => !other.affordances.includes(affordance)),\n ),\n missingAffordances: ALL_AFFORDANCES.filter(\n (affordance) =>\n !declaration.affordances.includes(affordance) &&\n declarations.some((other) => other.affordances.includes(affordance)),\n ),\n certification: declaration.certification,\n promptSha256: repairArmPromptSha256(declaration.budget, declaration.promptContract),\n }))\n return {\n armIds: ids,\n sharedAffordances: shared,\n asymmetries,\n noArmCertified: certified.length === 0,\n budget,\n repairTurns,\n questionSha256: repairQuestionSha256(budget),\n }\n}\n\nconst ALL_AFFORDANCES: readonly RepairArmAffordance[] = Object.freeze([\n 'inline-trajectory',\n 'trajectory-tools',\n 'code-interpreter',\n 'agent-loop',\n])\n\nfunction sameBudget(a: InterventionBudget, b: InterventionBudget): boolean {\n return (\n a.maxBytes === b.maxBytes &&\n a.maxStatements === b.maxStatements &&\n a.maxHeredocs === b.maxHeredocs\n )\n}\n\nfunction assertDeclaration(declaration: RepairArmDeclaration): void {\n if (\n typeof declaration.id !== 'string' ||\n declaration.id.trim() !== declaration.id ||\n !declaration.id\n ) {\n throw new ValidationError('a repair arm id must be a trimmed non-empty string')\n }\n if (typeof declaration.execution !== 'string' || !declaration.execution.trim()) {\n throw new ValidationError(`arm '${declaration.id}' must state what executes its answer`)\n }\n if (!Number.isInteger(declaration.repairTurns) || declaration.repairTurns < 0) {\n throw new ValidationError(\n `arm '${declaration.id}' repairTurns must be a non-negative integer, got ${declaration.repairTurns}`,\n )\n }\n if (\n declaration.certification.kind === 'none' &&\n (typeof declaration.certification.reason !== 'string' ||\n !declaration.certification.reason.trim())\n ) {\n throw new ValidationError(\n `arm '${declaration.id}' carries no certification and must say why in one sentence`,\n )\n }\n if (\n !Array.isArray(declaration.promptContract) ||\n declaration.promptContract.length === 0 ||\n declaration.promptContract.some((line) => typeof line !== 'string')\n ) {\n throw new ValidationError(\n `arm '${declaration.id}' must declare its contract text as a non-empty array of strings; ` +\n 'the per-arm prompt digest is computed from it',\n )\n }\n for (const affordance of declaration.affordances) {\n if (!ALL_AFFORDANCES.includes(affordance)) {\n throw new ValidationError(\n `arm '${declaration.id}' declares unknown affordance '${affordance}'`,\n )\n }\n }\n}\n\n/** An arm that reports more repair turns than it declared is not the arm the\n * comparison admitted, so the answer never reaches a grader. */\nfunction assertReplyWithinDeclaration(\n declaration: RepairArmDeclaration,\n reply: RepairArmReply,\n): void {\n if (reply.repair.attempted && declaration.repairTurns === 0) {\n throw new ValidationError(\n `arm '${declaration.id}' declares no bounded repair turn but took one`,\n )\n }\n if (reply.status === 'failed' && !reply.failure.trim()) {\n throw new ValidationError(`arm '${declaration.id}' failed without stating why`)\n }\n if (reply.status === 'finding' && !reply.intervention.action) {\n throw new ValidationError(\n `arm '${declaration.id}' returned a finding with an empty intervention`,\n )\n }\n}\n","/**\n * What an analyst is allowed to say about a blinded trajectory prefix.\n *\n * Exactly one of two answers:\n *\n * a finding {k, failureClaim, intervention}\n * the literal string no-decisive-failure\n *\n * Nothing else parses. A finding names one step, states what went wrong\n * there, and supplies one action to run instead. Declining is a real answer\n * with its own cell in the funnel, not a parse failure — an admitted row has\n * a failure by construction, but it need not have a single-action repair, and\n * an analyst that says so is answering the question it was asked.\n */\n\nimport { ValidationError } from '../errors'\nimport type { ActionPayloadKind } from './action-budget'\n\n/** The literal an analyst returns when no single step carries the failure. */\nexport const NO_DECISIVE_FAILURE = 'no-decisive-failure'\n\nexport interface RepairIntervention {\n /** What the action is: a shell command, or an edit that authors file content. */\n readonly kind: ActionPayloadKind\n /** The action itself, exactly as it will be executed at step k. */\n readonly action: string\n}\n\nexport interface RepairFinding {\n readonly kind: 'finding'\n /** 1-based step the analyst blames. The repair must work here; there is no\n * credit for naming a step and repairing elsewhere. */\n readonly k: number\n /** What the analyst says went wrong at step k. Recorded, never scored: a\n * claim graded by another model would put a judge inside the metric. */\n readonly failureClaim: string\n readonly intervention: RepairIntervention\n}\n\nexport interface RepairDeclined {\n readonly kind: 'no-decisive-failure'\n}\n\nexport type AnalystResponse = RepairFinding | RepairDeclined\n\n/** Why a response does not parse. Counted by name in the funnel. */\nexport type ResponseParseFailure =\n | 'unreadable'\n | 'not-a-single-answer'\n | 'missing-k'\n | 'missing-failure-claim'\n | 'missing-intervention'\n | 'unknown-intervention-kind'\n\nexport type ParseAnalystResponseOutcome =\n | { readonly succeeded: true; readonly value: AnalystResponse }\n | { readonly succeeded: false; readonly failure: ResponseParseFailure; readonly detail: string }\n\n/**\n * Read an analyst reply.\n *\n * Accepts the bare literal, or a JSON object carrying one finding. The reply\n * is untrusted text, so every field is checked and nothing is defaulted: a\n * missing `k` is a parse failure, never step 1.\n */\nexport function parseAnalystResponse(reply: string): ParseAnalystResponseOutcome {\n const trimmed = reply.trim()\n if (trimmed.length === 0) {\n return { succeeded: false, failure: 'unreadable', detail: 'the reply is empty' }\n }\n if (trimmed === NO_DECISIVE_FAILURE) {\n return { succeeded: true, value: { kind: 'no-decisive-failure' } }\n }\n\n const json = extractJsonObject(trimmed)\n if (!json) {\n return {\n succeeded: false,\n failure: 'unreadable',\n detail: `expected the literal \"${NO_DECISIVE_FAILURE}\" or one JSON object`,\n }\n }\n if (json.count > 1) {\n return {\n succeeded: false,\n failure: 'not-a-single-answer',\n detail: `the reply carries ${json.count} findings; exactly one is allowed`,\n }\n }\n\n const body = json.value\n if (body.no_decisive_failure === true || body.finding === NO_DECISIVE_FAILURE) {\n return { succeeded: true, value: { kind: 'no-decisive-failure' } }\n }\n\n const k = body.k\n if (typeof k !== 'number' || !Number.isInteger(k)) {\n return {\n succeeded: false,\n failure: 'missing-k',\n detail: `k must be an integer, got ${describe(k)}`,\n }\n }\n const failureClaim = body.failure_claim ?? body.failureClaim\n if (typeof failureClaim !== 'string' || failureClaim.trim().length === 0) {\n return {\n succeeded: false,\n failure: 'missing-failure-claim',\n detail: 'failure_claim must be a non-empty string',\n }\n }\n const raw = body.intervention\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n return {\n succeeded: false,\n failure: 'missing-intervention',\n detail: 'intervention must be an object with kind and action',\n }\n }\n const intervention = raw as Record<string, unknown>\n const action = intervention.action\n if (typeof action !== 'string') {\n return {\n succeeded: false,\n failure: 'missing-intervention',\n detail: 'intervention.action must be a string',\n }\n }\n const kind = intervention.kind\n if (kind !== 'shell' && kind !== 'edit') {\n return {\n succeeded: false,\n failure: 'unknown-intervention-kind',\n detail: `intervention.kind must be \"shell\" or \"edit\", got ${describe(kind)}`,\n }\n }\n\n return {\n succeeded: true,\n value: {\n kind: 'finding',\n k,\n failureClaim: failureClaim.trim(),\n intervention: { kind, action },\n },\n }\n}\n\n/** Build a finding directly, for callers that already hold typed fields. */\nexport function repairFinding(input: {\n k: number\n failureClaim: string\n intervention: RepairIntervention\n}): RepairFinding {\n if (!Number.isInteger(input.k) || input.k < 1) {\n throw new ValidationError(`repair finding k must be a positive integer, got ${input.k}`)\n }\n if (input.failureClaim.trim().length === 0) {\n throw new ValidationError('repair finding requires a non-empty failure claim')\n }\n return {\n kind: 'finding',\n k: input.k,\n failureClaim: input.failureClaim.trim(),\n intervention: input.intervention,\n }\n}\n\nfunction describe(value: unknown): string {\n if (value === null) return 'null'\n if (value === undefined) return 'undefined'\n return typeof value === 'string' ? JSON.stringify(value) : String(value)\n}\n\n/**\n * Pull the single JSON object out of a reply, tolerating a fenced block and\n * surrounding prose. `count` reports how many top-level objects were found so\n * a reply hedging with several findings is rejected rather than silently\n * reduced to the first one.\n */\nfunction extractJsonObject(\n reply: string,\n): { value: Record<string, unknown>; count: number } | null {\n const fenced = [...reply.matchAll(/```(?:json)?\\s*\\n([\\s\\S]*?)```/g)].map((m) => m[1]!.trim())\n const candidates = fenced.length > 0 ? fenced : [reply]\n const parsed: Record<string, unknown>[] = []\n for (const candidate of candidates) {\n for (const slice of topLevelObjectSlices(candidate)) {\n try {\n const value = JSON.parse(slice) as unknown\n if (Array.isArray(value)) {\n for (const item of value) {\n if (isPlainObject(item)) parsed.push(item)\n }\n } else if (isPlainObject(value)) {\n parsed.push(value)\n }\n } catch {\n // A slice that does not parse is not an answer; keep scanning.\n }\n }\n }\n if (parsed.length === 0) return null\n return { value: parsed[0]!, count: parsed.length }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** Balanced `{…}` and `[…]` slices at the top level of a candidate string. */\nfunction topLevelObjectSlices(text: string): string[] {\n const slices: string[] = []\n let depth = 0\n let start = -1\n let inString = false\n let escaped = false\n for (let i = 0; i < text.length; i += 1) {\n const char = text[i]!\n if (inString) {\n if (escaped) escaped = false\n else if (char === '\\\\') escaped = true\n else if (char === '\"') inString = false\n continue\n }\n if (char === '\"') {\n inString = true\n continue\n }\n if (char === '{' || char === '[') {\n if (depth === 0) start = i\n depth += 1\n continue\n }\n if (char === '}' || char === ']') {\n depth -= 1\n if (depth === 0 && start >= 0) {\n slices.push(text.slice(start, i + 1))\n start = -1\n }\n if (depth < 0) depth = 0\n }\n }\n return slices\n}\n","/**\n * The arms that answer over an OpenAI-compatible endpoint.\n *\n * Two arms share this factory because they differ only in what sits behind the\n * URL: `bare-framing` is one chat completion with no harness, `prime` is an\n * agent harness reached through a bridge that speaks the same wire shape. The\n * prompt, the reply grammar, the single bounded repair turn and the row cap\n * are identical, so the difference the comparison measures is the execution\n * path and not the framing.\n *\n * The exchange itself is `runPrimeExchange`: one call, one bounded repair turn\n * on a structurally malformed reply, then decoding. Zero valid rows from a\n * well-formed reply is an honest decline, not a failure.\n */\n\nimport type { PrimeBridgeTransport } from '../analyst/prime-bridge-transport'\nimport {\n analystUsageReceiptFromPrimeUsage,\n buildPrimePrompt,\n type PrimeRawUsage,\n type PrimeReplyContract,\n runPrimeExchange,\n} from '../analyst/prime-protocol'\nimport type { CustomTokenPricing } from '../cost-ledger'\nimport { ValidationError } from '../errors'\nimport type { ActionPayloadKind } from './action-budget'\nimport { type InterventionBudget, SCAFFOLD_INTERVENTION_BUDGET } from './action-budget'\nimport type {\n RepairArm,\n RepairArmAffordance,\n RepairArmCertification,\n RepairArmReply,\n RepairArmRequest,\n RepairArmUsage,\n} from './analyst-arm'\nimport type { BlindedTrajectoryPrefix } from './blinding'\nimport {\n REPAIR_CONTRACT_LINES,\n REPAIR_QUESTION,\n REPAIR_REPAIR_CONTRACT_LINES,\n renderRepairTrajectory,\n repairTaskDefinition,\n repairTrajectoryHeader,\n} from './repair-prompt'\n\n/** One decoded reply row, before it becomes a finding. */\ninterface CompletionRepairRow {\n readonly k: number\n readonly failureClaim: string\n readonly kind: ActionPayloadKind\n readonly action: string\n}\n\nexport interface CompletionRepairArmOptions {\n readonly id: string\n /** What actually answers the POST, in one plain sentence. */\n readonly execution: string\n /** Full endpoint, e.g. `http://127.0.0.1:4200/v1/chat/completions`. */\n readonly url: string\n readonly model: string\n /** Injected so a test drives the arm without a network. */\n readonly transport: PrimeBridgeTransport\n /** Deadline for ONE turn. */\n readonly timeoutMs: number\n /** Rates used to price the reported tokens. */\n readonly pricing: CustomTokenPricing\n readonly budget?: InterventionBudget\n /** What this arm can do that another cannot. */\n readonly affordances: readonly RepairArmAffordance[]\n readonly certification: RepairArmCertification\n}\n\nexport function createCompletionRepairArm(options: CompletionRepairArmOptions): RepairArm {\n if (!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs <= 0) {\n throw new ValidationError(\n `repair arm '${options.id}' timeoutMs must be a positive safe integer, got ${options.timeoutMs}`,\n )\n }\n const budget = options.budget ?? SCAFFOLD_INTERVENTION_BUDGET\n return {\n declaration: {\n id: options.id,\n execution: options.execution,\n certification: options.certification,\n budget,\n // `runPrimeExchange` takes exactly one repair turn on a malformed reply.\n repairTurns: 1,\n affordances: options.affordances,\n // The JSON reply grammar and its repair-turn restatement are this arm's\n // whole contract text; both enter the per-arm prompt digest.\n promptContract: [...REPAIR_CONTRACT_LINES, ...REPAIR_REPAIR_CONTRACT_LINES],\n },\n async ask(request: RepairArmRequest): Promise<RepairArmReply> {\n const prompt = buildPrimePrompt({\n question: REPAIR_QUESTION,\n taskDefinition: repairTaskDefinition(request.prefix, budget),\n contractLines: REPAIR_CONTRACT_LINES,\n trajectoryHeader: repairTrajectoryHeader(request.prefix),\n renderedTrajectory: renderRepairTrajectory(request.prefix),\n })\n const outcome = await runPrimeExchange<CompletionRepairRow>({\n contract: replyContract(request.prefix),\n prompt,\n transport: options.transport,\n url: options.url,\n model: options.model,\n timeoutMs: options.timeoutMs,\n repair: true,\n ...(request.signal ? { signal: request.signal } : {}),\n })\n const usage = armUsage(outcome.usage, options.pricing)\n if (!outcome.ok) {\n return {\n status: 'failed',\n failure: `${outcome.failure.kind}: ${outcome.failure.message}`,\n answer: null,\n rejectedRows: [],\n repair: outcome.repair,\n usage,\n }\n }\n const row = outcome.rows[0]\n if (row === undefined) {\n return {\n status: 'declined',\n answer: outcome.answer,\n reportedRows: outcome.reportedRows,\n rejectedRows: outcome.rejected,\n repair: outcome.repair,\n usage,\n }\n }\n return {\n status: 'finding',\n k: row.k,\n failureClaim: row.failureClaim,\n intervention: { kind: row.kind, action: row.action },\n answer: outcome.answer,\n reportedRows: outcome.reportedRows,\n rejectedRows: outcome.rejected,\n repair: outcome.repair,\n usage,\n }\n },\n }\n}\n\n/**\n * Decode one reply row.\n *\n * Every field is checked and nothing is defaulted: a `k` outside the recorded\n * step ids is a rejected row rather than a clamped one, because an arm that\n * names a step the recording does not hold has not localized anything.\n */\nfunction replyContract(prefix: BlindedTrajectoryPrefix): PrimeReplyContract<CompletionRepairRow> {\n const validSteps = prefix.steps.map((step) => step.step_id)\n return {\n rowsField: 'findings',\n contractLines: REPAIR_CONTRACT_LINES,\n repairContractLines: REPAIR_REPAIR_CONTRACT_LINES,\n maxRows: 1,\n decodeRow(row, index) {\n if (typeof row !== 'object' || row === null || Array.isArray(row)) {\n return { ok: false, reason: `row ${index} is not an object` }\n }\n const record = row as Record<string, unknown>\n const k = record.k\n if (!Number.isInteger(k) || !validSteps.includes(k as number)) {\n return {\n ok: false,\n reason: `k must be a recorded step_id in [${validSteps[0] ?? 1}, ${prefix.maxK}], got ${describe(k)}`,\n }\n }\n const claim = record.failure_claim ?? record.failureClaim\n if (typeof claim !== 'string' || claim.trim().length === 0) {\n return { ok: false, reason: 'failure_claim must be a non-empty string' }\n }\n const raw = record.intervention\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n return { ok: false, reason: 'intervention must be an object with kind and action' }\n }\n const intervention = raw as Record<string, unknown>\n const action = intervention.action\n if (typeof action !== 'string' || action.length === 0) {\n return { ok: false, reason: 'intervention.action must be a non-empty string' }\n }\n const kind = intervention.kind\n if (kind !== 'shell' && kind !== 'edit') {\n return {\n ok: false,\n reason: `intervention.kind must be \"shell\" or \"edit\", got ${describe(kind)}`,\n }\n }\n return {\n ok: true,\n row: { k: k as number, failureClaim: claim.trim(), kind, action },\n }\n },\n }\n}\n\nfunction armUsage(usage: PrimeRawUsage, pricing: CustomTokenPricing): RepairArmUsage {\n const receipt = analystUsageReceiptFromPrimeUsage(usage, pricing)\n return {\n calls: usage.calls,\n inputTokens: usage.inputTokens,\n outputTokens: usage.outputTokens,\n // A one-sided token count prices to a lower bound, which the receipt\n // reports separately from a complete cost. Neither becomes a zero.\n costUsd: receipt.cost.usd ?? receipt.knownCostUsd ?? null,\n }\n}\n\nfunction describe(value: unknown): string {\n if (value === null) return 'null'\n if (value === undefined) return 'undefined'\n return typeof value === 'string' ? JSON.stringify(value) : String(value)\n}\n","/**\n * The DSPy arm on the repair contract.\n *\n * THIS ARM CARRIES NO CERTIFICATION ON THIS TASK, and the code says so rather\n * than leaving a reader to assume otherwise. The one GEPA-certified analyst\n * artifact this repository holds — `oht2-coverage-instructions.txt` — was\n * earned on the CodeTraceBench incorrect-step task, whose output contract is a\n * set of blocks carrying `first_step`, `last_step`, `consequence_step` and\n * `escape_status` over recorded steps that were wrong. The repair task asks a\n * different question with a different answer: one step k, and one executable\n * action of the same type and budget the scaffold itself took, which must make\n * a held-out suite pass. Re-authoring the certified text for that contract\n * would void the certification, because the benchmark it was earned on has\n * been retired. So the instruction text here is authored fresh for the repair\n * task and declared uncertified.\n *\n * What DOES carry over is the engine, and that is the point of the arm: a DSPy\n * program with a typed signature, a structured module, and a code environment\n * it reads the subject with. The trajectory is delivered as a typed input\n * bound as a REPL variable rather than parsed back out of prompt text, which\n * is the difference between this arm and the ones that answer over a chat\n * completion.\n *\n * The typed repair rows travel back in `runtime.repair`, not in `findings`.\n * The engine-neutral finding schema caps `recommended_action` at 2000\n * characters while the scaffold action budget is 4096 bytes, so routing a\n * repair through it would hand this arm a smaller action than every other arm\n * gets — an affordance asymmetry hidden inside a schema. The measured\n * comparison run shows why that matters: chat-completion arms returned actions\n * of 2705, 3413, 3987 and 4733 bytes.\n */\n\nimport type { TraceAnalysisEngine, TraceAnalystLimits } from '../analyst/engine'\nimport type { CostLedgerHandle } from '../cost-ledger'\nimport { ValidationError } from '../errors'\nimport {\n type ActionPayloadKind,\n type InterventionBudget,\n SCAFFOLD_INTERVENTION_BUDGET,\n} from './action-budget'\nimport type {\n RepairArm,\n RepairArmRejectedRow,\n RepairArmReply,\n RepairArmRequest,\n RepairArmUsage,\n} from './analyst-arm'\nimport { REPAIR_QUESTION, repairTaskPolicy } from './repair-prompt'\n\n/**\n * Token the bridge reads to select the typed repair signature.\n *\n * The wire protocol carries instructions as opaque text, so the task is named\n * inside them rather than by adding a field every unrelated caller would have\n * to set. The same mechanism selects the CodeTraceBench typed signature.\n */\nexport const DSPY_REPAIR_TASK_TOKEN = 'tb-repair-typed-'\n\n/** Signature the bridge reports for a repair analysis. */\nexport const DSPY_REPAIR_SIGNATURE = 'tb-repair-typed-v1'\n\n/** The name the trajectory is bound to inside the program's environment. */\nexport const DSPY_REPAIR_TRAJECTORY_INPUT = 'trajectory'\n\n/**\n * The repair contract restated for the typed signature.\n *\n * Transport differs from the chat-completion arms — typed SUBMIT instead of a\n * fenced JSON object — and the QUESTION does not. Both read from\n * `repairTaskPolicy`, so the execution rules an arm is held to cannot drift\n * between arms.\n */\nexport function dspyRepairInstructions(\n budget: InterventionBudget = SCAFFOLD_INTERVENTION_BUDGET,\n): string {\n return [\n `TASK ${DSPY_REPAIR_TASK_TOKEN}${DSPY_REPAIR_SIGNATURE}`,\n '',\n ...repairTaskPolicy(budget),\n '',\n `The recorded trajectory is already loaded into your environment as \\`${DSPY_REPAIR_TRAJECTORY_INPUT}\\`,`,\n 'a list of {step_id, action, observation} objects in recorded order. Read it with code',\n 'rather than re-fetching it, and do not claim to have inspected anything you did not read.',\n '',\n 'SUBMIT at most ONE repair, shaped as:',\n '- k: the step_id whose action you replace. It must be a step_id present in the trajectory.',\n '- failure_claim: what went wrong at step k. Recorded, never scored.',\n '- intervention_kind: \"edit\" when the action authors a file with a heredoc, \"shell\" otherwise.',\n `- action: the EXACT shell text to run instead, at most ${budget.maxBytes} bytes and exactly`,\n ` ${budget.maxStatements === 1 ? 'one top-level statement' : `${budget.maxStatements} top-level statements`}. It is executed verbatim: not a description, not a diff, not a plan.`,\n 'SUBMIT an empty list only when no single replacement action could make the suite pass.',\n ].join('\\n')\n}\n\nexport interface DspyRepairArmOptions {\n /** The DSPy engine. Injected, so a test drives the arm with no subprocess. */\n readonly engine: TraceAnalysisEngine\n readonly limits: TraceAnalystLimits\n readonly costLedger: CostLedgerHandle\n readonly costPhase: string\n readonly analystId: string\n readonly costTags?: Record<string, string>\n readonly budget?: InterventionBudget\n readonly id?: string\n readonly log?: (message: string, fields?: Record<string, unknown>) => void\n}\n\nexport function createDspyRepairArm(options: DspyRepairArmOptions): RepairArm {\n assertDspyRepairEngine(options.engine)\n const budget = options.budget ?? SCAFFOLD_INTERVENTION_BUDGET\n const instructions = dspyRepairInstructions(budget)\n return {\n declaration: {\n id: options.id ?? 'dspy-rlm',\n execution: `DSPy RLM program (${options.engine.id} v${options.engine.version}) with a typed repair signature and a code environment`,\n certification: {\n kind: 'none',\n reason:\n 'the GEPA-certified analyst text was earned on the CodeTraceBench incorrect-step ' +\n 'contract, which asks for blocks of wrong steps rather than one executable repair; ' +\n 'this arm runs instruction text authored for the repair contract and certified by nothing',\n },\n budget,\n // The bridge takes exactly one bounded structured re-read when the typed\n // field comes back as text, which is the same single retry the\n // chat-completion arms get for a malformed reply.\n repairTurns: 1,\n affordances: ['inline-trajectory', 'code-interpreter', 'agent-loop'],\n // The instruction text names the signature version, so bumping\n // DSPY_REPAIR_SIGNATURE changes the per-arm prompt digest.\n promptContract: [instructions],\n },\n async ask(request: RepairArmRequest): Promise<RepairArmReply> {\n const steps = request.prefix.steps.map((step) => ({\n step_id: step.step_id,\n action: step.action,\n observation: step.observation,\n }))\n let result: Awaited<ReturnType<TraceAnalysisEngine['analyze']>>\n try {\n result = await options.engine.analyze({\n analystId: options.analystId,\n question: [\n REPAIR_QUESTION,\n '',\n `The trajectory has ${steps.length} recorded steps, step_ids ${steps\n .map((step) => step.step_id)\n .join(', ')}.`,\n ].join('\\n'),\n instructions,\n tools: [],\n taskInputs: {\n [DSPY_REPAIR_TRAJECTORY_INPUT]: steps,\n taskStatement: request.prefix.taskStatement,\n },\n limits: options.limits,\n costLedger: options.costLedger,\n costPhase: options.costPhase,\n ...(options.costTags ? { costTags: options.costTags } : {}),\n ...(request.signal ? { signal: request.signal } : {}),\n ...(options.log ? { log: options.log } : {}),\n })\n } catch (error) {\n return {\n status: 'failed',\n failure: `engine threw: ${error instanceof Error ? error.message : String(error)}`,\n answer: null,\n rejectedRows: [],\n repair: { attempted: false, succeeded: null },\n usage: engineUsage(null),\n }\n }\n const payload = readRepairPayload(result.runtime, {\n validSteps: steps.map((step) => step.step_id),\n })\n const usage = engineUsage(result.modelCalls)\n if (!payload.ok) {\n // The engine answered, but not under the repair contract. That is a\n // wiring fault or a signature mismatch, never an honest decline, so it\n // is reported as a failure with the reason attached.\n return {\n status: 'failed',\n failure: payload.reason,\n answer: result.answer,\n rejectedRows: [],\n repair: { attempted: false, succeeded: null },\n usage,\n }\n }\n const { rows, dropped, repair, reported, failure } = payload.value\n // Succeeded means the re-read produced a well-formed reply — the same\n // definition the chat-completion arms record — so a recovered empty\n // list, an honest decline, is a repair turn that succeeded.\n const repairTurn = {\n attempted: repair !== null,\n succeeded: repair === null ? null : failure === null,\n }\n if (failure !== null) {\n return {\n status: 'failed',\n failure,\n answer: result.answer,\n rejectedRows: dropped,\n repair: repairTurn,\n usage,\n }\n }\n const row = rows[0]\n if (row === undefined) {\n return {\n status: 'declined',\n answer: result.answer,\n reportedRows: reported,\n rejectedRows: dropped,\n repair: repairTurn,\n usage,\n }\n }\n return {\n status: 'finding',\n k: row.k,\n failureClaim: row.failureClaim,\n intervention: { kind: row.kind, action: row.action },\n answer: result.answer,\n reportedRows: reported,\n rejectedRows: dropped,\n repair: repairTurn,\n usage,\n }\n },\n }\n}\n\ninterface DspyRepairRow {\n readonly k: number\n readonly failureClaim: string\n readonly kind: ActionPayloadKind\n readonly action: string\n}\n\ninterface DspyRepairPayload {\n readonly signature: string\n readonly reported: number\n readonly rows: readonly DspyRepairRow[]\n readonly dropped: readonly RepairArmRejectedRow[]\n /** How the bounded structured re-read recovered the typed field, or null\n * when the field arrived typed and no re-read was needed. */\n readonly repair: string | null\n /** The bridge's own account of a typed field it could not read — a reply\n * that stayed malformed after the bounded re-read. The analysis completed,\n * so the answer text survives beside it; null on a readable reply. */\n readonly failure: string | null\n}\n\ntype ReadRepairPayload =\n | { readonly ok: true; readonly value: DspyRepairPayload }\n | { readonly ok: false; readonly reason: string }\n\nexport interface ReadRepairPayloadOptions {\n /** The step ids the blinded prefix holds. A row naming any other k is the\n * model's mistake, not the bridge's, so it lands in `dropped` — the same\n * rejected-row path the chat-completion arms take — never in a finding the\n * grader would refuse as out of range. */\n readonly validSteps: readonly number[]\n}\n\n/**\n * Read the bridge's typed repair block.\n *\n * Structure is checked and fails loud: a missing block, a wrong signature, or\n * a row that does not carry an integer k and a non-empty action is a wiring\n * fault with a reason — never a default, and never an empty list that would\n * grade as a decline the program did not make. A structurally sound row whose\n * k is not a recorded step id is the model's mistake, and it is dropped with\n * its reason instead.\n */\nexport function readRepairPayload(\n runtime: Record<string, unknown>,\n options: ReadRepairPayloadOptions,\n): ReadRepairPayload {\n const block = runtime.repair\n if (!isRecord(block)) {\n return {\n ok: false,\n reason:\n 'the engine returned no runtime.repair block; the bridge did not run the typed repair signature',\n }\n }\n if (block.signature !== DSPY_REPAIR_SIGNATURE) {\n return {\n ok: false,\n reason: `runtime.repair.signature is ${describe(block.signature)}, expected \"${DSPY_REPAIR_SIGNATURE}\"`,\n }\n }\n if (!Number.isSafeInteger(block.reported) || (block.reported as number) < 0) {\n return {\n ok: false,\n reason: `runtime.repair.reported must be a non-negative integer, got ${describe(block.reported)}`,\n }\n }\n if (!Array.isArray(block.rows)) {\n return { ok: false, reason: 'runtime.repair.rows must be an array' }\n }\n const repair = block.repair\n if (repair !== null && typeof repair !== 'string') {\n return {\n ok: false,\n reason: `runtime.repair.repair must be a string or null, got ${describe(repair)}`,\n }\n }\n const rawFailure = block.failure\n if (rawFailure !== undefined && rawFailure !== null && typeof rawFailure !== 'string') {\n return {\n ok: false,\n reason: `runtime.repair.failure must be a string or null, got ${describe(rawFailure)}`,\n }\n }\n const failure = typeof rawFailure === 'string' ? rawFailure : null\n const dropped: RepairArmRejectedRow[] = []\n if (block.dropped !== undefined) {\n if (!Array.isArray(block.dropped)) {\n return { ok: false, reason: 'runtime.repair.dropped must be an array' }\n }\n for (const [index, raw] of block.dropped.entries()) {\n if (!isRecord(raw) || typeof raw.reason !== 'string') {\n return {\n ok: false,\n reason: `runtime.repair.dropped[${index}] must carry a reason string`,\n }\n }\n dropped.push({\n index: Number.isSafeInteger(raw.index) ? (raw.index as number) : index,\n reason: raw.reason,\n })\n }\n }\n const rows: DspyRepairRow[] = []\n for (const [index, raw] of block.rows.entries()) {\n const decoded = decodeRepairRow(raw)\n if (!decoded.ok) {\n return { ok: false, reason: `runtime.repair.rows[${index}]: ${decoded.reason}` }\n }\n if (!options.validSteps.includes(decoded.row.k)) {\n dropped.push({\n index,\n reason: `k must be a recorded step_id in [${options.validSteps[0] ?? 1}, ${options.validSteps[options.validSteps.length - 1] ?? 1}], got ${decoded.row.k}`,\n })\n continue\n }\n if (rows.length >= 1) {\n // The bridge caps at one repair; a second valid row here means the cap\n // regressed, and the surplus is recorded rather than silently discarded.\n dropped.push({ index, reason: 'exceeds the one-repair cap' })\n continue\n }\n rows.push(decoded.row)\n }\n return {\n ok: true,\n value: {\n signature: DSPY_REPAIR_SIGNATURE,\n reported: block.reported as number,\n rows,\n dropped,\n repair: repair ?? null,\n failure,\n },\n }\n}\n\nfunction decodeRepairRow(\n raw: unknown,\n): { ok: true; row: DspyRepairRow } | { ok: false; reason: string } {\n if (!isRecord(raw)) return { ok: false, reason: 'not an object' }\n const k = raw.k\n if (!Number.isInteger(k) || (k as number) < 1) {\n return { ok: false, reason: `k must be a positive integer, got ${describe(k)}` }\n }\n const claim = raw.failure_claim\n if (typeof claim !== 'string' || claim.trim().length === 0) {\n return { ok: false, reason: 'failure_claim must be a non-empty string' }\n }\n const intervention = raw.intervention\n if (!isRecord(intervention)) {\n return { ok: false, reason: 'intervention must be an object with kind and action' }\n }\n const kind = intervention.kind\n if (kind !== 'shell' && kind !== 'edit') {\n return {\n ok: false,\n reason: `intervention.kind must be \"shell\" or \"edit\", got ${describe(kind)}`,\n }\n }\n const action = intervention.action\n if (typeof action !== 'string' || action.length === 0) {\n return { ok: false, reason: 'intervention.action must be a non-empty string' }\n }\n return { ok: true, row: { k: k as number, failureClaim: claim.trim(), kind, action } }\n}\n\n/**\n * The engine reports model calls; token counts and cost live in the caller's\n * cost ledger, which meters the proxy the engine ran through. Reporting them\n * here as zero would state a measurement this arm did not make.\n */\nfunction engineUsage(modelCalls: number | null): RepairArmUsage {\n return { calls: modelCalls, inputTokens: null, outputTokens: null, costUsd: null }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction describe(value: unknown): string {\n if (value === null) return 'null'\n if (value === undefined) return 'undefined'\n return typeof value === 'string' ? JSON.stringify(value) : String(value)\n}\n\n/** Thrown by callers that build a repair arm with a non-DSPy engine. */\nexport function assertDspyRepairEngine(engine: TraceAnalysisEngine): void {\n if (engine.id !== 'dspy-rlm') {\n throw new ValidationError(\n `the DSPy repair arm needs the dspy-rlm engine, got '${engine.id}'; another engine ` +\n 'does not run the typed repair signature and would answer a different contract',\n )\n }\n}\n","/**\n * Records the continuation runner produces, and the projection back into the\n * shape the Terminal-Bench-2 trajectory corpus stores.\n *\n * The replay layer reads recorded trajectories as\n * `{ src, msg, tools, obs }` steps. A continuation that emitted a private\n * shape would need a second reader and would drift from it, so the rollout\n * projects into the same four fields.\n */\n\nimport type { CostProvenance } from '../cost-ledger'\nimport type { RunTokenUsage } from '../run-record'\nimport { contentHash } from '../verdict-cache'\nimport { parseAction } from './mini-swe-scaffold'\n\n/** Which arm produced a rollout. The policy is identical across all three. */\nexport type ContinuationArm = 'intervention' | 'no-fix-control' | 'no-op-control'\n\n/** Chat message in the scaffold's own vocabulary. */\nexport interface ContinuationMessage {\n role: 'system' | 'user' | 'assistant'\n content: string\n}\n\n/** Why a rollout stopped. */\nexport type ContinuationExitStatus =\n | 'submitted'\n | 'step-budget-exhausted'\n | 'repeated-format-error'\n | 'model-error'\n | 'environment-error'\n\nexport interface ContinuationExecRecord {\n command: string\n returncode: number\n /** True when the environment killed the command at the policy timeout. */\n timedOut: boolean\n outputChars: number\n durationMs: number\n}\n\nexport interface ContinuationModelCall {\n /** Model id the provider reported serving, which can differ from the requested id. */\n servedModel: string\n seed: number\n latencyMs: number\n /** `null` when the provider reported no usage. Never a zero-filled stand-in. */\n usage: RunTokenUsage | null\n /** `null` when neither the provider nor local pricing produced an amount. */\n costUsd: number | null\n finishReason: string | null\n contentChars: number\n}\n\nexport interface ContinuationStepRecord {\n /** 1-based index within the continuation, not within the whole trajectory. */\n step: number\n assistantMessage: string\n /** `null` when the turn held zero or several bash blocks. */\n action: string | null\n /**\n * `null` when the command that ran ended the rollout: the submission\n * sentinel gets no observation, which is how the corpus records a finished\n * run, and a failed environment call produces none either.\n */\n observation: string | null\n /** `null` when no command ran, so a format error is never read as an exit-0 command. */\n execution: ContinuationExecRecord | null\n model: ContinuationModelCall\n /** Environment failure that ended the rollout at this step. */\n error?: string\n}\n\nexport interface ContinuationUsageTotals {\n /**\n * Recorded model calls. A call that threw produced no step, so it is absent\n * here and named in `terminalError` instead.\n */\n calls: number\n /** Calls that carried usage. Below `calls` means the totals cover part of the rollout. */\n callsWithUsage: number\n /** True only when every call reported usage. */\n captured: boolean\n input: number\n output: number\n reasoning?: number\n cached?: number\n cacheWrite?: number\n}\n\nexport interface ContinuationEnvironmentDescription {\n /** Docker network mode of the container. The policy admits `none` only. */\n networkMode: string\n image?: string\n}\n\nexport interface ContinuationRollout {\n rolloutId: string\n arm: ContinuationArm\n /** Corpus row the continuation belongs to. Pairs rollouts across arms. */\n rowId: string\n /** 0-based rollout index within the arm. */\n index: number\n /** Seed handed to the model for every call in this rollout. */\n seed: number\n /** Hash over the policy and scaffold templates. Equal across arms by construction. */\n policyDigest: string\n environmentId: string\n containerRef: string\n environment: ContinuationEnvironmentDescription\n steps: ContinuationStepRecord[]\n exitStatus: ContinuationExitStatus\n /** Text after the sentinel line, present only on `submitted`. */\n submission: string | null\n usage: ContinuationUsageTotals\n costProvenance: CostProvenance\n wallMs: number\n startedAt: string\n endedAt: string\n /** Message from the model or environment failure that ended the rollout. */\n terminalError?: string\n}\n\n/** A tool call in corpus shape. */\nexport interface RecordedToolCall {\n fn: 'bash_command'\n cmd: string\n}\n\n/** One trajectory step in corpus shape. */\nexport interface RecordedStep {\n src: 'system' | 'user' | 'agent'\n msg: string\n tools: RecordedToolCall[] | null\n obs: string | null\n}\n\n/**\n * Project a full message list into corpus steps: the system and task messages\n * become their own steps, and every assistant turn carries the command it\n * requested plus the observation that answered it. A trailing assistant turn\n * with no answer keeps `obs: null`, which is how the corpus records a run that\n * ended on its last command.\n */\nexport function toRecordedSteps(messages: readonly ContinuationMessage[]): RecordedStep[] {\n const steps: RecordedStep[] = []\n for (let i = 0; i < messages.length; i += 1) {\n const message = messages[i]\n if (!message) continue\n if (message.role === 'assistant') {\n const parsed = parseAction(message.content)\n const next = messages[i + 1]\n steps.push({\n src: 'agent',\n msg: message.content,\n tools: parsed.kind === 'action' ? [{ fn: 'bash_command', cmd: parsed.command }] : null,\n obs: next && next.role === 'user' ? next.content : null,\n })\n continue\n }\n if (message.role === 'system') {\n steps.push({ src: 'system', msg: message.content, tools: null, obs: null })\n continue\n }\n // A user message that answers an assistant turn is that turn's observation,\n // already attached above. Only the leading task message stands alone.\n const previous = messages[i - 1]\n if (!previous || previous.role === 'system') {\n steps.push({ src: 'user', msg: message.content, tools: null, obs: null })\n }\n }\n return steps\n}\n\n/** Corpus steps for the continuation alone, excluding the prefix it inherited. */\nexport function rolloutRecordedSteps(rollout: ContinuationRollout): RecordedStep[] {\n return rollout.steps.map((step) => ({\n src: 'agent',\n msg: step.assistantMessage,\n tools: step.action === null ? null : [{ fn: 'bash_command', cmd: step.action }],\n obs: step.observation,\n }))\n}\n\n/**\n * Hash over everything the policy determines: the actions taken, the\n * observations they produced, the seeds, the exit, and the usage.\n *\n * Wall-clock fields are excluded because they vary between identical runs;\n * two rollouts with the same digest did the same work, whatever they cost in\n * seconds. Use it to assert determinism, never to assert equal latency.\n */\nexport function rolloutDigest(rollout: ContinuationRollout): string {\n return contentHash({\n arm: rollout.arm,\n rowId: rollout.rowId,\n index: rollout.index,\n seed: rollout.seed,\n policyDigest: rollout.policyDigest,\n exitStatus: rollout.exitStatus,\n submission: rollout.submission,\n usage: rollout.usage,\n costUsd: rollout.costProvenance.usd,\n costKind: rollout.costProvenance.kind,\n steps: rollout.steps.map((step) => ({\n step: step.step,\n assistantMessage: step.assistantMessage,\n action: step.action,\n observation: step.observation,\n returncode: step.execution?.returncode ?? null,\n timedOut: step.execution?.timedOut ?? null,\n seed: step.model.seed,\n servedModel: step.model.servedModel,\n usage: step.model.usage,\n costUsd: step.model.costUsd,\n })),\n })\n}\n","/**\n * The strategies that would score without repairing anything, named here so a\n * reviewer can check each one against the mechanism that defeats it and a\n * test can be required for each.\n *\n * Two kinds of defeat, and the difference matters:\n *\n * gate the grader refuses the answer before spending a rollout\n * measurement the answer runs and measures the same as its control\n *\n * A gate is cheap and certain. A measurement defeat is the honest one where\n * no syntactic rule can decide — a semantic no-op looks like a repair until\n * the tests disagree with it — and it costs rollouts to establish.\n */\n\nexport type DegenerateDefeatKind = 'gate' | 'measurement'\n\nexport interface DegenerateStrategy {\n readonly id: string\n /** What the analyst does to score without repairing. */\n readonly strategy: string\n /** The mechanism that removes the reward. */\n readonly defeat: string\n readonly defeatKind: DegenerateDefeatKind\n /** Module that carries the mechanism. */\n readonly enforcedIn: string\n}\n\nexport const DEGENERATE_STRATEGIES = [\n {\n id: 'point-at-any-nonzero-exit-step',\n strategy:\n 'Name the first step with a nonzero returncode, claim it failed, and let the reproduction gate confirm it.',\n defeat:\n 'Reproduction is a gate, not a tier that pays. The credit vector has no term for it, so a reproduced step with no working intervention scores exactly what an unreproduced one scores: nothing.',\n defeatKind: 'gate',\n enforcedIn: 'funnel.ts (repairCredit has no reproduction term)',\n },\n {\n id: 'propose-the-recorded-command-again',\n strategy:\n 'Return the action the agent already ran at step k, so the arm reproduces the recorded state and looks like a faithful replay.',\n defeat:\n 'The intervention is compared against the recorded action at k after whitespace normalisation and rejected before a container opens.',\n defeatKind: 'gate',\n enforcedIn: 'grade.ts (recorded-action-reproposed rejection)',\n },\n {\n id: 'propose-a-no-op',\n strategy:\n 'Return an action that changes nothing, so the arm inherits whatever the trajectory would have done anyway.',\n defeat:\n 'Literal no-ops are rejected at the budget check. A semantic no-op cannot be detected syntactically, so it runs and measures at the no-op control floor: its paired delta is zero.',\n defeatKind: 'measurement',\n enforcedIn: 'action-budget.ts (NO_OP_ACTIONS) and delta-repair.ts (paired delta)',\n },\n {\n id: 'submit-instead-of-repair',\n strategy:\n 'Return the submit sentinel so the run ends immediately and the arm terminates cleanly.',\n defeat:\n 'An action carrying the submit sentinel is rejected at the budget check. Ending the run is what the recorded agent already did and the tests already failed on it.',\n defeatKind: 'gate',\n enforcedIn: 'action-budget.ts (SUBMIT_SENTINEL rejection)',\n },\n {\n id: 'touch-the-test-suite',\n strategy:\n \"Write a passing suite, or a reward file, at the path the grader will read, so the oracle grades the trajectory's own artifact.\",\n defeat:\n 'The oracle purges the suite root and uploads the held-out suite from outside the session at grade time, then verifies the bytes it reads back. A planted suite is overwritten; a session that refuses the overwrite raises a tamper error instead of returning a pass.',\n defeatKind: 'gate',\n enforcedIn: 'test-oracle.ts (purge, upload, read-back digest)',\n },\n {\n id: 'buy-a-bigger-action',\n strategy:\n 'Return a multi-command script or a whole-file rewrite that does far more than one scaffold turn could.',\n defeat:\n 'The budget counts top-level statements, heredocs and bytes. More than one action, more than one authored file, or more than 4 KB is rejected before a container opens.',\n defeatKind: 'gate',\n enforcedIn: 'action-budget.ts (checkInterventionBudget)',\n },\n {\n id: 'decline-every-hard-row',\n strategy:\n 'Answer no-decisive-failure on everything except the rows that are obviously repairable, so the reported rate is computed on an easy subset.',\n defeat:\n 'A declined row keeps its cell in the funnel and stays in the denominator with a paired delta of zero, because its intervention arm is definitionally its control arm. Declining cannot raise the headline; it can only dilute it.',\n defeatKind: 'measurement',\n enforcedIn: 'grade.ts (declined outcome) and delta-repair.ts (full admitted denominator)',\n },\n {\n id: 'repair-somewhere-other-than-k',\n strategy:\n 'Name a plausible-looking k, then submit an intervention that fixes the task from any state, so the answer scores without localising anything.',\n defeat:\n 'The intervention is executed at the k the analyst named, on the state produced by replaying steps 1..k-1. There is no separate localisation credit to win and no label the grader reads, so a wrong k is only penalised through the repair failing to work there.',\n defeatKind: 'measurement',\n enforcedIn: 'grade.ts (the intervention is applied at the named k only)',\n },\n] as const satisfies readonly DegenerateStrategy[]\n\nexport type DegenerateStrategyId = (typeof DEGENERATE_STRATEGIES)[number]['id']\n\nexport function degenerateStrategy(id: DegenerateStrategyId): DegenerateStrategy {\n const found = DEGENERATE_STRATEGIES.find((entry) => entry.id === id)\n if (!found) throw new Error(`unknown degenerate strategy: ${id}`)\n return found\n}\n","/**\n * The five-tier funnel and the only thing in it that pays.\n *\n * t0 parsed one finding or the literal decline, inside the budget\n * t1 reproduced the recorded state at k comes back under replay\n * t2 executes the intervention runs at k\n * t3 local flip the held-out suite passes immediately after it\n * t4 repair flip the suite passes after the pinned policy continues\n *\n * t0, t1 and t2 are nested gates. t3 and t4 are two different measurements of\n * the same intervention and neither contains the other: an intervention that\n * fixes the task outright flips locally, and one that unblocks an agent which\n * still has work left flips only after the continuation.\n *\n * `t1` is a gate that pays nothing, and that is structural rather than a\n * convention: `RepairCredit` has no reproduction term, so there is no field to\n * award. Naming a step whose nonzero exit reproduces earns exactly what naming\n * one that does not earns.\n *\n * Reproduction is deliberately not \"a nonzero exit came back\". Most admitted\n * rows end on a clean exit — the agent believed it was finished and the tests\n * disagreed — so the gate asks whether the RECORDED state at k reproduces,\n * whatever that state was, including a returncode of zero.\n */\n\nimport type { BudgetMeasurement, BudgetViolation } from './action-budget'\nimport type { ResponseParseFailure } from './analyst-response'\nimport type { RepairContinuationOutcome } from './ports'\n\n/** Why an answer never reached the reproduction gate. */\nexport type RepairRejection =\n | { readonly source: 'parse'; readonly reason: ResponseParseFailure; readonly detail: string }\n | {\n readonly source: 'budget'\n readonly reason: BudgetViolation\n readonly detail: string\n readonly measurement: BudgetMeasurement\n }\n | {\n readonly source: 'target'\n readonly reason: 'k-out-of-range' | 'recorded-action-reproposed'\n readonly detail: string\n }\n\nexport interface PrefixReplayEvidence {\n /** Recorded steps 1..k-1 executed to rebuild the state at k. */\n readonly stepsReplayed: number\n /** Replayed steps whose exit code differed from the recorded returncode. */\n readonly divergences: number\n readonly wallMs: number\n}\n\n/**\n * What the reproduction gate observed at k.\n *\n * `signature` and `signatureObserved` are null together when the recorded\n * observation carried no error line; the gate then rests on the returncode\n * alone and says so through `basis`.\n */\nexport type ReproductionEvidence =\n | {\n /** The step recorded no observation, so there is no state to reproduce.\n * The gate passes vacuously and no container is opened for it. */\n readonly basis: 'no-recorded-observation'\n readonly reproduced: true\n }\n | {\n readonly basis: 'returncode-only' | 'returncode+output-substring'\n readonly reproduced: boolean\n readonly recordedReturncode: number\n readonly observedExitCode: number\n readonly signature: string | null\n readonly signatureObserved: boolean | null\n readonly prefix: PrefixReplayEvidence\n }\n\nexport interface InterventionExecution {\n readonly command: string\n readonly exitCode: number\n readonly timedOut: boolean\n readonly wallMs: number\n readonly output: string\n readonly prefix: PrefixReplayEvidence\n}\n\nexport interface TestRunEvidence {\n readonly passed: boolean\n readonly exitCode: number\n readonly timedOut: boolean\n /** Digest of the suite the oracle read back from inside the container. */\n readonly suiteDigest: string\n}\n\n/**\n * One repair rollout.\n *\n * A rollout whose intervention failed to run is kept and counted as a\n * non-pass rather than dropped. Dropping it would quietly remove the rollouts\n * where the environment behaved worst, which is the direction that flatters\n * the intervention.\n */\nexport type RepairRolloutEvidence =\n | {\n readonly rolloutIndex: number\n readonly status: 'completed'\n readonly interventionExitCode: number\n readonly continuation: RepairContinuationOutcome\n readonly tests: TestRunEvidence\n }\n | {\n readonly rolloutIndex: number\n readonly status: 'intervention-failed'\n readonly interventionExitCode: number\n readonly timedOut: boolean\n }\n\nexport interface RepairArmEvidence {\n /** Rollouts attempted. The denominator of `repairRate`. */\n readonly rollouts: number\n /** Rollouts whose held-out suite passed. */\n readonly passes: number\n /** Rollouts where the intervention did not run, counted as non-passes. */\n readonly interventionFailures: number\n /** Policy digest every completed rollout reported, checked against the\n * controls. Null when no rollout completed. */\n readonly policyDigest: string | null\n readonly rolloutEvidence: readonly RepairRolloutEvidence[]\n}\n\n/**\n * The deepest state an answer reached.\n *\n * Only `measured` carries a repair, so a gate that closed has no field a score\n * could read.\n */\nexport type RepairGrade =\n | { readonly outcome: 'rejected'; readonly rejection: RepairRejection }\n | { readonly outcome: 'declined' }\n | {\n readonly outcome: 'not-reproduced'\n readonly k: number\n readonly reproduction: ReproductionEvidence\n }\n | {\n readonly outcome: 'did-not-execute'\n readonly k: number\n readonly reproduction: ReproductionEvidence\n readonly execution: InterventionExecution\n }\n | {\n readonly outcome: 'measured'\n readonly k: number\n readonly reproduction: ReproductionEvidence\n readonly execution: InterventionExecution\n readonly localFlip: TestRunEvidence\n readonly repair: RepairArmEvidence\n }\n\n/**\n * Everything an answer earns.\n *\n * Three numeric terms and no reproduction term. A vector rather than a scalar\n * because the three measure different things: whether the action ran, whether\n * it fixed the task outright, and how often it led to a fix once the agent\n * carried on.\n */\nexport interface RepairCredit {\n readonly executes: 0 | 1\n readonly localFlip: 0 | 1\n /** Share of repair rollouts whose held-out suite passed. */\n readonly repairRate: number\n}\n\n/**\n * Compile-time proof that no reproduction term can be added to the credit\n * vector without breaking `pnpm typecheck`. A tier that pays nothing must have\n * nothing to pay into.\n */\ntype CreditHasNoReproductionTerm =\n Extract<keyof RepairCredit, `${string}eproduc${string}`> extends never ? true : never\nconst _creditHasNoReproductionTerm: CreditHasNoReproductionTerm = true\nvoid _creditHasNoReproductionTerm\n\nexport const CREDIT_TERMS = [\n 'executes',\n 'localFlip',\n 'repairRate',\n] as const satisfies readonly (keyof RepairCredit)[]\n\nconst ZERO_CREDIT: RepairCredit = Object.freeze({ executes: 0, localFlip: 0, repairRate: 0 })\n\n/** What an answer earned. Every outcome but `measured` earns nothing. */\nexport function repairCredit(grade: RepairGrade): RepairCredit {\n if (grade.outcome !== 'measured') return ZERO_CREDIT\n return {\n executes: 1,\n localFlip: grade.localFlip.passed ? 1 : 0,\n repairRate: grade.repair.rollouts === 0 ? 0 : grade.repair.passes / grade.repair.rollouts,\n }\n}\n\n/** True once the answer is a well-formed, budget-admissible answer. A decline\n * is well formed, so it parses. */\nexport function reachedT0(grade: RepairGrade): boolean {\n return grade.outcome !== 'rejected'\n}\n\n/** True once the recorded state at k came back. A decline never reaches the\n * gate, because it names no k. */\nexport function reachedT1(grade: RepairGrade): boolean {\n return grade.outcome === 'did-not-execute' || grade.outcome === 'measured'\n}\n\n/** True once the intervention ran at k and exited cleanly. */\nexport function reachedT2(grade: RepairGrade): boolean {\n return grade.outcome === 'measured'\n}\n\nexport interface RepairFunnelCounts {\n readonly rows: number\n readonly rejected: number\n readonly declined: number\n readonly t0Parsed: number\n readonly t1Reproduced: number\n readonly t2Executed: number\n readonly t3LocalFlip: number\n /** Rows where at least one repair rollout passed the held-out suite. */\n readonly t4RepairFlipAny: number\n /** Rows where every repair rollout passed. */\n readonly t4RepairFlipAll: number\n}\n\nexport function countFunnel(grades: readonly RepairGrade[]): RepairFunnelCounts {\n let rejected = 0\n let declined = 0\n let t1 = 0\n let t2 = 0\n let t3 = 0\n let t4Any = 0\n let t4All = 0\n for (const grade of grades) {\n if (grade.outcome === 'rejected') rejected += 1\n if (grade.outcome === 'declined') declined += 1\n if (reachedT1(grade)) t1 += 1\n if (reachedT2(grade)) t2 += 1\n if (grade.outcome === 'measured') {\n if (grade.localFlip.passed) t3 += 1\n if (grade.repair.passes > 0) t4Any += 1\n if (grade.repair.rollouts > 0 && grade.repair.passes === grade.repair.rollouts) t4All += 1\n }\n }\n return {\n rows: grades.length,\n rejected,\n declined,\n t0Parsed: grades.length - rejected,\n t1Reproduced: t1,\n t2Executed: t2,\n t3LocalFlip: t3,\n t4RepairFlipAny: t4Any,\n t4RepairFlipAll: t4All,\n }\n}\n","/**\n * The headline metric.\n *\n * Delta-repair = P(tests pass | intervention) − P(tests pass | no-fix control)\n *\n * Paired per row, then bootstrapped over rows. Paired because the rows differ\n * enormously from each other and not at all between arms: the same trajectory,\n * the same image, the same held-out suite, the same continuation policy, and\n * one difference — the state the continuation starts from.\n *\n * Every admitted row stays in the denominator, including the ones an analyst\n * declined and the ones whose answer was rejected. Those rows contribute a\n * paired difference of exactly zero, because with no intervention to run their\n * arm IS their control arm. Declining is therefore free of error and free of\n * reward, which is what makes it an honest answer rather than a way to pick an\n * easy subset.\n *\n * The report never collapses to this one number. The funnel counts, the rates\n * on measured rows alone, the per-row table and the threats travel with it,\n * because a difference of means computed on a corpus that was admitted on the\n * control failing is conditional on that admission and the reader has to see\n * it to price it.\n */\n\nimport { ValidationError } from '../errors'\nimport { BOOTSTRAP_GATE_MIN_N, pairedBootstrap } from '../statistics'\nimport { countFunnel, type RepairFunnelCounts, type RepairGrade } from './funnel'\nimport type { RepairRowResult } from './grade'\n\nexport interface DeltaRepairOptions {\n /** Deterministic resampling seed. Derived from the deltas when omitted. */\n readonly seed?: number\n readonly resamples?: number\n readonly confidence?: number\n}\n\nexport interface DeltaRepairInterval {\n readonly n: number\n readonly mean: number\n readonly median: number\n readonly low: number\n readonly high: number\n readonly confidence: number\n readonly resamples: number\n /** False below the pair count where a percentile interval carries its\n * nominal error rate. A gate must not turn on a false one. */\n readonly gateEligible: boolean\n}\n\nexport type RepairThreatId =\n | 'control-position-asymmetry'\n | 'control-cannot-rescue'\n | 'admission-conditions-on-control-failure'\n | 'bootstrap-below-min-n'\n | 'prefix-divergence-present'\n | 'intervention-failures-present'\n | 'zero-variance-interval'\n | 'declines-carry-the-denominator'\n\nexport interface RepairThreat {\n readonly id: RepairThreatId\n readonly statement: string\n /** Which way the threat pushes the headline if it is real. */\n readonly direction: 'understates' | 'overstates' | 'unknown'\n}\n\nexport interface DeltaRepairReport {\n readonly rows: number\n readonly funnel: RepairFunnelCounts\n /** Mean over every admitted row. */\n readonly interventionRate: number\n readonly controlRate: number\n readonly deltaRepair: DeltaRepairInterval\n /** The same estimate restricted to rows that reached t2, where an\n * intervention actually ran. Conditional on the analyst answering, so it is\n * never the headline. */\n readonly measuredOnly: DeltaRepairInterval\n readonly measuredRows: number\n readonly rowResults: readonly RepairRowResult[]\n readonly threats: readonly RepairThreat[]\n}\n\nexport function deltaRepair(\n rowResults: readonly RepairRowResult[],\n options: DeltaRepairOptions = {},\n): DeltaRepairReport {\n if (rowResults.length === 0) {\n throw new ValidationError('deltaRepair needs at least one graded row')\n }\n const seen = new Set<string>()\n for (const row of rowResults) {\n if (seen.has(row.rowId)) {\n throw new ValidationError(`deltaRepair received row ${row.rowId} twice`)\n }\n seen.add(row.rowId)\n }\n\n const grades = rowResults.map((row) => row.grade)\n const funnel = countFunnel(grades)\n const control = rowResults.map((row) => row.controlRate)\n const intervention = rowResults.map((row) => row.interventionRate)\n const deltaAll = interval(control, intervention, options)\n\n const measured = rowResults.filter((row) => row.grade.outcome === 'measured')\n const measuredOnly =\n measured.length === 0\n ? emptyInterval(options)\n : interval(\n measured.map((row) => row.controlRate),\n measured.map((row) => row.interventionRate),\n options,\n )\n\n return {\n rows: rowResults.length,\n funnel,\n interventionRate: mean(intervention),\n controlRate: mean(control),\n deltaRepair: deltaAll,\n measuredOnly,\n measuredRows: measured.length,\n rowResults,\n threats: collectThreats(rowResults, funnel, deltaAll),\n }\n}\n\nfunction interval(\n control: readonly number[],\n intervention: readonly number[],\n options: DeltaRepairOptions,\n): DeltaRepairInterval {\n const result = pairedBootstrap([...control], [...intervention], {\n statistic: 'mean',\n seed: options.seed,\n resamples: options.resamples,\n confidence: options.confidence,\n })\n return {\n n: result.n,\n mean: result.mean,\n median: result.median,\n low: result.low,\n high: result.high,\n confidence: result.confidence,\n resamples: result.resamples,\n gateEligible: result.gateEligible,\n }\n}\n\nfunction emptyInterval(options: DeltaRepairOptions): DeltaRepairInterval {\n return {\n n: 0,\n mean: 0,\n median: 0,\n low: 0,\n high: 0,\n confidence: options.confidence ?? 0.95,\n resamples: options.resamples ?? 2000,\n gateEligible: false,\n }\n}\n\nfunction collectThreats(\n rowResults: readonly RepairRowResult[],\n funnel: RepairFunnelCounts,\n delta: DeltaRepairInterval,\n): RepairThreat[] {\n const threats: RepairThreat[] = [\n {\n id: 'control-position-asymmetry',\n statement:\n 'The no-fix control continues from the recorded end state, while the intervention arm continues from step k and has to redo the work the recording did after k inside the same step budget. The arms are matched on policy and budget, not on position.',\n direction: 'understates',\n },\n ]\n const inert = rowResults.filter((row) => row.controlScreening === 'declared-inert')\n if (inert.length > 0) {\n threats.push({\n id: 'control-cannot-rescue',\n statement: `${inert.length}/${rowResults.length} rows were screened under a control that makes no model call, so its rollouts graded the same bytes the end-state check graded as failing. A control rate of zero on those rows is a restatement of the end-state check, not a measurement of what continuing alone can repair.`,\n direction: 'unknown',\n })\n }\n if (inert.length === 0 && rowResults.every((row) => row.controlRate === 0)) {\n threats.push({\n id: 'admission-conditions-on-control-failure',\n statement:\n 'Every row was admitted on its no-fix control failing every rollout, so the control rate is zero everywhere and Delta-repair equals the intervention rate. The estimate is conditional on that admission and does not describe rows the control can already repair.',\n direction: 'unknown',\n })\n }\n if (!delta.gateEligible) {\n threats.push({\n id: 'bootstrap-below-min-n',\n statement: `The interval covers ${delta.n} paired rows, below the ${BOOTSTRAP_GATE_MIN_N} where a percentile bootstrap holds its nominal error rate. Read it as descriptive spread; a promotion must not turn on it.`,\n direction: 'unknown',\n })\n }\n const divergent = rowResults.filter((row) => measuredPrefixDivergences(row.grade) > 0).length\n if (divergent > 0) {\n threats.push({\n id: 'prefix-divergence-present',\n statement: `${divergent}/${rowResults.length} rows replayed at least one prefix step to a different exit code than the recording. The state the intervention landed on is close to the recorded one, not identical to it.`,\n direction: 'unknown',\n })\n }\n const withFailures = rowResults.filter(\n (row) => row.grade.outcome === 'measured' && row.grade.repair.interventionFailures > 0,\n ).length\n if (withFailures > 0) {\n threats.push({\n id: 'intervention-failures-present',\n statement: `${withFailures} rows had at least one rollout where the intervention failed to run after it had already run cleanly in the local-flip session. Those rollouts count as non-passes.`,\n direction: 'understates',\n })\n }\n if (delta.low === delta.high) {\n threats.push({\n id: 'zero-variance-interval',\n statement:\n 'Every resample produced the same statistic, so the interval has zero width. That is an absence of variation in the data, not certainty about the effect.',\n direction: 'unknown',\n })\n }\n if (funnel.declined + funnel.rejected > funnel.rows / 2) {\n threats.push({\n id: 'declines-carry-the-denominator',\n statement: `${funnel.declined} declined and ${funnel.rejected} rejected of ${funnel.rows} rows contribute a paired delta of zero. The headline is dominated by rows where no intervention ran.`,\n direction: 'understates',\n })\n }\n return threats\n}\n\nfunction measuredPrefixDivergences(grade: RepairGrade): number {\n if (grade.outcome === 'measured' || grade.outcome === 'did-not-execute') {\n return grade.execution.prefix.divergences\n }\n if (\n grade.outcome === 'not-reproduced' &&\n grade.reproduction.basis !== 'no-recorded-observation'\n ) {\n return grade.reproduction.prefix.divergences\n }\n return 0\n}\n\nfunction mean(values: readonly number[]): number {\n return values.reduce((sum, value) => sum + value, 0) / values.length\n}\n\n/** Markdown report: provenance, the funnel, every per-row column, the\n * distribution, and the threats. */\nexport function renderDeltaRepairReport(report: DeltaRepairReport): string {\n const lines: string[] = []\n const pct = (value: number): string => `${(value * 100).toFixed(1)} %`\n lines.push('# Delta-repair')\n lines.push('')\n lines.push(\n `**${signed(report.deltaRepair.mean)}** paired mean over ${report.rows} admitted rows ` +\n `(${(report.deltaRepair.confidence * 100).toFixed(0)} % CI ` +\n `${signed(report.deltaRepair.low)} … ${signed(report.deltaRepair.high)}, ` +\n `${report.deltaRepair.resamples} resamples, gate-eligible: ${report.deltaRepair.gateEligible}).`,\n )\n lines.push('')\n lines.push(\n `P(tests pass | intervention) = ${pct(report.interventionRate)}; ` +\n `P(tests pass | no-fix control) = ${pct(report.controlRate)}.`,\n )\n lines.push('')\n lines.push('## Funnel')\n lines.push('')\n lines.push('| cell | rows | share |')\n lines.push('| --- | --- | --- |')\n const f = report.funnel\n const share = (value: number): string => pct(f.rows === 0 ? 0 : value / f.rows)\n for (const [label, value] of [\n ['admitted rows', f.rows],\n ['t0 parsed', f.t0Parsed],\n ['t1 reproduced (gate, pays nothing)', f.t1Reproduced],\n ['t2 intervention executes', f.t2Executed],\n ['t3 local flip', f.t3LocalFlip],\n ['t4 repair flip (any rollout)', f.t4RepairFlipAny],\n ['t4 repair flip (every rollout)', f.t4RepairFlipAll],\n ['no-decisive-failure', f.declined],\n ['rejected', f.rejected],\n ] as const) {\n lines.push(`| ${label} | ${value} | ${share(value)} |`)\n }\n lines.push('')\n lines.push('## Rows')\n lines.push('')\n lines.push(\n '| row | outcome | k | reproduction basis | reproduced | intervention exit | local flip | repair passes | rollouts | intervention failures | prefix steps | prefix divergences | P(int) | P(ctl) | delta | wall ms |',\n )\n lines.push(\n '| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |',\n )\n for (const row of report.rowResults) {\n lines.push(`| ${rowCells(row).join(' | ')} |`)\n }\n lines.push('')\n lines.push('## Measured rows only')\n lines.push('')\n lines.push(\n `${report.measuredRows} rows reached t2. Paired mean ${signed(report.measuredOnly.mean)} ` +\n `(CI ${signed(report.measuredOnly.low)} … ${signed(report.measuredOnly.high)}). ` +\n 'Conditional on the analyst answering, so it is not the headline.',\n )\n lines.push('')\n lines.push('## Threats')\n lines.push('')\n for (const threat of report.threats) {\n lines.push(`- **${threat.id}** (${threat.direction} the effect) — ${threat.statement}`)\n }\n lines.push('')\n return lines.join('\\n')\n}\n\nfunction rowCells(row: RepairRowResult): string[] {\n const grade = row.grade\n const reproduction =\n grade.outcome === 'not-reproduced' ||\n grade.outcome === 'did-not-execute' ||\n grade.outcome === 'measured'\n ? grade.reproduction\n : null\n const execution =\n grade.outcome === 'did-not-execute' || grade.outcome === 'measured' ? grade.execution : null\n const repair = grade.outcome === 'measured' ? grade.repair : null\n const prefix =\n execution?.prefix ??\n (reproduction && reproduction.basis !== 'no-recorded-observation' ? reproduction.prefix : null)\n const rejection =\n grade.outcome === 'rejected' ? `rejected: ${grade.rejection.reason}` : grade.outcome\n return [\n row.rowId,\n rejection,\n grade.outcome === 'rejected' || grade.outcome === 'declined' ? '—' : String(grade.k),\n reproduction ? reproduction.basis : '—',\n reproduction ? String(reproduction.reproduced) : '—',\n execution ? String(execution.exitCode) : '—',\n grade.outcome === 'measured' ? String(grade.localFlip.passed) : '—',\n repair ? String(repair.passes) : '—',\n repair ? String(repair.rollouts) : '0',\n repair ? String(repair.interventionFailures) : '—',\n prefix ? String(prefix.stepsReplayed) : '—',\n prefix ? String(prefix.divergences) : '—',\n row.interventionRate.toFixed(3),\n row.controlRate.toFixed(3),\n signed(row.delta),\n String(row.wallMs),\n ]\n}\n\nfunction signed(value: number): string {\n const points = value * 100\n return `${points >= 0 ? '+' : ''}${points.toFixed(1)} pp`\n}\n","/**\n * Docker-backed continuation environment.\n *\n * The runner refuses any container whose network mode is not `none`, so this\n * builds containers that way and reports the mode it reads back from the\n * daemon rather than the mode it asked for. A container created elsewhere and\n * attached here is described the same way, so an environment that quietly kept\n * its network is rejected instead of producing evidence.\n *\n * Commands are bounded twice. `timeout` inside the container is the primary\n * bound, because killing the host-side `docker exec` client leaves the process\n * it started running in the container, where it would keep writing files under\n * later steps. The host-side kill is a backstop for a daemon that stops\n * answering. The container must therefore provide `timeout`; `describe()`\n * checks for it and refuses the container when it is absent.\n */\n\nimport { spawn } from 'node:child_process'\nimport { constants } from 'node:os'\nimport { ValidationError } from '../errors'\nimport type { ContinuationEnvironment, ContinuationExecResult } from './continuation-policy'\nimport type { ContinuationEnvironmentDescription } from './continuation-records'\n\nexport interface ProcessRequest {\n argv: string[]\n /** Kills the process group when exceeded. */\n timeoutSeconds?: number\n}\n\nexport interface ProcessResult {\n /** stdout and stderr interleaved, as the scaffold reads them. */\n output: string\n exitCode: number\n /** True when the process was killed for exceeding `timeoutSeconds`. */\n timedOut: boolean\n}\n\n/** Runs a process on the host. Injected so the environment is testable without a daemon. */\nexport type ProcessRunner = (request: ProcessRequest) => Promise<ProcessResult>\n\n/**\n * Spawns a process, merges stdout and stderr the way the scaffold reads them,\n * and kills the whole process group on timeout so a killed command leaves no\n * children running in the container's namespace.\n */\nexport const nodeProcessRunner: ProcessRunner = (request) =>\n new Promise<ProcessResult>((resolve, reject) => {\n const [command, ...args] = request.argv\n if (!command) {\n reject(new ValidationError('process runner requires a command'))\n return\n }\n const child = spawn(command, args, { detached: true, stdio: ['ignore', 'pipe', 'pipe'] })\n const chunks: string[] = []\n let timedOut = false\n child.stdout.setEncoding('utf8')\n child.stderr.setEncoding('utf8')\n child.stdout.on('data', (chunk: string) => chunks.push(chunk))\n child.stderr.on('data', (chunk: string) => chunks.push(chunk))\n\n const timer =\n request.timeoutSeconds === undefined\n ? undefined\n : setTimeout(() => {\n timedOut = true\n if (child.pid === undefined) return\n try {\n process.kill(-child.pid, 'SIGKILL')\n } catch (error) {\n // ESRCH means the group exited between the deadline and this\n // signal, and `close` resolves the promise. Any other failure\n // means the process may still be running, so surface it.\n if ((error as NodeJS.ErrnoException).code !== 'ESRCH') reject(error)\n }\n }, request.timeoutSeconds * 1000)\n\n child.on('error', (error) => {\n if (timer) clearTimeout(timer)\n reject(error)\n })\n child.on('close', (code, signal) => {\n if (timer) clearTimeout(timer)\n const output = chunks.join('')\n if (code !== null) {\n resolve({ output, exitCode: code, timedOut })\n return\n }\n // A signalled exit carries no code. Report the negative signal number,\n // which is how the corpus records a killed command.\n const signalNumber = signal === null ? undefined : constants.signals[signal]\n if (signalNumber === undefined) {\n reject(\n new ValidationError(`process closed with no exit code and no known signal: ${signal}`),\n )\n return\n }\n resolve({ output, exitCode: -signalNumber, timedOut })\n })\n })\n\nexport interface DockerContinuationEnvironmentOptions {\n /** Container id or name holding the post-step-k state. */\n containerRef: string\n /** Working directory for every command. */\n cwd: string\n /** Environment variables set on every command. */\n env?: Record<string, string>\n /** Interpreter the scaffold runs commands through. */\n interpreter?: string[]\n /** `docker` unless a compatible client is used. */\n executable?: string\n runProcess: ProcessRunner\n /** Removes the container on dispose. Leave false when the caller owns its lifecycle. */\n removeOnDispose?: boolean\n}\n\nconst DEFAULT_INTERPRETER = ['bash', '-lc']\nconst DEFAULT_EXECUTABLE = 'docker'\n\n/** Seconds `timeout` waits after SIGTERM before sending SIGKILL. */\nconst KILL_GRACE_SECONDS = 5\n\n/** Extra seconds the host-side backstop waits after the in-container bound. */\nconst BACKSTOP_SECONDS = 10\n\n/** `timeout` reports this when it stopped the command. */\nconst TIMEOUT_EXIT_CODE = 124\n\n/**\n * Arguments that create a container the policy accepts. `--network none` is\n * not optional: a continuation with network access could install what the\n * recorded run could not, and the arms would no longer differ only by the\n * intervention.\n */\nexport function dockerRunArgs(input: {\n image: string\n name: string\n cwd: string\n containerLifetime?: string\n executable?: string\n}): string[] {\n return [\n input.executable ?? DEFAULT_EXECUTABLE,\n 'run',\n '-d',\n '--name',\n input.name,\n '--network',\n 'none',\n '-w',\n input.cwd,\n '--rm',\n input.image,\n 'sleep',\n input.containerLifetime ?? '2h',\n ]\n}\n\nexport function createDockerContinuationEnvironment(\n options: DockerContinuationEnvironmentOptions,\n): ContinuationEnvironment {\n if (!options.containerRef.trim()) {\n throw new ValidationError('docker continuation environment requires a container reference')\n }\n const executable = options.executable ?? DEFAULT_EXECUTABLE\n const interpreter = options.interpreter ?? DEFAULT_INTERPRETER\n const envEntries = Object.entries(options.env ?? {})\n\n return {\n containerRef: options.containerRef,\n\n async describe(): Promise<ContinuationEnvironmentDescription> {\n const inspect = await options.runProcess({\n argv: [\n executable,\n 'inspect',\n '--format',\n '{{.HostConfig.NetworkMode}}\\t{{.Config.Image}}',\n options.containerRef,\n ],\n })\n if (inspect.exitCode !== 0) {\n throw new ValidationError(\n `docker inspect failed for ${options.containerRef} (exit ${inspect.exitCode}): ${inspect.output.trim()}`,\n )\n }\n const [networkMode, image] = inspect.output.trim().split('\\t')\n if (!networkMode) {\n throw new ValidationError(\n `docker inspect returned no network mode for ${options.containerRef}`,\n )\n }\n const hasTimeout = await options.runProcess({\n argv: [executable, 'exec', options.containerRef, ...interpreter, 'command -v timeout'],\n })\n if (hasTimeout.exitCode !== 0) {\n throw new ValidationError(\n `container ${options.containerRef} provides no \\`timeout\\`, so a long command cannot be bounded inside it`,\n )\n }\n return image ? { networkMode, image } : { networkMode }\n },\n\n async exec(\n command: string,\n execOptions: { timeoutSeconds: number },\n ): Promise<ContinuationExecResult> {\n const argv = [executable, 'exec', '-w', options.cwd]\n for (const [key, value] of envEntries) argv.push('-e', `${key}=${value}`)\n argv.push(\n options.containerRef,\n 'timeout',\n `--kill-after=${KILL_GRACE_SECONDS}s`,\n `${execOptions.timeoutSeconds}s`,\n ...interpreter,\n command,\n )\n const result = await options.runProcess({\n argv,\n // Backstop only: it fires after the in-container bound plus its grace.\n timeoutSeconds: execOptions.timeoutSeconds + KILL_GRACE_SECONDS + BACKSTOP_SECONDS,\n })\n // `timeout` exits 124 when it stopped the command. A command that exits\n // 124 on its own is reported the same way, which overstates timeouts\n // rather than hiding them.\n const timedOut = result.timedOut || result.exitCode === TIMEOUT_EXIT_CODE\n return {\n output: result.output,\n returncode: result.exitCode,\n timedOut,\n }\n },\n\n async dispose(): Promise<void> {\n if (!options.removeOnDispose) return\n await options.runProcess({ argv: [executable, 'rm', '-f', options.containerRef] })\n },\n }\n}\n","/**\n * Grade one analyst answer about one admitted row.\n *\n * The whole funnel runs here, in the order that spends the least before it\n * knows: parse and budget checks open no container, the reproduction gate\n * opens one, the local flip opens one more, and only then does the repair arm\n * pay for its rollouts.\n *\n * Two properties a reviewer should be able to check by reading this file:\n *\n * The intervention is applied at the k the analyst named, on the state\n * produced by replaying steps 1..k-1, and nowhere else. There is no search\n * over nearby steps, no credit for being close, and no label in scope — the\n * grader never receives one. A wrong k therefore scores zero the only honest\n * way it can: the repair has to work where the analyst said the failure was.\n *\n * The row must arrive branded by `admitRow`. That is the type-level form of\n * \"admission runs before any analyst sees a row\": there is no signature here\n * that accepts an unadmitted row.\n */\n\nimport { CaptureIntegrityError, ValidationError } from '../errors'\nimport { packageVersion } from '../package-version'\nimport { wrapActionForExec } from '../trajectory-replay/exec'\nimport {\n deriveFailureSignature,\n parseRecordedReturncode,\n type RecordedTrajectoryStep,\n} from '../trajectory-replay/steps'\nimport { certificationEvidenceDigest, type DefaultVerdict } from '../verdict'\nimport {\n checkInterventionBudget,\n type InterventionBudget,\n normalizeActionForComparison,\n SCAFFOLD_INTERVENTION_BUDGET,\n} from './action-budget'\nimport type { AdmittedRow } from './admission-contract'\nimport type { AnalystResponse, RepairFinding } from './analyst-response'\nimport type { ControlScreening } from './control-policy'\nimport {\n type InterventionExecution,\n type PrefixReplayEvidence,\n type RepairArmEvidence,\n type RepairCredit,\n type RepairGrade,\n type RepairRolloutEvidence,\n type ReproductionEvidence,\n repairCredit,\n type TestRunEvidence,\n} from './funnel'\nimport { isRecordedTimeout } from './mini-swe-scaffold'\nimport type {\n RepairArm,\n RepairContinuationOutcome,\n RepairContinuationRunner,\n RepairSession,\n RepairSessionFactory,\n TestOracle,\n} from './ports'\n\n/** Rollouts of the repair arm disagreed with the controls about the policy. */\nexport class RepairArmSymmetryError extends CaptureIntegrityError {}\n\nexport interface GradeRepairOptions {\n readonly row: AdmittedRow\n readonly response: AnalystResponse\n readonly sessions: RepairSessionFactory\n readonly oracle: TestOracle\n readonly continuation: RepairContinuationRunner\n /** Repair rollouts for the intervention arm. Defaults to the row's own\n * control rollout count so the arms are matched. */\n readonly repairRollouts?: number\n readonly budget?: InterventionBudget\n /** Wall-clock limit for one replayed or injected action. */\n readonly stepTimeoutMs?: number\n /**\n * Wall-clock limit for replaying a step the recording itself killed.\n *\n * Such a step carries no returncode, so the replay agrees with the recording\n * no matter how long it waits. Bounding it separately cuts what a prefix\n * costs without changing what it counts. Defaults to `stepTimeoutMs`.\n */\n readonly recordedTimeoutStepMs?: number\n readonly onProgress?: (message: string) => void\n}\n\n/** Extends the substrate verdict spine: `valid` = the intervention flipped\n * the held-out suite in at least one measurement (locally or after the\n * pinned continuation); `score` = the better of the two flip measurements\n * (`localFlip`, `repairRate`), so `valid` ⟺ `score > 0`. The credit\n * VECTOR stays authoritative in `credit` and travels in `scores` —\n * Delta-repair pairing reads `delta`, never the scalar. Certification is\n * present exactly when the suite executed (`outcome: 'measured'`); a\n * closed gate certifies nothing. */\nexport interface RepairRowResult extends DefaultVerdict {\n readonly rowId: string\n readonly grade: RepairGrade\n readonly credit: RepairCredit\n /** P(tests pass | intervention). Equals `controlRate` when no intervention\n * arm ran, because the row's state is then the control's state. */\n readonly interventionRate: number\n readonly controlRate: number\n readonly controlRollouts: number\n /** How the row's control pass was read. Travels with the result so a report\n * can say whether a control rate of zero was screened or merely inert. */\n readonly controlScreening: ControlScreening\n readonly controlPolicyDigest: string\n readonly repairRollouts: number\n /** The row's paired contribution to Delta-repair. */\n readonly delta: number\n readonly wallMs: number\n}\n\nconst DEFAULT_STEP_TIMEOUT_MS = 300_000\nconst OUTPUT_EXCERPT_CHARS = 4000\n\nexport async function gradeRepairRow(options: GradeRepairOptions): Promise<RepairRowResult> {\n const startedMs = Date.now()\n const grade = await produceGrade(options)\n return finish(options.row, grade, startedMs)\n}\n\nfunction finish(row: AdmittedRow, grade: RepairGrade, startedMs: number): RepairRowResult {\n const credit = repairCredit(grade)\n const interventionRate = grade.outcome === 'measured' ? credit.repairRate : row.controlRate\n const score = Math.max(credit.localFlip, credit.repairRate)\n return {\n rowId: row.rowId,\n grade,\n credit,\n interventionRate,\n controlRate: row.controlRate,\n controlRollouts: row.controlRollouts,\n controlScreening: row.controlScreening,\n controlPolicyDigest: row.policyDigest,\n repairRollouts: grade.outcome === 'measured' ? grade.repair.rollouts : 0,\n delta: interventionRate - row.controlRate,\n wallMs: Date.now() - startedMs,\n valid: score > 0,\n score,\n scores: { ...credit },\n notes: `outcome: ${grade.outcome}`,\n ...(grade.outcome === 'measured'\n ? {\n certification: {\n strategy: 'test',\n checker: {\n name: 'agent-eval:trace-repair-grader',\n version: packageVersion(),\n pins: { suite: row.suiteDigest, policy: row.policyDigest },\n },\n assumptions: gradeAssumptions(grade),\n evidenceDigest: certificationEvidenceDigest(grade),\n },\n }\n : {}),\n }\n}\n\n/** Steps a measured grade rests on that no suite run verified. */\nfunction gradeAssumptions(grade: Extract<RepairGrade, { outcome: 'measured' }>): string[] {\n const assumptions: string[] = []\n if (grade.reproduction.basis === 'no-recorded-observation') {\n assumptions.push('step k recorded no observation — the reproduction gate passed vacuously')\n }\n const prefix = grade.execution.prefix\n if (prefix.divergences > 0) {\n assumptions.push(\n `${prefix.divergences} of ${prefix.stepsReplayed} replayed prefix steps diverged from the recording — the state at k is approximate`,\n )\n }\n return assumptions\n}\n\nasync function produceGrade(options: GradeRepairOptions): Promise<RepairGrade> {\n const { row, response } = options\n if (response.kind === 'no-decisive-failure') return { outcome: 'declined' }\n\n const target = targetStep(row, response)\n if (!target.ok) return target.grade\n\n const budget = options.budget ?? SCAFFOLD_INTERVENTION_BUDGET\n const check = checkInterventionBudget(\n response.intervention.action,\n response.intervention.kind,\n budget,\n )\n if (!check.admissible) {\n return {\n outcome: 'rejected',\n rejection: {\n source: 'budget',\n reason: check.violation,\n detail: check.detail,\n measurement: check.measurement,\n },\n }\n }\n if (\n normalizeActionForComparison(response.intervention.action) ===\n normalizeActionForComparison(target.step.action)\n ) {\n return {\n outcome: 'rejected',\n rejection: {\n source: 'target',\n reason: 'recorded-action-reproposed',\n detail: `the intervention is the action already recorded at step ${response.k}`,\n },\n }\n }\n\n const reproduction = await runReproductionGate(options, response, target.step)\n if (!reproduction.reproduced) {\n return { outcome: 'not-reproduced', k: response.k, reproduction }\n }\n\n const local = await runLocalFlip(options, response)\n if (local.kind === 'did-not-execute') {\n return {\n outcome: 'did-not-execute',\n k: response.k,\n reproduction,\n execution: local.execution,\n }\n }\n\n const repair = await runRepairArm(options, response)\n return {\n outcome: 'measured',\n k: response.k,\n reproduction,\n execution: local.execution,\n localFlip: local.tests,\n repair,\n }\n}\n\nfunction targetStep(\n row: AdmittedRow,\n finding: RepairFinding,\n): { ok: true; step: RecordedTrajectoryStep } | { ok: false; grade: RepairGrade } {\n if (finding.k < 1 || finding.k > row.steps.length) {\n return {\n ok: false,\n grade: {\n outcome: 'rejected',\n rejection: {\n source: 'target',\n reason: 'k-out-of-range',\n detail: `k=${finding.k} is outside [1, ${row.steps.length}]`,\n },\n },\n }\n }\n const step = row.steps[finding.k - 1]!\n if (step.step_id !== finding.k) {\n throw new ValidationError(\n `trace-repair: row ${row.rowId} steps[${finding.k - 1}].step_id=${step.step_id} != ${finding.k}; ` +\n 'an admitted row must carry 1-based contiguous step ids',\n )\n }\n return { ok: true, step }\n}\n\nasync function runReproductionGate(\n options: GradeRepairOptions,\n finding: RepairFinding,\n target: RecordedTrajectoryStep,\n): Promise<ReproductionEvidence> {\n const { row } = options\n if (target.observation === null) {\n options.onProgress?.(\n `row ${row.rowId}: step ${finding.k} recorded no observation; the reproduction gate passes vacuously`,\n )\n return { basis: 'no-recorded-observation', reproduced: true }\n }\n const recordedReturncode = parseRecordedReturncode(target.observation)\n if (recordedReturncode === null) {\n throw new ValidationError(\n `trace-repair: row ${row.rowId} step ${finding.k} carries an observation with no <returncode>; ` +\n 'the corpus row is malformed and must not have been admitted',\n )\n }\n const signature = deriveFailureSignature(target.observation)\n\n const session = await options.sessions.open({\n rowId: row.rowId,\n image: row.image,\n arm: 'reproduce',\n rolloutIndex: 0,\n })\n try {\n const prefix = await replayPrefix(session, options, finding.k)\n const result = await session.exec(\n wrapActionForExec(target.action, row.cwd),\n options.stepTimeoutMs ?? DEFAULT_STEP_TIMEOUT_MS,\n )\n const output = `${result.stdout}\\n${result.stderr}`\n const signatureObserved = signature === null ? null : output.includes(signature)\n const reproduced =\n !result.timedOut && result.exitCode === recordedReturncode && signatureObserved !== false\n options.onProgress?.(\n `row ${row.rowId}: reproduction at step ${finding.k} exit=${result.exitCode} ` +\n `(recorded ${recordedReturncode}) reproduced=${reproduced}`,\n )\n return {\n basis: signature === null ? 'returncode-only' : 'returncode+output-substring',\n reproduced,\n recordedReturncode,\n observedExitCode: result.exitCode,\n signature,\n signatureObserved,\n prefix,\n }\n } finally {\n await session.close()\n }\n}\n\ntype LocalFlipOutcome =\n | { kind: 'did-not-execute'; execution: InterventionExecution }\n | { kind: 'measured'; execution: InterventionExecution; tests: TestRunEvidence }\n\nasync function runLocalFlip(\n options: GradeRepairOptions,\n finding: RepairFinding,\n): Promise<LocalFlipOutcome> {\n const { row } = options\n const session = await options.sessions.open({\n rowId: row.rowId,\n image: row.image,\n arm: 'local-flip',\n rolloutIndex: 0,\n })\n try {\n const prefix = await replayPrefix(session, options, finding.k)\n const startedMs = Date.now()\n const result = await session.exec(\n wrapActionForExec(finding.intervention.action, row.cwd),\n options.stepTimeoutMs ?? DEFAULT_STEP_TIMEOUT_MS,\n )\n const output = `${result.stdout}\\n${result.stderr}`.trim()\n const execution: InterventionExecution = {\n command: finding.intervention.action,\n exitCode: result.exitCode,\n timedOut: result.timedOut,\n wallMs: Date.now() - startedMs,\n output: excerpt(output),\n prefix,\n }\n if (result.timedOut || result.exitCode !== 0) {\n options.onProgress?.(\n `row ${row.rowId}: the intervention did not run at step ${finding.k} ` +\n `(exit=${result.exitCode} timedOut=${result.timedOut})`,\n )\n return { kind: 'did-not-execute', execution }\n }\n const tests = await gradeTests(options, session, 'local-flip', 0)\n options.onProgress?.(\n `row ${row.rowId}: local flip=${tests.passed} after the intervention at step ${finding.k}`,\n )\n return { kind: 'measured', execution, tests }\n } finally {\n await session.close()\n }\n}\n\nasync function runRepairArm(\n options: GradeRepairOptions,\n finding: RepairFinding,\n): Promise<RepairArmEvidence> {\n const { row } = options\n const rollouts = options.repairRollouts ?? row.controlRollouts\n if (!Number.isInteger(rollouts) || rollouts <= 0) {\n throw new ValidationError(`repairRollouts must be a positive integer, got ${rollouts}`)\n }\n const evidence: RepairRolloutEvidence[] = []\n let passes = 0\n let interventionFailures = 0\n let policyDigest: string | null = null\n\n for (let index = 0; index < rollouts; index += 1) {\n const session = await options.sessions.open({\n rowId: row.rowId,\n image: row.image,\n arm: 'intervention',\n rolloutIndex: index,\n })\n try {\n await replayPrefix(session, options, finding.k)\n const result = await session.exec(\n wrapActionForExec(finding.intervention.action, row.cwd),\n options.stepTimeoutMs ?? DEFAULT_STEP_TIMEOUT_MS,\n )\n if (result.timedOut || result.exitCode !== 0) {\n interventionFailures += 1\n evidence.push({\n rolloutIndex: index,\n status: 'intervention-failed',\n interventionExitCode: result.exitCode,\n timedOut: result.timedOut,\n })\n continue\n }\n const continuation = await options.continuation({\n rowId: row.rowId,\n arm: 'intervention',\n rolloutIndex: index,\n session,\n steps: row.steps,\n k: finding.k,\n injected: {\n action: finding.intervention.action,\n returncode: result.exitCode,\n output: `${result.stdout}\\n${result.stderr}`.trim(),\n timedOut: result.timedOut,\n },\n taskStatement: row.taskStatement,\n })\n assertPolicySymmetry(row, continuation, index)\n policyDigest = continuation.policyDigest\n const tests = await gradeTests(options, session, 'intervention', index)\n if (tests.passed) passes += 1\n evidence.push({\n rolloutIndex: index,\n status: 'completed',\n interventionExitCode: result.exitCode,\n continuation,\n tests,\n })\n options.onProgress?.(\n `row ${row.rowId}: repair rollout ${index} tests=${tests.passed} ` +\n `after ${continuation.steps} continuation steps (${continuation.exitStatus})`,\n )\n } finally {\n await session.close()\n }\n }\n\n return { rollouts, passes, interventionFailures, policyDigest, rolloutEvidence: evidence }\n}\n\nfunction assertPolicySymmetry(\n row: AdmittedRow,\n continuation: RepairContinuationOutcome,\n index: number,\n): void {\n if (continuation.policyDigest !== row.policyDigest) {\n throw new RepairArmSymmetryError(\n `row ${row.rowId} repair rollout ${index} ran policy ${continuation.policyDigest} but its ` +\n `controls ran ${row.policyDigest}; the difference between the arms would not be the intervention`,\n )\n }\n}\n\nasync function gradeTests(\n options: GradeRepairOptions,\n session: RepairSession,\n arm: RepairArm,\n rolloutIndex: number,\n): Promise<TestRunEvidence> {\n const outcome = await options.oracle.grade(session, {\n rowId: options.row.rowId,\n arm,\n rolloutIndex,\n })\n if (outcome.suiteDigest !== options.row.suiteDigest) {\n throw new RepairArmSymmetryError(\n `row ${options.row.rowId} was admitted against suite ${options.row.suiteDigest} but the ${arm} arm ` +\n `graded against ${outcome.suiteDigest}; the arms did not answer the same question`,\n )\n }\n return {\n passed: outcome.passed,\n exitCode: outcome.exitCode,\n timedOut: outcome.timedOut,\n suiteDigest: outcome.suiteDigest,\n }\n}\n\n/** Replay recorded steps 1..k-1 to rebuild the state the intervention lands\n * on. Divergence is counted and reported, never repaired. */\nasync function replayPrefix(\n session: RepairSession,\n options: GradeRepairOptions,\n k: number,\n): Promise<PrefixReplayEvidence> {\n const { row } = options\n const timeoutMs = options.stepTimeoutMs ?? DEFAULT_STEP_TIMEOUT_MS\n const recordedTimeoutMs = options.recordedTimeoutStepMs ?? timeoutMs\n const startedMs = Date.now()\n let divergences = 0\n let stepsReplayed = 0\n for (const step of row.steps.slice(0, k - 1)) {\n const bound = isRecordedTimeout(step.observation) ? recordedTimeoutMs : timeoutMs\n const result = await session.exec(wrapActionForExec(step.action, row.cwd), bound)\n stepsReplayed += 1\n const recorded = parseRecordedReturncode(step.observation)\n if (recorded !== null && recorded !== result.exitCode) divergences += 1\n }\n return { stepsReplayed, divergences, wallMs: Date.now() - startedMs }\n}\n\nfunction excerpt(text: string): string {\n if (text.length <= OUTPUT_EXCERPT_CHARS) return text\n const half = Math.floor(OUTPUT_EXCERPT_CHARS / 2)\n return `${text.slice(0, half)}\\n… [${text.length - OUTPUT_EXCERPT_CHARS} chars elided] …\\n${text.slice(-half)}`\n}\n","/**\n * Whether a task's own grader is a function of the container state.\n *\n * A repair benchmark uses the task's held-out suite as ground truth: the suite\n * says the state before the intervention fails and the state after it passes,\n * and the difference is the measurement. That reading needs the suite to answer\n * the same way twice on the same bytes. A suite that asserts on wall clock does\n * not: the same container passes or fails by chance, so a control arm can\n * \"rescue\" a row nothing touched, and an intervention arm can lose a repair it\n * made.\n *\n * The check is direct. Grade the same container N times with nothing written\n * between the runs, pool the replicates by the state they graded, and read the\n * minority share.\n *\n * It reads that share per ASSERTION, not per suite, wherever the suite reports\n * assertions. A pass/fail reward is a conjunction over many assertions, so a\n * suite whose timing assertions each flip independently can still return the\n * same reward on every replicate of a state that sits far from the threshold —\n * and then return a coin flip on the states a campaign actually grades, which\n * sit near it. Per-assertion counting sees the flip at the anchor; reward\n * counting does not. A state whose replicates carried no assertion report falls\n * back to the reward and records that it did, so a coarser measurement is\n * visible rather than assumed equivalent.\n *\n * Replicates are also run under machine contention, because unanimity on an\n * idle box proves nothing about a threshold the load never approached.\n * Replicates on one state pool across both loads, so a verdict that moves when\n * the machine gets busy reads as the flip it is.\n */\n\nimport { CaptureIntegrityError, ValidationError } from '../errors'\n\n/** A task graded a repair by something other than the state under test. */\nexport class NondeterministicOracleError extends CaptureIntegrityError {}\n\n/** The two states certification produces: the published image, and that image\n * after the task's own reference solution ran. */\nexport type OracleStateLabel = 'unsolved' | 'solved'\n\n/** Machine load the replicate ran under. */\nexport type OracleLoad = 'idle' | 'contended'\n\n/** The unit a whole-suite verdict is counted under when nothing finer exists. */\nexport const SUITE_REWARD_UNIT = 'suite-reward'\n\nexport interface OracleAssertionResult {\n /** Test identifier the suite reported, verbatim. */\n readonly id: string\n readonly passed: boolean\n}\n\nexport interface OracleReplicate {\n /** 0-based index within its group. */\n readonly index: number\n /**\n * Raw reward the task's grader wrote, verbatim. `null` when it wrote none —\n * a missing reward and a zero reward are different failures, and neither is\n * folded into the other.\n */\n readonly reward: string | null\n readonly passed: boolean\n readonly wallMs: number\n /** Per-assertion verdicts the suite reported, or `null` when it reported\n * none. Never an empty array standing in for \"the suite said nothing\". */\n readonly assertions: readonly OracleAssertionResult[] | null\n}\n\nexport interface OracleReplicateGroup {\n readonly state: OracleStateLabel\n readonly load: OracleLoad\n /**\n * Replicates that graded one container with nothing written between them.\n * Two or more, because a single grading measures no flip.\n */\n readonly replicates: readonly OracleReplicate[]\n}\n\nexport interface OracleDeterminismEvidence {\n readonly taskName: string\n /** Image the replicates ran on, by registry manifest digest. An image with no\n * published digest, such as one loaded from an archive, records its tag; the\n * absent `@sha256:` is what says so. */\n readonly image: string\n /**\n * Digest of the suite bytes every replicate graded against, in whatever\n * scheme the measuring tool uses. Provenance only: it identifies the suite a\n * certification is about and is never compared against a digest produced by\n * a different scheme.\n */\n readonly suiteDigest: string\n readonly groups: readonly OracleReplicateGroup[]\n readonly measuredAt: string\n}\n\n/** One thing that did not agree with itself across replicates of a state. */\nexport interface OracleFlippedUnit {\n /** An assertion id, or `suite-reward` when the suite reported no assertions. */\n readonly unit: string\n readonly passes: number\n readonly fails: number\n readonly flipRate: number\n}\n\nexport interface OracleStateVerdict {\n readonly state: OracleStateLabel\n readonly replicates: number\n /** Replicates whose whole-suite reward passed. */\n readonly passes: number\n readonly fails: number\n /** What the flip rate was counted over. `reward` is the coarser reading. */\n readonly granularity: 'per-assertion' | 'reward'\n /** Largest minority share over the counted units. */\n readonly flipRate: number\n readonly flipped: readonly OracleFlippedUnit[]\n /** Assertion ids some replicates reported and others did not. The suite's\n * own shape moved, which is a flip in itself. */\n readonly assertionSetUnstable: readonly string[]\n /** Loads whose whole-suite pass rate on this state differed. */\n readonly loadSensitive: boolean\n /** Every distinct raw reward the grader wrote, sorted. */\n readonly rewardsObserved: readonly string[]\n}\n\nexport interface OracleDeterminismVerdict {\n readonly taskName: string\n readonly image: string\n readonly suiteDigest: string\n /** True only when every counted unit agreed with itself on every state. */\n readonly stable: boolean\n readonly replicates: number\n /** Largest per-unit minority share over every state. Zero on a stable task. */\n readonly flipRate: number\n readonly byState: readonly OracleStateVerdict[]\n readonly measuredAt: string\n /** One line naming what was measured, for an artifact a human reads. */\n readonly detail: string\n}\n\n/** Replicates one group needs before a flip is measurable at all. */\nexport const MIN_ORACLE_REPLICATES = 2\n\n/**\n * Reduce measured replicates to a verdict.\n *\n * Pure: it opens no container. The tool that runs the replicates hands the\n * counts here, so the rule that decides stability is one rule and a reviewer\n * can re-derive any verdict from the recorded replicates.\n */\nexport function oracleDeterminism(evidence: OracleDeterminismEvidence): OracleDeterminismVerdict {\n if (evidence.groups.length === 0) {\n throw new ValidationError(\n `oracle determinism for ${evidence.taskName} received no replicate group`,\n )\n }\n for (const group of evidence.groups) {\n if (group.replicates.length < MIN_ORACLE_REPLICATES) {\n throw new ValidationError(\n `oracle determinism for ${evidence.taskName} received ${group.replicates.length} ` +\n `${group.load} replicate(s) on the ${group.state} state; ${MIN_ORACLE_REPLICATES} are ` +\n 'needed before a flip can be observed',\n )\n }\n }\n\n const byState: OracleStateVerdict[] = []\n for (const state of ['unsolved', 'solved'] as const) {\n const groups = evidence.groups.filter((group) => group.state === state)\n if (groups.length === 0) continue\n byState.push(stateVerdict(state, groups))\n }\n\n const flipRate = byState.reduce((worst, state) => Math.max(worst, state.flipRate), 0)\n const replicates = byState.reduce((total, state) => total + state.replicates, 0)\n return {\n taskName: evidence.taskName,\n image: evidence.image,\n suiteDigest: evidence.suiteDigest,\n stable: flipRate === 0,\n replicates,\n flipRate,\n byState,\n measuredAt: evidence.measuredAt,\n detail: byState.map(describeState).join('; '),\n }\n}\n\nfunction stateVerdict(\n state: OracleStateLabel,\n groups: readonly OracleReplicateGroup[],\n): OracleStateVerdict {\n const replicates = groups.flatMap((group) => [...group.replicates])\n const passes = replicates.filter((replicate) => replicate.passed).length\n const rates = groups.map(\n (group) => group.replicates.filter((r) => r.passed).length / group.replicates.length,\n )\n\n // Per-assertion counting needs every replicate to have reported assertions.\n // One replicate that did not makes the finer reading unavailable for this\n // state, and the coarser one is recorded as coarser rather than substituted.\n const perAssertion = replicates.every((replicate) => replicate.assertions !== null)\n const flipped: OracleFlippedUnit[] = []\n const assertionSetUnstable: string[] = []\n\n if (perAssertion) {\n const outcomes = new Map<string, boolean[]>()\n for (const replicate of replicates) {\n for (const assertion of replicate.assertions ?? []) {\n const seen = outcomes.get(assertion.id)\n if (seen) seen.push(assertion.passed)\n else outcomes.set(assertion.id, [assertion.passed])\n }\n }\n for (const [id, results] of [...outcomes].sort(([a], [b]) => a.localeCompare(b))) {\n if (results.length !== replicates.length) assertionSetUnstable.push(id)\n const unitPasses = results.filter(Boolean).length\n const unitFails = results.length - unitPasses\n const minority = Math.min(unitPasses, unitFails)\n // A unit missing from some replicates is a flip of the suite's shape, and\n // the replicates that did not report it count against it.\n const absent = replicates.length - results.length\n if (minority + absent > 0) {\n flipped.push({\n unit: id,\n passes: unitPasses,\n fails: unitFails + absent,\n flipRate: (minority + absent) / replicates.length,\n })\n }\n }\n } else {\n const minority = Math.min(passes, replicates.length - passes)\n if (minority > 0) {\n flipped.push({\n unit: SUITE_REWARD_UNIT,\n passes,\n fails: replicates.length - passes,\n flipRate: minority / replicates.length,\n })\n }\n }\n\n return {\n state,\n replicates: replicates.length,\n passes,\n fails: replicates.length - passes,\n granularity: perAssertion ? 'per-assertion' : 'reward',\n flipRate: flipped.reduce((worst, unit) => Math.max(worst, unit.flipRate), 0),\n flipped,\n assertionSetUnstable,\n loadSensitive: new Set(rates).size > 1,\n rewardsObserved: [...new Set(replicates.map((r) => r.reward ?? 'NO_REWARD_FILE'))].sort(),\n }\n}\n\nfunction describeState(state: OracleStateVerdict): string {\n const base =\n `${state.state}: ${state.passes}/${state.replicates} suite pass, ` +\n `${state.granularity} counting`\n if (state.flipped.length === 0) return `${base}, no flip`\n const worst = state.flipped.reduce((a, b) => (b.flipRate > a.flipRate ? b : a))\n return (\n `${base}, ${state.flipped.length} unit(s) flipped, worst ${worst.unit} ` +\n `${worst.passes}/${worst.passes + worst.fails} pass` +\n (state.loadSensitive ? ' (load-sensitive)' : '')\n )\n}\n\n/**\n * Certified verdicts by task name.\n *\n * A task with no entry is uncertified, which is not the same as unstable: one\n * says the check has not run, the other says it ran and the task failed it.\n * Both stop a row, with different reasons.\n */\nexport type TaskOracleRegistry = ReadonlyMap<string, OracleDeterminismVerdict>\n\n/**\n * What a checked-in certification file holds.\n *\n * It stores the measured replicates, not the verdicts they imply. The verdict\n * is re-derived on read by the same rule a campaign enforces, so a file cannot\n * declare a task stable — only the replicates can, and a reviewer can recount\n * them.\n */\nexport interface TaskOracleRegistryDocument {\n readonly version: 1\n readonly measurements: readonly OracleDeterminismEvidence[]\n}\n\nexport function parseTaskOracleRegistry(document: unknown): TaskOracleRegistry {\n if (typeof document !== 'object' || document === null) {\n throw new ValidationError('task oracle registry must be an object')\n }\n const { version, measurements } = document as Partial<TaskOracleRegistryDocument>\n if (version !== 1) {\n throw new ValidationError(`task oracle registry version must be 1, got ${String(version)}`)\n }\n if (!Array.isArray(measurements)) {\n throw new ValidationError('task oracle registry needs a measurements array')\n }\n return taskOracleRegistry(measurements.map((evidence) => oracleDeterminism(evidence)))\n}\n\nexport function taskOracleRegistry(\n verdicts: readonly OracleDeterminismVerdict[],\n): TaskOracleRegistry {\n const registry = new Map<string, OracleDeterminismVerdict>()\n for (const verdict of verdicts) {\n if (registry.has(verdict.taskName)) {\n throw new ValidationError(\n `task oracle registry received ${verdict.taskName} twice; a task has one certification`,\n )\n }\n registry.set(verdict.taskName, verdict)\n }\n return registry\n}\n\n/** Throws unless the task graded the same bytes the same way every replicate. */\nexport function assertDeterministicOracle(verdict: OracleDeterminismVerdict): void {\n if (verdict.stable) return\n throw new NondeterministicOracleError(\n `task ${verdict.taskName} graded byte-identical state inconsistently: flip rate ` +\n `${(verdict.flipRate * 100).toFixed(1)} % over ${verdict.replicates} replicates ` +\n `(${verdict.detail}). Its verdict is not a function of the state, so it cannot carry ` +\n 'ground truth for an intervention study.',\n )\n}\n","/**\n * The held-out suite, injected from outside the box at grade time.\n *\n * A repair is only measurable if the thing that decides pass or fail is out\n * of the trajectory's reach. Terminal-Bench gets that by uploading the suite\n * into the container at grade time, after the agent has stopped; a suite the\n * agent planted is overwritten before it is ever read. `injectedTestOracle`\n * reproduces that property and then proves it per call:\n *\n * 1. purge the suite root, so a planted extra file cannot survive\n * 2. upload every suite file from outside the session\n * 3. read the bytes back from inside and hash them\n * 4. refuse to grade when the read-back digest is not the uploaded digest\n *\n * Step 4 is why the property is asserted rather than assumed. A container\n * that silently drops the upload, or a filesystem trick that serves different\n * bytes to the reader, raises `TestSuiteTamperedError` instead of returning a\n * result. An oracle that cannot prove what it graded reports nothing.\n */\n\nimport { createHash } from 'node:crypto'\nimport { CaptureIntegrityError, ValidationError } from '../errors'\nimport type {\n RepairExecResult,\n RepairSession,\n TestOracle,\n TestOracleContext,\n TestOracleOutcome,\n} from './ports'\n\n/** The suite the oracle read back is not the suite it uploaded. */\nexport class TestSuiteTamperedError extends CaptureIntegrityError {}\n\n/** The oracle could not place or run the suite, so it graded nothing. */\nexport class TestOracleError extends CaptureIntegrityError {}\n\nexport interface TestSuiteFile {\n /** Absolute path inside the container. */\n readonly path: string\n readonly contents: string\n /** Octal mode applied after upload, e.g. '0755' for a runner script. */\n readonly mode?: string\n}\n\nexport interface InjectedTestOracleOptions {\n /** Every file of the held-out suite. Uploaded on every grade call. */\n readonly files: readonly TestSuiteFile[]\n /** Command that runs the suite. Exit 0 is the only pass. */\n readonly command: string\n /** Absolute directories removed before upload. A planted file that the\n * upload does not overwrite dies here. */\n readonly purge?: readonly string[]\n readonly uploadTimeoutMs?: number\n readonly commandTimeoutMs?: number\n}\n\nconst DEFAULT_UPLOAD_TIMEOUT_MS = 60_000\nconst DEFAULT_COMMAND_TIMEOUT_MS = 900_000\n\n/**\n * Content digest of the suite: sha256 over each path and its bytes, in path\n * order. Two suites with the same digest are the same suite.\n */\nexport function testSuiteDigest(files: readonly TestSuiteFile[]): string {\n const hash = createHash('sha256')\n for (const file of [...files].sort((a, b) => a.path.localeCompare(b.path))) {\n hash.update(file.path)\n hash.update('\\0')\n hash.update(Buffer.from(file.contents, 'utf8'))\n hash.update('\\0')\n }\n return hash.digest('hex')\n}\n\nexport function injectedTestOracle(options: InjectedTestOracleOptions): TestOracle {\n assertOracleOptions(options)\n const uploadTimeoutMs = options.uploadTimeoutMs ?? DEFAULT_UPLOAD_TIMEOUT_MS\n const commandTimeoutMs = options.commandTimeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS\n const expectedDigest = testSuiteDigest(options.files)\n\n return {\n async grade(session: RepairSession, context: TestOracleContext): Promise<TestOracleOutcome> {\n const where = `${context.rowId}/${context.arm}#${context.rolloutIndex}`\n\n for (const directory of options.purge ?? []) {\n await mustSucceed(\n session,\n `rm -rf ${shellQuote(directory)}`,\n uploadTimeoutMs,\n `purge ${directory} in ${where}`,\n )\n }\n\n for (const file of options.files) {\n const directory = parentDirectory(file.path)\n if (directory) {\n await mustSucceed(\n session,\n `mkdir -p ${shellQuote(directory)}`,\n uploadTimeoutMs,\n `mkdir ${directory} in ${where}`,\n )\n }\n const payload = Buffer.from(file.contents, 'utf8').toString('base64')\n await mustSucceed(\n session,\n `printf %s ${shellQuote(payload)} | base64 -d > ${shellQuote(file.path)}`,\n uploadTimeoutMs,\n `upload ${file.path} in ${where}`,\n )\n if (file.mode) {\n await mustSucceed(\n session,\n `chmod ${file.mode} ${shellQuote(file.path)}`,\n uploadTimeoutMs,\n `chmod ${file.path} in ${where}`,\n )\n }\n }\n\n const readBack: TestSuiteFile[] = []\n for (const file of options.files) {\n const result = await mustSucceed(\n session,\n `base64 < ${shellQuote(file.path)} | tr -d '\\\\n'`,\n uploadTimeoutMs,\n `read back ${file.path} in ${where}`,\n )\n readBack.push({\n path: file.path,\n contents: Buffer.from(result.stdout.trim(), 'base64').toString('utf8'),\n })\n }\n const observedDigest = testSuiteDigest(readBack)\n if (observedDigest !== expectedDigest) {\n throw new TestSuiteTamperedError(\n `test suite in ${where} does not match the suite uploaded from outside ` +\n `(expected ${expectedDigest}, read back ${observedDigest}); the graded result is discarded`,\n )\n }\n\n const run = await session.exec(options.command, commandTimeoutMs)\n return {\n passed: run.exitCode === 0 && !run.timedOut,\n exitCode: run.exitCode,\n output: `${run.stdout}\\n${run.stderr}`.trim(),\n suiteDigest: observedDigest,\n timedOut: run.timedOut,\n }\n },\n }\n}\n\n/**\n * Run a setup command that must succeed. A failed upload is an oracle\n * failure, never a failed test: reporting it as a failing suite would turn a\n * broken container into evidence against the intervention.\n */\nasync function mustSucceed(\n session: RepairSession,\n command: string,\n timeoutMs: number,\n what: string,\n): Promise<RepairExecResult> {\n const result = await session.exec(command, timeoutMs)\n if (result.timedOut) {\n throw new TestOracleError(`test oracle timed out while it tried to ${what}`)\n }\n if (result.exitCode !== 0) {\n throw new TestOracleError(\n `test oracle failed to ${what}: exit ${result.exitCode}\\n${result.stderr.trim()}`,\n )\n }\n return result\n}\n\nfunction assertOracleOptions(options: InjectedTestOracleOptions): void {\n if (options.files.length === 0) {\n throw new ValidationError('injectedTestOracle requires at least one suite file')\n }\n const seen = new Set<string>()\n for (const file of options.files) {\n if (!file.path.startsWith('/')) {\n throw new ValidationError(`suite file path must be absolute, got \"${file.path}\"`)\n }\n if (seen.has(file.path)) {\n throw new ValidationError(`suite file ${file.path} is listed twice`)\n }\n seen.add(file.path)\n }\n if (options.command.trim().length === 0) {\n throw new ValidationError('injectedTestOracle requires a suite command')\n }\n for (const directory of options.purge ?? []) {\n if (!directory.startsWith('/') || directory.trim() === '/') {\n throw new ValidationError(\n `purge path must be an absolute directory below the root, got \"${directory}\"`,\n )\n }\n }\n}\n\nfunction parentDirectory(path: string): string | null {\n const index = path.lastIndexOf('/')\n if (index <= 0) return null\n return path.slice(0, index)\n}\n\nfunction shellQuote(value: string): string {\n return `'${value.replaceAll(\"'\", `'\\\\''`)}'`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,kBAAkB;;A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rE,IAAI,QAAQ,MAAM,WAAW,GAC3B,MAAM,IAAI,gBAAgB,qDAAqD;CAEjF,MAAM,uBAAO,IAAI,IAAY;CAC7B,KAAK,MAAM,QAAQ,QAAQ,OAAO;EAChC,IAAI,CAAC,KAAK,KAAK,WAAW,GAAG,GAC3B,MAAM,IAAI,gBAAgB,0CAA0C,KAAK,KAAK,EAAE;EAElF,IAAI,KAAK,IAAI,KAAK,IAAI,GACpB,MAAM,IAAI,gBAAgB,cAAc,KAAK,KAAK,iBAAiB;EAErE,KAAK,IAAI,KAAK,IAAI;CACpB;CACA,IAAI,QAAQ,QAAQ,KAAK,CAAC,CAAC,WAAW,GACpC,MAAM,IAAI,gBAAgB,6CAA6C;CAEzE,KAAK,MAAM,aAAa,QAAQ,SAAS,CAAC,GACxC,IAAI,CAAC,UAAU,WAAW,GAAG,KAAK,UAAU,KAAK,MAAM,KACrD,MAAM,IAAI,gBACR,iEAAiE,UAAU,EAC7E;AAGN;AAEA,SAAS,gBAAgB,MAA6B;CACpD,MAAM,QAAQ,KAAK,YAAY,GAAG;CAClC,IAAI,SAAS,GAAG,OAAO;CACvB,OAAO,KAAK,MAAM,GAAG,KAAK;AAC5B;AAEA,SAAS,WAAW,OAAuB;CACzC,OAAO,IAAI,MAAM,WAAW,KAAK,OAAO,EAAE;AAC5C"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["requirePositiveInteger","admitRow","describe","describe"],"sources":["../../src/trace-repair/mini-swe-scaffold.ts","../../src/trace-repair/action-budget.ts","../../src/trace-repair/admission-records.ts","../../src/trace-repair/continuation-policy.ts","../../src/trace-repair/control-policy.ts","../../src/trace-repair/admission.ts","../../src/trace-repair/admission-contract.ts","../../src/trace-repair/admission-report.ts","../../src/trace-repair/blinding.ts","../../src/trace-repair/repair-prompt.ts","../../src/trace-repair/analyst-arm.ts","../../src/trace-repair/analyst-response.ts","../../src/trace-repair/arm-completion.ts","../../src/trace-repair/arm-dspy.ts","../../src/trace-repair/continuation-records.ts","../../src/trace-repair/degenerate-strategies.ts","../../src/trace-repair/funnel.ts","../../src/trace-repair/delta-repair.ts","../../src/trace-repair/docker-environment.ts","../../src/trace-repair/grade.ts","../../src/trace-repair/oracle-determinism.ts","../../src/trace-repair/test-oracle.ts"],"sourcesContent":["/**\n * The mini-swe-agent scaffold as the Terminal-Bench-2 trajectory corpus\n * recorded it: one bash block per turn, one observation per command, and a\n * sentinel command that ends the run.\n *\n * Every template here is byte-verified against\n * `yoonholee/terminalbench-trajectories` (agent = `mini-swe-agent`, 6663 rows,\n * one distinct system prompt across all of them). A continuation that renders\n * different bytes puts the model in a different distribution than the prefix\n * it inherits, so these strings are pinned, not configurable.\n *\n * The markers a reader matches on live in `trajectory-replay/steps`, which owns\n * the recorded grammar. This module writes with them so a rendered observation\n * and a recorded one classify the same way.\n */\n\nimport {\n FORMAT_ERROR_OBSERVATION_PREFIX,\n SUBMIT_ACTION_SIGNATURE,\n TIMEOUT_OBSERVATION_MARKER,\n} from '../trajectory-replay/steps'\n\nexport { isRecordedTimeout } from '../trajectory-replay/steps'\n\n/** Whole-line marker that ends a run. The first output line must equal it and the command must exit 0. */\nexport const SUBMIT_SENTINEL = SUBMIT_ACTION_SIGNATURE\n\n/** Outputs at or above this length are elided head+tail instead of shown whole. */\nexport const OUTPUT_ELISION_THRESHOLD = 10_000\n\n/** Characters kept from each end of an elided output. */\nconst OUTPUT_ELISION_WINDOW = 5_000\n\nexport const MINI_SWE_SYSTEM_MESSAGE = `You are a helpful assistant that can interact with a computer.\n\nYour response must contain exactly ONE bash code block with ONE command (or commands connected with && or ||).\nInclude a THOUGHT section before your command where you explain your reasoning process.\nFormat your response as shown in <format_example>.\n\n<format_example>\nYour reasoning and analysis here. Explain why you want to perform the action.\n\n\\`\\`\\`bash\nyour_command_here\n\\`\\`\\`\n</format_example>\n\nFailure to follow these rules will cause your response to be rejected.\n`\n\nexport interface InstanceMessageInput {\n /** The task statement, substituted verbatim. */\n task: string\n /**\n * `uname`-style line the recorded runs rendered from the host running the\n * scaffold, e.g. `Linux 6.8.0-86-generic #87-Ubuntu SMP ... x86_64`.\n */\n systemInformation: string\n}\n\n/** The second message of every recorded run: task plus workflow rules. */\nexport function renderInstanceMessage(input: InstanceMessageInput): string {\n return `Please solve this issue: ${input.task}\n\nYou can execute bash commands and edit files to implement the necessary changes.\n\n## Recommended Workflow\n\nThis workflows should be done step-by-step so that you can iterate on your changes and any possible problems.\n\n1. Analyze the codebase by finding and reading relevant files\n2. Create a script to reproduce the issue\n3. Edit the source code to resolve the issue\n4. Verify your fix works by running your script again\n5. Test edge cases to ensure your fix is robust\n6. Submit your changes and finish your work by issuing the following command: \\`echo ${SUBMIT_SENTINEL}\\`.\n Do not combine it with any other command. <important>After this command, you cannot continue working on this task.</important>\n\n## Important Rules\n\n1. Every response must contain exactly one action\n2. The action must be enclosed in triple backticks\n3. Directory or environment variable changes are not persistent. Every action is executed in a new subshell.\n However, you can prefix any action with \\`MY_ENV_VAR=MY_VALUE cd /path/to/working/dir && ...\\` or write/load environment variables from files\n\n<system_information>\n${input.systemInformation}\n</system_information>\n\n## Formatting your response\n\nHere is an example of a correct response:\n\n<example_response>\nTHOUGHT: I need to understand the structure of the repository first. Let me check what files are in the current directory to get a better understanding of the codebase.\n\n\\`\\`\\`bash\nls -la\n\\`\\`\\`\n</example_response>\n\n## Useful command examples\n\n### Create a new file:\n\n\\`\\`\\`bash\ncat <<'EOF' > newfile.py\nimport numpy as np\nhello = \"world\"\nprint(hello)\nEOF\n\\`\\`\\`\n\n### Edit files with sed:\\`\\`\\`bash\n# Replace all occurrences\nsed -i 's/old_string/new_string/g' filename.py\n\n# Replace only first occurrence\nsed -i 's/old_string/new_string/' filename.py\n\n# Replace first occurrence on line 1\nsed -i '1s/old_string/new_string/' filename.py\n\n# Replace all occurrences in lines 1-10\nsed -i '1,10s/old_string/new_string/g' filename.py\n\\`\\`\\`\n\n### View file content:\n\n\\`\\`\\`bash\n# View specific lines with numbers\nnl -ba filename.py | sed -n '10,20p'\n\\`\\`\\`\n\n### Any other command you want to run\n\n\\`\\`\\`bash\nanything\n\\`\\`\\`\n`\n}\n\nexport type ParsedAction =\n | { kind: 'action'; command: string }\n | { kind: 'format-error'; actionCount: number }\n\nconst BASH_BLOCK = /```bash\\n(.*?)\\n```/gs\n\n/**\n * Exactly one fenced bash block is an action; zero or many is a format error.\n * The scaffold trims the command, so a block padded with blank lines executes\n * the same command as an unpadded one.\n */\nexport function parseAction(assistantMessage: string): ParsedAction {\n const blocks = [...assistantMessage.matchAll(BASH_BLOCK)].map((match) => match[1] ?? '')\n if (blocks.length !== 1) return { kind: 'format-error', actionCount: blocks.length }\n return { kind: 'action', command: (blocks[0] ?? '').trim() }\n}\n\nexport interface CommandOutput {\n returncode: number\n output: string\n /** Set when the environment itself failed rather than the command. */\n exceptionInfo?: string\n}\n\n/**\n * The observation the agent reads after a command. Short outputs are shown\n * whole; long ones keep the first and last `OUTPUT_ELISION_WINDOW` characters\n * with the dropped count between them.\n */\nexport function renderObservation(output: CommandOutput): string {\n const head = output.exceptionInfo ? `<exception>${output.exceptionInfo}</exception>\\n` : ''\n const returncode = `<returncode>${output.returncode}</returncode>\\n`\n if (output.output.length < OUTPUT_ELISION_THRESHOLD) {\n return `${head}${returncode}<output>\\n${output.output}</output>`\n }\n const elided = output.output.length - OUTPUT_ELISION_THRESHOLD\n return (\n `${head}${returncode}<warning>\\n` +\n 'The output of your last command was too long.\\n' +\n 'Please try a different command that produces less output.\\n' +\n \"If you're looking at a file you can try use head, tail or sed to view a smaller number of lines selectively.\\n\" +\n \"If you're using grep or find and it produced too much output, you can use a more selective search pattern.\\n\" +\n \"If you really need to see something from the full command's output, you can redirect output to a file and then search in that file.\\n\" +\n '</warning>' +\n `<output_head>\\n${output.output.slice(0, OUTPUT_ELISION_WINDOW)}\\n</output_head>\\n` +\n `<elided_chars>\\n${elided} characters elided\\n</elided_chars>\\n` +\n `<output_tail>\\n${output.output.slice(-OUTPUT_ELISION_WINDOW)}\\n</output_tail>`\n )\n}\n\n/** The observation after the environment killed a command for exceeding its timeout. */\nexport function renderTimeoutObservation(command: string, partialOutput: string): string {\n return (\n `The last command <command>${command}</command> ${TIMEOUT_OBSERVATION_MARKER}.\\n` +\n `The output of the command was:\\n <output>\\n${partialOutput}\\n</output>\\n` +\n 'Please try another command and make sure to avoid those requiring interactive input.'\n )\n}\n\n/** The observation after a turn that did not contain exactly one bash block. */\nexport function renderFormatErrorObservation(actionCount: number): string {\n return (\n `${FORMAT_ERROR_OBSERVATION_PREFIX}${actionCount} actions.\\n` +\n `If you want to end the task, please issue the following command: \\`echo ${SUBMIT_SENTINEL}\\`\\n` +\n 'without any other command.\\n' +\n 'Else, please format your response exactly as follows:\\n' +\n '\\n' +\n '<response_example>\\n' +\n 'Here are some thoughts about why you want to perform the action.\\n' +\n '\\n' +\n '```bash\\n' +\n '<action>\\n' +\n '```\\n' +\n '</response_example>\\n' +\n '\\n' +\n 'Note: In rare cases, if you need to reference a similar format in your command, you might have\\n' +\n 'to proceed in two steps, first writing TRIPLEBACKTICKSBASH, then replacing them with ```bash.'\n )\n}\n\n/**\n * The submission text when this output ends the run, `null` otherwise.\n * A non-zero exit does not submit even when the sentinel is echoed, so an\n * agent cannot end the run through a command that failed.\n */\nexport function submissionOf(output: CommandOutput): string | null {\n if (output.returncode !== 0) return null\n const lines = output.output.replace(/^\\s+/, '').split(/(?<=\\n)/)\n const first = lines[0]\n if (first === undefined || first.trim() !== SUBMIT_SENTINEL) return null\n return lines.slice(1).join('')\n}\n","/**\n * The action budget an intervention must fit inside.\n *\n * The analyst answers with one action, applied at step k, drawn from the same\n * action space the scaffold had: one shell command or one edit, at most 4 KB.\n * An answer that buys a bigger action than the scaffold could take is not a\n * counterfactual about the recorded run, so the budget is enforced before any\n * container is opened and a violation never reaches the reproduction gate.\n *\n * \"One action\" is decided by counting top-level statements, not lines. A\n * command list joined by `&&`, `||` or a pipe is one statement, because that\n * is one thing the shell runs and one thing the scaffold could have typed.\n * Two statements separated by a newline or `;` are two actions and are\n * rejected. Heredoc bodies, comments and compound blocks (`if`, `for`,\n * `while`, `until`, `case`, `{ … }`) are inside a statement, never separators.\n */\n\nimport { ValidationError } from '../errors'\nimport { SUBMIT_SENTINEL } from './mini-swe-scaffold'\n\n/**\n * Payload shape of an action.\n *\n * `edit` authors file content inline through a heredoc; `shell` runs a\n * command. The split matters because the two carry different amounts of\n * information for the same byte count, and a report that pools them hides it.\n */\nexport type ActionPayloadKind = 'shell' | 'edit'\n\nexport interface InterventionBudget {\n /** Hard cap on the UTF-8 byte length of the action. */\n readonly maxBytes: number\n /** Top-level statements the action may contain. One means one action. */\n readonly maxStatements: number\n /** Heredoc redirections an `edit` may contain. One means one file. */\n readonly maxHeredocs: number\n}\n\n/** The scaffold's own per-action budget, pre-registered for the campaign. */\nexport const SCAFFOLD_INTERVENTION_BUDGET: InterventionBudget = Object.freeze({\n maxBytes: 4096,\n maxStatements: 1,\n maxHeredocs: 1,\n})\n\n/**\n * Actions whose only effect is to consume a turn. They are rejected before a\n * container opens: an intervention that changes nothing is measurably\n * identical to the no-op control, and paying rollouts to rediscover that\n * wastes the corpus.\n */\nexport const NO_OP_ACTIONS: readonly string[] = Object.freeze([\n ':',\n 'true',\n '/bin/true',\n 'exit',\n 'exit 0',\n])\n\ninterface HeredocMark {\n delimiter: string\n stripTabs: boolean\n quoted: boolean\n}\n\ninterface ScanState {\n statements: string[]\n current: string\n heredocs: number\n}\n\nconst BLOCK_OPENERS = new Set(['if', 'for', 'while', 'until', 'case', 'select', 'do', 'then'])\nconst BLOCK_CLOSERS = new Set(['fi', 'done', 'esac'])\n\n/**\n * Split a shell script into top-level statements and count its heredocs.\n *\n * The scan tracks quoting, escapes, command substitution, brace and paren\n * grouping, comments, compound-block keywords, and heredoc bodies. Anything\n * it cannot resolve stays inside the current statement, so an unparseable\n * action reads as one oversized statement and is rejected on bytes rather\n * than silently accepted as one clean action.\n */\nexport function scanShellAction(script: string): { statements: string[]; heredocs: number } {\n const state: ScanState = { statements: [], current: '', heredocs: 0 }\n let index = 0\n let parenDepth = 0\n let braceDepth = 0\n let blockDepth = 0\n let inSingle = false\n let inDouble = false\n let inBacktick = false\n let pendingHeredocs: HeredocMark[] = []\n let word = ''\n let atStatementStart = true\n\n const flushWord = (): void => {\n if (word.length === 0) return\n if (BLOCK_OPENERS.has(word)) blockDepth += 1\n else if (BLOCK_CLOSERS.has(word)) blockDepth = Math.max(0, blockDepth - 1)\n word = ''\n }\n\n const endStatement = (): void => {\n flushWord()\n const text = state.current.trim()\n // A comment runs no command, so a comment-only chunk is not a statement.\n if (text.length > 0 && !isCommentOnly(text)) state.statements.push(text)\n state.current = ''\n atStatementStart = true\n }\n\n while (index < script.length) {\n const char = script[index]!\n\n if (inSingle) {\n state.current += char\n if (char === \"'\") inSingle = false\n index += 1\n continue\n }\n\n if (char === '\\\\' && index + 1 < script.length) {\n const next = script[index + 1]!\n if (next === '\\n' && !inDouble) {\n // Line continuation: the statement carries on.\n state.current += char + next\n index += 2\n continue\n }\n state.current += char + next\n index += 2\n continue\n }\n\n if (inDouble) {\n state.current += char\n if (char === '\"') inDouble = false\n index += 1\n continue\n }\n\n if (char === \"'\") {\n flushWord()\n inSingle = true\n state.current += char\n index += 1\n atStatementStart = false\n continue\n }\n\n if (char === '\"') {\n flushWord()\n inDouble = true\n state.current += char\n index += 1\n atStatementStart = false\n continue\n }\n\n if (char === '`') {\n inBacktick = !inBacktick\n state.current += char\n index += 1\n atStatementStart = false\n continue\n }\n\n if (char === '#' && (atStatementStart || /\\s/.test(script[index - 1] ?? ' '))) {\n const end = script.indexOf('\\n', index)\n const stop = end === -1 ? script.length : end\n state.current += script.slice(index, stop)\n index = stop\n continue\n }\n\n // Heredoc introducer: `<<WORD`, `<<-WORD`, `<<'WORD'`. A run of three `<`\n // is a herestring, so neither of its `<<` pairs may open a heredoc.\n if (\n char === '<' &&\n script[index + 1] === '<' &&\n script[index + 2] !== '<' &&\n script[index - 1] !== '<'\n ) {\n const mark = readHeredocMark(script, index)\n if (mark) {\n pendingHeredocs.push(mark.mark)\n state.heredocs += 1\n state.current += script.slice(index, mark.nextIndex)\n index = mark.nextIndex\n atStatementStart = false\n continue\n }\n }\n\n if (char === '(') {\n flushWord()\n parenDepth += 1\n state.current += char\n index += 1\n atStatementStart = true\n continue\n }\n if (char === ')') {\n flushWord()\n parenDepth = Math.max(0, parenDepth - 1)\n state.current += char\n index += 1\n atStatementStart = false\n continue\n }\n if (char === '{') {\n flushWord()\n braceDepth += 1\n state.current += char\n index += 1\n atStatementStart = true\n continue\n }\n if (char === '}') {\n flushWord()\n braceDepth = Math.max(0, braceDepth - 1)\n state.current += char\n index += 1\n atStatementStart = false\n continue\n }\n\n if (char === '\\n') {\n flushWord()\n if (pendingHeredocs.length > 0) {\n const consumed = consumeHeredocBodies(script, index + 1, pendingHeredocs)\n state.current += script.slice(index, consumed)\n pendingHeredocs = []\n index = consumed\n continue\n }\n if (\n parenDepth > 0 ||\n braceDepth > 0 ||\n blockDepth > 0 ||\n inBacktick ||\n endsWithContinuation(state.current)\n ) {\n state.current += char\n index += 1\n atStatementStart = true\n continue\n }\n endStatement()\n index += 1\n continue\n }\n\n if (char === ';') {\n flushWord()\n if (parenDepth > 0 || braceDepth > 0 || blockDepth > 0 || inBacktick) {\n state.current += char\n index += 1\n atStatementStart = true\n continue\n }\n endStatement()\n index += 1\n continue\n }\n\n if (/\\s/.test(char)) {\n flushWord()\n state.current += char\n index += 1\n continue\n }\n\n if (char === '&' || char === '|') {\n flushWord()\n state.current += char\n index += 1\n atStatementStart = true\n continue\n }\n\n word += char\n state.current += char\n atStatementStart = false\n index += 1\n }\n\n endStatement()\n return { statements: state.statements, heredocs: state.heredocs }\n}\n\nfunction isCommentOnly(text: string): boolean {\n return text.split('\\n').every((line) => line.trim().length === 0 || line.trim().startsWith('#'))\n}\n\nfunction endsWithContinuation(current: string): boolean {\n const trimmed = current.trimEnd()\n return /(&&|\\|\\||\\||&|\\\\)$/.test(trimmed)\n}\n\nfunction readHeredocMark(\n script: string,\n index: number,\n): { mark: HeredocMark; nextIndex: number } | null {\n let cursor = index + 2\n let stripTabs = false\n if (script[cursor] === '-') {\n stripTabs = true\n cursor += 1\n }\n while (script[cursor] === ' ' || script[cursor] === '\\t') cursor += 1\n const quote = script[cursor]\n if (quote === \"'\" || quote === '\"') {\n const close = script.indexOf(quote, cursor + 1)\n if (close === -1) return null\n return {\n mark: { delimiter: script.slice(cursor + 1, close), stripTabs, quoted: true },\n nextIndex: close + 1,\n }\n }\n const match = /^[A-Za-z_][A-Za-z0-9_]*/.exec(script.slice(cursor))\n if (!match) return null\n return {\n mark: { delimiter: match[0], stripTabs, quoted: false },\n nextIndex: cursor + match[0].length,\n }\n}\n\n/** Consume every pending heredoc body; returns the offset just past the last\n * terminator, or the end of the script when a terminator never arrives. */\nfunction consumeHeredocBodies(script: string, from: number, marks: HeredocMark[]): number {\n let cursor = from\n for (const mark of marks) {\n let closed = false\n while (cursor < script.length) {\n const lineEnd = script.indexOf('\\n', cursor)\n const stop = lineEnd === -1 ? script.length : lineEnd\n const line = script.slice(cursor, stop)\n const candidate = mark.stripTabs ? line.replace(/^\\t+/, '') : line\n cursor = lineEnd === -1 ? script.length : lineEnd + 1\n if (candidate === mark.delimiter) {\n closed = true\n break\n }\n }\n if (!closed) return script.length\n }\n return cursor\n}\n\n/** Payload shape of an action: `edit` when it authors file content through a\n * heredoc, `shell` otherwise. */\nexport function classifyActionPayload(action: string): ActionPayloadKind {\n return scanShellAction(action).heredocs > 0 ? 'edit' : 'shell'\n}\n\n/** Why an action fails the budget. Every value is a rejection the report\n * counts by name; none of them is a scoring judgement. */\nexport type BudgetViolation =\n | 'empty'\n | 'over-byte-cap'\n | 'multiple-statements'\n | 'multiple-heredocs'\n | 'no-op-action'\n | 'submit-instead-of-repair'\n\nexport interface BudgetMeasurement {\n bytes: number\n statements: number\n heredocs: number\n /** What the action IS, measured from its text. */\n payload: ActionPayloadKind\n /** What the analyst SAID it was. Recorded, never a rejection. */\n declared: ActionPayloadKind\n}\n\nexport type BudgetCheck =\n | { readonly admissible: true; readonly measurement: BudgetMeasurement }\n | {\n readonly admissible: false\n readonly violation: BudgetViolation\n readonly detail: string\n readonly measurement: BudgetMeasurement\n }\n\n/** Re-exported so budget callers read the sentinel from the module that\n * measures actions. Submitting is how the recorded agent ended a run that the\n * tests then failed, so it can never be the repair. */\nexport { SUBMIT_SENTINEL } from './mini-swe-scaffold'\n\n/**\n * Measure an action against the budget.\n *\n * The budget bounds what the scaffold can execute: one top-level statement,\n * one authored file, a byte cap, and neither a no-op nor a submit. Every\n * rejection here is one of those.\n *\n * `declaredKind` is what the analyst called its own action. It is recorded\n * beside the measured payload and never rejected on, because the scaffold runs\n * the action identically either way — so rejecting the label scores an arm on\n * how it described a repair rather than on the repair. A reader who wants the\n * mismatch counts `declared` against `payload`.\n */\nexport function checkInterventionBudget(\n action: string,\n declaredKind: ActionPayloadKind,\n budget: InterventionBudget = SCAFFOLD_INTERVENTION_BUDGET,\n): BudgetCheck {\n assertBudget(budget)\n const scan = scanShellAction(action)\n const payload: ActionPayloadKind = scan.heredocs > 0 ? 'edit' : 'shell'\n const measurement: BudgetMeasurement = {\n bytes: Buffer.byteLength(action, 'utf8'),\n statements: scan.statements.length,\n heredocs: scan.heredocs,\n payload,\n declared: declaredKind,\n }\n const reject = (violation: BudgetViolation, detail: string): BudgetCheck => ({\n admissible: false,\n violation,\n detail,\n measurement,\n })\n\n if (action.trim().length === 0) return reject('empty', 'the intervention is empty')\n if (measurement.bytes > budget.maxBytes) {\n return reject(\n 'over-byte-cap',\n `${measurement.bytes} bytes exceeds the ${budget.maxBytes}-byte action budget`,\n )\n }\n if (measurement.statements > budget.maxStatements) {\n return reject(\n 'multiple-statements',\n `${measurement.statements} top-level statements exceeds the ${budget.maxStatements} the scaffold takes per action`,\n )\n }\n if (measurement.heredocs > budget.maxHeredocs) {\n return reject(\n 'multiple-heredocs',\n `${measurement.heredocs} heredocs exceeds the ${budget.maxHeredocs} one edit may author`,\n )\n }\n if (action.includes(SUBMIT_SENTINEL)) {\n return reject('submit-instead-of-repair', 'the action submits the run instead of repairing it')\n }\n if (NO_OP_ACTIONS.includes(action.trim())) {\n return reject('no-op-action', `\"${action.trim()}\" changes nothing`)\n }\n return { admissible: true, measurement }\n}\n\nfunction assertBudget(budget: InterventionBudget): void {\n for (const field of ['maxBytes', 'maxStatements', 'maxHeredocs'] as const) {\n const value = budget[field]\n if (!Number.isInteger(value) || value <= 0) {\n throw new ValidationError(\n `intervention budget ${field} must be a positive integer, got ${value}`,\n )\n }\n }\n}\n\n/**\n * Whitespace-insensitive comparison used to reject an intervention that is\n * the recorded action again. Trailing whitespace and blank lines are the only\n * differences a re-proposal can carry without changing what runs.\n */\nexport function normalizeActionForComparison(action: string): string {\n return action\n .split('\\n')\n .map((line) => line.trimEnd())\n .filter((line, index, lines) => line.length > 0 || (index > 0 && index < lines.length - 1))\n .join('\\n')\n .trim()\n}\n","/**\n * The vocabulary of the TB-Repair admission pre-pass: what a corpus row is,\n * which failure population it belongs to, why it can leave the funnel, and the\n * denominator chain those exclusions add up to.\n *\n * Pure data and pure functions. The gate that spends containers on these types\n * lives in `admission.ts`, and the artifact that publishes them lives in\n * `admission-report.ts`.\n */\n\nimport { CaptureIntegrityError } from '../errors'\nimport type { ContinuationRollout } from './continuation-records'\nimport type { ControlScreening } from './control-policy'\n\n/** A campaign scored rows the pre-pass did not admit, or dropped rows it did. */\nexport class AdmissionDenominatorError extends CaptureIntegrityError {}\n\n/** A row handed to the pre-pass carried a field only an analyst could produce. */\nexport class AdmissionIndependenceError extends CaptureIntegrityError {}\n\n// ── Rows ─────────────────────────────────────────────────────────────\n\n/**\n * One corpus row, described by what the recording holds and nothing else.\n *\n * The field list is closed on purpose: `assertAnalystIndependent` rejects any\n * extra key, which is what stops a finding, a step index, or a proposed\n * intervention from reaching the gate that fixes the denominator.\n */\nexport interface AdmissionRow {\n /** Stable identifier for the recorded trajectory. Duplicates are rejected. */\n rowId: string\n /** Terminal-Bench-2 task the trajectory ran. */\n taskName: string\n /** Model that produced the recorded trajectory. */\n recordedModel: string\n /**\n * Recorded shell commands. An action can be substituted at any one of them,\n * and a replay must execute all of them to reach the recorded end state.\n */\n recordedCommands: number\n /**\n * Return code of the trajectory's last recorded observation. Negative values\n * are signal kills and are real. `null` means the recording did not parse,\n * which excludes the row instead of defaulting it.\n */\n finalReturncode: number | null\n}\n\nconst ADMISSION_ROW_KEYS: readonly string[] = [\n 'rowId',\n 'taskName',\n 'recordedModel',\n 'recordedCommands',\n 'finalReturncode',\n]\n\n/**\n * Reject rows that carry anything beyond the recording.\n *\n * The check is a closed key list rather than a list of known analyst field\n * names, because the failure to catch is \"some new analyst output leaked into\n * the gate\", and only a closed shape catches the fields nobody thought of.\n */\nexport function assertAnalystIndependent(rows: readonly AdmissionRow[]): void {\n const allowed = new Set(ADMISSION_ROW_KEYS)\n for (const row of rows) {\n const extra = Object.keys(row).filter((key) => !allowed.has(key))\n if (extra.length > 0) {\n throw new AdmissionIndependenceError(\n `admission row ${String(row.rowId)} carries analyst-side fields: ${extra.sort().join(', ')}`,\n )\n }\n }\n}\n\n// ── Strata ───────────────────────────────────────────────────────────\n\n/**\n * Failure population a row belongs to.\n *\n * - `clean-exit` — the last command exited 0 and the tests still fail, so the\n * agent stopped believing it was done. The assay measured 87.13% of admitted\n * failures here.\n * - `command-error` — the last command exited non-zero.\n * - `signal-kill` — the last command was killed by a signal, recorded as a\n * negative return code. Substituting one command does not address a timeout,\n * so this population stays separate from the other two.\n */\nexport type AdmissionStratum = 'clean-exit' | 'command-error' | 'signal-kill'\n\nexport const ADMISSION_STRATA: readonly AdmissionStratum[] = [\n 'clean-exit',\n 'command-error',\n 'signal-kill',\n]\n\n/** `null` when the recording holds no parseable final return code. */\nexport function stratumOf(finalReturncode: number | null): AdmissionStratum | null {\n if (finalReturncode === null || !Number.isInteger(finalReturncode)) return null\n if (finalReturncode === 0) return 'clean-exit'\n return finalReturncode < 0 ? 'signal-kill' : 'command-error'\n}\n\n// ── Exclusion reasons ────────────────────────────────────────────────\n\n/**\n * Why a row left the funnel.\n *\n * `ADMISSION_EXCLUSION_ORDER` is the order the gate applies the checks, and it\n * is cost-ordered: everything decidable from the recording runs before the\n * first container, and the control rollouts run last.\n */\nexport type AdmissionExclusionReason =\n | 'no-recorded-commands'\n | 'unparseable-final-returncode'\n | 'stratum-not-admitted'\n | 'task-oracle-uncertified'\n | 'task-oracle-nondeterministic'\n | 'prefix-replay-error'\n | 'prefix-replay-empty'\n | 'prefix-replay-truncated'\n | 'prefix-divergence-above-threshold'\n | 'end-state-oracle-error'\n | 'end-state-tests-pass'\n | 'no-fix-control-error'\n | 'no-fix-control-rescued'\n | 'no-op-control-error'\n | 'no-op-control-rescued'\n\nexport const ADMISSION_EXCLUSION_ORDER: readonly AdmissionExclusionReason[] = [\n 'no-recorded-commands',\n 'unparseable-final-returncode',\n 'stratum-not-admitted',\n 'task-oracle-uncertified',\n 'task-oracle-nondeterministic',\n 'prefix-replay-error',\n 'prefix-replay-empty',\n 'prefix-replay-truncated',\n 'prefix-divergence-above-threshold',\n 'end-state-oracle-error',\n 'end-state-tests-pass',\n 'no-fix-control-error',\n 'no-fix-control-rescued',\n 'no-op-control-error',\n 'no-op-control-rescued',\n]\n\n/** Reasons decided from the recording alone, before a row can be stratified. */\nconst PRE_STRATUM_REASONS: readonly AdmissionExclusionReason[] = [\n 'no-recorded-commands',\n 'unparseable-final-returncode',\n]\n\nfunction isPreStratumReason(reason: AdmissionExclusionReason): boolean {\n return PRE_STRATUM_REASONS.includes(reason)\n}\n\n/** One line of prose per reason, for the rendered chain. */\nexport const ADMISSION_EXCLUSION_MEANING: Readonly<Record<AdmissionExclusionReason, string>> =\n Object.freeze({\n 'no-recorded-commands': 'the recording holds no command to substitute',\n 'unparseable-final-returncode': 'the last observation carries no return code',\n 'stratum-not-admitted': 'the row belongs to a population this campaign excluded',\n 'task-oracle-uncertified': 'the task grader has no determinism certification on file',\n 'task-oracle-nondeterministic':\n 'the task grader returns different verdicts on byte-identical state',\n 'prefix-replay-error': 'the replay boundary failed, so divergence is unmeasured',\n 'prefix-replay-empty': 'the replay executed no recorded step',\n 'prefix-replay-truncated': 'the replay stopped short of the recorded end state',\n 'prefix-divergence-above-threshold': 'replaying the prefix did not reproduce the recording',\n 'end-state-oracle-error': 'the task grader failed, so the end state is unjudged',\n 'end-state-tests-pass': 'the task tests pass on the recorded end state, so nothing failed',\n 'no-fix-control-error': 'a no-fix rollout failed to run, so the control is unmeasured',\n 'no-fix-control-rescued': 'the continuation policy passes the task with no intervention',\n 'no-op-control-error': 'a no-op rollout failed to run, so the control is unmeasured',\n 'no-op-control-rescued': 'an inert action plus continuation passes the task',\n })\n\n// ── Per-row verdict ──────────────────────────────────────────────────\n\nexport type AdmissionControlArm = 'no-fix-control' | 'no-op-control'\n\n/** The inert action the no-op control substitutes, and where it goes. */\nexport interface AdmissionNoOpInjection {\n /** 1-based recorded command the inert action replaces. */\n step: number\n action: string\n}\n\nexport type AdmissionCheckRecord =\n | { check: 'stratum'; stratum: AdmissionStratum }\n | {\n check: 'prefix-replay'\n prefixExecuted: number\n divergences: number\n divergenceRatio: number\n }\n | { check: 'task-oracle'; stable: boolean; flipRate: number; replicates: number }\n | { check: 'end-state-tests'; passed: boolean; reward: number | null }\n | {\n check: 'control'\n arm: AdmissionControlArm\n rolloutsRun: number\n passes: number\n injections: AdmissionNoOpInjection[]\n }\n\n/** What one control rollout did, small enough to serialize for every row. */\nexport interface AdmissionRolloutSummary {\n arm: AdmissionControlArm\n index: number\n seed: number\n policyDigest: string\n exitStatus: ContinuationRollout['exitStatus']\n testsPassed: boolean\n /** `null` when the rollout carried an unpriced model call. */\n costUsd: number | null\n}\n\nexport interface AdmissionRowVerdict {\n rowId: string\n taskName: string\n recordedModel: string\n recordedCommands: number\n finalReturncode: number | null\n /** `null` only together with a pre-stratum exclusion reason. */\n stratum: AdmissionStratum | null\n /** The control this row was screened under, and how a control pass reads.\n * Recorded on every verdict, including rows excluded before a control ran,\n * so a reader never has to open the runner's source to learn what screened\n * the row. */\n controlPolicyDigest: string\n controlScreening: ControlScreening\n /** The task's certified oracle flip rate. Zero on a certified-stable task,\n * `null` when the task carried no certification. */\n oracleFlipRate: number | null\n admitted: boolean\n /** `null` when the row is admitted. */\n excludedBy: AdmissionExclusionReason | null\n /** Message from the boundary that failed, on the four `*-error` reasons. */\n errorDetail: string | null\n /** Checks that ran, in order. A check never reached is absent, not zero. */\n checks: AdmissionCheckRecord[]\n rollouts: AdmissionRolloutSummary[]\n}\n\n// ── Denominator chain ────────────────────────────────────────────────\n\nexport interface DenominatorStage {\n reason: AdmissionExclusionReason\n entering: number\n excluded: number\n remaining: number\n}\n\nexport interface DenominatorChain {\n /** `all` counts every input row; a stratum chain starts after stratification. */\n scope: 'all' | AdmissionStratum\n input: number\n stages: DenominatorStage[]\n admitted: number\n}\n\nexport interface DenominatorChainArtifact {\n version: 1\n overall: DenominatorChain\n byStratum: DenominatorChain[]\n reasonTotals: Record<AdmissionExclusionReason, number>\n /** Rows excluded before a stratum could be assigned. */\n unstratified: number\n /** Strata this run admitted. Others can only reach `stratum-not-admitted`. */\n admitStrata: readonly AdmissionStratum[]\n}\n\n/**\n * Build the funnel every campaign report publishes.\n *\n * Each stage names the reason, the rows that reached it, the rows it removed,\n * and the rows that survived, so `input = admitted + sum(excluded)` can be read\n * off the table instead of trusted.\n */\nexport function buildDenominatorChain(\n verdicts: readonly AdmissionRowVerdict[],\n admitStrata: readonly AdmissionStratum[],\n): DenominatorChainArtifact {\n const reasonTotals = emptyReasonTotals()\n for (const verdict of verdicts) {\n if (verdict.excludedBy !== null) reasonTotals[verdict.excludedBy] += 1\n }\n const stratumReasons = ADMISSION_EXCLUSION_ORDER.filter((reason) => !isPreStratumReason(reason))\n const artifact: DenominatorChainArtifact = {\n version: 1,\n overall: chainOf('all', verdicts, ADMISSION_EXCLUSION_ORDER),\n byStratum: ADMISSION_STRATA.filter((stratum) =>\n verdicts.some((verdict) => verdict.stratum === stratum),\n ).map((stratum) =>\n chainOf(\n stratum,\n verdicts.filter((verdict) => verdict.stratum === stratum),\n stratumReasons,\n ),\n ),\n reasonTotals,\n unstratified: verdicts.filter((verdict) => verdict.stratum === null).length,\n admitStrata: [...admitStrata],\n }\n assertChainReconciles(artifact)\n return artifact\n}\n\nfunction chainOf(\n scope: 'all' | AdmissionStratum,\n verdicts: readonly AdmissionRowVerdict[],\n reasons: readonly AdmissionExclusionReason[],\n): DenominatorChain {\n let remaining = verdicts.length\n const stages: DenominatorStage[] = []\n for (const reason of reasons) {\n const excluded = verdicts.filter((verdict) => verdict.excludedBy === reason).length\n const entering = remaining\n remaining -= excluded\n stages.push({ reason, entering, excluded, remaining })\n }\n return {\n scope,\n input: verdicts.length,\n stages,\n admitted: verdicts.filter((verdict) => verdict.admitted).length,\n }\n}\n\nfunction emptyReasonTotals(): Record<AdmissionExclusionReason, number> {\n const totals = {} as Record<AdmissionExclusionReason, number>\n for (const reason of ADMISSION_EXCLUSION_ORDER) totals[reason] = 0\n return totals\n}\n\n/** A chain that does not add up is a broken denominator, so this throws. */\nexport function assertChainReconciles(artifact: DenominatorChainArtifact): void {\n for (const chain of [artifact.overall, ...artifact.byStratum]) {\n const excluded = chain.stages.reduce((total, stage) => total + stage.excluded, 0)\n if (chain.input !== chain.admitted + excluded) {\n throw new AdmissionDenominatorError(\n `denominator chain (${chain.scope}) does not reconcile: input ${chain.input} != admitted ${chain.admitted} + excluded ${excluded}`,\n )\n }\n const last = chain.stages[chain.stages.length - 1]\n if (last && last.remaining !== chain.admitted) {\n throw new AdmissionDenominatorError(\n `denominator chain (${chain.scope}) ends at ${last.remaining} rows but reports ${chain.admitted} admitted`,\n )\n }\n }\n const stratumInputs = artifact.byStratum.reduce((total, chain) => total + chain.input, 0)\n if (stratumInputs + artifact.unstratified !== artifact.overall.input) {\n throw new AdmissionDenominatorError(\n `stratum inputs ${stratumInputs} plus ${artifact.unstratified} unstratified do not cover ${artifact.overall.input} input rows`,\n )\n }\n}\n","/**\n * The pinned continuation policy: given a container restored to the state\n * after step k, run the mini-swe-agent scaffold forward under one frozen\n * configuration and record everything it did.\n *\n * `Delta-repair = P(tests pass | intervention) - P(tests pass | no-fix control)`\n * only measures the intervention if the continuation is identical across arms.\n * That symmetry is structural here: arms differ by the container state handed\n * in, never by the policy. One code path serves all three, the arm is a label,\n * the seed derivation cannot see it, and `policyDigest` is recorded on every\n * rollout so a mismatch is caught in the data rather than argued about.\n */\n\nimport type { CostProvenance } from '../cost-ledger'\nimport { CaptureIntegrityError, ValidationError } from '../errors'\nimport type { RunTokenUsage } from '../run-record'\nimport { contentHash } from '../verdict-cache'\nimport type {\n ContinuationArm,\n ContinuationEnvironmentDescription,\n ContinuationExitStatus,\n ContinuationMessage,\n ContinuationModelCall,\n ContinuationRollout,\n ContinuationStepRecord,\n ContinuationUsageTotals,\n} from './continuation-records'\nimport {\n MINI_SWE_SYSTEM_MESSAGE,\n parseAction,\n renderFormatErrorObservation,\n renderInstanceMessage,\n renderObservation,\n renderTimeoutObservation,\n submissionOf,\n} from './mini-swe-scaffold'\n\n/** A rollout ran outside the pinned policy, so its evidence cannot be used. */\nexport class ContinuationPolicyViolationError extends CaptureIntegrityError {}\n\n/** Two arms did not run the same policy, so their difference is not the intervention. */\nexport class ContinuationSymmetryError extends CaptureIntegrityError {}\n\nexport interface PinnedContinuationPolicy {\n /** Stable name for the frozen configuration, recorded on every rollout. */\n readonly id: string\n /** Requested model id. The served id is recorded per call and can differ. */\n readonly model: string\n /** Seed root. Per-rollout seeds derive from it and never from the arm. */\n readonly seed: number\n /** Model calls allowed per rollout. */\n readonly stepBudget: number\n readonly temperature: number\n readonly maxTokens: number\n /** Per-command wall-clock limit inside the container. */\n readonly commandTimeoutSeconds: number\n /** Consecutive unparseable turns that end a rollout. */\n readonly maxConsecutiveFormatErrors: number\n /** The only admissible container network mode. */\n readonly networkMode: 'none'\n readonly scaffold: 'mini-swe-agent'\n}\n\n/**\n * Everything the policy fixes except the two a campaign must choose.\n *\n * `commandTimeoutSeconds` is 30 because the recorded runs used the scaffold's\n * own 30-second environment timeout; a longer limit would let the continuation\n * finish commands the recorded agent could not.\n */\nconst CONTINUATION_POLICY_DEFAULTS = {\n id: 'tb-repair-continuation-v1',\n stepBudget: 20,\n temperature: 0,\n maxTokens: 4096,\n commandTimeoutSeconds: 30,\n maxConsecutiveFormatErrors: 3,\n networkMode: 'none',\n scaffold: 'mini-swe-agent',\n} as const satisfies Omit<PinnedContinuationPolicy, 'model' | 'seed'>\n\nexport interface DefineContinuationPolicyInput\n extends Partial<Omit<PinnedContinuationPolicy, 'networkMode' | 'scaffold'>> {\n /** Required: a campaign pins one model, and no default can stand in for it. */\n model: string\n /** Required: a default seed would make two campaigns silently share a draw. */\n seed: number\n}\n\nexport function definePinnedContinuationPolicy(\n input: DefineContinuationPolicyInput,\n): PinnedContinuationPolicy {\n const policy: PinnedContinuationPolicy = { ...CONTINUATION_POLICY_DEFAULTS, ...input }\n if (!policy.model.trim()) throw new ValidationError('continuation policy requires a model id')\n if (!Number.isInteger(policy.seed)) {\n throw new ValidationError(`continuation policy seed must be an integer, got ${policy.seed}`)\n }\n requirePositiveInteger(policy.stepBudget, 'stepBudget')\n requirePositiveInteger(policy.maxTokens, 'maxTokens')\n requirePositiveInteger(policy.commandTimeoutSeconds, 'commandTimeoutSeconds')\n requirePositiveInteger(policy.maxConsecutiveFormatErrors, 'maxConsecutiveFormatErrors')\n if (!Number.isFinite(policy.temperature) || policy.temperature < 0) {\n throw new ValidationError(\n `continuation policy temperature must be a non-negative number, got ${policy.temperature}`,\n )\n }\n return Object.freeze(policy)\n}\n\nfunction requirePositiveInteger(value: number, field: string): void {\n if (!Number.isInteger(value) || value <= 0) {\n throw new ValidationError(\n `continuation policy ${field} must be a positive integer, got ${value}`,\n )\n }\n}\n\n/**\n * Hash over the policy and the scaffold text it renders. A changed template\n * changes the digest, so rollouts recorded before and after an edit cannot be\n * pooled by accident.\n */\nexport function continuationPolicyDigest(policy: PinnedContinuationPolicy): string {\n return contentHash({\n policy: { ...policy },\n systemMessage: MINI_SWE_SYSTEM_MESSAGE,\n instanceMessage: renderInstanceMessage({ task: '<task>', systemInformation: '<system>' }),\n formatErrorObservation: renderFormatErrorObservation(0),\n timeoutObservation: renderTimeoutObservation('<command>', '<output>'),\n observation: renderObservation({ returncode: 0, output: '' }),\n })\n}\n\n/**\n * Per-rollout seed. It reads the policy seed, the row, and the rollout index —\n * deliberately not the arm, so paired rollouts across arms draw identically.\n */\nexport function continuationSeed(policySeed: number, rowId: string, rolloutIndex: number): number {\n const input = `${policySeed}:${rowId}:${rolloutIndex}`\n let hash = 0x811c9dc5\n for (let i = 0; i < input.length; i += 1) {\n hash ^= input.charCodeAt(i)\n hash = Math.imul(hash, 0x01000193) >>> 0\n }\n return hash >>> 1\n}\n\nexport interface ContinuationModelRequest {\n model: string\n messages: ContinuationMessage[]\n seed: number\n temperature: number\n maxTokens: number\n}\n\nexport interface ContinuationModelResponse {\n content: string\n /** Model id the provider reported serving. */\n servedModel: string\n /** `null` when the provider omitted usage. Callers must not substitute zeros. */\n usage: RunTokenUsage | null\n /** `null` when no amount is available from the provider or local pricing. */\n costUsd: number | null\n finishReason?: string | null\n}\n\nexport type ContinuationModel = (\n request: ContinuationModelRequest,\n) => Promise<ContinuationModelResponse>\n\nexport interface ContinuationExecResult {\n output: string\n returncode: number\n /** True when the environment killed the command at the policy timeout. */\n timedOut: boolean\n /** Set when the environment itself failed rather than the command. */\n exceptionInfo?: string\n}\n\nexport interface ContinuationEnvironment {\n /** Container id or equivalent handle, recorded for provenance. */\n containerRef: string\n describe(): Promise<ContinuationEnvironmentDescription>\n exec(command: string, options: { timeoutSeconds: number }): Promise<ContinuationExecResult>\n dispose(): Promise<void>\n}\n\nexport interface ContinuationEnvironmentRequest {\n rowId: string\n arm: ContinuationArm\n rolloutIndex: number\n}\n\nexport interface ContinuationEnvironmentFactory {\n id: string\n /**\n * A container restored to the post-step-k state for one rollout. The arm is\n * passed because the state under test differs by arm; the policy applied to\n * that state does not.\n */\n create(request: ContinuationEnvironmentRequest): Promise<ContinuationEnvironment>\n}\n\nexport interface RunContinuationOptions {\n policy: PinnedContinuationPolicy\n arm: ContinuationArm\n /** Corpus row under repair. Pairs rollouts across arms. */\n rowId: string\n /**\n * Messages through step k, as the replay layer rebuilt them: the pinned\n * system and task messages, then every replayed turn with the observation\n * the replay itself produced.\n */\n prefix: readonly ContinuationMessage[]\n /** Rollouts to run for this arm. */\n rollouts: number\n /**\n * Global index of the first rollout this invocation produces. The per-rollout\n * seed derives from the global index, so a campaign that adds rollouts in\n * later passes must shift this base — an index that repeats is a rollout\n * that repeats. Defaults to 0.\n */\n rolloutBase?: number\n model: ContinuationModel\n environments: ContinuationEnvironmentFactory\n /** Epoch milliseconds. Injected so tests can assert on records without wall-clock noise. */\n clock?: () => number\n}\n\n/**\n * Run the scaffold forward for `rollouts` independent continuations.\n *\n * Each rollout gets its own environment from the factory, because a rollout\n * mutates the container it runs in and the next one must start from the same\n * state, not from the previous rollout's leftovers.\n */\nexport async function runContinuation(\n options: RunContinuationOptions,\n): Promise<ContinuationRollout[]> {\n const { policy, arm, rowId, prefix, rollouts, model, environments } = options\n const clock = options.clock ?? Date.now\n const rolloutBase = options.rolloutBase ?? 0\n requirePositiveInteger(rollouts, 'rollouts')\n if (!Number.isInteger(rolloutBase) || rolloutBase < 0) {\n throw new ValidationError(\n `continuation policy rolloutBase must be a non-negative integer, got ${rolloutBase}`,\n )\n }\n assertPrefix(prefix)\n const policyDigest = continuationPolicyDigest(policy)\n\n const records: ContinuationRollout[] = []\n for (let offset = 0; offset < rollouts; offset += 1) {\n records.push(\n await runOneRollout({\n policy,\n policyDigest,\n arm,\n rowId,\n index: rolloutBase + offset,\n prefix,\n model,\n environments,\n clock,\n }),\n )\n }\n return records\n}\n\nfunction assertPrefix(prefix: readonly ContinuationMessage[]): void {\n if (prefix.length < 2) {\n throw new ValidationError('continuation prefix needs the system and task messages')\n }\n if (prefix[0]?.role !== 'system' || prefix[1]?.role !== 'user') {\n throw new ValidationError('continuation prefix must start with a system then a user message')\n }\n if (prefix[prefix.length - 1]?.role !== 'user') {\n throw new ValidationError(\n 'continuation prefix must end on a user message; an assistant turn with no observation means the replay left an action unanswered',\n )\n }\n}\n\ninterface RolloutInput {\n policy: PinnedContinuationPolicy\n policyDigest: string\n arm: ContinuationArm\n rowId: string\n index: number\n prefix: readonly ContinuationMessage[]\n model: ContinuationModel\n environments: ContinuationEnvironmentFactory\n clock: () => number\n}\n\nasync function runOneRollout(input: RolloutInput): Promise<ContinuationRollout> {\n const { policy, arm, rowId, index, clock } = input\n const seed = continuationSeed(policy.seed, rowId, index)\n const startedMs = clock()\n const environment = await input.environments.create({ rowId, arm, rolloutIndex: index })\n try {\n const description = await environment.describe()\n if (description.networkMode !== policy.networkMode) {\n throw new ContinuationPolicyViolationError(\n `continuation requires network mode \"${policy.networkMode}\", container ${environment.containerRef} reports \"${description.networkMode}\"`,\n )\n }\n\n const messages: ContinuationMessage[] = [...input.prefix]\n const steps: ContinuationStepRecord[] = []\n let exitStatus: ContinuationExitStatus = 'step-budget-exhausted'\n let submission: string | null = null\n let terminalError: string | undefined\n let consecutiveFormatErrors = 0\n\n for (let step = 1; step <= policy.stepBudget; step += 1) {\n const callStartedMs = clock()\n let response: ContinuationModelResponse\n try {\n response = await input.model({\n model: policy.model,\n messages: [...messages],\n seed,\n temperature: policy.temperature,\n maxTokens: policy.maxTokens,\n })\n } catch (error) {\n exitStatus = 'model-error'\n terminalError = errorMessage(error)\n break\n }\n const call: ContinuationModelCall = {\n servedModel: response.servedModel,\n seed,\n latencyMs: clock() - callStartedMs,\n usage: response.usage,\n costUsd: response.costUsd,\n finishReason: response.finishReason ?? null,\n contentChars: response.content.length,\n }\n messages.push({ role: 'assistant', content: response.content })\n\n const parsed = parseAction(response.content)\n if (parsed.kind === 'format-error') {\n consecutiveFormatErrors += 1\n const observation = renderFormatErrorObservation(parsed.actionCount)\n messages.push({ role: 'user', content: observation })\n steps.push({\n step,\n assistantMessage: response.content,\n action: null,\n observation,\n execution: null,\n model: call,\n })\n if (consecutiveFormatErrors >= policy.maxConsecutiveFormatErrors) {\n exitStatus = 'repeated-format-error'\n break\n }\n continue\n }\n\n consecutiveFormatErrors = 0\n const execStartedMs = clock()\n let execution: ContinuationExecResult\n try {\n execution = await environment.exec(parsed.command, {\n timeoutSeconds: policy.commandTimeoutSeconds,\n })\n } catch (error) {\n exitStatus = 'environment-error'\n terminalError = errorMessage(error)\n steps.push({\n step,\n assistantMessage: response.content,\n action: parsed.command,\n observation: null,\n execution: null,\n model: call,\n error: errorMessage(error),\n })\n break\n }\n const execRecord = {\n command: parsed.command,\n returncode: execution.returncode,\n timedOut: execution.timedOut,\n outputChars: execution.output.length,\n durationMs: clock() - execStartedMs,\n }\n\n if (execution.timedOut) {\n const observation = renderTimeoutObservation(parsed.command, execution.output)\n messages.push({ role: 'user', content: observation })\n steps.push({\n step,\n assistantMessage: response.content,\n action: parsed.command,\n observation,\n execution: execRecord,\n model: call,\n })\n continue\n }\n\n const submitted = submissionOf(execution)\n if (submitted !== null) {\n exitStatus = 'submitted'\n submission = submitted\n // The recorded runs end here: the sentinel command gets no observation.\n steps.push({\n step,\n assistantMessage: response.content,\n action: parsed.command,\n observation: null,\n execution: execRecord,\n model: call,\n })\n break\n }\n\n const observation = renderObservation(execution)\n messages.push({ role: 'user', content: observation })\n steps.push({\n step,\n assistantMessage: response.content,\n action: parsed.command,\n observation,\n execution: execRecord,\n model: call,\n })\n }\n\n const endedMs = clock()\n const rollout: ContinuationRollout = {\n rolloutId: `${rowId}:${arm}:${index}`,\n arm,\n rowId,\n index,\n seed,\n policyDigest: input.policyDigest,\n environmentId: input.environments.id,\n containerRef: environment.containerRef,\n environment: description,\n steps,\n exitStatus,\n submission,\n usage: totalUsage(steps),\n costProvenance: totalCost(steps),\n wallMs: endedMs - startedMs,\n startedAt: new Date(startedMs).toISOString(),\n endedAt: new Date(endedMs).toISOString(),\n }\n return terminalError === undefined ? rollout : { ...rollout, terminalError }\n } finally {\n await environment.dispose()\n }\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/**\n * Sum only what the provider reported. A call with no usage raises\n * `callsWithUsage` short of `calls` and clears `captured`, so a partially\n * reported rollout can never read as a fully measured one.\n */\nexport function totalUsage(steps: readonly ContinuationStepRecord[]): ContinuationUsageTotals {\n let input = 0\n let output = 0\n let reasoning = 0\n let cached = 0\n let cacheWrite = 0\n let sawReasoning = false\n let sawCached = false\n let sawCacheWrite = false\n let callsWithUsage = 0\n for (const step of steps) {\n const usage = step.model.usage\n if (!usage) continue\n callsWithUsage += 1\n input += usage.input\n output += usage.output\n if (usage.reasoning !== undefined) {\n reasoning += usage.reasoning\n sawReasoning = true\n }\n if (usage.cached !== undefined) {\n cached += usage.cached\n sawCached = true\n }\n if (usage.cacheWrite !== undefined) {\n cacheWrite += usage.cacheWrite\n sawCacheWrite = true\n }\n }\n const totals: ContinuationUsageTotals = {\n calls: steps.length,\n callsWithUsage,\n captured: steps.length > 0 && callsWithUsage === steps.length,\n input,\n output,\n }\n if (sawReasoning) totals.reasoning = reasoning\n if (sawCached) totals.cached = cached\n if (sawCacheWrite) totals.cacheWrite = cacheWrite\n return totals\n}\n\n/**\n * One unpriced call makes the rollout's cost unknown. Summing the rest would\n * report a number smaller than what was spent.\n */\nexport function totalCost(steps: readonly ContinuationStepRecord[]): CostProvenance {\n if (steps.length === 0) return { kind: 'uncaptured', usd: null }\n let usd = 0\n for (const step of steps) {\n if (step.model.costUsd === null) return { kind: 'uncaptured', usd: null }\n usd += step.model.costUsd\n }\n return { kind: 'observed', usd }\n}\n\n/**\n * Prove the arms ran the same policy. Rollouts paired by row and index must\n * carry the same policy digest and the same seed; anything else means the\n * measured difference includes a policy change, not only the intervention.\n */\nexport function assertArmSymmetry(rollouts: readonly ContinuationRollout[]): void {\n const digests = new Set(rollouts.map((rollout) => rollout.policyDigest))\n if (digests.size > 1) {\n throw new ContinuationSymmetryError(\n `arms ran different policies: ${[...digests].sort().join(', ')}`,\n )\n }\n const seeds = new Map<string, { seed: number; arm: ContinuationArm }>()\n for (const rollout of rollouts) {\n const key = `${rollout.rowId}:${rollout.index}`\n const seen = seeds.get(key)\n if (!seen) {\n seeds.set(key, { seed: rollout.seed, arm: rollout.arm })\n continue\n }\n if (seen.seed !== rollout.seed) {\n throw new ContinuationSymmetryError(\n `paired rollouts ${key} drew different seeds: ${seen.arm}=${seen.seed}, ${rollout.arm}=${rollout.seed}`,\n )\n }\n }\n}\n","/**\n * The control policy admission screens under, declared rather than assumed.\n *\n * Admission conditions 3 and 4 ask whether a row is rescued by continuing from\n * the recorded end state with no intervention, and by continuing after an\n * action that changes nothing. Both are questions about a policy, and neither\n * is answerable without knowing what that policy is allowed to do.\n *\n * One number decides whether the question can be answered at all. Condition 2\n * has already graded the recorded end state and found it failing. A control\n * rollout that makes no model call executes no command, so the container it\n * grades holds those same bytes — the ones already graded as failing. Under\n * such a policy a control pass is not a rescue; it is the task's own grader\n * answering differently about identical state. The condition cannot fire for\n * the reason it exists, and every row walks through it.\n *\n * So the policy is a required, hashed parameter that lands on every admission\n * decision, and a configuration whose control cannot reach the outcome it\n * screens for is refused where it is configured rather than passed silently.\n */\n\nimport { CaptureIntegrityError, ValidationError } from '../errors'\nimport { contentHash } from '../verdict-cache'\n\n/** The declared control cannot produce the outcome the criteria screen for. */\nexport class UncalibratedControlError extends CaptureIntegrityError {}\n\n/**\n * What the criteria expect of the control.\n *\n * - `enforced` — conditions 3 and 4 decide admission, so the control must be\n * able to rescue a row.\n * - `declared-inert` — the campaign has pinned a control that cannot rescue\n * anything (a calibration run comparing arms at equal depth, for instance).\n * Conditions 3 and 4 still run, but a pass then means the task's grader\n * disagreed with itself about identical state, and the row leaves as that.\n */\nexport type ControlScreening = 'enforced' | 'declared-inert'\n\nexport const CONTROL_SCREENING_MODES: readonly ControlScreening[] = ['enforced', 'declared-inert']\n\nexport interface ControlPolicyInput {\n /** Stable name for the frozen configuration. */\n readonly id: string\n /** Model calls one control rollout may make after the arm's own treatment. */\n readonly stepBudget: number\n /** Scaffold the rollout runs under. */\n readonly scaffold: string\n /** Requested model id, or `null` when the budget calls no model. */\n readonly model: string | null\n /** Per-command wall-clock limit inside the container. */\n readonly commandTimeoutSeconds: number\n}\n\n/**\n * The part of a control the calibration rule reads.\n *\n * Both admission paths declare a control in their own vocabulary — the pure\n * contract takes a `ControlPolicy`, the executing pre-pass runs a pinned\n * continuation policy — and both are checked by one rule against this shape,\n * so the two cannot drift into disagreeing about what a usable control is.\n */\nexport interface ControlCapability {\n readonly id: string\n readonly digest: string\n /** Model calls one control rollout may make after the arm's own treatment. */\n readonly stepBudget: number\n}\n\nexport interface ControlPolicy extends ControlPolicyInput, ControlCapability {\n /** Hash over the whole declaration. A hand-written label cannot stand in for\n * it, so two runs cannot share a digest while differing in step budget. */\n readonly digest: string\n /**\n * Whether a rollout under this policy can reach a state the recorded end\n * state was not already in. False at a zero step budget: no model call means\n * no command, which means the graded bytes are the ones condition 2 read.\n */\n readonly canRescue: boolean\n}\n\n/**\n * A control rollout changes the graded state only by executing something, and\n * it executes only what a model call asks for. At a zero budget it grades the\n * bytes it was handed.\n */\nexport function controlCanRescue(stepBudget: number): boolean {\n return stepBudget > 0\n}\n\nexport function defineControlPolicy(input: ControlPolicyInput): ControlPolicy {\n if (!input.id.trim()) throw new ValidationError('control policy requires an id')\n if (!input.scaffold.trim()) throw new ValidationError('control policy requires a scaffold name')\n if (!Number.isInteger(input.stepBudget) || input.stepBudget < 0) {\n throw new ValidationError(\n `control policy stepBudget must be a non-negative integer, got ${input.stepBudget}`,\n )\n }\n if (!Number.isInteger(input.commandTimeoutSeconds) || input.commandTimeoutSeconds <= 0) {\n throw new ValidationError(\n `control policy commandTimeoutSeconds must be a positive integer, got ${input.commandTimeoutSeconds}`,\n )\n }\n // The model is the other half of \"which control screened this row\". A budget\n // that calls a model without naming one, or names one it will never call,\n // makes the recorded policy unreadable either way.\n if (input.stepBudget === 0 && input.model !== null) {\n throw new ValidationError(\n `control policy ${input.id} declares model ${input.model} at a zero step budget; ` +\n 'a policy that makes no model call must record model: null',\n )\n }\n if (input.stepBudget > 0 && !input.model?.trim()) {\n throw new ValidationError(\n `control policy ${input.id} allows ${input.stepBudget} model call(s) but names no model`,\n )\n }\n const declaration: ControlPolicyInput = {\n id: input.id,\n stepBudget: input.stepBudget,\n scaffold: input.scaffold,\n model: input.model,\n commandTimeoutSeconds: input.commandTimeoutSeconds,\n }\n return Object.freeze({\n ...declaration,\n digest: contentHash(declaration),\n canRescue: controlCanRescue(input.stepBudget),\n })\n}\n\n/**\n * Refuse a configuration whose control and screening mode contradict.\n *\n * Both directions are faults, and both are silent without this. A screening\n * control that cannot act passes every row through a condition it can never\n * fire. A control declared inert that can in fact act hides a real screen\n * behind a label that says nothing was screened.\n */\nexport function assertControlCalibrated(\n policy: ControlCapability,\n screening: ControlScreening,\n): void {\n if (!CONTROL_SCREENING_MODES.includes(screening)) {\n throw new ValidationError(`unknown control screening mode: ${screening}`)\n }\n const canRescue = controlCanRescue(policy.stepBudget)\n if (screening === 'enforced' && !canRescue) {\n throw new UncalibratedControlError(\n `control policy ${policy.id} (digest ${policy.digest}) allows ${policy.stepBudget} model ` +\n 'call(s) per rollout, so a control rollout executes no command and grades the same bytes ' +\n 'the end-state check already graded as failing. Under it conditions 3 and 4 can only fire ' +\n 'on a grader that disagrees with itself, so they screen nothing. Give the control a step ' +\n \"budget of at least 1, or set controlScreening to 'declared-inert' and read a control pass \" +\n 'as the oracle flip it is.',\n )\n }\n if (screening === 'declared-inert' && canRescue) {\n throw new UncalibratedControlError(\n `control policy ${policy.id} (digest ${policy.digest}) allows ${policy.stepBudget} model ` +\n 'call(s) per rollout, so it can rescue a row, but the criteria declare it inert. Set ' +\n \"controlScreening to 'enforced' so a control pass is recorded as a rescue.\",\n )\n }\n}\n","/**\n * The TB-Repair admission pre-pass: decide which corpus rows may enter a\n * campaign, before any analyst reads one.\n *\n * A repair benchmark reports `Delta-repair = P(pass | intervention) - P(pass |\n * no-fix control)`. That number is only honest if the row set it averages over\n * was fixed by something the analyst cannot influence. An analyst that declines\n * the rows it cannot solve shrinks its own denominator and raises its own\n * score, so admission runs first, records every row it saw, and publishes the\n * reason each excluded row left.\n *\n * A row is admitted only when all four conditions hold:\n *\n * 1. the recorded prefix replays with divergence at or below the threshold,\n * 2. the task's held-out tests fail on the recorded end state,\n * 3. the no-fix control fails every rollout under the pinned policy,\n * 4. the no-op control fails every rollout under the pinned policy.\n *\n * Conditions 3 and 4 delete rows the continuation policy rescues on its own and\n * rows whose task grades flakily. Both would otherwise be counted as repair.\n *\n * Rows are stratified before anything samples them, and the report exposes\n * admitted rows per stratum only: pooling a population a single command can\n * repair with one it cannot requires an explicit concatenation at the call\n * site.\n *\n * The three external boundaries — prefix replay, the task's test oracle, and\n * the control rollouts — are injected. Each carries an `id` that lands in the\n * artifact, so a report produced against fakes cannot be read as one produced\n * against real containers.\n */\n\nimport type { CostProvenance } from '../cost-ledger'\nimport { ValidationError } from '../errors'\nimport { contentHash } from '../verdict-cache'\nimport {\n ADMISSION_STRATA,\n type AdmissionCheckRecord,\n type AdmissionControlArm,\n AdmissionDenominatorError,\n type AdmissionExclusionReason,\n type AdmissionNoOpInjection,\n type AdmissionRolloutSummary,\n type AdmissionRow,\n type AdmissionRowVerdict,\n type AdmissionStratum,\n assertAnalystIndependent,\n buildDenominatorChain,\n type DenominatorChainArtifact,\n stratumOf,\n} from './admission-records'\nimport {\n assertArmSymmetry,\n continuationPolicyDigest,\n type PinnedContinuationPolicy,\n} from './continuation-policy'\nimport type { ContinuationRollout } from './continuation-records'\nimport {\n assertControlCalibrated,\n CONTROL_SCREENING_MODES,\n type ControlScreening,\n} from './control-policy'\nimport type { TaskOracleRegistry } from './oracle-determinism'\n\n// ── Injected boundaries ──────────────────────────────────────────────\n\n/**\n * Result of an external call. Callers read `succeeded` before `value`: a\n * boundary failure is an exclusion with its own reason, never a false verdict.\n */\nexport type AdmissionOutcome<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; error: string }\n\nexport interface AdmissionDivergence {\n /** 1-based recorded step. */\n step: number\n expectedReturncode: number | null\n actualExit: number\n}\n\nexport interface AdmissionPrefixReplay {\n /** Recorded steps the replay actually executed. */\n prefixExecuted: number\n /** Steps whose replayed exit differs from the recorded return code. */\n prefixDivergences: readonly AdmissionDivergence[]\n}\n\nexport interface AdmissionPrefixReplayer {\n /** Lands in the artifact. A fake and a container replayer must not share one. */\n id: string\n /** Replay the recorded prefix in the task's pinned image and report divergence. */\n replay(row: AdmissionRow): Promise<AdmissionOutcome<AdmissionPrefixReplay>>\n}\n\nexport interface AdmissionTestVerdict {\n passed: boolean\n /** Reward the task's own grader reported. `null` when it reported none. */\n reward: number | null\n}\n\nexport interface AdmissionEndStateOracle {\n id: string\n /** Run the task's held-out tests against the recorded end state. */\n grade(row: AdmissionRow): Promise<AdmissionOutcome<AdmissionTestVerdict>>\n}\n\nexport interface AdmissionControlRequest {\n row: AdmissionRow\n arm: AdmissionControlArm\n /** 0-based rollout index within the arm. */\n rolloutIndex: number\n /** Present for `no-op-control` only; `null` for `no-fix-control`. */\n injection: AdmissionNoOpInjection | null\n}\n\nexport interface AdmissionControlObservation {\n /** The task's held-out tests, run after the continuation stopped. */\n tests: AdmissionTestVerdict\n /** The rollout the pinned policy produced. Its digest and seed prove symmetry. */\n rollout: ContinuationRollout\n}\n\nexport interface AdmissionControlRunner {\n id: string\n /**\n * Restore the row's post-trajectory state, apply the arm's treatment, run the\n * pinned continuation policy forward, then grade the container it left.\n */\n run(request: AdmissionControlRequest): Promise<AdmissionOutcome<AdmissionControlObservation>>\n}\n\n// ── Configuration ────────────────────────────────────────────────────\n\nexport interface AdmissionConfigInput {\n /** Share of replayed prefix steps allowed to diverge. Default 0.10. */\n maxPrefixDivergence?: number\n /** Rollouts each control arm must fail. Default 3. */\n controlRollouts?: number\n /**\n * Strata a campaign accepts. The default omits `signal-kill`, because\n * substituting one command does not address a timeout. The excluded count\n * stays visible in the chain instead of disappearing.\n */\n admitStrata?: readonly AdmissionStratum[]\n /** Shell action the no-op control substitutes. Default `true`. */\n inertAction?: string\n /**\n * How a control pass is read. Default `enforced`, which requires a control\n * that can act; `resolveAdmissionConfig` refuses the pairing that cannot.\n */\n controlScreening?: ControlScreening\n /** Rows processed at once. Output order always follows input order. Default 1. */\n concurrency?: number\n}\n\nexport interface AdmissionConfig {\n readonly maxPrefixDivergence: number\n readonly controlRollouts: number\n readonly admitStrata: readonly AdmissionStratum[]\n readonly inertAction: string\n readonly controlScreening: ControlScreening\n readonly concurrency: number\n}\n\nexport const ADMISSION_CONFIG_DEFAULTS: AdmissionConfig = Object.freeze({\n maxPrefixDivergence: 0.1,\n controlRollouts: 3,\n admitStrata: Object.freeze(['clean-exit', 'command-error']) as readonly AdmissionStratum[],\n inertAction: 'true',\n controlScreening: 'enforced' as ControlScreening,\n concurrency: 1,\n})\n\nexport function resolveAdmissionConfig(input: AdmissionConfigInput = {}): AdmissionConfig {\n const config: AdmissionConfig = { ...ADMISSION_CONFIG_DEFAULTS, ...input }\n if (!Number.isFinite(config.maxPrefixDivergence)) {\n throw new ValidationError(\n `admission maxPrefixDivergence must be a number, got ${config.maxPrefixDivergence}`,\n )\n }\n if (config.maxPrefixDivergence < 0 || config.maxPrefixDivergence > 1) {\n throw new ValidationError(\n `admission maxPrefixDivergence must be a share between 0 and 1, got ${config.maxPrefixDivergence}`,\n )\n }\n requirePositiveInteger(config.controlRollouts, 'controlRollouts')\n requirePositiveInteger(config.concurrency, 'concurrency')\n if (config.admitStrata.length === 0) {\n throw new ValidationError('admission admitStrata must name at least one stratum')\n }\n for (const stratum of config.admitStrata) {\n if (!ADMISSION_STRATA.includes(stratum)) {\n throw new ValidationError(`admission admitStrata holds an unknown stratum: ${stratum}`)\n }\n }\n if (config.inertAction.trim().length === 0) {\n throw new ValidationError('admission inertAction must be a non-empty command')\n }\n if (!CONTROL_SCREENING_MODES.includes(config.controlScreening)) {\n throw new ValidationError(\n `admission controlScreening must be one of ${CONTROL_SCREENING_MODES.join(', ')}, got ${config.controlScreening}`,\n )\n }\n return Object.freeze({ ...config, admitStrata: Object.freeze([...config.admitStrata]) })\n}\n\nfunction requirePositiveInteger(value: number, field: string): void {\n if (!Number.isInteger(value) || value <= 0) {\n throw new ValidationError(`admission ${field} must be a positive integer, got ${value}`)\n }\n}\n\n/**\n * The recorded command the no-op control replaces, drawn per rollout.\n *\n * The draw reads the policy seed, the row, and the rollout index, so it is\n * reproducible from the artifact and cannot depend on when the pre-pass ran.\n */\nexport function noOpInjectionStep(\n policySeed: number,\n rowId: string,\n rolloutIndex: number,\n recordedCommands: number,\n): number {\n requirePositiveInteger(recordedCommands, 'recordedCommands')\n const input = `no-op:${policySeed}:${rowId}:${rolloutIndex}`\n let hash = 0x811c9dc5\n for (let i = 0; i < input.length; i += 1) {\n hash ^= input.charCodeAt(i)\n hash = Math.imul(hash, 0x01000193) >>> 0\n }\n return ((hash >>> 1) % recordedCommands) + 1\n}\n\n// ── Report ───────────────────────────────────────────────────────────\n\nexport interface AdmissionProvenance {\n replayerId: string\n oracleId: string\n controlRunnerId: string\n policyId: string\n policyModel: string\n policySeed: number\n policyDigest: string\n /** Model calls a control rollout may make. Zero cannot screen anything, and\n * `resolveAdmissionConfig` refuses that pairing before a container opens. */\n policyStepBudget: number\n controlScreening: ControlScreening\n /** Tasks whose oracle carried a determinism certification, and their\n * measured flip rates. */\n certifiedTasks: Readonly<Record<string, number>>\n}\n\nexport interface AdmissionReport {\n config: AdmissionConfig\n provenance: AdmissionProvenance\n /** Every input row, in input order, admitted or not. */\n rows: readonly AdmissionRowVerdict[]\n /** Admitted row ids per stratum. There is no pooled list; pooling is explicit. */\n strata: Readonly<Record<AdmissionStratum, readonly string[]>>\n chain: DenominatorChainArtifact\n /** Model cost of the control rollouts. One unpriced rollout makes it uncaptured. */\n controlCost: CostProvenance\n /** Hash over the admitted ids, the config, and the provenance. */\n digest: string\n generatedAt: string\n}\n\nexport interface RunAdmissionOptions {\n rows: readonly AdmissionRow[]\n /** The policy the campaign's arms run under. Its seed drives the no-op draw. */\n policy: PinnedContinuationPolicy\n replayer: AdmissionPrefixReplayer\n oracle: AdmissionEndStateOracle\n controls: AdmissionControlRunner\n /**\n * Determinism certifications by task name. Required: every check below reads\n * the task's own suite, so a suite whose verdict is not a function of the\n * state makes each of them a coin flip. A task with no entry is excluded as\n * uncertified rather than assumed stable.\n */\n taskOracles: TaskOracleRegistry\n config?: AdmissionConfigInput\n /** Epoch milliseconds. Injected so a report can be compared exactly in a test. */\n clock?: () => number\n}\n\n/**\n * Run the pre-pass over every row and publish the denominator it produced.\n *\n * Nothing here reads an analyst output. The report is frozen, and a campaign\n * proves it measured this denominator by passing the report back to\n * `assertDenominatorIntact`.\n */\nexport async function runAdmission(options: RunAdmissionOptions): Promise<AdmissionReport> {\n const { rows, policy, replayer, oracle, controls, taskOracles } = options\n const config = resolveAdmissionConfig(options.config)\n const clock = options.clock ?? Date.now\n assertAnalystIndependent(rows)\n assertUniqueRowIds(rows)\n const policyDigest = continuationPolicyDigest(policy)\n // Both admission paths check the same rule against the same shape, so the\n // pure contract and this pre-pass cannot drift about what a control that can\n // screen looks like.\n assertControlCalibrated(\n { id: policy.id, digest: policyDigest, stepBudget: policy.stepBudget },\n config.controlScreening,\n )\n\n const verdicts = await mapOrdered(rows, config.concurrency, (row) =>\n admitRow({ row, policy, policyDigest, replayer, oracle, controls, taskOracles, config }),\n )\n\n const strata = groupAdmittedByStratum(verdicts)\n const provenance: AdmissionProvenance = {\n replayerId: replayer.id,\n oracleId: oracle.id,\n controlRunnerId: controls.id,\n policyId: policy.id,\n policyModel: policy.model,\n policySeed: policy.seed,\n policyDigest,\n policyStepBudget: policy.stepBudget,\n controlScreening: config.controlScreening,\n certifiedTasks: Object.freeze(\n Object.fromEntries([...taskOracles].map(([task, verdict]) => [task, verdict.flipRate])),\n ),\n }\n return Object.freeze({\n config,\n provenance,\n rows: Object.freeze(verdicts),\n strata,\n chain: buildDenominatorChain(verdicts, config.admitStrata),\n controlCost: summarizeControlCost(verdicts),\n digest: contentHash({\n config,\n provenance,\n admitted: ADMISSION_STRATA.map((stratum) => ({ stratum, rowIds: strata[stratum] })),\n }),\n generatedAt: new Date(clock()).toISOString(),\n })\n}\n\nfunction assertUniqueRowIds(rows: readonly AdmissionRow[]): void {\n const seen = new Set<string>()\n for (const row of rows) {\n if (typeof row.rowId !== 'string' || row.rowId.length === 0) {\n throw new ValidationError('admission row requires a non-empty rowId')\n }\n if (seen.has(row.rowId)) {\n throw new ValidationError(`admission received rowId ${row.rowId} twice`)\n }\n seen.add(row.rowId)\n }\n}\n\ninterface AdmitRowInput {\n row: AdmissionRow\n policy: PinnedContinuationPolicy\n policyDigest: string\n replayer: AdmissionPrefixReplayer\n oracle: AdmissionEndStateOracle\n controls: AdmissionControlRunner\n taskOracles: TaskOracleRegistry\n config: AdmissionConfig\n}\n\nasync function admitRow(input: AdmitRowInput): Promise<AdmissionRowVerdict> {\n const { row, config } = input\n const checks: AdmissionCheckRecord[] = []\n const rollouts: ContinuationRollout[] = []\n const summaries: AdmissionRolloutSummary[] = []\n const certification = input.taskOracles.get(row.taskName) ?? null\n const base = {\n rowId: row.rowId,\n taskName: row.taskName,\n recordedModel: row.recordedModel,\n recordedCommands: row.recordedCommands,\n finalReturncode: row.finalReturncode,\n controlPolicyDigest: input.policyDigest,\n controlScreening: config.controlScreening,\n oracleFlipRate: certification === null ? null : certification.flipRate,\n }\n const finish = (\n stratum: AdmissionStratum | null,\n reason: AdmissionExclusionReason | null,\n errorDetail: string | null = null,\n ): AdmissionRowVerdict => ({\n ...base,\n stratum,\n admitted: reason === null,\n excludedBy: reason,\n errorDetail,\n checks,\n rollouts: summaries,\n })\n\n if (!Number.isInteger(row.recordedCommands) || row.recordedCommands < 1) {\n return finish(null, 'no-recorded-commands')\n }\n const stratum = stratumOf(row.finalReturncode)\n if (stratum === null) return finish(null, 'unparseable-final-returncode')\n checks.push({ check: 'stratum', stratum })\n if (!config.admitStrata.includes(stratum)) return finish(stratum, 'stratum-not-admitted')\n\n // Ahead of the first container: every check below reads this task's suite, so\n // a suite that answers differently about identical bytes turns each of them\n // into a draw. An absent certification is its own reason — the check has not\n // run, which is not the same as having run and failed.\n if (certification === null) return finish(stratum, 'task-oracle-uncertified')\n checks.push({\n check: 'task-oracle',\n stable: certification.stable,\n flipRate: certification.flipRate,\n replicates: certification.replicates,\n })\n if (!certification.stable) {\n return finish(stratum, 'task-oracle-nondeterministic', certification.detail)\n }\n\n const replay = await input.replayer.replay(row)\n if (!replay.succeeded) return finish(stratum, 'prefix-replay-error', replay.error)\n const { prefixExecuted, prefixDivergences } = replay.value\n if (!Number.isInteger(prefixExecuted) || prefixExecuted < 1) {\n return finish(stratum, 'prefix-replay-empty')\n }\n // A replay that stopped early would compute divergence over the steps it did\n // reach, so a truncated run could report a low ratio and admit a row that\n // never reproduced its end state.\n if (prefixExecuted < row.recordedCommands) return finish(stratum, 'prefix-replay-truncated')\n const divergenceRatio = prefixDivergences.length / prefixExecuted\n checks.push({\n check: 'prefix-replay',\n prefixExecuted,\n divergences: prefixDivergences.length,\n divergenceRatio,\n })\n if (divergenceRatio > config.maxPrefixDivergence) {\n return finish(stratum, 'prefix-divergence-above-threshold')\n }\n\n const endState = await input.oracle.grade(row)\n if (!endState.succeeded) return finish(stratum, 'end-state-oracle-error', endState.error)\n checks.push({\n check: 'end-state-tests',\n passed: endState.value.passed,\n reward: endState.value.reward,\n })\n if (endState.value.passed) return finish(stratum, 'end-state-tests-pass')\n\n for (const arm of CONTROL_ARMS) {\n const control = await runControlArm({ ...input, arm })\n checks.push(control.record)\n rollouts.push(...control.rollouts)\n summaries.push(...control.summaries)\n if (control.outcome === 'error') {\n return finish(stratum, CONTROL_EXCLUSIONS[arm].error, control.error)\n }\n if (control.outcome === 'rescued') return finish(stratum, CONTROL_EXCLUSIONS[arm].rescued)\n }\n\n // Both arms ran the full rollout count, so a policy or seed that differs\n // between them is a wiring fault in the runner, not a property of the row.\n assertArmSymmetry(rollouts)\n return finish(stratum, null)\n}\n\nconst CONTROL_ARMS: readonly AdmissionControlArm[] = ['no-fix-control', 'no-op-control']\n\nconst CONTROL_EXCLUSIONS: Readonly<\n Record<\n AdmissionControlArm,\n { error: AdmissionExclusionReason; rescued: AdmissionExclusionReason }\n >\n> = Object.freeze({\n 'no-fix-control': { error: 'no-fix-control-error', rescued: 'no-fix-control-rescued' },\n 'no-op-control': { error: 'no-op-control-error', rescued: 'no-op-control-rescued' },\n})\n\ninterface ControlArmResult {\n outcome: 'failed-every-rollout' | 'rescued' | 'error'\n error: string | null\n record: AdmissionCheckRecord\n /** Kept whole for the symmetry assertion; the verdict stores the summaries. */\n rollouts: ContinuationRollout[]\n summaries: AdmissionRolloutSummary[]\n}\n\n/**\n * Run one control arm until it is decided.\n *\n * A rollout that passes decides the arm at once, so the remaining rollouts go\n * unpaid. A boundary failure decides it too, and as an error: counting an\n * unmeasured rollout as a failure would admit a row nobody verified.\n */\nasync function runControlArm(\n input: AdmitRowInput & { arm: AdmissionControlArm },\n): Promise<ControlArmResult> {\n const { row, arm, config, policy } = input\n const rollouts: ContinuationRollout[] = []\n const summaries: AdmissionRolloutSummary[] = []\n const injections: AdmissionNoOpInjection[] = []\n let passes = 0\n let error: string | null = null\n\n for (let index = 0; index < config.controlRollouts; index += 1) {\n const injection =\n arm === 'no-op-control'\n ? {\n step: noOpInjectionStep(policy.seed, row.rowId, index, row.recordedCommands),\n action: config.inertAction,\n }\n : null\n if (injection) injections.push(injection)\n const result = await input.controls.run({ row, arm, rolloutIndex: index, injection })\n if (!result.succeeded) {\n error = result.error\n break\n }\n const { rollout, tests } = result.value\n assertRolloutMatchesRequest(rollout, { row, arm, index })\n rollouts.push(rollout)\n summaries.push({\n arm,\n index: rollout.index,\n seed: rollout.seed,\n policyDigest: rollout.policyDigest,\n exitStatus: rollout.exitStatus,\n testsPassed: tests.passed,\n costUsd: rollout.costProvenance.usd,\n })\n if (tests.passed) {\n passes += 1\n break\n }\n }\n\n const record: AdmissionCheckRecord = {\n check: 'control',\n arm,\n rolloutsRun: rollouts.length,\n passes,\n injections,\n }\n if (error !== null) return { outcome: 'error', error, record, rollouts, summaries }\n if (passes > 0) return { outcome: 'rescued', error: null, record, rollouts, summaries }\n return { outcome: 'failed-every-rollout', error: null, record, rollouts, summaries }\n}\n\nfunction assertRolloutMatchesRequest(\n rollout: ContinuationRollout,\n request: { row: AdmissionRow; arm: AdmissionControlArm; index: number },\n): void {\n if (rollout.arm !== request.arm) {\n throw new AdmissionDenominatorError(\n `control runner returned a ${rollout.arm} rollout for the ${request.arm} arm`,\n )\n }\n if (rollout.rowId !== request.row.rowId) {\n throw new AdmissionDenominatorError(\n `control runner returned a rollout for row ${rollout.rowId} while deciding ${request.row.rowId}`,\n )\n }\n if (rollout.index !== request.index) {\n throw new AdmissionDenominatorError(\n `control runner returned rollout index ${rollout.index} for requested index ${request.index}`,\n )\n }\n}\n\n/**\n * Model cost of every control rollout that ran.\n *\n * One unpriced rollout makes the total uncaptured, because summing the priced\n * ones reports less than the pre-pass spent. Zero rollouts is an observed zero:\n * nothing ran, so nothing is missing.\n */\nfunction summarizeControlCost(verdicts: readonly AdmissionRowVerdict[]): CostProvenance {\n let usd = 0\n for (const verdict of verdicts) {\n for (const rollout of verdict.rollouts) {\n if (rollout.costUsd === null) return { kind: 'uncaptured', usd: null }\n usd += rollout.costUsd\n }\n }\n return { kind: 'observed', usd }\n}\n\nfunction groupAdmittedByStratum(\n verdicts: readonly AdmissionRowVerdict[],\n): Readonly<Record<AdmissionStratum, readonly string[]>> {\n const grouped: Record<AdmissionStratum, string[]> = {\n 'clean-exit': [],\n 'command-error': [],\n 'signal-kill': [],\n }\n for (const verdict of verdicts) {\n if (!verdict.admitted || verdict.stratum === null) continue\n grouped[verdict.stratum].push(verdict.rowId)\n }\n return Object.freeze({\n 'clean-exit': Object.freeze(grouped['clean-exit']),\n 'command-error': Object.freeze(grouped['command-error']),\n 'signal-kill': Object.freeze(grouped['signal-kill']),\n })\n}\n\n/** Bounded worker pool that keeps results in input order. */\nasync function mapOrdered<T, R>(\n items: readonly T[],\n concurrency: number,\n fn: (item: T) => Promise<R>,\n): Promise<R[]> {\n const results = new Array<R>(items.length)\n let next = 0\n const workerCount = Math.max(1, Math.min(concurrency, items.length))\n const workers = Array.from({ length: workerCount }, async () => {\n for (;;) {\n const index = next\n next += 1\n if (index >= items.length) return\n const item = items[index]\n if (item === undefined) return\n results[index] = await fn(item)\n }\n })\n await Promise.all(workers)\n return results\n}\n\n// ── Reading the report ───────────────────────────────────────────────\n\n/** Admitted row ids in one stratum. No call returns them pooled. */\nexport function admittedRowIds(\n report: AdmissionReport,\n stratum: AdmissionStratum,\n): readonly string[] {\n return report.strata[stratum]\n}\n\nexport function admittedCount(report: AdmissionReport): number {\n return ADMISSION_STRATA.reduce((total, stratum) => total + report.strata[stratum].length, 0)\n}\n\nexport interface DenominatorIntactInput {\n report: AdmissionReport\n /** Strata the campaign drew from. Rows outside them are not expected. */\n strata: readonly AdmissionStratum[]\n /** Rows the campaign sampled from the admitted set. */\n sampled: readonly string[]\n /** Rows the campaign produced an outcome for, including `no-decisive-failure`. */\n scored: readonly string[]\n}\n\n/**\n * Prove a campaign measured the denominator admission published.\n *\n * Three ways a denominator moves after the fact, each rejected here: scoring a\n * row that was never admitted, scoring a row that was never sampled, and\n * dropping a sampled row instead of scoring it. The third is the one an analyst\n * can cause on its own — declining a row it cannot solve — so a sampled row\n * with no outcome is an error, not a smaller `n`.\n */\nexport function assertDenominatorIntact(input: DenominatorIntactInput): void {\n const { report, strata, sampled, scored } = input\n for (const stratum of strata) {\n if (!ADMISSION_STRATA.includes(stratum)) {\n throw new ValidationError(`unknown stratum in denominator check: ${stratum}`)\n }\n }\n assertNoDuplicates(sampled, 'sampled')\n assertNoDuplicates(scored, 'scored')\n const eligible = new Set(strata.flatMap((stratum) => [...report.strata[stratum]]))\n const notAdmitted = sampled.filter((rowId) => !eligible.has(rowId))\n if (notAdmitted.length > 0) {\n throw new AdmissionDenominatorError(\n `${notAdmitted.length} sampled row(s) are not admitted in strata ${strata.join(', ')}: ${preview(notAdmitted)}`,\n )\n }\n const sampledSet = new Set(sampled)\n const unsampled = scored.filter((rowId) => !sampledSet.has(rowId))\n if (unsampled.length > 0) {\n throw new AdmissionDenominatorError(\n `${unsampled.length} scored row(s) were never sampled: ${preview(unsampled)}`,\n )\n }\n const scoredSet = new Set(scored)\n const dropped = sampled.filter((rowId) => !scoredSet.has(rowId))\n if (dropped.length > 0) {\n throw new AdmissionDenominatorError(\n `denominator shrank by ${dropped.length} row(s): sampled but never scored: ${preview(dropped)}`,\n )\n }\n}\n\n/** A row counted twice raises `n` without measuring anything twice. */\nfunction assertNoDuplicates(rowIds: readonly string[], field: string): void {\n const seen = new Set<string>()\n const duplicates = rowIds.filter((rowId) => {\n if (seen.has(rowId)) return true\n seen.add(rowId)\n return false\n })\n if (duplicates.length > 0) {\n throw new AdmissionDenominatorError(\n `${field} lists ${duplicates.length} duplicate row id(s): ${preview([...new Set(duplicates)])}`,\n )\n }\n}\n\nfunction preview(rowIds: readonly string[]): string {\n const shown = rowIds.slice(0, 5).join(', ')\n return rowIds.length > 5 ? `${shown}, +${rowIds.length - 5} more` : shown\n}\n","/**\n * Admission: the executed checks a row must pass before an analyst is allowed\n * to see it, and the brand that proves it did.\n *\n * Every check is analyst-independent. None of them reads a finding, a label,\n * or a k, and all of them are anchored at the recorded end state — the point\n * the agent actually stopped at — so the same evidence admits a row no matter\n * which step an analyst later blames:\n *\n * oracle-determinism the task's own suite returns one verdict on identical\n * bytes, so its answer is about the state\n * prefix-fidelity the recorded trajectory replays with at most 10 % of\n * its steps diverging from their recorded returncode\n * end-state-fails the held-out suite fails on the recorded end state\n * no-fix-control 3 of 3 continuations from the end state fail\n * no-op-control 3 of 3 continuations from the end state, after an\n * action that changes nothing, fail\n *\n * The two controls are what make `Delta-repair` a difference rather than a\n * rate, and what stops a row where the agent was one free step from success\n * from counting as a repair the analyst caused. They only do that under a\n * control that can act: `control-policy.ts` holds the declaration, and the\n * criteria name which reading of a control pass applies.\n *\n * The determinism check sits in front of all of it. Every downstream check\n * reads the same suite, so a suite whose verdict is not a function of the state\n * makes each of them a coin flip rather than a measurement.\n *\n * This module owns the CONTRACT, not the execution. `runAdmission` in\n * `./admission` executes the checks against real containers and hands the\n * measured evidence to `admitRow`, which decides and brands. Splitting it that\n * way keeps the decision auditable from the recorded numbers alone: a reviewer\n * can re-derive every admission from the evidence file without re-running a\n * container.\n */\n\nimport { ValidationError } from '../errors'\nimport type { RecordedTrajectoryStep } from '../trajectory-replay/steps'\nimport {\n assertControlCalibrated,\n type ControlPolicy,\n type ControlScreening,\n} from './control-policy'\nimport type { OracleDeterminismVerdict } from './oracle-determinism'\n\n/** Pre-registered admission thresholds. */\nexport interface AdmissionCriteria {\n /** Share of replayed prefix steps allowed to diverge from their recorded\n * returncode. Above it the container state under test is not the recorded\n * one, so nothing measured on it is about the recorded run. */\n readonly maxPrefixDivergenceRatio: number\n /** Control rollouts each control arm must run. */\n readonly controlRollouts: number\n /** How a control pass is read. `enforced` requires a control that can act. */\n readonly controlScreening: ControlScreening\n}\n\nexport const TB_REPAIR_ADMISSION_CRITERIA: AdmissionCriteria = Object.freeze({\n maxPrefixDivergenceRatio: 0.1,\n controlRollouts: 3,\n controlScreening: 'enforced' as ControlScreening,\n})\n\nexport interface PrefixFidelityEvidence {\n /** Recorded steps that were replayed. */\n readonly stepsReplayed: number\n /** Replayed steps whose exit code differed from the recorded returncode. */\n readonly divergences: number\n}\n\nexport interface ControlArmEvidence {\n readonly rollouts: number\n /** Rollouts whose held-out suite passed. Admission requires zero. */\n readonly passes: number\n /** Policy digest every rollout reported. An arm that ran something other\n * than the declared control is not the control the criteria describe. */\n readonly policyDigest: string\n}\n\nexport interface AdmissionEvidence {\n readonly rowId: string\n /** Terminal-Bench-2 task the trajectory ran. It selects the certification\n * below, and a certification for another task is refused rather than read. */\n readonly taskName: string\n /** Published image the trajectory was recorded against. */\n readonly image: string\n /** Working directory the scaffold ran every action from. */\n readonly cwd: string\n /** Task statement handed to the recorded agent. */\n readonly taskStatement: string\n readonly steps: readonly RecordedTrajectoryStep[]\n /**\n * The task's certified oracle determinism. Required: a campaign that has not\n * measured whether its ground truth is a function of the state cannot\n * construct evidence, which is where that omission should stop.\n */\n readonly oracleDeterminism: OracleDeterminismVerdict\n /** The control both arms ran, declared and hashed. */\n readonly controlPolicy: ControlPolicy\n readonly prefixFidelity: PrefixFidelityEvidence\n /** Held-out suite result on the recorded end state. Admission requires a fail. */\n readonly endStatePassed: boolean\n /** Digest of the suite that produced every result above. */\n readonly suiteDigest: string\n readonly noFixControl: ControlArmEvidence\n readonly noOpControl: ControlArmEvidence\n}\n\n/** Which pre-registered check refused the row. */\nexport type AdmissionRejection =\n | 'task-oracle-nondeterministic'\n | 'prefix-divergence-too-high'\n | 'end-state-already-passes'\n | 'no-fix-control-passed'\n | 'no-op-control-passed'\n | 'control-passed-on-identical-state'\n | 'control-rollouts-short'\n | 'control-policy-mismatch'\n | 'empty-trajectory'\n\ndeclare const ADMITTED: unique symbol\n\n/**\n * A row that passed every admission check.\n *\n * The brand is a phantom: it exists in the type and never in the value, and\n * the symbol that names it is not exported, so `AdmittedRow` cannot be\n * constructed anywhere but here. Both `blindTrajectory` and `gradeRepairRow`\n * require one. That is the structural form of \"admission runs before any\n * analyst sees a row\": there is no signature that accepts an unadmitted row.\n */\nexport interface AdmittedRow {\n readonly [ADMITTED]: true\n readonly rowId: string\n readonly taskName: string\n readonly image: string\n readonly cwd: string\n readonly taskStatement: string\n readonly steps: readonly RecordedTrajectoryStep[]\n readonly criteria: AdmissionCriteria\n readonly prefixDivergenceRatio: number\n readonly suiteDigest: string\n /** The control the row was screened under, carried whole so a later reader\n * never has to open the runner's source to learn what screened it. */\n readonly controlPolicy: ControlPolicy\n readonly controlScreening: ControlScreening\n /** Policy digest both controls ran under. Every intervention rollout must\n * report the same one or the arms are not comparable. */\n readonly policyDigest: string\n /** Control rate the paired delta subtracts. Zero by admission, carried\n * explicitly so the estimator never hardcodes it. */\n readonly controlRate: number\n readonly controlRollouts: number\n}\n\n/** Carried by every decision, admitted or not, so an artifact answers \"which\n * control screened this row\" without reading the runner's source. */\nexport interface AdmissionScreeningRecord {\n readonly controlPolicy: ControlPolicy\n readonly controlScreening: ControlScreening\n readonly controlPolicyDigest: string\n readonly taskName: string\n readonly oracleStable: boolean\n readonly oracleFlipRate: number\n}\n\nexport type AdmissionDecision =\n | {\n readonly admitted: true\n readonly screening: AdmissionScreeningRecord\n readonly row: AdmittedRow\n }\n | {\n readonly admitted: false\n readonly rowId: string\n readonly screening: AdmissionScreeningRecord\n readonly rejection: AdmissionRejection\n readonly detail: string\n }\n\n/**\n * Decide admission from executed evidence.\n *\n * Pure: it opens no container and calls no model. Every threshold it applies\n * is in `criteria`, and every number it reads is in `evidence`, so an\n * admission decision is reproducible from the recorded evidence alone.\n *\n * It throws, rather than rejecting, when the criteria and the declared control\n * contradict. A contradiction there is a property of the configuration and not\n * of the row, so it must stop the run instead of producing one verdict per row\n * that reads as if a check had been applied.\n */\nexport function admitRow(\n evidence: AdmissionEvidence,\n criteria: AdmissionCriteria = TB_REPAIR_ADMISSION_CRITERIA,\n): AdmissionDecision {\n assertCriteria(criteria)\n assertControlCalibrated(evidence.controlPolicy, criteria.controlScreening)\n // A certification measured on another task says nothing about this one, and\n // reading it as if it did is the same corruption the certification exists to\n // prevent. It is a wiring fault, so it stops the run.\n if (evidence.oracleDeterminism.taskName !== evidence.taskName) {\n throw new ValidationError(\n `row ${evidence.rowId} is from task ${evidence.taskName} but carries the oracle ` +\n `certification for ${evidence.oracleDeterminism.taskName}`,\n )\n }\n\n const screening: AdmissionScreeningRecord = {\n controlPolicy: evidence.controlPolicy,\n controlScreening: criteria.controlScreening,\n controlPolicyDigest: evidence.controlPolicy.digest,\n taskName: evidence.oracleDeterminism.taskName,\n oracleStable: evidence.oracleDeterminism.stable,\n oracleFlipRate: evidence.oracleDeterminism.flipRate,\n }\n const reject = (rejection: AdmissionRejection, detail: string): AdmissionDecision => ({\n admitted: false,\n rowId: evidence.rowId,\n screening,\n rejection,\n detail,\n })\n\n const oracle = evidence.oracleDeterminism\n if (!oracle.stable) {\n return reject(\n 'task-oracle-nondeterministic',\n `task ${oracle.taskName} graded byte-identical state inconsistently: flip rate ` +\n `${(oracle.flipRate * 100).toFixed(1)} % over ${oracle.replicates} replicates ` +\n `(${oracle.detail}). Every check below reads that suite, so none of them measures state.`,\n )\n }\n\n if (evidence.steps.length === 0) {\n return reject('empty-trajectory', 'the row records no steps')\n }\n const { stepsReplayed, divergences } = evidence.prefixFidelity\n if (stepsReplayed <= 0) {\n return reject('empty-trajectory', 'no recorded step was replayed')\n }\n const prefixDivergenceRatio = divergences / stepsReplayed\n if (prefixDivergenceRatio > criteria.maxPrefixDivergenceRatio) {\n return reject(\n 'prefix-divergence-too-high',\n `${divergences}/${stepsReplayed} replayed steps diverged (${(prefixDivergenceRatio * 100).toFixed(1)} %), ` +\n `above the ${(criteria.maxPrefixDivergenceRatio * 100).toFixed(1)} % ceiling`,\n )\n }\n if (evidence.endStatePassed) {\n return reject(\n 'end-state-already-passes',\n 'the held-out suite passes on the recorded end state, so the row records no failure to repair',\n )\n }\n for (const [name, arm, rescued] of [\n ['no-fix control', evidence.noFixControl, 'no-fix-control-passed'],\n ['no-op control', evidence.noOpControl, 'no-op-control-passed'],\n ] as const) {\n if (arm.rollouts !== criteria.controlRollouts) {\n return reject(\n 'control-rollouts-short',\n `${name} ran ${arm.rollouts} rollouts, the criteria pre-register ${criteria.controlRollouts}`,\n )\n }\n if (arm.policyDigest !== evidence.controlPolicy.digest) {\n return reject(\n 'control-policy-mismatch',\n `${name} reported policy ${arm.policyDigest} but the criteria screen under ` +\n `${evidence.controlPolicy.id} (${evidence.controlPolicy.digest}); the arm did not run the declared control`,\n )\n }\n if (arm.passes !== 0) {\n // Under a control that cannot act, the arm graded the same bytes the\n // end-state check read as failing. That is the task's grader answering\n // twice about one state, so it is recorded as the flip and never as a\n // rescue the control performed.\n return criteria.controlScreening === 'enforced'\n ? reject(\n rescued,\n `${name} passed ${arm.passes}/${arm.rollouts}; the row is repairable by continuing alone`,\n )\n : reject(\n 'control-passed-on-identical-state',\n `${name} passed ${arm.passes}/${arm.rollouts} under ${evidence.controlPolicy.id}, which ` +\n 'executes no command, so it graded the same bytes the end-state check graded as failing. ' +\n `The task's certification reports flip rate ${(oracle.flipRate * 100).toFixed(1)} %; this row ` +\n 'is a further flip, not a rescue.',\n )\n }\n }\n\n return {\n admitted: true,\n screening,\n // The brand is type-level only, so the branded value carries no phantom\n // property a consumer could copy to forge one.\n row: {\n rowId: evidence.rowId,\n taskName: evidence.taskName,\n image: evidence.image,\n cwd: evidence.cwd,\n taskStatement: evidence.taskStatement,\n steps: evidence.steps,\n criteria,\n prefixDivergenceRatio,\n suiteDigest: evidence.suiteDigest,\n controlPolicy: evidence.controlPolicy,\n controlScreening: criteria.controlScreening,\n policyDigest: evidence.controlPolicy.digest,\n controlRate: evidence.noFixControl.passes / evidence.noFixControl.rollouts,\n controlRollouts: evidence.noFixControl.rollouts,\n } as unknown as AdmittedRow,\n }\n}\n\nfunction assertCriteria(criteria: AdmissionCriteria): void {\n const { maxPrefixDivergenceRatio, controlRollouts } = criteria\n if (!(maxPrefixDivergenceRatio >= 0 && maxPrefixDivergenceRatio <= 1)) {\n throw new ValidationError(\n `admission maxPrefixDivergenceRatio must be within [0,1], got ${maxPrefixDivergenceRatio}`,\n )\n }\n if (!Number.isInteger(controlRollouts) || controlRollouts <= 0) {\n throw new ValidationError(\n `admission controlRollouts must be a positive integer, got ${controlRollouts}`,\n )\n }\n}\n","/**\n * The published form of an admission run: a JSON artifact a later process can\n * check the campaign against, and the Markdown a reader can audit.\n *\n * A benchmark whose denominator is not auditable is not a benchmark, so both\n * carry the same numbers: every exclusion reason with its count, the funnel per\n * stratum, and the provenance of the three boundaries that decided it.\n */\n\nimport type { AdmissionConfig, AdmissionProvenance, AdmissionReport } from './admission'\nimport {\n ADMISSION_EXCLUSION_MEANING,\n ADMISSION_EXCLUSION_ORDER,\n ADMISSION_STRATA,\n type AdmissionExclusionReason,\n type AdmissionRowVerdict,\n type AdmissionStratum,\n assertChainReconciles,\n type DenominatorChain,\n type DenominatorChainArtifact,\n} from './admission-records'\n\nexport interface AdmissionArtifact {\n version: 1\n kind: 'tb-repair-admission'\n generatedAt: string\n /** Hash over the admitted ids, the config, and the provenance. */\n digest: string\n config: AdmissionConfig\n provenance: AdmissionProvenance\n chain: DenominatorChainArtifact\n /** Admitted row ids per stratum, the only form the campaign may sample from. */\n admitted: Record<AdmissionStratum, readonly string[]>\n controlCost: { kind: string; usd: number | null }\n /** Every input row, admitted or not, with the stratum and reason it carried. */\n rows: readonly AdmissionRowVerdict[]\n}\n\n/** Plain JSON. `JSON.stringify` of this object is the machine-readable artifact. */\nexport function admissionArtifact(report: AdmissionReport): AdmissionArtifact {\n assertChainReconciles(report.chain)\n return {\n version: 1,\n kind: 'tb-repair-admission',\n generatedAt: report.generatedAt,\n digest: report.digest,\n config: report.config,\n provenance: report.provenance,\n chain: report.chain,\n admitted: {\n 'clean-exit': report.strata['clean-exit'],\n 'command-error': report.strata['command-error'],\n 'signal-kill': report.strata['signal-kill'],\n },\n controlCost: { kind: report.controlCost.kind, usd: report.controlCost.usd },\n rows: report.rows,\n }\n}\n\nexport interface RenderAdmissionOptions {\n /** Rows listed in the per-row appendix. Default 0, which omits the appendix. */\n rowLimit?: number\n}\n\n/** Markdown for the campaign report. Every number here is also in the artifact. */\nexport function renderAdmissionReport(\n artifact: AdmissionArtifact,\n options: RenderAdmissionOptions = {},\n): string {\n const lines: string[] = []\n lines.push('# TB-Repair admission', '')\n lines.push(\n `${artifact.chain.overall.admitted} of ${artifact.chain.overall.input} rows admitted. Digest \\`${artifact.digest}\\`.`,\n '',\n )\n lines.push(...provenanceSection(artifact))\n lines.push(...chainSection(artifact.chain.overall, 'Denominator chain'))\n for (const chain of artifact.chain.byStratum) {\n lines.push(...chainSection(chain, `Denominator chain — ${chain.scope}`))\n }\n lines.push(...stratumSection(artifact))\n lines.push(...reasonSection(artifact.chain.reasonTotals))\n const rowLimit = options.rowLimit ?? 0\n if (rowLimit > 0) lines.push(...rowSection(artifact.rows, rowLimit))\n return `${lines.join('\\n').trimEnd()}\\n`\n}\n\nfunction provenanceSection(artifact: AdmissionArtifact): string[] {\n const { provenance, config, controlCost } = artifact\n const cost = controlCost.usd === null ? 'uncaptured' : `$${controlCost.usd.toFixed(4)}`\n return [\n '## Provenance',\n '',\n '| field | value |',\n '| --- | --- |',\n `| generated | ${artifact.generatedAt} |`,\n `| prefix replayer | \\`${provenance.replayerId}\\` |`,\n `| end-state oracle | \\`${provenance.oracleId}\\` |`,\n `| control runner | \\`${provenance.controlRunnerId}\\` |`,\n `| continuation policy | \\`${provenance.policyId}\\` |`,\n `| policy model | \\`${provenance.policyModel}\\` |`,\n `| policy seed | ${provenance.policySeed} |`,\n `| policy digest | \\`${provenance.policyDigest}\\` |`,\n `| policy step budget | ${provenance.policyStepBudget} model call(s) per control rollout |`,\n `| control screening | \\`${provenance.controlScreening}\\` |`,\n `| certified task oracles | ${formatCertifiedTasks(provenance.certifiedTasks)} |`,\n `| max prefix divergence | ${formatShare(config.maxPrefixDivergence)} |`,\n `| control rollouts per arm | ${config.controlRollouts} |`,\n `| inert action | \\`${config.inertAction}\\` |`,\n `| strata admitted | ${config.admitStrata.join(', ')} |`,\n `| control model cost | ${cost} (${controlCost.kind}) |`,\n '',\n ]\n}\n\nfunction formatCertifiedTasks(certified: Readonly<Record<string, number>>): string {\n const entries = Object.entries(certified).sort(([a], [b]) => a.localeCompare(b))\n if (entries.length === 0) return 'none'\n return entries.map(([task, flipRate]) => `${task} (flip ${formatShare(flipRate)})`).join(', ')\n}\n\nfunction chainSection(chain: DenominatorChain, heading: string): string[] {\n const lines = [\n `## ${heading}`,\n '',\n '| stage | exclusion reason | entering | excluded | remaining |',\n '| --- | --- | --- | --- | --- |',\n ]\n chain.stages.forEach((stage, index) => {\n lines.push(\n `| ${index + 1} | \\`${stage.reason}\\` | ${stage.entering} | ${stage.excluded} | ${stage.remaining} |`,\n )\n })\n const excluded = chain.input - chain.admitted\n lines.push(\n '',\n `Input ${chain.input} = admitted ${chain.admitted} + excluded ${excluded}. Admission rate ${formatShare(rate(chain.admitted, chain.input))}.`,\n '',\n )\n return lines\n}\n\nfunction stratumSection(artifact: AdmissionArtifact): string[] {\n const lines = [\n '## Strata',\n '',\n '| stratum | admitted rows | in this campaign |',\n '| --- | --- | --- |',\n ]\n for (const stratum of ADMISSION_STRATA) {\n const admitted = artifact.admitted[stratum].length\n const eligible = artifact.chain.admitStrata.includes(stratum) ? 'yes' : 'no'\n lines.push(`| ${stratum} | ${admitted} | ${eligible} |`)\n }\n lines.push(\n '',\n 'Sample within a stratum. A command-level repair cannot address a signal kill, so pooling that population with the others averages an addressable class with an unaddressable one.',\n '',\n )\n return lines\n}\n\nfunction reasonSection(totals: Record<AdmissionExclusionReason, number>): string[] {\n const lines = ['## Exclusions', '', '| reason | rows | what it means |', '| --- | --- | --- |']\n for (const reason of ADMISSION_EXCLUSION_ORDER) {\n lines.push(`| \\`${reason}\\` | ${totals[reason]} | ${ADMISSION_EXCLUSION_MEANING[reason]} |`)\n }\n lines.push('')\n return lines\n}\n\nfunction rowSection(rows: readonly AdmissionRowVerdict[], limit: number): string[] {\n const lines = [\n '## Rows',\n '',\n '| row | task | stratum | final rc | admitted | excluded by |',\n '| --- | --- | --- | --- | --- | --- |',\n ]\n for (const row of rows.slice(0, limit)) {\n lines.push(\n `| \\`${row.rowId}\\` | ${row.taskName} | ${row.stratum ?? '—'} | ${row.finalReturncode ?? '—'} | ${row.admitted ? 'yes' : 'no'} | ${row.excludedBy === null ? '—' : `\\`${row.excludedBy}\\``} |`,\n )\n }\n if (rows.length > limit) lines.push('', `${rows.length - limit} further rows in the artifact.`)\n lines.push('')\n return lines\n}\n\nfunction rate(part: number, total: number): number {\n return total === 0 ? 0 : part / total\n}\n\nfunction formatShare(share: number): string {\n return `${(share * 100).toFixed(2)}%`\n}\n","/**\n * What the analyst is shown.\n *\n * A blinded trajectory prefix: the task the agent was given and the actions\n * and observations it produced, and nothing about how the run was judged. No\n * held-out suite, no suite digest, no control rates, no end-state result, no\n * label.\n *\n * The blinding is by construction rather than by redaction. The returned\n * object is assembled field by field from an admitted row, so a field added to\n * `AdmittedRow` later cannot leak into an analyst prompt by default — it has\n * to be copied here on purpose.\n *\n * Requiring an `AdmittedRow` is the other half of the guarantee: a row cannot\n * be shown to an analyst before the four admission checks have executed and\n * passed.\n */\n\nimport { ValidationError } from '../errors'\nimport type { AdmittedRow } from './admission-contract'\n\nexport interface BlindedStep {\n readonly step_id: number\n readonly action: string\n readonly observation: string | null\n}\n\nexport interface BlindedTrajectoryPrefix {\n readonly rowId: string\n /** The task statement the recorded agent was given. */\n readonly taskStatement: string\n readonly steps: readonly BlindedStep[]\n /** Steps the recording holds. Equal to `steps.length` unless the prefix was\n * deliberately truncated. */\n readonly recordedSteps: number\n /** Largest k the analyst may name for this prefix. */\n readonly maxK: number\n}\n\nexport interface BlindTrajectoryOptions {\n /** Truncate the prefix after this 1-based step. Defaults to the whole\n * recording, which is what the recorded agent itself saw before it stopped. */\n readonly throughStep?: number\n}\n\nexport function blindTrajectory(\n row: AdmittedRow,\n options: BlindTrajectoryOptions = {},\n): BlindedTrajectoryPrefix {\n const through = options.throughStep ?? row.steps.length\n if (!Number.isInteger(through) || through < 1 || through > row.steps.length) {\n throw new ValidationError(\n `blindTrajectory throughStep must be within [1, ${row.steps.length}], got ${through}`,\n )\n }\n const steps = row.steps.slice(0, through).map((step) => ({\n step_id: step.step_id,\n action: step.action,\n observation: step.observation,\n }))\n return {\n rowId: row.rowId,\n taskStatement: row.taskStatement,\n steps,\n recordedSteps: row.steps.length,\n maxK: through,\n }\n}\n\n/**\n * Fields an analyst prompt must never carry. Exported so a consumer that\n * builds its own prompt can assert against the same list this module honours.\n */\nexport const BLINDED_FIELDS: readonly string[] = Object.freeze([\n 'criteria',\n 'controlPolicy',\n 'controlRate',\n 'controlRollouts',\n 'controlScreening',\n 'suiteDigest',\n 'policyDigest',\n 'prefixDivergenceRatio',\n 'image',\n 'cwd',\n])\n","/**\n * The one question every repair arm answers.\n *\n * Arms differ in what EXECUTES the question — a single chat completion, an\n * agent harness, a DSPy program — and in nothing else. One prompt module is\n * what makes a comparison between them an ablation of the execution path\n * rather than a comparison of two prompts.\n *\n * The execution environment is stated, not hinted. The recorded scaffold runs\n * every action in a fresh `/bin/sh` and takes exactly one top-level statement,\n * so an arm that is not told that writes bash-only syntax and dies at\n * execution for a reason that has nothing to do with whether it localized the\n * failure. Stating the shell leaks no label: the held-out suite, the control\n * rates and the end-state verdict all stay out, and the prompt is built from a\n * `BlindedTrajectoryPrefix`, which cannot carry them.\n *\n * The action caps in the prose are read from the budget the grader enforces,\n * so the instruction and the rejection can never drift apart.\n */\n\nimport { createHash } from 'node:crypto'\nimport { type InterventionBudget, SCAFFOLD_INTERVENTION_BUDGET } from './action-budget'\nimport type { BlindedTrajectoryPrefix } from './blinding'\n\nexport const REPAIR_QUESTION =\n 'This coding agent ran and did not finish the task. Name the ONE recorded step whose action you would replace, and give the single shell action to run instead of it.'\n\n/**\n * The task definition. Parameterised by the budget so the stated caps are the\n * enforced caps.\n */\nexport function repairTaskPolicy(\n budget: InterventionBudget = SCAFFOLD_INTERVENTION_BUDGET,\n): readonly string[] {\n return Object.freeze([\n 'You are given a task statement and the complete recorded trajectory of an agent that attempted it and failed.',\n \"Your answer is executed. The action you return is run inside the real task container, at the point in the trajectory you name, and the task's held-out test suite is then run against the resulting state. You are scored on whether the suite passes, never on how your explanation reads.\",\n '',\n 'HOW YOUR ACTION IS EXECUTED — read this before writing it:',\n '- The action runs in a FRESH `/bin/sh`, which is dash on this image, not bash. C-style `for ((i=0;i<n;i++))`, `[[ ]]`, arrays, and `local` are bash-only and will fail with a syntax error.',\n `- The scaffold accepts exactly ${budget.maxStatements === 1 ? 'ONE top-level statement' : `${budget.maxStatements} top-level statements`}. Wrap multiple commands in a single \\`{ ...; }\\` block or chain them with \\`&&\\`.`,\n `- The action is at most ${budget.maxBytes} bytes, and must not be a no-op such as \\`true\\`, \\`:\\` or an empty string.`,\n '- It runs from the task working directory, as root, with the network available.',\n '- Prefer writing a complete correct file with a heredoc over patching in place; you cannot see the result of your own action, so it must work on the first attempt.',\n 'Name the step whose action you would replace as `k`, using the step_id shown in the trajectory. Choosing the last step means \"instead of the last thing the agent did, do this\". You are not repairing the agent\\'s reasoning; you are producing the state the suite requires.',\n 'Return no finding only when no single replacement action could plausibly make the suite pass.',\n ])\n}\n\n/** The reply grammar, stated to an arm that answers in one JSON object. */\nexport const REPAIR_CONTRACT_LINES: readonly string[] = Object.freeze([\n 'OUTPUT CONTRACT — reply with ONE fenced JSON object and nothing else:',\n '```json',\n '{\"answer\": \"<one sentence on what went wrong>\", \"findings\": [{\"k\": <int>, \"failure_claim\": \"<what went wrong at step k>\", \"intervention\": {\"kind\": \"shell\", \"action\": \"<the single shell action to run instead>\"}}]}',\n '```',\n 'Rules:',\n '- `findings` carries AT MOST ONE object. Never more.',\n '- `k` is an integer step_id present in the trajectory below.',\n '- `failure_claim` is a non-empty string. It is recorded and never scored, so spend your effort on the action.',\n '- `intervention.kind` is the string \"shell\", or \"edit\" when the action authors a file with a heredoc.',\n '- `intervention.action` is the exact shell text to execute. It is not a description and not a diff.',\n '- Return `\"findings\": []` only to say that no single action could repair this run.',\n])\n\n/** The same grammar restated for the bounded repair turn, which never carries\n * the trajectory again. */\nexport const REPAIR_REPAIR_CONTRACT_LINES: readonly string[] = Object.freeze([\n 'Your previous reply did not satisfy the output contract. Resend the answer, and nothing else, as ONE fenced JSON object:',\n '```json',\n '{\"answer\": \"<one sentence>\", \"findings\": [{\"k\": <int>, \"failure_claim\": \"<string>\", \"intervention\": {\"kind\": \"shell\", \"action\": \"<shell text>\"}}]}',\n '```',\n '`findings` carries at most one object. Do not restate the trajectory.',\n])\n\n/** The trajectory as an arm sees it: actions, observations, nothing about grading. */\nexport function renderRepairTrajectory(prefix: BlindedTrajectoryPrefix): string {\n return prefix.steps\n .map((step) =>\n [\n `--- step_id ${step.step_id} ---`,\n 'ACTION:',\n step.action,\n 'OBSERVATION:',\n step.observation === null ? '(no observation recorded)' : step.observation,\n ].join('\\n'),\n )\n .join('\\n\\n')\n}\n\nexport function repairTrajectoryHeader(prefix: BlindedTrajectoryPrefix): string {\n return `RECORDED TRAJECTORY (${prefix.steps.length} steps; valid k is any step_id below, the last is ${prefix.maxK}):`\n}\n\n/** The task definition an arm receives: the policy plus the statement the\n * recorded agent was given. */\nexport function repairTaskDefinition(\n prefix: BlindedTrajectoryPrefix,\n budget: InterventionBudget = SCAFFOLD_INTERVENTION_BUDGET,\n): string {\n return [\n ...repairTaskPolicy(budget),\n '',\n 'TASK STATEMENT GIVEN TO THE AGENT:',\n prefix.taskStatement,\n ].join('\\n')\n}\n\n/**\n * Digest of the question and task policy every arm shares.\n *\n * This is the part of the prompt that is equal by construction across arms:\n * the question, the execution rules, and the budget the caps are read from.\n * An arm's own contract text — its output grammar, its typed-signature\n * instructions — is deliberately outside it, because arms differ there.\n */\nexport function repairQuestionSha256(\n budget: InterventionBudget = SCAFFOLD_INTERVENTION_BUDGET,\n): string {\n return createHash('sha256')\n .update(\n JSON.stringify({\n kind: 'tb-repair-analyst-question',\n question: REPAIR_QUESTION,\n taskPolicy: repairTaskPolicy(budget),\n budget,\n }),\n )\n .digest('hex')\n}\n\n/**\n * Digest of the composed question one arm answered.\n *\n * Covers the shared question and the arm's own declared contract text, so two\n * arms that ask materially different composed questions — a JSON grammar\n * versus a typed SUBMIT signature — stamp different digests, and two arms\n * that ask the identical composed question share one.\n */\nexport function repairArmPromptSha256(\n budget: InterventionBudget,\n contract: readonly string[],\n): string {\n return createHash('sha256')\n .update(\n JSON.stringify({\n kind: 'tb-repair-analyst-prompt',\n question: REPAIR_QUESTION,\n taskPolicy: repairTaskPolicy(budget),\n budget,\n contract,\n }),\n )\n .digest('hex')\n}\n","/**\n * What an analyst arm is, and what every arm owes the comparison.\n *\n * An arm is one way of EXECUTING the repair question: a single chat\n * completion, an agent harness, a DSPy program. The question, the reply\n * grammar, the action budget and the bounded repair turn belong to the\n * comparison, not to the arm — so they live here and every arm inherits them.\n *\n * Three rules this module makes structural rather than customary:\n *\n * one contract an arm returns `RepairFinding` or an honest decline,\n * and nothing else parses. An arm that produced neither\n * fails loud with a typed reason; nothing is defaulted.\n * one budget `askRepairArm` measures every action against the\n * scaffold budget and records the measurement. The grader\n * remains the single authority that rejects, so a\n * violation is reported here and refused there — never\n * silently trimmed to fit.\n * one repair turn arms declare how many bounded retries a malformed reply\n * earns. `repairArmAsymmetries` refuses a set whose arms\n * disagree, because a second attempt is a second sample\n * the other arms never got.\n *\n * What arms are ALLOWED to differ in is declared, not hidden: `affordances`\n * names what an arm can do that another cannot — read the trajectory through\n * a code interpreter, take internal turns — and `repairArmAsymmetries` renders\n * those differences so a reader sees them beside the result instead of having\n * to infer them from two runners' source.\n */\n\nimport { assertEqualDeclarativeTerms } from '../analyst/equal-terms'\nimport { ValidationError } from '../errors'\nimport {\n type BudgetMeasurement,\n type BudgetViolation,\n checkInterventionBudget,\n type InterventionBudget,\n} from './action-budget'\nimport type { AdmittedRow } from './admission-contract'\nimport type { AnalystResponse, RepairFinding, RepairIntervention } from './analyst-response'\nimport { type BlindedTrajectoryPrefix, blindTrajectory } from './blinding'\nimport { repairArmPromptSha256, repairQuestionSha256 } from './repair-prompt'\n\n/**\n * Something an arm can do that another arm cannot.\n *\n * Declared per arm and reported beside the result. This list is the vocabulary\n * of admissible difference: an arm whose advantage is not nameable here is not\n * comparable to the others, and that is a design decision to take deliberately\n * rather than a field to widen.\n */\nexport type RepairArmAffordance =\n /** The whole trajectory arrives in the prompt text. */\n | 'inline-trajectory'\n /** The trajectory is read through bounded tools instead of the prompt. */\n | 'trajectory-tools'\n /** The arm may run code while it reasons. */\n | 'code-interpreter'\n /** The arm takes internal turns of its own before answering. */\n | 'agent-loop'\n\n/**\n * Whether the arm's instruction text carries a certification, and from where.\n *\n * On the repair task nothing is certified: the one certified analyst artifact\n * this repository holds was earned on a different benchmark under a different\n * output contract. `kind: 'none'` with a reason is therefore the expected\n * value, and it is recorded rather than omitted so a reader never has to\n * assume.\n */\nexport type RepairArmCertification =\n | { readonly kind: 'none'; readonly reason: string }\n | {\n readonly kind: 'certified'\n /** The artifact whose text this arm runs. */\n readonly artifact: string\n /** The benchmark the certification was earned on. */\n readonly benchmark: string\n /** The output contract it was certified for. */\n readonly contract: string\n }\n\nexport interface RepairArmDeclaration {\n readonly id: string\n /** What actually answers, in one plain sentence. Recorded so a report never\n * has to infer the execution path from the runner's source. */\n readonly execution: string\n readonly certification: RepairArmCertification\n /** The action budget the arm's answers are measured against. */\n readonly budget: InterventionBudget\n /** Bounded retries a structurally malformed reply earns. */\n readonly repairTurns: number\n readonly affordances: readonly RepairArmAffordance[]\n /** The arm's own instruction and output-grammar text, exactly as the arm\n * composes it into the question. It enters the per-arm prompt digest, so a\n * contract change — a reworded grammar, a new signature version — changes\n * the digest of every answer the arm stamps. */\n readonly promptContract: readonly string[]\n}\n\n/** What an arm is handed. The type carries only the blinded prefix, so a\n * grading field is unreachable rather than merely unread: the admitted row\n * stays with `askRepairArm`, which does the blinding and the bookkeeping. */\nexport interface RepairArmRequest {\n readonly prefix: BlindedTrajectoryPrefix\n readonly signal?: AbortSignal\n}\n\n/** Token accounting exactly as the execution path reported it. A side nobody\n * measured stays null rather than becoming a zero. */\nexport interface RepairArmUsage {\n readonly calls: number | null\n readonly inputTokens: number | null\n readonly outputTokens: number | null\n readonly costUsd: number | null\n}\n\nexport interface RepairArmRepairTurn {\n readonly attempted: boolean\n /** Null when no repair turn ran, or when it never returned a reply. */\n readonly succeeded: boolean | null\n}\n\n/** A row an arm reported and the pipeline refused, counted by reason. */\nexport interface RepairArmRejectedRow {\n readonly index: number\n readonly reason: string\n}\n\n/**\n * What an arm hands back.\n *\n * `finding` and `declined` are the two answers the grader consumes. `failed`\n * is everything else, and it always carries a reason: an arm that could not\n * answer must say so rather than return an empty finding that grades as a\n * decline it never made.\n */\nexport type RepairArmReply =\n | {\n readonly status: 'finding'\n readonly k: number\n readonly failureClaim: string\n readonly intervention: RepairIntervention\n readonly answer: string | null\n readonly reportedRows: number\n readonly rejectedRows: readonly RepairArmRejectedRow[]\n readonly repair: RepairArmRepairTurn\n readonly usage: RepairArmUsage\n }\n | {\n readonly status: 'declined'\n readonly answer: string | null\n readonly reportedRows: number\n readonly rejectedRows: readonly RepairArmRejectedRow[]\n readonly repair: RepairArmRepairTurn\n readonly usage: RepairArmUsage\n }\n | {\n readonly status: 'failed'\n readonly failure: string\n readonly answer: string | null\n readonly rejectedRows: readonly RepairArmRejectedRow[]\n readonly repair: RepairArmRepairTurn\n readonly usage: RepairArmUsage\n }\n\nexport interface RepairArm {\n readonly declaration: RepairArmDeclaration\n ask(request: RepairArmRequest): Promise<RepairArmReply>\n}\n\n/**\n * The budget verdict on an arm's action, measured before any container opens.\n *\n * Recorded, never enforced here: `gradeRepairRow` refuses an inadmissible\n * action, and one authority is the point. Measuring it at answer time is what\n * lets a report say what an arm spent its bytes on without paying for a\n * rollout to find out.\n */\nexport type RepairArmBudgetRecord =\n | { readonly admissible: true; readonly measurement: BudgetMeasurement }\n | {\n readonly admissible: false\n readonly violation: BudgetViolation\n readonly detail: string\n readonly measurement: BudgetMeasurement\n }\n\nexport interface RepairArmAnswer {\n readonly rowId: string\n readonly armId: string\n /** Digest of the composed question the arm answered. */\n readonly promptSha256: string\n readonly reply: RepairArmReply\n /** Present only for a finding. */\n readonly budget: RepairArmBudgetRecord | null\n readonly wallMs: number\n}\n\nexport interface AskRepairArmOptions {\n readonly arm: RepairArm\n readonly row: AdmittedRow\n /** Truncate the prefix after this 1-based step. Defaults to the whole recording. */\n readonly throughStep?: number\n readonly signal?: AbortSignal\n /** Injectable clock so a test can assert a recorded duration. */\n readonly now?: () => number\n}\n\n/**\n * Ask one arm about one admitted row.\n *\n * Blinding, prompt identity and budget measurement happen here, once, for\n * every arm. An arm that wants a different question does not get one.\n */\nexport async function askRepairArm(options: AskRepairArmOptions): Promise<RepairArmAnswer> {\n const { arm, row } = options\n assertDeclaration(arm.declaration)\n const now = options.now ?? Date.now\n const startedMs = now()\n const prefix = blindTrajectory(\n row,\n options.throughStep === undefined ? {} : { throughStep: options.throughStep },\n )\n const reply = await arm.ask({\n prefix,\n ...(options.signal ? { signal: options.signal } : {}),\n })\n assertReplyWithinDeclaration(arm.declaration, reply)\n const budget =\n reply.status === 'finding'\n ? checkInterventionBudget(\n reply.intervention.action,\n reply.intervention.kind,\n arm.declaration.budget,\n )\n : null\n return {\n rowId: row.rowId,\n armId: arm.declaration.id,\n promptSha256: repairArmPromptSha256(arm.declaration.budget, arm.declaration.promptContract),\n reply,\n budget,\n wallMs: now() - startedMs,\n }\n}\n\n/**\n * The answer in the grammar the grader consumes.\n *\n * Null for a failure: a run that could not answer has no answer to grade, and\n * turning it into a decline would credit an arm with an honest null it never\n * produced.\n */\nexport function repairArmResponse(answer: RepairArmAnswer): AnalystResponse | null {\n const { reply } = answer\n if (reply.status === 'declined') return { kind: 'no-decisive-failure' }\n if (reply.status === 'failed') return null\n const finding: RepairFinding = {\n kind: 'finding',\n k: reply.k,\n failureClaim: reply.failureClaim,\n intervention: reply.intervention,\n }\n return finding\n}\n\n/** One arm's difference from the set, as a report renders it. */\nexport interface RepairArmAsymmetry {\n readonly armId: string\n /** Affordances this arm has that at least one other arm lacks. */\n readonly extraAffordances: readonly RepairArmAffordance[]\n /** Affordances at least one other arm has and this one lacks. */\n readonly missingAffordances: readonly RepairArmAffordance[]\n readonly certification: RepairArmCertification\n /** Digest of the composed question this arm answers: the shared question\n * plus the arm's own contract text. Two arms with the same digest asked the\n * identical composed question; two arms with different digests did not. */\n readonly promptSha256: string\n}\n\nexport interface RepairArmAsymmetryReport {\n readonly armIds: readonly string[]\n /** Affordances every arm has. Not an asymmetry; recorded so a reader can see\n * the floor the comparison runs on. */\n readonly sharedAffordances: readonly RepairArmAffordance[]\n readonly asymmetries: readonly RepairArmAsymmetry[]\n /** True when no arm carries a certification. The honest state on a task\n * whose graders are newer than every certified artifact. */\n readonly noArmCertified: boolean\n readonly budget: InterventionBudget\n readonly repairTurns: number\n /** Digest of the question and task policy every arm shares. Per-arm\n * composed-question digests live on each asymmetry entry. */\n readonly questionSha256: string\n}\n\n/**\n * Refuse a set of arms that cannot be compared, and describe what still\n * differs between the ones that can.\n *\n * Two properties are hard: the arms measure actions against the same budget,\n * and a malformed reply earns the same number of retries everywhere. Both are\n * things that would move a score without moving the thing being measured.\n *\n * Certification is the third: a set where some arms run certified text and\n * others do not is refused outright. An optimisation applies to every arm or\n * to none — a mixed set measures the optimisation, then reports it as the\n * harness.\n */\nexport function repairArmAsymmetries(\n arms: readonly RepairArm[],\n options: { readonly budget?: InterventionBudget } = {},\n): RepairArmAsymmetryReport {\n if (arms.length === 0) {\n throw new ValidationError('a repair-arm comparison needs at least one arm')\n }\n const declarations = arms.map((arm) => arm.declaration)\n for (const declaration of declarations) assertDeclaration(declaration)\n\n const { ids, repairTurns } = assertEqualDeclarativeTerms(\n 'repair arm',\n declarations.map((declaration) => ({\n id: declaration.id,\n repairTurns: declaration.repairTurns,\n })),\n )\n\n const budget = options.budget ?? declarations[0]!.budget\n const mismatched = declarations.find((declaration) => !sameBudget(declaration.budget, budget))\n if (mismatched) {\n throw new ValidationError(\n `arm '${mismatched.id}' measures actions against ${JSON.stringify(mismatched.budget)}, ` +\n `the comparison runs ${JSON.stringify(budget)}; one arm buying a bigger action than ` +\n 'another is a difference in what was asked, not in what answered',\n )\n }\n\n const certified = declarations.filter(\n (declaration) => declaration.certification.kind === 'certified',\n )\n if (certified.length > 0 && certified.length !== declarations.length) {\n throw new ValidationError(\n `${certified.length}/${declarations.length} arms run certified text ` +\n `(${certified.map((declaration) => declaration.id).join(', ')}); an optimisation applies ` +\n 'to every arm or to none',\n )\n }\n\n const shared = ALL_AFFORDANCES.filter((affordance) =>\n declarations.every((declaration) => declaration.affordances.includes(affordance)),\n )\n const asymmetries = declarations.map((declaration) => ({\n armId: declaration.id,\n extraAffordances: ALL_AFFORDANCES.filter(\n (affordance) =>\n declaration.affordances.includes(affordance) &&\n declarations.some((other) => !other.affordances.includes(affordance)),\n ),\n missingAffordances: ALL_AFFORDANCES.filter(\n (affordance) =>\n !declaration.affordances.includes(affordance) &&\n declarations.some((other) => other.affordances.includes(affordance)),\n ),\n certification: declaration.certification,\n promptSha256: repairArmPromptSha256(declaration.budget, declaration.promptContract),\n }))\n return {\n armIds: ids,\n sharedAffordances: shared,\n asymmetries,\n noArmCertified: certified.length === 0,\n budget,\n repairTurns,\n questionSha256: repairQuestionSha256(budget),\n }\n}\n\nconst ALL_AFFORDANCES: readonly RepairArmAffordance[] = Object.freeze([\n 'inline-trajectory',\n 'trajectory-tools',\n 'code-interpreter',\n 'agent-loop',\n])\n\nfunction sameBudget(a: InterventionBudget, b: InterventionBudget): boolean {\n return (\n a.maxBytes === b.maxBytes &&\n a.maxStatements === b.maxStatements &&\n a.maxHeredocs === b.maxHeredocs\n )\n}\n\nfunction assertDeclaration(declaration: RepairArmDeclaration): void {\n if (\n typeof declaration.id !== 'string' ||\n declaration.id.trim() !== declaration.id ||\n !declaration.id\n ) {\n throw new ValidationError('a repair arm id must be a trimmed non-empty string')\n }\n if (typeof declaration.execution !== 'string' || !declaration.execution.trim()) {\n throw new ValidationError(`arm '${declaration.id}' must state what executes its answer`)\n }\n if (!Number.isInteger(declaration.repairTurns) || declaration.repairTurns < 0) {\n throw new ValidationError(\n `arm '${declaration.id}' repairTurns must be a non-negative integer, got ${declaration.repairTurns}`,\n )\n }\n if (\n declaration.certification.kind === 'none' &&\n (typeof declaration.certification.reason !== 'string' ||\n !declaration.certification.reason.trim())\n ) {\n throw new ValidationError(\n `arm '${declaration.id}' carries no certification and must say why in one sentence`,\n )\n }\n if (\n !Array.isArray(declaration.promptContract) ||\n declaration.promptContract.length === 0 ||\n declaration.promptContract.some((line) => typeof line !== 'string')\n ) {\n throw new ValidationError(\n `arm '${declaration.id}' must declare its contract text as a non-empty array of strings; ` +\n 'the per-arm prompt digest is computed from it',\n )\n }\n for (const affordance of declaration.affordances) {\n if (!ALL_AFFORDANCES.includes(affordance)) {\n throw new ValidationError(\n `arm '${declaration.id}' declares unknown affordance '${affordance}'`,\n )\n }\n }\n}\n\n/** An arm that reports more repair turns than it declared is not the arm the\n * comparison admitted, so the answer never reaches a grader. */\nfunction assertReplyWithinDeclaration(\n declaration: RepairArmDeclaration,\n reply: RepairArmReply,\n): void {\n if (reply.repair.attempted && declaration.repairTurns === 0) {\n throw new ValidationError(\n `arm '${declaration.id}' declares no bounded repair turn but took one`,\n )\n }\n if (reply.status === 'failed' && !reply.failure.trim()) {\n throw new ValidationError(`arm '${declaration.id}' failed without stating why`)\n }\n if (reply.status === 'finding' && !reply.intervention.action) {\n throw new ValidationError(\n `arm '${declaration.id}' returned a finding with an empty intervention`,\n )\n }\n}\n","/**\n * What an analyst is allowed to say about a blinded trajectory prefix.\n *\n * Exactly one of two answers:\n *\n * a finding {k, failureClaim, intervention}\n * the literal string no-decisive-failure\n *\n * Nothing else parses. A finding names one step, states what went wrong\n * there, and supplies one action to run instead. Declining is a real answer\n * with its own cell in the funnel, not a parse failure — an admitted row has\n * a failure by construction, but it need not have a single-action repair, and\n * an analyst that says so is answering the question it was asked.\n */\n\nimport { ValidationError } from '../errors'\nimport type { ActionPayloadKind } from './action-budget'\n\n/** The literal an analyst returns when no single step carries the failure. */\nexport const NO_DECISIVE_FAILURE = 'no-decisive-failure'\n\nexport interface RepairIntervention {\n /** What the action is: a shell command, or an edit that authors file content. */\n readonly kind: ActionPayloadKind\n /** The action itself, exactly as it will be executed at step k. */\n readonly action: string\n}\n\nexport interface RepairFinding {\n readonly kind: 'finding'\n /** 1-based step the analyst blames. The repair must work here; there is no\n * credit for naming a step and repairing elsewhere. */\n readonly k: number\n /** What the analyst says went wrong at step k. Recorded, never scored: a\n * claim graded by another model would put a judge inside the metric. */\n readonly failureClaim: string\n readonly intervention: RepairIntervention\n}\n\nexport interface RepairDeclined {\n readonly kind: 'no-decisive-failure'\n}\n\nexport type AnalystResponse = RepairFinding | RepairDeclined\n\n/** Why a response does not parse. Counted by name in the funnel. */\nexport type ResponseParseFailure =\n | 'unreadable'\n | 'not-a-single-answer'\n | 'missing-k'\n | 'missing-failure-claim'\n | 'missing-intervention'\n | 'unknown-intervention-kind'\n\nexport type ParseAnalystResponseOutcome =\n | { readonly succeeded: true; readonly value: AnalystResponse }\n | { readonly succeeded: false; readonly failure: ResponseParseFailure; readonly detail: string }\n\n/**\n * Read an analyst reply.\n *\n * Accepts the bare literal, or a JSON object carrying one finding. The reply\n * is untrusted text, so every field is checked and nothing is defaulted: a\n * missing `k` is a parse failure, never step 1.\n */\nexport function parseAnalystResponse(reply: string): ParseAnalystResponseOutcome {\n const trimmed = reply.trim()\n if (trimmed.length === 0) {\n return { succeeded: false, failure: 'unreadable', detail: 'the reply is empty' }\n }\n if (trimmed === NO_DECISIVE_FAILURE) {\n return { succeeded: true, value: { kind: 'no-decisive-failure' } }\n }\n\n const json = extractJsonObject(trimmed)\n if (!json) {\n return {\n succeeded: false,\n failure: 'unreadable',\n detail: `expected the literal \"${NO_DECISIVE_FAILURE}\" or one JSON object`,\n }\n }\n if (json.count > 1) {\n return {\n succeeded: false,\n failure: 'not-a-single-answer',\n detail: `the reply carries ${json.count} findings; exactly one is allowed`,\n }\n }\n\n const body = json.value\n if (body.no_decisive_failure === true || body.finding === NO_DECISIVE_FAILURE) {\n return { succeeded: true, value: { kind: 'no-decisive-failure' } }\n }\n\n const k = body.k\n if (typeof k !== 'number' || !Number.isInteger(k)) {\n return {\n succeeded: false,\n failure: 'missing-k',\n detail: `k must be an integer, got ${describe(k)}`,\n }\n }\n const failureClaim = body.failure_claim ?? body.failureClaim\n if (typeof failureClaim !== 'string' || failureClaim.trim().length === 0) {\n return {\n succeeded: false,\n failure: 'missing-failure-claim',\n detail: 'failure_claim must be a non-empty string',\n }\n }\n const raw = body.intervention\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n return {\n succeeded: false,\n failure: 'missing-intervention',\n detail: 'intervention must be an object with kind and action',\n }\n }\n const intervention = raw as Record<string, unknown>\n const action = intervention.action\n if (typeof action !== 'string') {\n return {\n succeeded: false,\n failure: 'missing-intervention',\n detail: 'intervention.action must be a string',\n }\n }\n const kind = intervention.kind\n if (kind !== 'shell' && kind !== 'edit') {\n return {\n succeeded: false,\n failure: 'unknown-intervention-kind',\n detail: `intervention.kind must be \"shell\" or \"edit\", got ${describe(kind)}`,\n }\n }\n\n return {\n succeeded: true,\n value: {\n kind: 'finding',\n k,\n failureClaim: failureClaim.trim(),\n intervention: { kind, action },\n },\n }\n}\n\n/** Build a finding directly, for callers that already hold typed fields. */\nexport function repairFinding(input: {\n k: number\n failureClaim: string\n intervention: RepairIntervention\n}): RepairFinding {\n if (!Number.isInteger(input.k) || input.k < 1) {\n throw new ValidationError(`repair finding k must be a positive integer, got ${input.k}`)\n }\n if (input.failureClaim.trim().length === 0) {\n throw new ValidationError('repair finding requires a non-empty failure claim')\n }\n return {\n kind: 'finding',\n k: input.k,\n failureClaim: input.failureClaim.trim(),\n intervention: input.intervention,\n }\n}\n\nfunction describe(value: unknown): string {\n if (value === null) return 'null'\n if (value === undefined) return 'undefined'\n return typeof value === 'string' ? JSON.stringify(value) : String(value)\n}\n\n/**\n * Pull the single JSON object out of a reply, tolerating a fenced block and\n * surrounding prose. `count` reports how many top-level objects were found so\n * a reply hedging with several findings is rejected rather than silently\n * reduced to the first one.\n */\nfunction extractJsonObject(\n reply: string,\n): { value: Record<string, unknown>; count: number } | null {\n const fenced = [...reply.matchAll(/```(?:json)?\\s*\\n([\\s\\S]*?)```/g)].map((m) => m[1]!.trim())\n const candidates = fenced.length > 0 ? fenced : [reply]\n const parsed: Record<string, unknown>[] = []\n for (const candidate of candidates) {\n for (const slice of topLevelObjectSlices(candidate)) {\n try {\n const value = JSON.parse(slice) as unknown\n if (Array.isArray(value)) {\n for (const item of value) {\n if (isPlainObject(item)) parsed.push(item)\n }\n } else if (isPlainObject(value)) {\n parsed.push(value)\n }\n } catch {\n // A slice that does not parse is not an answer; keep scanning.\n }\n }\n }\n if (parsed.length === 0) return null\n return { value: parsed[0]!, count: parsed.length }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** Balanced `{…}` and `[…]` slices at the top level of a candidate string. */\nfunction topLevelObjectSlices(text: string): string[] {\n const slices: string[] = []\n let depth = 0\n let start = -1\n let inString = false\n let escaped = false\n for (let i = 0; i < text.length; i += 1) {\n const char = text[i]!\n if (inString) {\n if (escaped) escaped = false\n else if (char === '\\\\') escaped = true\n else if (char === '\"') inString = false\n continue\n }\n if (char === '\"') {\n inString = true\n continue\n }\n if (char === '{' || char === '[') {\n if (depth === 0) start = i\n depth += 1\n continue\n }\n if (char === '}' || char === ']') {\n depth -= 1\n if (depth === 0 && start >= 0) {\n slices.push(text.slice(start, i + 1))\n start = -1\n }\n if (depth < 0) depth = 0\n }\n }\n return slices\n}\n","/**\n * The arms that answer over an OpenAI-compatible endpoint.\n *\n * Two arms share this factory because they differ only in what sits behind the\n * URL: `bare-framing` is one chat completion with no harness, `prime` is an\n * agent harness reached through a bridge that speaks the same wire shape. The\n * prompt, the reply grammar, the single bounded repair turn and the row cap\n * are identical, so the difference the comparison measures is the execution\n * path and not the framing.\n *\n * The exchange itself is `runPrimeExchange`: one call, one bounded repair turn\n * on a structurally malformed reply, then decoding. Zero valid rows from a\n * well-formed reply is an honest decline, not a failure.\n */\n\nimport type { PrimeBridgeTransport } from '../analyst/prime-bridge-transport'\nimport {\n analystUsageReceiptFromPrimeUsage,\n buildPrimePrompt,\n type PrimeRawUsage,\n type PrimeReplyContract,\n runPrimeExchange,\n} from '../analyst/prime-protocol'\nimport type { CustomTokenPricing } from '../cost-ledger'\nimport { ValidationError } from '../errors'\nimport type { ActionPayloadKind } from './action-budget'\nimport { type InterventionBudget, SCAFFOLD_INTERVENTION_BUDGET } from './action-budget'\nimport type {\n RepairArm,\n RepairArmAffordance,\n RepairArmCertification,\n RepairArmReply,\n RepairArmRequest,\n RepairArmUsage,\n} from './analyst-arm'\nimport type { BlindedTrajectoryPrefix } from './blinding'\nimport {\n REPAIR_CONTRACT_LINES,\n REPAIR_QUESTION,\n REPAIR_REPAIR_CONTRACT_LINES,\n renderRepairTrajectory,\n repairTaskDefinition,\n repairTrajectoryHeader,\n} from './repair-prompt'\n\n/** One decoded reply row, before it becomes a finding. */\ninterface CompletionRepairRow {\n readonly k: number\n readonly failureClaim: string\n readonly kind: ActionPayloadKind\n readonly action: string\n}\n\nexport interface CompletionRepairArmOptions {\n readonly id: string\n /** What actually answers the POST, in one plain sentence. */\n readonly execution: string\n /** Full endpoint, e.g. `http://127.0.0.1:4200/v1/chat/completions`. */\n readonly url: string\n readonly model: string\n /** Injected so a test drives the arm without a network. */\n readonly transport: PrimeBridgeTransport\n /** Deadline for ONE turn. */\n readonly timeoutMs: number\n /** Rates used to price the reported tokens. */\n readonly pricing: CustomTokenPricing\n readonly budget?: InterventionBudget\n /** What this arm can do that another cannot. */\n readonly affordances: readonly RepairArmAffordance[]\n readonly certification: RepairArmCertification\n}\n\nexport function createCompletionRepairArm(options: CompletionRepairArmOptions): RepairArm {\n if (!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs <= 0) {\n throw new ValidationError(\n `repair arm '${options.id}' timeoutMs must be a positive safe integer, got ${options.timeoutMs}`,\n )\n }\n const budget = options.budget ?? SCAFFOLD_INTERVENTION_BUDGET\n return {\n declaration: {\n id: options.id,\n execution: options.execution,\n certification: options.certification,\n budget,\n // `runPrimeExchange` takes exactly one repair turn on a malformed reply.\n repairTurns: 1,\n affordances: options.affordances,\n // The JSON reply grammar and its repair-turn restatement are this arm's\n // whole contract text; both enter the per-arm prompt digest.\n promptContract: [...REPAIR_CONTRACT_LINES, ...REPAIR_REPAIR_CONTRACT_LINES],\n },\n async ask(request: RepairArmRequest): Promise<RepairArmReply> {\n const prompt = buildPrimePrompt({\n question: REPAIR_QUESTION,\n taskDefinition: repairTaskDefinition(request.prefix, budget),\n contractLines: REPAIR_CONTRACT_LINES,\n trajectoryHeader: repairTrajectoryHeader(request.prefix),\n renderedTrajectory: renderRepairTrajectory(request.prefix),\n })\n const outcome = await runPrimeExchange<CompletionRepairRow>({\n contract: replyContract(request.prefix),\n prompt,\n transport: options.transport,\n url: options.url,\n model: options.model,\n timeoutMs: options.timeoutMs,\n repair: true,\n ...(request.signal ? { signal: request.signal } : {}),\n })\n const usage = armUsage(outcome.usage, options.pricing)\n if (!outcome.ok) {\n return {\n status: 'failed',\n failure: `${outcome.failure.kind}: ${outcome.failure.message}`,\n answer: null,\n rejectedRows: [],\n repair: outcome.repair,\n usage,\n }\n }\n const row = outcome.rows[0]\n if (row === undefined) {\n return {\n status: 'declined',\n answer: outcome.answer,\n reportedRows: outcome.reportedRows,\n rejectedRows: outcome.rejected,\n repair: outcome.repair,\n usage,\n }\n }\n return {\n status: 'finding',\n k: row.k,\n failureClaim: row.failureClaim,\n intervention: { kind: row.kind, action: row.action },\n answer: outcome.answer,\n reportedRows: outcome.reportedRows,\n rejectedRows: outcome.rejected,\n repair: outcome.repair,\n usage,\n }\n },\n }\n}\n\n/**\n * Decode one reply row.\n *\n * Every field is checked and nothing is defaulted: a `k` outside the recorded\n * step ids is a rejected row rather than a clamped one, because an arm that\n * names a step the recording does not hold has not localized anything.\n */\nfunction replyContract(prefix: BlindedTrajectoryPrefix): PrimeReplyContract<CompletionRepairRow> {\n const validSteps = prefix.steps.map((step) => step.step_id)\n return {\n rowsField: 'findings',\n contractLines: REPAIR_CONTRACT_LINES,\n repairContractLines: REPAIR_REPAIR_CONTRACT_LINES,\n maxRows: 1,\n decodeRow(row, index) {\n if (typeof row !== 'object' || row === null || Array.isArray(row)) {\n return { ok: false, reason: `row ${index} is not an object` }\n }\n const record = row as Record<string, unknown>\n const k = record.k\n if (!Number.isInteger(k) || !validSteps.includes(k as number)) {\n return {\n ok: false,\n reason: `k must be a recorded step_id in [${validSteps[0] ?? 1}, ${prefix.maxK}], got ${describe(k)}`,\n }\n }\n const claim = record.failure_claim ?? record.failureClaim\n if (typeof claim !== 'string' || claim.trim().length === 0) {\n return { ok: false, reason: 'failure_claim must be a non-empty string' }\n }\n const raw = record.intervention\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n return { ok: false, reason: 'intervention must be an object with kind and action' }\n }\n const intervention = raw as Record<string, unknown>\n const action = intervention.action\n if (typeof action !== 'string' || action.length === 0) {\n return { ok: false, reason: 'intervention.action must be a non-empty string' }\n }\n const kind = intervention.kind\n if (kind !== 'shell' && kind !== 'edit') {\n return {\n ok: false,\n reason: `intervention.kind must be \"shell\" or \"edit\", got ${describe(kind)}`,\n }\n }\n return {\n ok: true,\n row: { k: k as number, failureClaim: claim.trim(), kind, action },\n }\n },\n }\n}\n\nfunction armUsage(usage: PrimeRawUsage, pricing: CustomTokenPricing): RepairArmUsage {\n const receipt = analystUsageReceiptFromPrimeUsage(usage, pricing)\n return {\n calls: usage.calls,\n inputTokens: usage.inputTokens,\n outputTokens: usage.outputTokens,\n // A one-sided token count prices to a lower bound, which the receipt\n // reports separately from a complete cost. Neither becomes a zero.\n costUsd: receipt.cost.usd ?? receipt.knownCostUsd ?? null,\n }\n}\n\nfunction describe(value: unknown): string {\n if (value === null) return 'null'\n if (value === undefined) return 'undefined'\n return typeof value === 'string' ? JSON.stringify(value) : String(value)\n}\n","/**\n * The DSPy arm on the repair contract.\n *\n * THIS ARM CARRIES NO CERTIFICATION ON THIS TASK, and the code says so rather\n * than leaving a reader to assume otherwise. The one GEPA-certified analyst\n * artifact this repository holds — `oht2-coverage-instructions.txt` — was\n * earned on the CodeTraceBench incorrect-step task, whose output contract is a\n * set of blocks carrying `first_step`, `last_step`, `consequence_step` and\n * `escape_status` over recorded steps that were wrong. The repair task asks a\n * different question with a different answer: one step k, and one executable\n * action of the same type and budget the scaffold itself took, which must make\n * a held-out suite pass. Re-authoring the certified text for that contract\n * would void the certification, because the benchmark it was earned on has\n * been retired. So the instruction text here is authored fresh for the repair\n * task and declared uncertified.\n *\n * What DOES carry over is the engine, and that is the point of the arm: a DSPy\n * program with a typed signature, a structured module, and a code environment\n * it reads the subject with. The trajectory is delivered as a typed input\n * bound as a REPL variable rather than parsed back out of prompt text, which\n * is the difference between this arm and the ones that answer over a chat\n * completion.\n *\n * The typed repair rows travel back in `runtime.repair`, not in `findings`.\n * The engine-neutral finding schema caps `recommended_action` at 2000\n * characters while the scaffold action budget is 4096 bytes, so routing a\n * repair through it would hand this arm a smaller action than every other arm\n * gets — an affordance asymmetry hidden inside a schema. The measured\n * comparison run shows why that matters: chat-completion arms returned actions\n * of 2705, 3413, 3987 and 4733 bytes.\n */\n\nimport type { TraceAnalysisEngine, TraceAnalystLimits } from '../analyst/engine'\nimport type { CostLedgerHandle } from '../cost-ledger'\nimport { ValidationError } from '../errors'\nimport {\n type ActionPayloadKind,\n type InterventionBudget,\n SCAFFOLD_INTERVENTION_BUDGET,\n} from './action-budget'\nimport type {\n RepairArm,\n RepairArmRejectedRow,\n RepairArmReply,\n RepairArmRequest,\n RepairArmUsage,\n} from './analyst-arm'\nimport { REPAIR_QUESTION, repairTaskPolicy } from './repair-prompt'\n\n/**\n * Token the bridge reads to select the typed repair signature.\n *\n * The wire protocol carries instructions as opaque text, so the task is named\n * inside them rather than by adding a field every unrelated caller would have\n * to set. The same mechanism selects the CodeTraceBench typed signature.\n */\nexport const DSPY_REPAIR_TASK_TOKEN = 'tb-repair-typed-'\n\n/** Signature the bridge reports for a repair analysis. */\nexport const DSPY_REPAIR_SIGNATURE = 'tb-repair-typed-v1'\n\n/** The name the trajectory is bound to inside the program's environment. */\nconst DSPY_REPAIR_TRAJECTORY_INPUT = 'trajectory'\n\n/**\n * The repair contract restated for the typed signature.\n *\n * Transport differs from the chat-completion arms — typed SUBMIT instead of a\n * fenced JSON object — and the QUESTION does not. Both read from\n * `repairTaskPolicy`, so the execution rules an arm is held to cannot drift\n * between arms.\n */\nexport function dspyRepairInstructions(\n budget: InterventionBudget = SCAFFOLD_INTERVENTION_BUDGET,\n): string {\n return [\n `TASK ${DSPY_REPAIR_TASK_TOKEN}${DSPY_REPAIR_SIGNATURE}`,\n '',\n ...repairTaskPolicy(budget),\n '',\n `The recorded trajectory is already loaded into your environment as \\`${DSPY_REPAIR_TRAJECTORY_INPUT}\\`,`,\n 'a list of {step_id, action, observation} objects in recorded order. Read it with code',\n 'rather than re-fetching it, and do not claim to have inspected anything you did not read.',\n '',\n 'SUBMIT at most ONE repair, shaped as:',\n '- k: the step_id whose action you replace. It must be a step_id present in the trajectory.',\n '- failure_claim: what went wrong at step k. Recorded, never scored.',\n '- intervention_kind: \"edit\" when the action authors a file with a heredoc, \"shell\" otherwise.',\n `- action: the EXACT shell text to run instead, at most ${budget.maxBytes} bytes and exactly`,\n ` ${budget.maxStatements === 1 ? 'one top-level statement' : `${budget.maxStatements} top-level statements`}. It is executed verbatim: not a description, not a diff, not a plan.`,\n 'SUBMIT an empty list only when no single replacement action could make the suite pass.',\n ].join('\\n')\n}\n\nexport interface DspyRepairArmOptions {\n /** The DSPy engine. Injected, so a test drives the arm with no subprocess. */\n readonly engine: TraceAnalysisEngine\n readonly limits: TraceAnalystLimits\n readonly costLedger: CostLedgerHandle\n readonly costPhase: string\n readonly analystId: string\n readonly costTags?: Record<string, string>\n readonly budget?: InterventionBudget\n readonly id?: string\n readonly log?: (message: string, fields?: Record<string, unknown>) => void\n}\n\nexport function createDspyRepairArm(options: DspyRepairArmOptions): RepairArm {\n assertDspyRepairEngine(options.engine)\n const budget = options.budget ?? SCAFFOLD_INTERVENTION_BUDGET\n const instructions = dspyRepairInstructions(budget)\n return {\n declaration: {\n id: options.id ?? 'dspy-rlm',\n execution: `DSPy RLM program (${options.engine.id} v${options.engine.version}) with a typed repair signature and a code environment`,\n certification: {\n kind: 'none',\n reason:\n 'the GEPA-certified analyst text was earned on the CodeTraceBench incorrect-step ' +\n 'contract, which asks for blocks of wrong steps rather than one executable repair; ' +\n 'this arm runs instruction text authored for the repair contract and certified by nothing',\n },\n budget,\n // The bridge takes exactly one bounded structured re-read when the typed\n // field comes back as text, which is the same single retry the\n // chat-completion arms get for a malformed reply.\n repairTurns: 1,\n affordances: ['inline-trajectory', 'code-interpreter', 'agent-loop'],\n // The instruction text names the signature version, so bumping\n // DSPY_REPAIR_SIGNATURE changes the per-arm prompt digest.\n promptContract: [instructions],\n },\n async ask(request: RepairArmRequest): Promise<RepairArmReply> {\n const steps = request.prefix.steps.map((step) => ({\n step_id: step.step_id,\n action: step.action,\n observation: step.observation,\n }))\n let result: Awaited<ReturnType<TraceAnalysisEngine['analyze']>>\n try {\n result = await options.engine.analyze({\n analystId: options.analystId,\n question: [\n REPAIR_QUESTION,\n '',\n `The trajectory has ${steps.length} recorded steps, step_ids ${steps\n .map((step) => step.step_id)\n .join(', ')}.`,\n ].join('\\n'),\n instructions,\n tools: [],\n taskInputs: {\n [DSPY_REPAIR_TRAJECTORY_INPUT]: steps,\n taskStatement: request.prefix.taskStatement,\n },\n limits: options.limits,\n costLedger: options.costLedger,\n costPhase: options.costPhase,\n ...(options.costTags ? { costTags: options.costTags } : {}),\n ...(request.signal ? { signal: request.signal } : {}),\n ...(options.log ? { log: options.log } : {}),\n })\n } catch (error) {\n return {\n status: 'failed',\n failure: `engine threw: ${error instanceof Error ? error.message : String(error)}`,\n answer: null,\n rejectedRows: [],\n repair: { attempted: false, succeeded: null },\n usage: engineUsage(null),\n }\n }\n const payload = readRepairPayload(result.runtime, {\n validSteps: steps.map((step) => step.step_id),\n })\n const usage = engineUsage(result.modelCalls)\n if (!payload.ok) {\n // The engine answered, but not under the repair contract. That is a\n // wiring fault or a signature mismatch, never an honest decline, so it\n // is reported as a failure with the reason attached.\n return {\n status: 'failed',\n failure: payload.reason,\n answer: result.answer,\n rejectedRows: [],\n repair: { attempted: false, succeeded: null },\n usage,\n }\n }\n const { rows, dropped, repair, reported, failure } = payload.value\n // Succeeded means the re-read produced a well-formed reply — the same\n // definition the chat-completion arms record — so a recovered empty\n // list, an honest decline, is a repair turn that succeeded.\n const repairTurn = {\n attempted: repair !== null,\n succeeded: repair === null ? null : failure === null,\n }\n if (failure !== null) {\n return {\n status: 'failed',\n failure,\n answer: result.answer,\n rejectedRows: dropped,\n repair: repairTurn,\n usage,\n }\n }\n const row = rows[0]\n if (row === undefined) {\n return {\n status: 'declined',\n answer: result.answer,\n reportedRows: reported,\n rejectedRows: dropped,\n repair: repairTurn,\n usage,\n }\n }\n return {\n status: 'finding',\n k: row.k,\n failureClaim: row.failureClaim,\n intervention: { kind: row.kind, action: row.action },\n answer: result.answer,\n reportedRows: reported,\n rejectedRows: dropped,\n repair: repairTurn,\n usage,\n }\n },\n }\n}\n\ninterface DspyRepairRow {\n readonly k: number\n readonly failureClaim: string\n readonly kind: ActionPayloadKind\n readonly action: string\n}\n\ninterface DspyRepairPayload {\n readonly signature: string\n readonly reported: number\n readonly rows: readonly DspyRepairRow[]\n readonly dropped: readonly RepairArmRejectedRow[]\n /** How the bounded structured re-read recovered the typed field, or null\n * when the field arrived typed and no re-read was needed. */\n readonly repair: string | null\n /** The bridge's own account of a typed field it could not read — a reply\n * that stayed malformed after the bounded re-read. The analysis completed,\n * so the answer text survives beside it; null on a readable reply. */\n readonly failure: string | null\n}\n\ntype ReadRepairPayload =\n | { readonly ok: true; readonly value: DspyRepairPayload }\n | { readonly ok: false; readonly reason: string }\n\nexport interface ReadRepairPayloadOptions {\n /** The step ids the blinded prefix holds. A row naming any other k is the\n * model's mistake, not the bridge's, so it lands in `dropped` — the same\n * rejected-row path the chat-completion arms take — never in a finding the\n * grader would refuse as out of range. */\n readonly validSteps: readonly number[]\n}\n\n/**\n * Read the bridge's typed repair block.\n *\n * Structure is checked and fails loud: a missing block, a wrong signature, or\n * a row that does not carry an integer k and a non-empty action is a wiring\n * fault with a reason — never a default, and never an empty list that would\n * grade as a decline the program did not make. A structurally sound row whose\n * k is not a recorded step id is the model's mistake, and it is dropped with\n * its reason instead.\n */\nfunction readRepairPayload(\n runtime: Record<string, unknown>,\n options: ReadRepairPayloadOptions,\n): ReadRepairPayload {\n const block = runtime.repair\n if (!isRecord(block)) {\n return {\n ok: false,\n reason:\n 'the engine returned no runtime.repair block; the bridge did not run the typed repair signature',\n }\n }\n if (block.signature !== DSPY_REPAIR_SIGNATURE) {\n return {\n ok: false,\n reason: `runtime.repair.signature is ${describe(block.signature)}, expected \"${DSPY_REPAIR_SIGNATURE}\"`,\n }\n }\n if (!Number.isSafeInteger(block.reported) || (block.reported as number) < 0) {\n return {\n ok: false,\n reason: `runtime.repair.reported must be a non-negative integer, got ${describe(block.reported)}`,\n }\n }\n if (!Array.isArray(block.rows)) {\n return { ok: false, reason: 'runtime.repair.rows must be an array' }\n }\n const repair = block.repair\n if (repair !== null && typeof repair !== 'string') {\n return {\n ok: false,\n reason: `runtime.repair.repair must be a string or null, got ${describe(repair)}`,\n }\n }\n const rawFailure = block.failure\n if (rawFailure !== undefined && rawFailure !== null && typeof rawFailure !== 'string') {\n return {\n ok: false,\n reason: `runtime.repair.failure must be a string or null, got ${describe(rawFailure)}`,\n }\n }\n const failure = typeof rawFailure === 'string' ? rawFailure : null\n const dropped: RepairArmRejectedRow[] = []\n if (block.dropped !== undefined) {\n if (!Array.isArray(block.dropped)) {\n return { ok: false, reason: 'runtime.repair.dropped must be an array' }\n }\n for (const [index, raw] of block.dropped.entries()) {\n if (!isRecord(raw) || typeof raw.reason !== 'string') {\n return {\n ok: false,\n reason: `runtime.repair.dropped[${index}] must carry a reason string`,\n }\n }\n dropped.push({\n index: Number.isSafeInteger(raw.index) ? (raw.index as number) : index,\n reason: raw.reason,\n })\n }\n }\n const rows: DspyRepairRow[] = []\n for (const [index, raw] of block.rows.entries()) {\n const decoded = decodeRepairRow(raw)\n if (!decoded.ok) {\n return { ok: false, reason: `runtime.repair.rows[${index}]: ${decoded.reason}` }\n }\n if (!options.validSteps.includes(decoded.row.k)) {\n dropped.push({\n index,\n reason: `k must be a recorded step_id in [${options.validSteps[0] ?? 1}, ${options.validSteps[options.validSteps.length - 1] ?? 1}], got ${decoded.row.k}`,\n })\n continue\n }\n if (rows.length >= 1) {\n // The bridge caps at one repair; a second valid row here means the cap\n // regressed, and the surplus is recorded rather than silently discarded.\n dropped.push({ index, reason: 'exceeds the one-repair cap' })\n continue\n }\n rows.push(decoded.row)\n }\n return {\n ok: true,\n value: {\n signature: DSPY_REPAIR_SIGNATURE,\n reported: block.reported as number,\n rows,\n dropped,\n repair: repair ?? null,\n failure,\n },\n }\n}\n\nfunction decodeRepairRow(\n raw: unknown,\n): { ok: true; row: DspyRepairRow } | { ok: false; reason: string } {\n if (!isRecord(raw)) return { ok: false, reason: 'not an object' }\n const k = raw.k\n if (!Number.isInteger(k) || (k as number) < 1) {\n return { ok: false, reason: `k must be a positive integer, got ${describe(k)}` }\n }\n const claim = raw.failure_claim\n if (typeof claim !== 'string' || claim.trim().length === 0) {\n return { ok: false, reason: 'failure_claim must be a non-empty string' }\n }\n const intervention = raw.intervention\n if (!isRecord(intervention)) {\n return { ok: false, reason: 'intervention must be an object with kind and action' }\n }\n const kind = intervention.kind\n if (kind !== 'shell' && kind !== 'edit') {\n return {\n ok: false,\n reason: `intervention.kind must be \"shell\" or \"edit\", got ${describe(kind)}`,\n }\n }\n const action = intervention.action\n if (typeof action !== 'string' || action.length === 0) {\n return { ok: false, reason: 'intervention.action must be a non-empty string' }\n }\n return { ok: true, row: { k: k as number, failureClaim: claim.trim(), kind, action } }\n}\n\n/**\n * The engine reports model calls; token counts and cost live in the caller's\n * cost ledger, which meters the proxy the engine ran through. Reporting them\n * here as zero would state a measurement this arm did not make.\n */\nfunction engineUsage(modelCalls: number | null): RepairArmUsage {\n return { calls: modelCalls, inputTokens: null, outputTokens: null, costUsd: null }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction describe(value: unknown): string {\n if (value === null) return 'null'\n if (value === undefined) return 'undefined'\n return typeof value === 'string' ? JSON.stringify(value) : String(value)\n}\n\n/** Thrown by callers that build a repair arm with a non-DSPy engine. */\nexport function assertDspyRepairEngine(engine: TraceAnalysisEngine): void {\n if (engine.id !== 'dspy-rlm') {\n throw new ValidationError(\n `the DSPy repair arm needs the dspy-rlm engine, got '${engine.id}'; another engine ` +\n 'does not run the typed repair signature and would answer a different contract',\n )\n }\n}\n","/**\n * Records the continuation runner produces, and the projection back into the\n * shape the Terminal-Bench-2 trajectory corpus stores.\n *\n * The replay layer reads recorded trajectories as\n * `{ src, msg, tools, obs }` steps. A continuation that emitted a private\n * shape would need a second reader and would drift from it, so the rollout\n * projects into the same four fields.\n */\n\nimport type { CostProvenance } from '../cost-ledger'\nimport type { RunTokenUsage } from '../run-record'\nimport { contentHash } from '../verdict-cache'\nimport { parseAction } from './mini-swe-scaffold'\n\n/** Which arm produced a rollout. The policy is identical across all three. */\nexport type ContinuationArm = 'intervention' | 'no-fix-control' | 'no-op-control'\n\n/** Chat message in the scaffold's own vocabulary. */\nexport interface ContinuationMessage {\n role: 'system' | 'user' | 'assistant'\n content: string\n}\n\n/** Why a rollout stopped. */\nexport type ContinuationExitStatus =\n | 'submitted'\n | 'step-budget-exhausted'\n | 'repeated-format-error'\n | 'model-error'\n | 'environment-error'\n\nexport interface ContinuationExecRecord {\n command: string\n returncode: number\n /** True when the environment killed the command at the policy timeout. */\n timedOut: boolean\n outputChars: number\n durationMs: number\n}\n\nexport interface ContinuationModelCall {\n /** Model id the provider reported serving, which can differ from the requested id. */\n servedModel: string\n seed: number\n latencyMs: number\n /** `null` when the provider reported no usage. Never a zero-filled stand-in. */\n usage: RunTokenUsage | null\n /** `null` when neither the provider nor local pricing produced an amount. */\n costUsd: number | null\n finishReason: string | null\n contentChars: number\n}\n\nexport interface ContinuationStepRecord {\n /** 1-based index within the continuation, not within the whole trajectory. */\n step: number\n assistantMessage: string\n /** `null` when the turn held zero or several bash blocks. */\n action: string | null\n /**\n * `null` when the command that ran ended the rollout: the submission\n * sentinel gets no observation, which is how the corpus records a finished\n * run, and a failed environment call produces none either.\n */\n observation: string | null\n /** `null` when no command ran, so a format error is never read as an exit-0 command. */\n execution: ContinuationExecRecord | null\n model: ContinuationModelCall\n /** Environment failure that ended the rollout at this step. */\n error?: string\n}\n\nexport interface ContinuationUsageTotals {\n /**\n * Recorded model calls. A call that threw produced no step, so it is absent\n * here and named in `terminalError` instead.\n */\n calls: number\n /** Calls that carried usage. Below `calls` means the totals cover part of the rollout. */\n callsWithUsage: number\n /** True only when every call reported usage. */\n captured: boolean\n input: number\n output: number\n reasoning?: number\n cached?: number\n cacheWrite?: number\n}\n\nexport interface ContinuationEnvironmentDescription {\n /** Docker network mode of the container. The policy admits `none` only. */\n networkMode: string\n image?: string\n}\n\nexport interface ContinuationRollout {\n rolloutId: string\n arm: ContinuationArm\n /** Corpus row the continuation belongs to. Pairs rollouts across arms. */\n rowId: string\n /** 0-based rollout index within the arm. */\n index: number\n /** Seed handed to the model for every call in this rollout. */\n seed: number\n /** Hash over the policy and scaffold templates. Equal across arms by construction. */\n policyDigest: string\n environmentId: string\n containerRef: string\n environment: ContinuationEnvironmentDescription\n steps: ContinuationStepRecord[]\n exitStatus: ContinuationExitStatus\n /** Text after the sentinel line, present only on `submitted`. */\n submission: string | null\n usage: ContinuationUsageTotals\n costProvenance: CostProvenance\n wallMs: number\n startedAt: string\n endedAt: string\n /** Message from the model or environment failure that ended the rollout. */\n terminalError?: string\n}\n\n/** A tool call in corpus shape. */\nexport interface RecordedToolCall {\n fn: 'bash_command'\n cmd: string\n}\n\n/** One trajectory step in corpus shape. */\nexport interface RecordedStep {\n src: 'system' | 'user' | 'agent'\n msg: string\n tools: RecordedToolCall[] | null\n obs: string | null\n}\n\n/**\n * Project a full message list into corpus steps: the system and task messages\n * become their own steps, and every assistant turn carries the command it\n * requested plus the observation that answered it. A trailing assistant turn\n * with no answer keeps `obs: null`, which is how the corpus records a run that\n * ended on its last command.\n */\nexport function toRecordedSteps(messages: readonly ContinuationMessage[]): RecordedStep[] {\n const steps: RecordedStep[] = []\n for (let i = 0; i < messages.length; i += 1) {\n const message = messages[i]\n if (!message) continue\n if (message.role === 'assistant') {\n const parsed = parseAction(message.content)\n const next = messages[i + 1]\n steps.push({\n src: 'agent',\n msg: message.content,\n tools: parsed.kind === 'action' ? [{ fn: 'bash_command', cmd: parsed.command }] : null,\n obs: next && next.role === 'user' ? next.content : null,\n })\n continue\n }\n if (message.role === 'system') {\n steps.push({ src: 'system', msg: message.content, tools: null, obs: null })\n continue\n }\n // A user message that answers an assistant turn is that turn's observation,\n // already attached above. Only the leading task message stands alone.\n const previous = messages[i - 1]\n if (!previous || previous.role === 'system') {\n steps.push({ src: 'user', msg: message.content, tools: null, obs: null })\n }\n }\n return steps\n}\n\n/** Corpus steps for the continuation alone, excluding the prefix it inherited. */\nexport function rolloutRecordedSteps(rollout: ContinuationRollout): RecordedStep[] {\n return rollout.steps.map((step) => ({\n src: 'agent',\n msg: step.assistantMessage,\n tools: step.action === null ? null : [{ fn: 'bash_command', cmd: step.action }],\n obs: step.observation,\n }))\n}\n\n/**\n * Hash over everything the policy determines: the actions taken, the\n * observations they produced, the seeds, the exit, and the usage.\n *\n * Wall-clock fields are excluded because they vary between identical runs;\n * two rollouts with the same digest did the same work, whatever they cost in\n * seconds. Use it to assert determinism, never to assert equal latency.\n */\nexport function rolloutDigest(rollout: ContinuationRollout): string {\n return contentHash({\n arm: rollout.arm,\n rowId: rollout.rowId,\n index: rollout.index,\n seed: rollout.seed,\n policyDigest: rollout.policyDigest,\n exitStatus: rollout.exitStatus,\n submission: rollout.submission,\n usage: rollout.usage,\n costUsd: rollout.costProvenance.usd,\n costKind: rollout.costProvenance.kind,\n steps: rollout.steps.map((step) => ({\n step: step.step,\n assistantMessage: step.assistantMessage,\n action: step.action,\n observation: step.observation,\n returncode: step.execution?.returncode ?? null,\n timedOut: step.execution?.timedOut ?? null,\n seed: step.model.seed,\n servedModel: step.model.servedModel,\n usage: step.model.usage,\n costUsd: step.model.costUsd,\n })),\n })\n}\n","/**\n * The strategies that would score without repairing anything, named here so a\n * reviewer can check each one against the mechanism that defeats it and a\n * test can be required for each.\n *\n * Two kinds of defeat, and the difference matters:\n *\n * gate the grader refuses the answer before spending a rollout\n * measurement the answer runs and measures the same as its control\n *\n * A gate is cheap and certain. A measurement defeat is the honest one where\n * no syntactic rule can decide — a semantic no-op looks like a repair until\n * the tests disagree with it — and it costs rollouts to establish.\n */\n\nexport type DegenerateDefeatKind = 'gate' | 'measurement'\n\nexport interface DegenerateStrategy {\n readonly id: string\n /** What the analyst does to score without repairing. */\n readonly strategy: string\n /** The mechanism that removes the reward. */\n readonly defeat: string\n readonly defeatKind: DegenerateDefeatKind\n /** Module that carries the mechanism. */\n readonly enforcedIn: string\n}\n\nexport const DEGENERATE_STRATEGIES = [\n {\n id: 'point-at-any-nonzero-exit-step',\n strategy:\n 'Name the first step with a nonzero returncode, claim it failed, and let the reproduction gate confirm it.',\n defeat:\n 'Reproduction is a gate, not a tier that pays. The credit vector has no term for it, so a reproduced step with no working intervention scores exactly what an unreproduced one scores: nothing.',\n defeatKind: 'gate',\n enforcedIn: 'funnel.ts (repairCredit has no reproduction term)',\n },\n {\n id: 'propose-the-recorded-command-again',\n strategy:\n 'Return the action the agent already ran at step k, so the arm reproduces the recorded state and looks like a faithful replay.',\n defeat:\n 'The intervention is compared against the recorded action at k after whitespace normalisation and rejected before a container opens.',\n defeatKind: 'gate',\n enforcedIn: 'grade.ts (recorded-action-reproposed rejection)',\n },\n {\n id: 'propose-a-no-op',\n strategy:\n 'Return an action that changes nothing, so the arm inherits whatever the trajectory would have done anyway.',\n defeat:\n 'Literal no-ops are rejected at the budget check. A semantic no-op cannot be detected syntactically, so it runs and measures at the no-op control floor: its paired delta is zero.',\n defeatKind: 'measurement',\n enforcedIn: 'action-budget.ts (NO_OP_ACTIONS) and delta-repair.ts (paired delta)',\n },\n {\n id: 'submit-instead-of-repair',\n strategy:\n 'Return the submit sentinel so the run ends immediately and the arm terminates cleanly.',\n defeat:\n 'An action carrying the submit sentinel is rejected at the budget check. Ending the run is what the recorded agent already did and the tests already failed on it.',\n defeatKind: 'gate',\n enforcedIn: 'action-budget.ts (SUBMIT_SENTINEL rejection)',\n },\n {\n id: 'touch-the-test-suite',\n strategy:\n \"Write a passing suite, or a reward file, at the path the grader will read, so the oracle grades the trajectory's own artifact.\",\n defeat:\n 'The oracle purges the suite root and uploads the held-out suite from outside the session at grade time, then verifies the bytes it reads back. A planted suite is overwritten; a session that refuses the overwrite raises a tamper error instead of returning a pass.',\n defeatKind: 'gate',\n enforcedIn: 'test-oracle.ts (purge, upload, read-back digest)',\n },\n {\n id: 'buy-a-bigger-action',\n strategy:\n 'Return a multi-command script or a whole-file rewrite that does far more than one scaffold turn could.',\n defeat:\n 'The budget counts top-level statements, heredocs and bytes. More than one action, more than one authored file, or more than 4 KB is rejected before a container opens.',\n defeatKind: 'gate',\n enforcedIn: 'action-budget.ts (checkInterventionBudget)',\n },\n {\n id: 'decline-every-hard-row',\n strategy:\n 'Answer no-decisive-failure on everything except the rows that are obviously repairable, so the reported rate is computed on an easy subset.',\n defeat:\n 'A declined row keeps its cell in the funnel and stays in the denominator with a paired delta of zero, because its intervention arm is definitionally its control arm. Declining cannot raise the headline; it can only dilute it.',\n defeatKind: 'measurement',\n enforcedIn: 'grade.ts (declined outcome) and delta-repair.ts (full admitted denominator)',\n },\n {\n id: 'repair-somewhere-other-than-k',\n strategy:\n 'Name a plausible-looking k, then submit an intervention that fixes the task from any state, so the answer scores without localising anything.',\n defeat:\n 'The intervention is executed at the k the analyst named, on the state produced by replaying steps 1..k-1. There is no separate localisation credit to win and no label the grader reads, so a wrong k is only penalised through the repair failing to work there.',\n defeatKind: 'measurement',\n enforcedIn: 'grade.ts (the intervention is applied at the named k only)',\n },\n] as const satisfies readonly DegenerateStrategy[]\n\nexport type DegenerateStrategyId = (typeof DEGENERATE_STRATEGIES)[number]['id']\n","/**\n * The five-tier funnel and the only thing in it that pays.\n *\n * t0 parsed one finding or the literal decline, inside the budget\n * t1 reproduced the recorded state at k comes back under replay\n * t2 executes the intervention runs at k\n * t3 local flip the held-out suite passes immediately after it\n * t4 repair flip the suite passes after the pinned policy continues\n *\n * t0, t1 and t2 are nested gates. t3 and t4 are two different measurements of\n * the same intervention and neither contains the other: an intervention that\n * fixes the task outright flips locally, and one that unblocks an agent which\n * still has work left flips only after the continuation.\n *\n * `t1` is a gate that pays nothing, and that is structural rather than a\n * convention: `RepairCredit` has no reproduction term, so there is no field to\n * award. Naming a step whose nonzero exit reproduces earns exactly what naming\n * one that does not earns.\n *\n * Reproduction is deliberately not \"a nonzero exit came back\". Most admitted\n * rows end on a clean exit — the agent believed it was finished and the tests\n * disagreed — so the gate asks whether the RECORDED state at k reproduces,\n * whatever that state was, including a returncode of zero.\n */\n\nimport type { BudgetMeasurement, BudgetViolation } from './action-budget'\nimport type { ResponseParseFailure } from './analyst-response'\nimport type { RepairContinuationOutcome } from './ports'\n\n/** Why an answer never reached the reproduction gate. */\nexport type RepairRejection =\n | { readonly source: 'parse'; readonly reason: ResponseParseFailure; readonly detail: string }\n | {\n readonly source: 'budget'\n readonly reason: BudgetViolation\n readonly detail: string\n readonly measurement: BudgetMeasurement\n }\n | {\n readonly source: 'target'\n readonly reason: 'k-out-of-range' | 'recorded-action-reproposed'\n readonly detail: string\n }\n\nexport interface PrefixReplayEvidence {\n /** Recorded steps 1..k-1 executed to rebuild the state at k. */\n readonly stepsReplayed: number\n /** Replayed steps whose exit code differed from the recorded returncode. */\n readonly divergences: number\n readonly wallMs: number\n}\n\n/**\n * What the reproduction gate observed at k.\n *\n * `signature` and `signatureObserved` are null together when the recorded\n * observation carried no error line; the gate then rests on the returncode\n * alone and says so through `basis`.\n */\nexport type ReproductionEvidence =\n | {\n /** The step recorded no observation, so there is no state to reproduce.\n * The gate passes vacuously and no container is opened for it. */\n readonly basis: 'no-recorded-observation'\n readonly reproduced: true\n }\n | {\n readonly basis: 'returncode-only' | 'returncode+output-substring'\n readonly reproduced: boolean\n readonly recordedReturncode: number\n readonly observedExitCode: number\n readonly signature: string | null\n readonly signatureObserved: boolean | null\n readonly prefix: PrefixReplayEvidence\n }\n\nexport interface InterventionExecution {\n readonly command: string\n readonly exitCode: number\n readonly timedOut: boolean\n readonly wallMs: number\n readonly output: string\n readonly prefix: PrefixReplayEvidence\n}\n\nexport interface TestRunEvidence {\n readonly passed: boolean\n readonly exitCode: number\n readonly timedOut: boolean\n /** Digest of the suite the oracle read back from inside the container. */\n readonly suiteDigest: string\n}\n\n/**\n * One repair rollout.\n *\n * A rollout whose intervention failed to run is kept and counted as a\n * non-pass rather than dropped. Dropping it would quietly remove the rollouts\n * where the environment behaved worst, which is the direction that flatters\n * the intervention.\n */\nexport type RepairRolloutEvidence =\n | {\n readonly rolloutIndex: number\n readonly status: 'completed'\n readonly interventionExitCode: number\n readonly continuation: RepairContinuationOutcome\n readonly tests: TestRunEvidence\n }\n | {\n readonly rolloutIndex: number\n readonly status: 'intervention-failed'\n readonly interventionExitCode: number\n readonly timedOut: boolean\n }\n\nexport interface RepairArmEvidence {\n /** Rollouts attempted. The denominator of `repairRate`. */\n readonly rollouts: number\n /** Rollouts whose held-out suite passed. */\n readonly passes: number\n /** Rollouts where the intervention did not run, counted as non-passes. */\n readonly interventionFailures: number\n /** Policy digest every completed rollout reported, checked against the\n * controls. Null when no rollout completed. */\n readonly policyDigest: string | null\n readonly rolloutEvidence: readonly RepairRolloutEvidence[]\n}\n\n/**\n * The deepest state an answer reached.\n *\n * Only `measured` carries a repair, so a gate that closed has no field a score\n * could read.\n */\nexport type RepairGrade =\n | { readonly outcome: 'rejected'; readonly rejection: RepairRejection }\n | { readonly outcome: 'declined' }\n | {\n readonly outcome: 'not-reproduced'\n readonly k: number\n readonly reproduction: ReproductionEvidence\n }\n | {\n readonly outcome: 'did-not-execute'\n readonly k: number\n readonly reproduction: ReproductionEvidence\n readonly execution: InterventionExecution\n }\n | {\n readonly outcome: 'measured'\n readonly k: number\n readonly reproduction: ReproductionEvidence\n readonly execution: InterventionExecution\n readonly localFlip: TestRunEvidence\n readonly repair: RepairArmEvidence\n }\n\n/**\n * Everything an answer earns.\n *\n * Three numeric terms and no reproduction term. A vector rather than a scalar\n * because the three measure different things: whether the action ran, whether\n * it fixed the task outright, and how often it led to a fix once the agent\n * carried on.\n */\nexport interface RepairCredit {\n readonly executes: 0 | 1\n readonly localFlip: 0 | 1\n /** Share of repair rollouts whose held-out suite passed. */\n readonly repairRate: number\n}\n\n/**\n * Compile-time proof that no reproduction term can be added to the credit\n * vector without breaking `pnpm typecheck`. A tier that pays nothing must have\n * nothing to pay into.\n */\ntype CreditHasNoReproductionTerm =\n Extract<keyof RepairCredit, `${string}eproduc${string}`> extends never ? true : never\nconst _creditHasNoReproductionTerm: CreditHasNoReproductionTerm = true\nvoid _creditHasNoReproductionTerm\n\nexport const CREDIT_TERMS = [\n 'executes',\n 'localFlip',\n 'repairRate',\n] as const satisfies readonly (keyof RepairCredit)[]\n\nconst ZERO_CREDIT: RepairCredit = Object.freeze({ executes: 0, localFlip: 0, repairRate: 0 })\n\n/** What an answer earned. Every outcome but `measured` earns nothing. */\nexport function repairCredit(grade: RepairGrade): RepairCredit {\n if (grade.outcome !== 'measured') return ZERO_CREDIT\n return {\n executes: 1,\n localFlip: grade.localFlip.passed ? 1 : 0,\n repairRate: grade.repair.rollouts === 0 ? 0 : grade.repair.passes / grade.repair.rollouts,\n }\n}\n\n/** True once the recorded state at k came back. A decline never reaches the\n * gate, because it names no k. */\nfunction reachedT1(grade: RepairGrade): boolean {\n return grade.outcome === 'did-not-execute' || grade.outcome === 'measured'\n}\n\n/** True once the intervention ran at k and exited cleanly. */\nfunction reachedT2(grade: RepairGrade): boolean {\n return grade.outcome === 'measured'\n}\n\nexport interface RepairFunnelCounts {\n readonly rows: number\n readonly rejected: number\n readonly declined: number\n readonly t0Parsed: number\n readonly t1Reproduced: number\n readonly t2Executed: number\n readonly t3LocalFlip: number\n /** Rows where at least one repair rollout passed the held-out suite. */\n readonly t4RepairFlipAny: number\n /** Rows where every repair rollout passed. */\n readonly t4RepairFlipAll: number\n}\n\nexport function countFunnel(grades: readonly RepairGrade[]): RepairFunnelCounts {\n let rejected = 0\n let declined = 0\n let t1 = 0\n let t2 = 0\n let t3 = 0\n let t4Any = 0\n let t4All = 0\n for (const grade of grades) {\n if (grade.outcome === 'rejected') rejected += 1\n if (grade.outcome === 'declined') declined += 1\n if (reachedT1(grade)) t1 += 1\n if (reachedT2(grade)) t2 += 1\n if (grade.outcome === 'measured') {\n if (grade.localFlip.passed) t3 += 1\n if (grade.repair.passes > 0) t4Any += 1\n if (grade.repair.rollouts > 0 && grade.repair.passes === grade.repair.rollouts) t4All += 1\n }\n }\n return {\n rows: grades.length,\n rejected,\n declined,\n t0Parsed: grades.length - rejected,\n t1Reproduced: t1,\n t2Executed: t2,\n t3LocalFlip: t3,\n t4RepairFlipAny: t4Any,\n t4RepairFlipAll: t4All,\n }\n}\n","/**\n * The headline metric.\n *\n * Delta-repair = P(tests pass | intervention) − P(tests pass | no-fix control)\n *\n * Paired per row, then bootstrapped over rows. Paired because the rows differ\n * enormously from each other and not at all between arms: the same trajectory,\n * the same image, the same held-out suite, the same continuation policy, and\n * one difference — the state the continuation starts from.\n *\n * Every admitted row stays in the denominator, including the ones an analyst\n * declined and the ones whose answer was rejected. Those rows contribute a\n * paired difference of exactly zero, because with no intervention to run their\n * arm IS their control arm. Declining is therefore free of error and free of\n * reward, which is what makes it an honest answer rather than a way to pick an\n * easy subset.\n *\n * The report never collapses to this one number. The funnel counts, the rates\n * on measured rows alone, the per-row table and the threats travel with it,\n * because a difference of means computed on a corpus that was admitted on the\n * control failing is conditional on that admission and the reader has to see\n * it to price it.\n */\n\nimport { ValidationError } from '../errors'\nimport { BOOTSTRAP_GATE_MIN_N, pairedBootstrap } from '../statistics'\nimport { countFunnel, type RepairFunnelCounts, type RepairGrade } from './funnel'\nimport type { RepairRowResult } from './grade'\n\nexport interface DeltaRepairOptions {\n /** Deterministic resampling seed. Derived from the deltas when omitted. */\n readonly seed?: number\n readonly resamples?: number\n readonly confidence?: number\n}\n\nexport interface DeltaRepairInterval {\n readonly n: number\n readonly mean: number\n readonly median: number\n readonly low: number\n readonly high: number\n readonly confidence: number\n readonly resamples: number\n /** False below the pair count where a percentile interval carries its\n * nominal error rate. A gate must not turn on a false one. */\n readonly gateEligible: boolean\n}\n\nexport type RepairThreatId =\n | 'control-position-asymmetry'\n | 'control-cannot-rescue'\n | 'admission-conditions-on-control-failure'\n | 'bootstrap-below-min-n'\n | 'prefix-divergence-present'\n | 'intervention-failures-present'\n | 'zero-variance-interval'\n | 'declines-carry-the-denominator'\n\nexport interface RepairThreat {\n readonly id: RepairThreatId\n readonly statement: string\n /** Which way the threat pushes the headline if it is real. */\n readonly direction: 'understates' | 'overstates' | 'unknown'\n}\n\nexport interface DeltaRepairReport {\n readonly rows: number\n readonly funnel: RepairFunnelCounts\n /** Mean over every admitted row. */\n readonly interventionRate: number\n readonly controlRate: number\n readonly deltaRepair: DeltaRepairInterval\n /** The same estimate restricted to rows that reached t2, where an\n * intervention actually ran. Conditional on the analyst answering, so it is\n * never the headline. */\n readonly measuredOnly: DeltaRepairInterval\n readonly measuredRows: number\n readonly rowResults: readonly RepairRowResult[]\n readonly threats: readonly RepairThreat[]\n}\n\nexport function deltaRepair(\n rowResults: readonly RepairRowResult[],\n options: DeltaRepairOptions = {},\n): DeltaRepairReport {\n if (rowResults.length === 0) {\n throw new ValidationError('deltaRepair needs at least one graded row')\n }\n const seen = new Set<string>()\n for (const row of rowResults) {\n if (seen.has(row.rowId)) {\n throw new ValidationError(`deltaRepair received row ${row.rowId} twice`)\n }\n seen.add(row.rowId)\n }\n\n const grades = rowResults.map((row) => row.grade)\n const funnel = countFunnel(grades)\n const control = rowResults.map((row) => row.controlRate)\n const intervention = rowResults.map((row) => row.interventionRate)\n const deltaAll = interval(control, intervention, options)\n\n const measured = rowResults.filter((row) => row.grade.outcome === 'measured')\n const measuredOnly =\n measured.length === 0\n ? emptyInterval(options)\n : interval(\n measured.map((row) => row.controlRate),\n measured.map((row) => row.interventionRate),\n options,\n )\n\n return {\n rows: rowResults.length,\n funnel,\n interventionRate: mean(intervention),\n controlRate: mean(control),\n deltaRepair: deltaAll,\n measuredOnly,\n measuredRows: measured.length,\n rowResults,\n threats: collectThreats(rowResults, funnel, deltaAll),\n }\n}\n\nfunction interval(\n control: readonly number[],\n intervention: readonly number[],\n options: DeltaRepairOptions,\n): DeltaRepairInterval {\n const result = pairedBootstrap([...control], [...intervention], {\n statistic: 'mean',\n seed: options.seed,\n resamples: options.resamples,\n confidence: options.confidence,\n })\n return {\n n: result.n,\n mean: result.mean,\n median: result.median,\n low: result.low,\n high: result.high,\n confidence: result.confidence,\n resamples: result.resamples,\n gateEligible: result.gateEligible,\n }\n}\n\nfunction emptyInterval(options: DeltaRepairOptions): DeltaRepairInterval {\n return {\n n: 0,\n mean: 0,\n median: 0,\n low: 0,\n high: 0,\n confidence: options.confidence ?? 0.95,\n resamples: options.resamples ?? 2000,\n gateEligible: false,\n }\n}\n\nfunction collectThreats(\n rowResults: readonly RepairRowResult[],\n funnel: RepairFunnelCounts,\n delta: DeltaRepairInterval,\n): RepairThreat[] {\n const threats: RepairThreat[] = [\n {\n id: 'control-position-asymmetry',\n statement:\n 'The no-fix control continues from the recorded end state, while the intervention arm continues from step k and has to redo the work the recording did after k inside the same step budget. The arms are matched on policy and budget, not on position.',\n direction: 'understates',\n },\n ]\n const inert = rowResults.filter((row) => row.controlScreening === 'declared-inert')\n if (inert.length > 0) {\n threats.push({\n id: 'control-cannot-rescue',\n statement: `${inert.length}/${rowResults.length} rows were screened under a control that makes no model call, so its rollouts graded the same bytes the end-state check graded as failing. A control rate of zero on those rows is a restatement of the end-state check, not a measurement of what continuing alone can repair.`,\n direction: 'unknown',\n })\n }\n if (inert.length === 0 && rowResults.every((row) => row.controlRate === 0)) {\n threats.push({\n id: 'admission-conditions-on-control-failure',\n statement:\n 'Every row was admitted on its no-fix control failing every rollout, so the control rate is zero everywhere and Delta-repair equals the intervention rate. The estimate is conditional on that admission and does not describe rows the control can already repair.',\n direction: 'unknown',\n })\n }\n if (!delta.gateEligible) {\n threats.push({\n id: 'bootstrap-below-min-n',\n statement: `The interval covers ${delta.n} paired rows, below the ${BOOTSTRAP_GATE_MIN_N} where a percentile bootstrap holds its nominal error rate. Read it as descriptive spread; a promotion must not turn on it.`,\n direction: 'unknown',\n })\n }\n const divergent = rowResults.filter((row) => measuredPrefixDivergences(row.grade) > 0).length\n if (divergent > 0) {\n threats.push({\n id: 'prefix-divergence-present',\n statement: `${divergent}/${rowResults.length} rows replayed at least one prefix step to a different exit code than the recording. The state the intervention landed on is close to the recorded one, not identical to it.`,\n direction: 'unknown',\n })\n }\n const withFailures = rowResults.filter(\n (row) => row.grade.outcome === 'measured' && row.grade.repair.interventionFailures > 0,\n ).length\n if (withFailures > 0) {\n threats.push({\n id: 'intervention-failures-present',\n statement: `${withFailures} rows had at least one rollout where the intervention failed to run after it had already run cleanly in the local-flip session. Those rollouts count as non-passes.`,\n direction: 'understates',\n })\n }\n if (delta.low === delta.high) {\n threats.push({\n id: 'zero-variance-interval',\n statement:\n 'Every resample produced the same statistic, so the interval has zero width. That is an absence of variation in the data, not certainty about the effect.',\n direction: 'unknown',\n })\n }\n if (funnel.declined + funnel.rejected > funnel.rows / 2) {\n threats.push({\n id: 'declines-carry-the-denominator',\n statement: `${funnel.declined} declined and ${funnel.rejected} rejected of ${funnel.rows} rows contribute a paired delta of zero. The headline is dominated by rows where no intervention ran.`,\n direction: 'understates',\n })\n }\n return threats\n}\n\nfunction measuredPrefixDivergences(grade: RepairGrade): number {\n if (grade.outcome === 'measured' || grade.outcome === 'did-not-execute') {\n return grade.execution.prefix.divergences\n }\n if (\n grade.outcome === 'not-reproduced' &&\n grade.reproduction.basis !== 'no-recorded-observation'\n ) {\n return grade.reproduction.prefix.divergences\n }\n return 0\n}\n\nfunction mean(values: readonly number[]): number {\n return values.reduce((sum, value) => sum + value, 0) / values.length\n}\n\n/** Markdown report: provenance, the funnel, every per-row column, the\n * distribution, and the threats. */\nexport function renderDeltaRepairReport(report: DeltaRepairReport): string {\n const lines: string[] = []\n const pct = (value: number): string => `${(value * 100).toFixed(1)} %`\n lines.push('# Delta-repair')\n lines.push('')\n lines.push(\n `**${signed(report.deltaRepair.mean)}** paired mean over ${report.rows} admitted rows ` +\n `(${(report.deltaRepair.confidence * 100).toFixed(0)} % CI ` +\n `${signed(report.deltaRepair.low)} … ${signed(report.deltaRepair.high)}, ` +\n `${report.deltaRepair.resamples} resamples, gate-eligible: ${report.deltaRepair.gateEligible}).`,\n )\n lines.push('')\n lines.push(\n `P(tests pass | intervention) = ${pct(report.interventionRate)}; ` +\n `P(tests pass | no-fix control) = ${pct(report.controlRate)}.`,\n )\n lines.push('')\n lines.push('## Funnel')\n lines.push('')\n lines.push('| cell | rows | share |')\n lines.push('| --- | --- | --- |')\n const f = report.funnel\n const share = (value: number): string => pct(f.rows === 0 ? 0 : value / f.rows)\n for (const [label, value] of [\n ['admitted rows', f.rows],\n ['t0 parsed', f.t0Parsed],\n ['t1 reproduced (gate, pays nothing)', f.t1Reproduced],\n ['t2 intervention executes', f.t2Executed],\n ['t3 local flip', f.t3LocalFlip],\n ['t4 repair flip (any rollout)', f.t4RepairFlipAny],\n ['t4 repair flip (every rollout)', f.t4RepairFlipAll],\n ['no-decisive-failure', f.declined],\n ['rejected', f.rejected],\n ] as const) {\n lines.push(`| ${label} | ${value} | ${share(value)} |`)\n }\n lines.push('')\n lines.push('## Rows')\n lines.push('')\n lines.push(\n '| row | outcome | k | reproduction basis | reproduced | intervention exit | local flip | repair passes | rollouts | intervention failures | prefix steps | prefix divergences | P(int) | P(ctl) | delta | wall ms |',\n )\n lines.push(\n '| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |',\n )\n for (const row of report.rowResults) {\n lines.push(`| ${rowCells(row).join(' | ')} |`)\n }\n lines.push('')\n lines.push('## Measured rows only')\n lines.push('')\n lines.push(\n `${report.measuredRows} rows reached t2. Paired mean ${signed(report.measuredOnly.mean)} ` +\n `(CI ${signed(report.measuredOnly.low)} … ${signed(report.measuredOnly.high)}). ` +\n 'Conditional on the analyst answering, so it is not the headline.',\n )\n lines.push('')\n lines.push('## Threats')\n lines.push('')\n for (const threat of report.threats) {\n lines.push(`- **${threat.id}** (${threat.direction} the effect) — ${threat.statement}`)\n }\n lines.push('')\n return lines.join('\\n')\n}\n\nfunction rowCells(row: RepairRowResult): string[] {\n const grade = row.grade\n const reproduction =\n grade.outcome === 'not-reproduced' ||\n grade.outcome === 'did-not-execute' ||\n grade.outcome === 'measured'\n ? grade.reproduction\n : null\n const execution =\n grade.outcome === 'did-not-execute' || grade.outcome === 'measured' ? grade.execution : null\n const repair = grade.outcome === 'measured' ? grade.repair : null\n const prefix =\n execution?.prefix ??\n (reproduction && reproduction.basis !== 'no-recorded-observation' ? reproduction.prefix : null)\n const rejection =\n grade.outcome === 'rejected' ? `rejected: ${grade.rejection.reason}` : grade.outcome\n return [\n row.rowId,\n rejection,\n grade.outcome === 'rejected' || grade.outcome === 'declined' ? '—' : String(grade.k),\n reproduction ? reproduction.basis : '—',\n reproduction ? String(reproduction.reproduced) : '—',\n execution ? String(execution.exitCode) : '—',\n grade.outcome === 'measured' ? String(grade.localFlip.passed) : '—',\n repair ? String(repair.passes) : '—',\n repair ? String(repair.rollouts) : '0',\n repair ? String(repair.interventionFailures) : '—',\n prefix ? String(prefix.stepsReplayed) : '—',\n prefix ? String(prefix.divergences) : '—',\n row.interventionRate.toFixed(3),\n row.controlRate.toFixed(3),\n signed(row.delta),\n String(row.wallMs),\n ]\n}\n\nfunction signed(value: number): string {\n const points = value * 100\n return `${points >= 0 ? '+' : ''}${points.toFixed(1)} pp`\n}\n","/**\n * Docker-backed continuation environment.\n *\n * The runner refuses any container whose network mode is not `none`, so this\n * builds containers that way and reports the mode it reads back from the\n * daemon rather than the mode it asked for. A container created elsewhere and\n * attached here is described the same way, so an environment that quietly kept\n * its network is rejected instead of producing evidence.\n *\n * Commands are bounded twice. `timeout` inside the container is the primary\n * bound, because killing the host-side `docker exec` client leaves the process\n * it started running in the container, where it would keep writing files under\n * later steps. The host-side kill is a backstop for a daemon that stops\n * answering. The container must therefore provide `timeout`; `describe()`\n * checks for it and refuses the container when it is absent.\n */\n\nimport { spawn } from 'node:child_process'\nimport { constants } from 'node:os'\nimport { ValidationError } from '../errors'\nimport type { ContinuationEnvironment, ContinuationExecResult } from './continuation-policy'\nimport type { ContinuationEnvironmentDescription } from './continuation-records'\n\nexport interface ProcessRequest {\n argv: string[]\n /** Kills the process group when exceeded. */\n timeoutSeconds?: number\n}\n\nexport interface ProcessResult {\n /** stdout and stderr interleaved, as the scaffold reads them. */\n output: string\n exitCode: number\n /** True when the process was killed for exceeding `timeoutSeconds`. */\n timedOut: boolean\n}\n\n/** Runs a process on the host. Injected so the environment is testable without a daemon. */\nexport type ProcessRunner = (request: ProcessRequest) => Promise<ProcessResult>\n\n/**\n * Spawns a process, merges stdout and stderr the way the scaffold reads them,\n * and kills the whole process group on timeout so a killed command leaves no\n * children running in the container's namespace.\n */\nexport const nodeProcessRunner: ProcessRunner = (request) =>\n new Promise<ProcessResult>((resolve, reject) => {\n const [command, ...args] = request.argv\n if (!command) {\n reject(new ValidationError('process runner requires a command'))\n return\n }\n const child = spawn(command, args, { detached: true, stdio: ['ignore', 'pipe', 'pipe'] })\n const chunks: string[] = []\n let timedOut = false\n child.stdout.setEncoding('utf8')\n child.stderr.setEncoding('utf8')\n child.stdout.on('data', (chunk: string) => chunks.push(chunk))\n child.stderr.on('data', (chunk: string) => chunks.push(chunk))\n\n const timer =\n request.timeoutSeconds === undefined\n ? undefined\n : setTimeout(() => {\n timedOut = true\n if (child.pid === undefined) return\n try {\n process.kill(-child.pid, 'SIGKILL')\n } catch (error) {\n // ESRCH means the group exited between the deadline and this\n // signal, and `close` resolves the promise. Any other failure\n // means the process may still be running, so surface it.\n if ((error as NodeJS.ErrnoException).code !== 'ESRCH') reject(error)\n }\n }, request.timeoutSeconds * 1000)\n\n child.on('error', (error) => {\n if (timer) clearTimeout(timer)\n reject(error)\n })\n child.on('close', (code, signal) => {\n if (timer) clearTimeout(timer)\n const output = chunks.join('')\n if (code !== null) {\n resolve({ output, exitCode: code, timedOut })\n return\n }\n // A signalled exit carries no code. Report the negative signal number,\n // which is how the corpus records a killed command.\n const signalNumber = signal === null ? undefined : constants.signals[signal]\n if (signalNumber === undefined) {\n reject(\n new ValidationError(`process closed with no exit code and no known signal: ${signal}`),\n )\n return\n }\n resolve({ output, exitCode: -signalNumber, timedOut })\n })\n })\n\nexport interface DockerContinuationEnvironmentOptions {\n /** Container id or name holding the post-step-k state. */\n containerRef: string\n /** Working directory for every command. */\n cwd: string\n /** Environment variables set on every command. */\n env?: Record<string, string>\n /** Interpreter the scaffold runs commands through. */\n interpreter?: string[]\n /** `docker` unless a compatible client is used. */\n executable?: string\n runProcess: ProcessRunner\n /** Removes the container on dispose. Leave false when the caller owns its lifecycle. */\n removeOnDispose?: boolean\n}\n\nconst DEFAULT_INTERPRETER = ['bash', '-lc']\nconst DEFAULT_EXECUTABLE = 'docker'\n\n/** Seconds `timeout` waits after SIGTERM before sending SIGKILL. */\nconst KILL_GRACE_SECONDS = 5\n\n/** Extra seconds the host-side backstop waits after the in-container bound. */\nconst BACKSTOP_SECONDS = 10\n\n/** `timeout` reports this when it stopped the command. */\nconst TIMEOUT_EXIT_CODE = 124\n\n/**\n * Arguments that create a container the policy accepts. `--network none` is\n * not optional: a continuation with network access could install what the\n * recorded run could not, and the arms would no longer differ only by the\n * intervention.\n */\nexport function dockerRunArgs(input: {\n image: string\n name: string\n cwd: string\n containerLifetime?: string\n executable?: string\n}): string[] {\n return [\n input.executable ?? DEFAULT_EXECUTABLE,\n 'run',\n '-d',\n '--name',\n input.name,\n '--network',\n 'none',\n '-w',\n input.cwd,\n '--rm',\n input.image,\n 'sleep',\n input.containerLifetime ?? '2h',\n ]\n}\n\nexport function createDockerContinuationEnvironment(\n options: DockerContinuationEnvironmentOptions,\n): ContinuationEnvironment {\n if (!options.containerRef.trim()) {\n throw new ValidationError('docker continuation environment requires a container reference')\n }\n const executable = options.executable ?? DEFAULT_EXECUTABLE\n const interpreter = options.interpreter ?? DEFAULT_INTERPRETER\n const envEntries = Object.entries(options.env ?? {})\n\n return {\n containerRef: options.containerRef,\n\n async describe(): Promise<ContinuationEnvironmentDescription> {\n const inspect = await options.runProcess({\n argv: [\n executable,\n 'inspect',\n '--format',\n '{{.HostConfig.NetworkMode}}\\t{{.Config.Image}}',\n options.containerRef,\n ],\n })\n if (inspect.exitCode !== 0) {\n throw new ValidationError(\n `docker inspect failed for ${options.containerRef} (exit ${inspect.exitCode}): ${inspect.output.trim()}`,\n )\n }\n const [networkMode, image] = inspect.output.trim().split('\\t')\n if (!networkMode) {\n throw new ValidationError(\n `docker inspect returned no network mode for ${options.containerRef}`,\n )\n }\n const hasTimeout = await options.runProcess({\n argv: [executable, 'exec', options.containerRef, ...interpreter, 'command -v timeout'],\n })\n if (hasTimeout.exitCode !== 0) {\n throw new ValidationError(\n `container ${options.containerRef} provides no \\`timeout\\`, so a long command cannot be bounded inside it`,\n )\n }\n return image ? { networkMode, image } : { networkMode }\n },\n\n async exec(\n command: string,\n execOptions: { timeoutSeconds: number },\n ): Promise<ContinuationExecResult> {\n const argv = [executable, 'exec', '-w', options.cwd]\n for (const [key, value] of envEntries) argv.push('-e', `${key}=${value}`)\n argv.push(\n options.containerRef,\n 'timeout',\n `--kill-after=${KILL_GRACE_SECONDS}s`,\n `${execOptions.timeoutSeconds}s`,\n ...interpreter,\n command,\n )\n const result = await options.runProcess({\n argv,\n // Backstop only: it fires after the in-container bound plus its grace.\n timeoutSeconds: execOptions.timeoutSeconds + KILL_GRACE_SECONDS + BACKSTOP_SECONDS,\n })\n // `timeout` exits 124 when it stopped the command. A command that exits\n // 124 on its own is reported the same way, which overstates timeouts\n // rather than hiding them.\n const timedOut = result.timedOut || result.exitCode === TIMEOUT_EXIT_CODE\n return {\n output: result.output,\n returncode: result.exitCode,\n timedOut,\n }\n },\n\n async dispose(): Promise<void> {\n if (!options.removeOnDispose) return\n await options.runProcess({ argv: [executable, 'rm', '-f', options.containerRef] })\n },\n }\n}\n","/**\n * Grade one analyst answer about one admitted row.\n *\n * The whole funnel runs here, in the order that spends the least before it\n * knows: parse and budget checks open no container, the reproduction gate\n * opens one, the local flip opens one more, and only then does the repair arm\n * pay for its rollouts.\n *\n * Two properties a reviewer should be able to check by reading this file:\n *\n * The intervention is applied at the k the analyst named, on the state\n * produced by replaying steps 1..k-1, and nowhere else. There is no search\n * over nearby steps, no credit for being close, and no label in scope — the\n * grader never receives one. A wrong k therefore scores zero the only honest\n * way it can: the repair has to work where the analyst said the failure was.\n *\n * The row must arrive branded by `admitRow`. That is the type-level form of\n * \"admission runs before any analyst sees a row\": there is no signature here\n * that accepts an unadmitted row.\n */\n\nimport { CaptureIntegrityError, ValidationError } from '../errors'\nimport { packageVersion } from '../package-version'\nimport { wrapActionForExec } from '../trajectory-replay/exec'\nimport {\n deriveFailureSignature,\n parseRecordedReturncode,\n type RecordedTrajectoryStep,\n} from '../trajectory-replay/steps'\nimport { certificationEvidenceDigest, type DefaultVerdict } from '../verdict'\nimport {\n checkInterventionBudget,\n type InterventionBudget,\n normalizeActionForComparison,\n SCAFFOLD_INTERVENTION_BUDGET,\n} from './action-budget'\nimport type { AdmittedRow } from './admission-contract'\nimport type { AnalystResponse, RepairFinding } from './analyst-response'\nimport type { ControlScreening } from './control-policy'\nimport {\n type InterventionExecution,\n type PrefixReplayEvidence,\n type RepairArmEvidence,\n type RepairCredit,\n type RepairGrade,\n type RepairRolloutEvidence,\n type ReproductionEvidence,\n repairCredit,\n type TestRunEvidence,\n} from './funnel'\nimport { isRecordedTimeout } from './mini-swe-scaffold'\nimport type {\n RepairArm,\n RepairContinuationOutcome,\n RepairContinuationRunner,\n RepairSession,\n RepairSessionFactory,\n TestOracle,\n} from './ports'\n\n/** Rollouts of the repair arm disagreed with the controls about the policy. */\nclass RepairArmSymmetryError extends CaptureIntegrityError {}\n\nexport interface GradeRepairOptions {\n readonly row: AdmittedRow\n readonly response: AnalystResponse\n readonly sessions: RepairSessionFactory\n readonly oracle: TestOracle\n readonly continuation: RepairContinuationRunner\n /** Repair rollouts for the intervention arm. Defaults to the row's own\n * control rollout count so the arms are matched. */\n readonly repairRollouts?: number\n readonly budget?: InterventionBudget\n /** Wall-clock limit for one replayed or injected action. */\n readonly stepTimeoutMs?: number\n /**\n * Wall-clock limit for replaying a step the recording itself killed.\n *\n * Such a step carries no returncode, so the replay agrees with the recording\n * no matter how long it waits. Bounding it separately cuts what a prefix\n * costs without changing what it counts. Defaults to `stepTimeoutMs`.\n */\n readonly recordedTimeoutStepMs?: number\n readonly onProgress?: (message: string) => void\n}\n\n/** Extends the substrate verdict spine: `valid` = the intervention flipped\n * the held-out suite in at least one measurement (locally or after the\n * pinned continuation); `score` = the better of the two flip measurements\n * (`localFlip`, `repairRate`), so `valid` ⟺ `score > 0`. The credit\n * VECTOR stays authoritative in `credit` and travels in `scores` —\n * Delta-repair pairing reads `delta`, never the scalar. Certification is\n * present exactly when the suite executed (`outcome: 'measured'`); a\n * closed gate certifies nothing. */\nexport interface RepairRowResult extends DefaultVerdict {\n readonly rowId: string\n readonly grade: RepairGrade\n readonly credit: RepairCredit\n /** P(tests pass | intervention). Equals `controlRate` when no intervention\n * arm ran, because the row's state is then the control's state. */\n readonly interventionRate: number\n readonly controlRate: number\n readonly controlRollouts: number\n /** How the row's control pass was read. Travels with the result so a report\n * can say whether a control rate of zero was screened or merely inert. */\n readonly controlScreening: ControlScreening\n readonly controlPolicyDigest: string\n readonly repairRollouts: number\n /** The row's paired contribution to Delta-repair. */\n readonly delta: number\n readonly wallMs: number\n}\n\nconst DEFAULT_STEP_TIMEOUT_MS = 300_000\nconst OUTPUT_EXCERPT_CHARS = 4000\n\nexport async function gradeRepairRow(options: GradeRepairOptions): Promise<RepairRowResult> {\n const startedMs = Date.now()\n const grade = await produceGrade(options)\n return finish(options.row, grade, startedMs)\n}\n\nfunction finish(row: AdmittedRow, grade: RepairGrade, startedMs: number): RepairRowResult {\n const credit = repairCredit(grade)\n const interventionRate = grade.outcome === 'measured' ? credit.repairRate : row.controlRate\n const score = Math.max(credit.localFlip, credit.repairRate)\n return {\n rowId: row.rowId,\n grade,\n credit,\n interventionRate,\n controlRate: row.controlRate,\n controlRollouts: row.controlRollouts,\n controlScreening: row.controlScreening,\n controlPolicyDigest: row.policyDigest,\n repairRollouts: grade.outcome === 'measured' ? grade.repair.rollouts : 0,\n delta: interventionRate - row.controlRate,\n wallMs: Date.now() - startedMs,\n valid: score > 0,\n score,\n scores: { ...credit },\n notes: `outcome: ${grade.outcome}`,\n ...(grade.outcome === 'measured'\n ? {\n certification: {\n strategy: 'test',\n checker: {\n name: 'agent-eval:trace-repair-grader',\n version: packageVersion(),\n pins: { suite: row.suiteDigest, policy: row.policyDigest },\n },\n assumptions: gradeAssumptions(grade),\n evidenceDigest: certificationEvidenceDigest(grade),\n },\n }\n : {}),\n }\n}\n\n/** Steps a measured grade rests on that no suite run verified. */\nfunction gradeAssumptions(grade: Extract<RepairGrade, { outcome: 'measured' }>): string[] {\n const assumptions: string[] = []\n if (grade.reproduction.basis === 'no-recorded-observation') {\n assumptions.push('step k recorded no observation — the reproduction gate passed vacuously')\n }\n const prefix = grade.execution.prefix\n if (prefix.divergences > 0) {\n assumptions.push(\n `${prefix.divergences} of ${prefix.stepsReplayed} replayed prefix steps diverged from the recording — the state at k is approximate`,\n )\n }\n return assumptions\n}\n\nasync function produceGrade(options: GradeRepairOptions): Promise<RepairGrade> {\n const { row, response } = options\n if (response.kind === 'no-decisive-failure') return { outcome: 'declined' }\n\n const target = targetStep(row, response)\n if (!target.ok) return target.grade\n\n const budget = options.budget ?? SCAFFOLD_INTERVENTION_BUDGET\n const check = checkInterventionBudget(\n response.intervention.action,\n response.intervention.kind,\n budget,\n )\n if (!check.admissible) {\n return {\n outcome: 'rejected',\n rejection: {\n source: 'budget',\n reason: check.violation,\n detail: check.detail,\n measurement: check.measurement,\n },\n }\n }\n if (\n normalizeActionForComparison(response.intervention.action) ===\n normalizeActionForComparison(target.step.action)\n ) {\n return {\n outcome: 'rejected',\n rejection: {\n source: 'target',\n reason: 'recorded-action-reproposed',\n detail: `the intervention is the action already recorded at step ${response.k}`,\n },\n }\n }\n\n const reproduction = await runReproductionGate(options, response, target.step)\n if (!reproduction.reproduced) {\n return { outcome: 'not-reproduced', k: response.k, reproduction }\n }\n\n const local = await runLocalFlip(options, response)\n if (local.kind === 'did-not-execute') {\n return {\n outcome: 'did-not-execute',\n k: response.k,\n reproduction,\n execution: local.execution,\n }\n }\n\n const repair = await runRepairArm(options, response)\n return {\n outcome: 'measured',\n k: response.k,\n reproduction,\n execution: local.execution,\n localFlip: local.tests,\n repair,\n }\n}\n\nfunction targetStep(\n row: AdmittedRow,\n finding: RepairFinding,\n): { ok: true; step: RecordedTrajectoryStep } | { ok: false; grade: RepairGrade } {\n if (finding.k < 1 || finding.k > row.steps.length) {\n return {\n ok: false,\n grade: {\n outcome: 'rejected',\n rejection: {\n source: 'target',\n reason: 'k-out-of-range',\n detail: `k=${finding.k} is outside [1, ${row.steps.length}]`,\n },\n },\n }\n }\n const step = row.steps[finding.k - 1]!\n if (step.step_id !== finding.k) {\n throw new ValidationError(\n `trace-repair: row ${row.rowId} steps[${finding.k - 1}].step_id=${step.step_id} != ${finding.k}; ` +\n 'an admitted row must carry 1-based contiguous step ids',\n )\n }\n return { ok: true, step }\n}\n\nasync function runReproductionGate(\n options: GradeRepairOptions,\n finding: RepairFinding,\n target: RecordedTrajectoryStep,\n): Promise<ReproductionEvidence> {\n const { row } = options\n if (target.observation === null) {\n options.onProgress?.(\n `row ${row.rowId}: step ${finding.k} recorded no observation; the reproduction gate passes vacuously`,\n )\n return { basis: 'no-recorded-observation', reproduced: true }\n }\n const recordedReturncode = parseRecordedReturncode(target.observation)\n if (recordedReturncode === null) {\n throw new ValidationError(\n `trace-repair: row ${row.rowId} step ${finding.k} carries an observation with no <returncode>; ` +\n 'the corpus row is malformed and must not have been admitted',\n )\n }\n const signature = deriveFailureSignature(target.observation)\n\n const session = await options.sessions.open({\n rowId: row.rowId,\n image: row.image,\n arm: 'reproduce',\n rolloutIndex: 0,\n })\n try {\n const prefix = await replayPrefix(session, options, finding.k)\n const result = await session.exec(\n wrapActionForExec(target.action, row.cwd),\n options.stepTimeoutMs ?? DEFAULT_STEP_TIMEOUT_MS,\n )\n const output = `${result.stdout}\\n${result.stderr}`\n const signatureObserved = signature === null ? null : output.includes(signature)\n const reproduced =\n !result.timedOut && result.exitCode === recordedReturncode && signatureObserved !== false\n options.onProgress?.(\n `row ${row.rowId}: reproduction at step ${finding.k} exit=${result.exitCode} ` +\n `(recorded ${recordedReturncode}) reproduced=${reproduced}`,\n )\n return {\n basis: signature === null ? 'returncode-only' : 'returncode+output-substring',\n reproduced,\n recordedReturncode,\n observedExitCode: result.exitCode,\n signature,\n signatureObserved,\n prefix,\n }\n } finally {\n await session.close()\n }\n}\n\ntype LocalFlipOutcome =\n | { kind: 'did-not-execute'; execution: InterventionExecution }\n | { kind: 'measured'; execution: InterventionExecution; tests: TestRunEvidence }\n\nasync function runLocalFlip(\n options: GradeRepairOptions,\n finding: RepairFinding,\n): Promise<LocalFlipOutcome> {\n const { row } = options\n const session = await options.sessions.open({\n rowId: row.rowId,\n image: row.image,\n arm: 'local-flip',\n rolloutIndex: 0,\n })\n try {\n const prefix = await replayPrefix(session, options, finding.k)\n const startedMs = Date.now()\n const result = await session.exec(\n wrapActionForExec(finding.intervention.action, row.cwd),\n options.stepTimeoutMs ?? DEFAULT_STEP_TIMEOUT_MS,\n )\n const output = `${result.stdout}\\n${result.stderr}`.trim()\n const execution: InterventionExecution = {\n command: finding.intervention.action,\n exitCode: result.exitCode,\n timedOut: result.timedOut,\n wallMs: Date.now() - startedMs,\n output: excerpt(output),\n prefix,\n }\n if (result.timedOut || result.exitCode !== 0) {\n options.onProgress?.(\n `row ${row.rowId}: the intervention did not run at step ${finding.k} ` +\n `(exit=${result.exitCode} timedOut=${result.timedOut})`,\n )\n return { kind: 'did-not-execute', execution }\n }\n const tests = await gradeTests(options, session, 'local-flip', 0)\n options.onProgress?.(\n `row ${row.rowId}: local flip=${tests.passed} after the intervention at step ${finding.k}`,\n )\n return { kind: 'measured', execution, tests }\n } finally {\n await session.close()\n }\n}\n\nasync function runRepairArm(\n options: GradeRepairOptions,\n finding: RepairFinding,\n): Promise<RepairArmEvidence> {\n const { row } = options\n const rollouts = options.repairRollouts ?? row.controlRollouts\n if (!Number.isInteger(rollouts) || rollouts <= 0) {\n throw new ValidationError(`repairRollouts must be a positive integer, got ${rollouts}`)\n }\n const evidence: RepairRolloutEvidence[] = []\n let passes = 0\n let interventionFailures = 0\n let policyDigest: string | null = null\n\n for (let index = 0; index < rollouts; index += 1) {\n const session = await options.sessions.open({\n rowId: row.rowId,\n image: row.image,\n arm: 'intervention',\n rolloutIndex: index,\n })\n try {\n await replayPrefix(session, options, finding.k)\n const result = await session.exec(\n wrapActionForExec(finding.intervention.action, row.cwd),\n options.stepTimeoutMs ?? DEFAULT_STEP_TIMEOUT_MS,\n )\n if (result.timedOut || result.exitCode !== 0) {\n interventionFailures += 1\n evidence.push({\n rolloutIndex: index,\n status: 'intervention-failed',\n interventionExitCode: result.exitCode,\n timedOut: result.timedOut,\n })\n continue\n }\n const continuation = await options.continuation({\n rowId: row.rowId,\n arm: 'intervention',\n rolloutIndex: index,\n session,\n steps: row.steps,\n k: finding.k,\n injected: {\n action: finding.intervention.action,\n returncode: result.exitCode,\n output: `${result.stdout}\\n${result.stderr}`.trim(),\n timedOut: result.timedOut,\n },\n taskStatement: row.taskStatement,\n })\n assertPolicySymmetry(row, continuation, index)\n policyDigest = continuation.policyDigest\n const tests = await gradeTests(options, session, 'intervention', index)\n if (tests.passed) passes += 1\n evidence.push({\n rolloutIndex: index,\n status: 'completed',\n interventionExitCode: result.exitCode,\n continuation,\n tests,\n })\n options.onProgress?.(\n `row ${row.rowId}: repair rollout ${index} tests=${tests.passed} ` +\n `after ${continuation.steps} continuation steps (${continuation.exitStatus})`,\n )\n } finally {\n await session.close()\n }\n }\n\n return { rollouts, passes, interventionFailures, policyDigest, rolloutEvidence: evidence }\n}\n\nfunction assertPolicySymmetry(\n row: AdmittedRow,\n continuation: RepairContinuationOutcome,\n index: number,\n): void {\n if (continuation.policyDigest !== row.policyDigest) {\n throw new RepairArmSymmetryError(\n `row ${row.rowId} repair rollout ${index} ran policy ${continuation.policyDigest} but its ` +\n `controls ran ${row.policyDigest}; the difference between the arms would not be the intervention`,\n )\n }\n}\n\nasync function gradeTests(\n options: GradeRepairOptions,\n session: RepairSession,\n arm: RepairArm,\n rolloutIndex: number,\n): Promise<TestRunEvidence> {\n const outcome = await options.oracle.grade(session, {\n rowId: options.row.rowId,\n arm,\n rolloutIndex,\n })\n if (outcome.suiteDigest !== options.row.suiteDigest) {\n throw new RepairArmSymmetryError(\n `row ${options.row.rowId} was admitted against suite ${options.row.suiteDigest} but the ${arm} arm ` +\n `graded against ${outcome.suiteDigest}; the arms did not answer the same question`,\n )\n }\n return {\n passed: outcome.passed,\n exitCode: outcome.exitCode,\n timedOut: outcome.timedOut,\n suiteDigest: outcome.suiteDigest,\n }\n}\n\n/** Replay recorded steps 1..k-1 to rebuild the state the intervention lands\n * on. Divergence is counted and reported, never repaired. */\nasync function replayPrefix(\n session: RepairSession,\n options: GradeRepairOptions,\n k: number,\n): Promise<PrefixReplayEvidence> {\n const { row } = options\n const timeoutMs = options.stepTimeoutMs ?? DEFAULT_STEP_TIMEOUT_MS\n const recordedTimeoutMs = options.recordedTimeoutStepMs ?? timeoutMs\n const startedMs = Date.now()\n let divergences = 0\n let stepsReplayed = 0\n for (const step of row.steps.slice(0, k - 1)) {\n const bound = isRecordedTimeout(step.observation) ? recordedTimeoutMs : timeoutMs\n const result = await session.exec(wrapActionForExec(step.action, row.cwd), bound)\n stepsReplayed += 1\n const recorded = parseRecordedReturncode(step.observation)\n if (recorded !== null && recorded !== result.exitCode) divergences += 1\n }\n return { stepsReplayed, divergences, wallMs: Date.now() - startedMs }\n}\n\nfunction excerpt(text: string): string {\n if (text.length <= OUTPUT_EXCERPT_CHARS) return text\n const half = Math.floor(OUTPUT_EXCERPT_CHARS / 2)\n return `${text.slice(0, half)}\\n… [${text.length - OUTPUT_EXCERPT_CHARS} chars elided] …\\n${text.slice(-half)}`\n}\n","/**\n * Whether a task's own grader is a function of the container state.\n *\n * A repair benchmark uses the task's held-out suite as ground truth: the suite\n * says the state before the intervention fails and the state after it passes,\n * and the difference is the measurement. That reading needs the suite to answer\n * the same way twice on the same bytes. A suite that asserts on wall clock does\n * not: the same container passes or fails by chance, so a control arm can\n * \"rescue\" a row nothing touched, and an intervention arm can lose a repair it\n * made.\n *\n * The check is direct. Grade the same container N times with nothing written\n * between the runs, pool the replicates by the state they graded, and read the\n * minority share.\n *\n * It reads that share per ASSERTION, not per suite, wherever the suite reports\n * assertions. A pass/fail reward is a conjunction over many assertions, so a\n * suite whose timing assertions each flip independently can still return the\n * same reward on every replicate of a state that sits far from the threshold —\n * and then return a coin flip on the states a campaign actually grades, which\n * sit near it. Per-assertion counting sees the flip at the anchor; reward\n * counting does not. A state whose replicates carried no assertion report falls\n * back to the reward and records that it did, so a coarser measurement is\n * visible rather than assumed equivalent.\n *\n * Replicates are also run under machine contention, because unanimity on an\n * idle box proves nothing about a threshold the load never approached.\n * Replicates on one state pool across both loads, so a verdict that moves when\n * the machine gets busy reads as the flip it is.\n */\n\nimport { CaptureIntegrityError, ValidationError } from '../errors'\n\n/** A task graded a repair by something other than the state under test. */\nexport class NondeterministicOracleError extends CaptureIntegrityError {}\n\n/** The two states certification produces: the published image, and that image\n * after the task's own reference solution ran. */\nexport type OracleStateLabel = 'unsolved' | 'solved'\n\n/** Machine load the replicate ran under. */\nexport type OracleLoad = 'idle' | 'contended'\n\n/** The unit a whole-suite verdict is counted under when nothing finer exists. */\nexport const SUITE_REWARD_UNIT = 'suite-reward'\n\nexport interface OracleAssertionResult {\n /** Test identifier the suite reported, verbatim. */\n readonly id: string\n readonly passed: boolean\n}\n\nexport interface OracleReplicate {\n /** 0-based index within its group. */\n readonly index: number\n /**\n * Raw reward the task's grader wrote, verbatim. `null` when it wrote none —\n * a missing reward and a zero reward are different failures, and neither is\n * folded into the other.\n */\n readonly reward: string | null\n readonly passed: boolean\n readonly wallMs: number\n /** Per-assertion verdicts the suite reported, or `null` when it reported\n * none. Never an empty array standing in for \"the suite said nothing\". */\n readonly assertions: readonly OracleAssertionResult[] | null\n}\n\nexport interface OracleReplicateGroup {\n readonly state: OracleStateLabel\n readonly load: OracleLoad\n /**\n * Replicates that graded one container with nothing written between them.\n * Two or more, because a single grading measures no flip.\n */\n readonly replicates: readonly OracleReplicate[]\n}\n\nexport interface OracleDeterminismEvidence {\n readonly taskName: string\n /** Image the replicates ran on, by registry manifest digest. An image with no\n * published digest, such as one loaded from an archive, records its tag; the\n * absent `@sha256:` is what says so. */\n readonly image: string\n /**\n * Digest of the suite bytes every replicate graded against, in whatever\n * scheme the measuring tool uses. Provenance only: it identifies the suite a\n * certification is about and is never compared against a digest produced by\n * a different scheme.\n */\n readonly suiteDigest: string\n readonly groups: readonly OracleReplicateGroup[]\n readonly measuredAt: string\n}\n\n/** One thing that did not agree with itself across replicates of a state. */\nexport interface OracleFlippedUnit {\n /** An assertion id, or `suite-reward` when the suite reported no assertions. */\n readonly unit: string\n readonly passes: number\n readonly fails: number\n readonly flipRate: number\n}\n\nexport interface OracleStateVerdict {\n readonly state: OracleStateLabel\n readonly replicates: number\n /** Replicates whose whole-suite reward passed. */\n readonly passes: number\n readonly fails: number\n /** What the flip rate was counted over. `reward` is the coarser reading. */\n readonly granularity: 'per-assertion' | 'reward'\n /** Largest minority share over the counted units. */\n readonly flipRate: number\n readonly flipped: readonly OracleFlippedUnit[]\n /** Assertion ids some replicates reported and others did not. The suite's\n * own shape moved, which is a flip in itself. */\n readonly assertionSetUnstable: readonly string[]\n /** Loads whose whole-suite pass rate on this state differed. */\n readonly loadSensitive: boolean\n /** Every distinct raw reward the grader wrote, sorted. */\n readonly rewardsObserved: readonly string[]\n}\n\nexport interface OracleDeterminismVerdict {\n readonly taskName: string\n readonly image: string\n readonly suiteDigest: string\n /** True only when every counted unit agreed with itself on every state. */\n readonly stable: boolean\n readonly replicates: number\n /** Largest per-unit minority share over every state. Zero on a stable task. */\n readonly flipRate: number\n readonly byState: readonly OracleStateVerdict[]\n readonly measuredAt: string\n /** One line naming what was measured, for an artifact a human reads. */\n readonly detail: string\n}\n\n/** Replicates one group needs before a flip is measurable at all. */\nconst MIN_ORACLE_REPLICATES = 2\n\n/**\n * Reduce measured replicates to a verdict.\n *\n * Pure: it opens no container. The tool that runs the replicates hands the\n * counts here, so the rule that decides stability is one rule and a reviewer\n * can re-derive any verdict from the recorded replicates.\n */\nexport function oracleDeterminism(evidence: OracleDeterminismEvidence): OracleDeterminismVerdict {\n if (evidence.groups.length === 0) {\n throw new ValidationError(\n `oracle determinism for ${evidence.taskName} received no replicate group`,\n )\n }\n for (const group of evidence.groups) {\n if (group.replicates.length < MIN_ORACLE_REPLICATES) {\n throw new ValidationError(\n `oracle determinism for ${evidence.taskName} received ${group.replicates.length} ` +\n `${group.load} replicate(s) on the ${group.state} state; ${MIN_ORACLE_REPLICATES} are ` +\n 'needed before a flip can be observed',\n )\n }\n }\n\n const byState: OracleStateVerdict[] = []\n for (const state of ['unsolved', 'solved'] as const) {\n const groups = evidence.groups.filter((group) => group.state === state)\n if (groups.length === 0) continue\n byState.push(stateVerdict(state, groups))\n }\n\n const flipRate = byState.reduce((worst, state) => Math.max(worst, state.flipRate), 0)\n const replicates = byState.reduce((total, state) => total + state.replicates, 0)\n return {\n taskName: evidence.taskName,\n image: evidence.image,\n suiteDigest: evidence.suiteDigest,\n stable: flipRate === 0,\n replicates,\n flipRate,\n byState,\n measuredAt: evidence.measuredAt,\n detail: byState.map(describeState).join('; '),\n }\n}\n\nfunction stateVerdict(\n state: OracleStateLabel,\n groups: readonly OracleReplicateGroup[],\n): OracleStateVerdict {\n const replicates = groups.flatMap((group) => [...group.replicates])\n const passes = replicates.filter((replicate) => replicate.passed).length\n const rates = groups.map(\n (group) => group.replicates.filter((r) => r.passed).length / group.replicates.length,\n )\n\n // Per-assertion counting needs every replicate to have reported assertions.\n // One replicate that did not makes the finer reading unavailable for this\n // state, and the coarser one is recorded as coarser rather than substituted.\n const perAssertion = replicates.every((replicate) => replicate.assertions !== null)\n const flipped: OracleFlippedUnit[] = []\n const assertionSetUnstable: string[] = []\n\n if (perAssertion) {\n const outcomes = new Map<string, boolean[]>()\n for (const replicate of replicates) {\n for (const assertion of replicate.assertions ?? []) {\n const seen = outcomes.get(assertion.id)\n if (seen) seen.push(assertion.passed)\n else outcomes.set(assertion.id, [assertion.passed])\n }\n }\n for (const [id, results] of [...outcomes].sort(([a], [b]) => a.localeCompare(b))) {\n if (results.length !== replicates.length) assertionSetUnstable.push(id)\n const unitPasses = results.filter(Boolean).length\n const unitFails = results.length - unitPasses\n const minority = Math.min(unitPasses, unitFails)\n // A unit missing from some replicates is a flip of the suite's shape, and\n // the replicates that did not report it count against it.\n const absent = replicates.length - results.length\n if (minority + absent > 0) {\n flipped.push({\n unit: id,\n passes: unitPasses,\n fails: unitFails + absent,\n flipRate: (minority + absent) / replicates.length,\n })\n }\n }\n } else {\n const minority = Math.min(passes, replicates.length - passes)\n if (minority > 0) {\n flipped.push({\n unit: SUITE_REWARD_UNIT,\n passes,\n fails: replicates.length - passes,\n flipRate: minority / replicates.length,\n })\n }\n }\n\n return {\n state,\n replicates: replicates.length,\n passes,\n fails: replicates.length - passes,\n granularity: perAssertion ? 'per-assertion' : 'reward',\n flipRate: flipped.reduce((worst, unit) => Math.max(worst, unit.flipRate), 0),\n flipped,\n assertionSetUnstable,\n loadSensitive: new Set(rates).size > 1,\n rewardsObserved: [...new Set(replicates.map((r) => r.reward ?? 'NO_REWARD_FILE'))].sort(),\n }\n}\n\nfunction describeState(state: OracleStateVerdict): string {\n const base =\n `${state.state}: ${state.passes}/${state.replicates} suite pass, ` +\n `${state.granularity} counting`\n if (state.flipped.length === 0) return `${base}, no flip`\n const worst = state.flipped.reduce((a, b) => (b.flipRate > a.flipRate ? b : a))\n return (\n `${base}, ${state.flipped.length} unit(s) flipped, worst ${worst.unit} ` +\n `${worst.passes}/${worst.passes + worst.fails} pass` +\n (state.loadSensitive ? ' (load-sensitive)' : '')\n )\n}\n\n/**\n * Certified verdicts by task name.\n *\n * A task with no entry is uncertified, which is not the same as unstable: one\n * says the check has not run, the other says it ran and the task failed it.\n * Both stop a row, with different reasons.\n */\nexport type TaskOracleRegistry = ReadonlyMap<string, OracleDeterminismVerdict>\n\n/**\n * What a checked-in certification file holds.\n *\n * It stores the measured replicates, not the verdicts they imply. The verdict\n * is re-derived on read by the same rule a campaign enforces, so a file cannot\n * declare a task stable — only the replicates can, and a reviewer can recount\n * them.\n */\nexport interface TaskOracleRegistryDocument {\n readonly version: 1\n readonly measurements: readonly OracleDeterminismEvidence[]\n}\n\nexport function parseTaskOracleRegistry(document: unknown): TaskOracleRegistry {\n if (typeof document !== 'object' || document === null) {\n throw new ValidationError('task oracle registry must be an object')\n }\n const { version, measurements } = document as Partial<TaskOracleRegistryDocument>\n if (version !== 1) {\n throw new ValidationError(`task oracle registry version must be 1, got ${String(version)}`)\n }\n if (!Array.isArray(measurements)) {\n throw new ValidationError('task oracle registry needs a measurements array')\n }\n return taskOracleRegistry(measurements.map((evidence) => oracleDeterminism(evidence)))\n}\n\nexport function taskOracleRegistry(\n verdicts: readonly OracleDeterminismVerdict[],\n): TaskOracleRegistry {\n const registry = new Map<string, OracleDeterminismVerdict>()\n for (const verdict of verdicts) {\n if (registry.has(verdict.taskName)) {\n throw new ValidationError(\n `task oracle registry received ${verdict.taskName} twice; a task has one certification`,\n )\n }\n registry.set(verdict.taskName, verdict)\n }\n return registry\n}\n\n/** Throws unless the task graded the same bytes the same way every replicate. */\nexport function assertDeterministicOracle(verdict: OracleDeterminismVerdict): void {\n if (verdict.stable) return\n throw new NondeterministicOracleError(\n `task ${verdict.taskName} graded byte-identical state inconsistently: flip rate ` +\n `${(verdict.flipRate * 100).toFixed(1)} % over ${verdict.replicates} replicates ` +\n `(${verdict.detail}). Its verdict is not a function of the state, so it cannot carry ` +\n 'ground truth for an intervention study.',\n )\n}\n","/**\n * The held-out suite, injected from outside the box at grade time.\n *\n * A repair is only measurable if the thing that decides pass or fail is out\n * of the trajectory's reach. Terminal-Bench gets that by uploading the suite\n * into the container at grade time, after the agent has stopped; a suite the\n * agent planted is overwritten before it is ever read. `injectedTestOracle`\n * reproduces that property and then proves it per call:\n *\n * 1. purge the suite root, so a planted extra file cannot survive\n * 2. upload every suite file from outside the session\n * 3. read the bytes back from inside and hash them\n * 4. refuse to grade when the read-back digest is not the uploaded digest\n *\n * Step 4 is why the property is asserted rather than assumed. A container\n * that silently drops the upload, or a filesystem trick that serves different\n * bytes to the reader, raises `TestSuiteTamperedError` instead of returning a\n * result. An oracle that cannot prove what it graded reports nothing.\n */\n\nimport { createHash } from 'node:crypto'\nimport { CaptureIntegrityError, ValidationError } from '../errors'\nimport type {\n RepairExecResult,\n RepairSession,\n TestOracle,\n TestOracleContext,\n TestOracleOutcome,\n} from './ports'\n\n/** The suite the oracle read back is not the suite it uploaded. */\nexport class TestSuiteTamperedError extends CaptureIntegrityError {}\n\n/** The oracle could not place or run the suite, so it graded nothing. */\nexport class TestOracleError extends CaptureIntegrityError {}\n\nexport interface TestSuiteFile {\n /** Absolute path inside the container. */\n readonly path: string\n readonly contents: string\n /** Octal mode applied after upload, e.g. '0755' for a runner script. */\n readonly mode?: string\n}\n\nexport interface InjectedTestOracleOptions {\n /** Every file of the held-out suite. Uploaded on every grade call. */\n readonly files: readonly TestSuiteFile[]\n /** Command that runs the suite. Exit 0 is the only pass. */\n readonly command: string\n /** Absolute directories removed before upload. A planted file that the\n * upload does not overwrite dies here. */\n readonly purge?: readonly string[]\n readonly uploadTimeoutMs?: number\n readonly commandTimeoutMs?: number\n}\n\nconst DEFAULT_UPLOAD_TIMEOUT_MS = 60_000\nconst DEFAULT_COMMAND_TIMEOUT_MS = 900_000\n\n/**\n * Content digest of the suite: sha256 over each path and its bytes, in path\n * order. Two suites with the same digest are the same suite.\n */\nexport function testSuiteDigest(files: readonly TestSuiteFile[]): string {\n const hash = createHash('sha256')\n for (const file of [...files].sort((a, b) => a.path.localeCompare(b.path))) {\n hash.update(file.path)\n hash.update('\\0')\n hash.update(Buffer.from(file.contents, 'utf8'))\n hash.update('\\0')\n }\n return hash.digest('hex')\n}\n\nexport function injectedTestOracle(options: InjectedTestOracleOptions): TestOracle {\n assertOracleOptions(options)\n const uploadTimeoutMs = options.uploadTimeoutMs ?? DEFAULT_UPLOAD_TIMEOUT_MS\n const commandTimeoutMs = options.commandTimeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS\n const expectedDigest = testSuiteDigest(options.files)\n\n return {\n async grade(session: RepairSession, context: TestOracleContext): Promise<TestOracleOutcome> {\n const where = `${context.rowId}/${context.arm}#${context.rolloutIndex}`\n\n for (const directory of options.purge ?? []) {\n await mustSucceed(\n session,\n `rm -rf ${shellQuote(directory)}`,\n uploadTimeoutMs,\n `purge ${directory} in ${where}`,\n )\n }\n\n for (const file of options.files) {\n const directory = parentDirectory(file.path)\n if (directory) {\n await mustSucceed(\n session,\n `mkdir -p ${shellQuote(directory)}`,\n uploadTimeoutMs,\n `mkdir ${directory} in ${where}`,\n )\n }\n const payload = Buffer.from(file.contents, 'utf8').toString('base64')\n await mustSucceed(\n session,\n `printf %s ${shellQuote(payload)} | base64 -d > ${shellQuote(file.path)}`,\n uploadTimeoutMs,\n `upload ${file.path} in ${where}`,\n )\n if (file.mode) {\n await mustSucceed(\n session,\n `chmod ${file.mode} ${shellQuote(file.path)}`,\n uploadTimeoutMs,\n `chmod ${file.path} in ${where}`,\n )\n }\n }\n\n const readBack: TestSuiteFile[] = []\n for (const file of options.files) {\n const result = await mustSucceed(\n session,\n `base64 < ${shellQuote(file.path)} | tr -d '\\\\n'`,\n uploadTimeoutMs,\n `read back ${file.path} in ${where}`,\n )\n readBack.push({\n path: file.path,\n contents: Buffer.from(result.stdout.trim(), 'base64').toString('utf8'),\n })\n }\n const observedDigest = testSuiteDigest(readBack)\n if (observedDigest !== expectedDigest) {\n throw new TestSuiteTamperedError(\n `test suite in ${where} does not match the suite uploaded from outside ` +\n `(expected ${expectedDigest}, read back ${observedDigest}); the graded result is discarded`,\n )\n }\n\n const run = await session.exec(options.command, commandTimeoutMs)\n return {\n passed: run.exitCode === 0 && !run.timedOut,\n exitCode: run.exitCode,\n output: `${run.stdout}\\n${run.stderr}`.trim(),\n suiteDigest: observedDigest,\n timedOut: run.timedOut,\n }\n },\n }\n}\n\n/**\n * Run a setup command that must succeed. A failed upload is an oracle\n * failure, never a failed test: reporting it as a failing suite would turn a\n * broken container into evidence against the intervention.\n */\nasync function mustSucceed(\n session: RepairSession,\n command: string,\n timeoutMs: number,\n what: string,\n): Promise<RepairExecResult> {\n const result = await session.exec(command, timeoutMs)\n if (result.timedOut) {\n throw new TestOracleError(`test oracle timed out while it tried to ${what}`)\n }\n if (result.exitCode !== 0) {\n throw new TestOracleError(\n `test oracle failed to ${what}: exit ${result.exitCode}\\n${result.stderr.trim()}`,\n )\n }\n return result\n}\n\nfunction assertOracleOptions(options: InjectedTestOracleOptions): void {\n if (options.files.length === 0) {\n throw new ValidationError('injectedTestOracle requires at least one suite file')\n }\n const seen = new Set<string>()\n for (const file of options.files) {\n if (!file.path.startsWith('/')) {\n throw new ValidationError(`suite file path must be absolute, got \"${file.path}\"`)\n }\n if (seen.has(file.path)) {\n throw new ValidationError(`suite file ${file.path} is listed twice`)\n }\n seen.add(file.path)\n }\n if (options.command.trim().length === 0) {\n throw new ValidationError('injectedTestOracle requires a suite command')\n }\n for (const directory of options.purge ?? []) {\n if (!directory.startsWith('/') || directory.trim() === '/') {\n throw new ValidationError(\n `purge path must be an absolute directory below the root, got \"${directory}\"`,\n )\n }\n }\n}\n\nfunction parentDirectory(path: string): string | null {\n const index = path.lastIndexOf('/')\n if (index <= 0) return null\n return path.slice(0, index)\n}\n\nfunction shellQuote(value: string): string {\n return `'${value.replaceAll(\"'\", `'\\\\''`)}'`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,kBAAkB;;AAG/B,MAAa,2BAA2B;;AAGxC,MAAM,wBAAwB;AAE9B,MAAa,0BAA0B;;;;;;;;;;;;;;;;;AA4BvC,SAAgB,sBAAsB,OAAqC;CACzE,OAAO,4BAA4B,MAAM,KAAK;;;;;;;;;;;;;uFAauC,gBAAgB;;;;;;;;;;;EAWrG,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsD1B;AAMA,MAAM,aAAa;;;;;;AAOnB,SAAgB,YAAY,kBAAwC;CAClE,MAAM,SAAS,CAAC,GAAG,iBAAiB,SAAS,UAAU,CAAC,CAAC,CAAC,KAAK,UAAU,MAAM,MAAM,EAAE;CACvF,IAAI,OAAO,WAAW,GAAG,OAAO;EAAE,MAAM;EAAgB,aAAa,OAAO;CAAO;CACnF,OAAO;EAAE,MAAM;EAAU,UAAU,OAAO,MAAM,GAAA,CAAI,KAAK;CAAE;AAC7D;;;;;;AAcA,SAAgB,kBAAkB,QAA+B;CAC/D,MAAM,OAAO,OAAO,gBAAgB,cAAc,OAAO,cAAc,kBAAkB;CACzF,MAAM,aAAa,eAAe,OAAO,WAAW;CACpD,IAAI,OAAO,OAAO,SAAA,KAChB,OAAO,GAAG,OAAO,WAAW,YAAY,OAAO,OAA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