@tangle-network/agent-eval 0.172.0 → 0.173.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +49 -0
- package/README.md +17 -2
- package/dist/adapters/http.d.ts +2 -2
- package/dist/analyst/index.d.ts +13 -13
- package/dist/analyst/index.js +7 -6
- package/dist/analyst/index.js.map +1 -1
- package/dist/{attestation-CJBGmMVh.d.ts → attestation-c1QvaBdX.d.ts} +2 -2
- package/dist/{attestation-CJBGmMVh.d.ts.map → attestation-c1QvaBdX.d.ts.map} +1 -1
- package/dist/{backend-integrity-e79K3UPD.d.ts → backend-integrity-CeuTgqsd.d.ts} +3 -4
- package/dist/backend-integrity-CeuTgqsd.d.ts.map +1 -0
- package/dist/{benchmark-h-h4bfqj.d.ts → benchmark-BjLGkfnN.d.ts} +3 -3
- package/dist/{benchmark-h-h4bfqj.d.ts.map → benchmark-BjLGkfnN.d.ts.map} +1 -1
- package/dist/{benchmark-command-DoFcisuM.js → benchmark-command-9S20PRel.js} +9 -9
- package/dist/{benchmark-command-DoFcisuM.js.map → benchmark-command-9S20PRel.js.map} +1 -1
- package/dist/benchmarks/index.d.ts +5 -5
- package/dist/benchmarks/index.js +3 -3
- package/dist/{bounded-process-CVOC_D3H.js → bounded-process-BBZob7vl.js} +64 -10
- package/dist/bounded-process-BBZob7vl.js.map +1 -0
- 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 +6 -6
- package/dist/{campaign-Dp35pBbS.js → campaign-pxS0wmo4.js} +8 -8
- package/dist/{campaign-Dp35pBbS.js.map → campaign-pxS0wmo4.js.map} +1 -1
- package/dist/chat-client-Db4bqYfA.js +115 -0
- package/dist/chat-client-Db4bqYfA.js.map +1 -0
- package/dist/{chat-json-call-5Jxna-aV.js → chat-json-call-C26igCih.js} +16 -6
- package/dist/chat-json-call-C26igCih.js.map +1 -0
- package/dist/cli.js +31 -17
- package/dist/cli.js.map +1 -1
- package/dist/{client-BvwNkIRN.js → client-BlLY6o2w.js} +2 -2
- package/dist/{client-BvwNkIRN.js.map → client-BlLY6o2w.js.map} +1 -1
- package/dist/{client-Df7wdslk.d.ts → client-DlqdbM7n.d.ts} +4 -4
- package/dist/{client-Df7wdslk.d.ts.map → client-DlqdbM7n.d.ts.map} +1 -1
- package/dist/contract/index.d.ts +13 -13
- package/dist/contract/index.js +202 -10
- package/dist/contract/index.js.map +1 -1
- package/dist/{counterfactual-Bee5_BIn.d.ts → counterfactual-CLgrwhkY.d.ts} +4 -4
- package/dist/{counterfactual-Bee5_BIn.d.ts.map → counterfactual-CLgrwhkY.d.ts.map} +1 -1
- package/dist/{chat-client-DI79OPye.js → default-registry-B0bKikCb.js} +3 -39
- package/dist/default-registry-B0bKikCb.js.map +1 -0
- package/dist/{default-registry-XxedTLwu.d.ts → default-registry-BKwc8bN5.d.ts} +6 -6
- package/dist/{default-registry-XxedTLwu.d.ts.map → default-registry-BKwc8bN5.d.ts.map} +1 -1
- package/dist/{define-agent-eval-0wW7gFhr.d.ts → define-agent-eval-CY6qdlGV.d.ts} +6 -6
- package/dist/{define-agent-eval-0wW7gFhr.d.ts.map → define-agent-eval-CY6qdlGV.d.ts.map} +1 -1
- package/dist/{define-agent-eval-jS8xj_Q_.js → define-agent-eval-D_i_s69h.js} +7 -7
- package/dist/{define-agent-eval-jS8xj_Q_.js.map → define-agent-eval-D_i_s69h.js.map} +1 -1
- package/dist/{dspy-rlm-engine-CS3qcCEk.js → dspy-rlm-engine-D5byiHn9.js} +5 -6
- package/dist/dspy-rlm-engine-D5byiHn9.js.map +1 -0
- package/dist/{emitter-Bvnu0VzL.d.ts → emitter-Cs0egaFd.d.ts} +3 -3
- package/dist/{emitter-Bvnu0VzL.d.ts.map → emitter-Cs0egaFd.d.ts.map} +1 -1
- package/dist/{engine-BfRay1qD.d.ts → engine-DhFir3Ys.d.ts} +23 -8
- package/dist/{engine-BfRay1qD.d.ts.map → engine-DhFir3Ys.d.ts.map} +1 -1
- package/dist/{eval-campaign-JDTeE6Pl.js → eval-campaign-BeAjdhzC.js} +2 -2
- package/dist/{eval-campaign-JDTeE6Pl.js.map → eval-campaign-BeAjdhzC.js.map} +1 -1
- package/dist/{exact-types-BEecmnWm.d.ts → exact-types-BKOEILRP.d.ts} +2 -2
- package/dist/{exact-types-BEecmnWm.d.ts.map → exact-types-BKOEILRP.d.ts.map} +1 -1
- package/dist/experiment/index.d.ts +4 -4
- package/dist/{external-optimizer-contracts-szBJ_1vh.d.ts → external-optimizer-contracts-CQCpyrIL.d.ts} +2 -2
- package/dist/{external-optimizer-contracts-szBJ_1vh.d.ts.map → external-optimizer-contracts-CQCpyrIL.d.ts.map} +1 -1
- package/dist/{external-optimizer-process-CQxylYeG.js → external-optimizer-process-Cq_Pg15r.js} +2 -2
- package/dist/{external-optimizer-process-CQxylYeG.js.map → external-optimizer-process-Cq_Pg15r.js.map} +1 -1
- package/dist/{external-optimizer-subprocess-Cex8Da2i.js → external-optimizer-subprocess-DgNebftP.js} +2 -2
- package/dist/{external-optimizer-subprocess-Cex8Da2i.js.map → external-optimizer-subprocess-DgNebftP.js.map} +1 -1
- package/dist/failure-cluster-OldNRoAt.d.ts +154 -0
- package/dist/failure-cluster-OldNRoAt.d.ts.map +1 -0
- package/dist/{feedback-trajectory-DIqpCyF0.d.ts → feedback-trajectory-CMnv_uYs.d.ts} +6 -6
- package/dist/{feedback-trajectory-DIqpCyF0.d.ts.map → feedback-trajectory-CMnv_uYs.d.ts.map} +1 -1
- package/dist/{heldout-gate-JgNRDZwZ.d.ts → heldout-gate-Df5hsqmm.d.ts} +7 -7
- package/dist/{heldout-gate-JgNRDZwZ.d.ts.map → heldout-gate-Df5hsqmm.d.ts.map} +1 -1
- package/dist/hosted/index.d.ts +2 -2
- package/dist/hosted/index.js +1 -1
- package/dist/{index-DnglhM0A.d.ts → index-BQqOjerE.d.ts} +94 -13
- package/dist/index-BQqOjerE.d.ts.map +1 -0
- package/dist/{index-_vPrVMRX.d.ts → index-CFDffsKz.d.ts} +11 -11
- package/dist/{index-_vPrVMRX.d.ts.map → index-CFDffsKz.d.ts.map} +1 -1
- package/dist/{index-DDAPhUJJ.d.ts → index-D0Db5X-4.d.ts} +45 -9
- package/dist/index-D0Db5X-4.d.ts.map +1 -0
- package/dist/{index-DMoxLG8P.d.ts → index-e7LXeRVa.d.ts} +3 -3
- package/dist/{index-DMoxLG8P.d.ts.map → index-e7LXeRVa.d.ts.map} +1 -1
- package/dist/index.d.ts +172 -46
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +64 -41
- package/dist/index.js.map +1 -1
- package/dist/{insight-report-08F022xN.d.ts → insight-report-DETqPc_A.d.ts} +4 -4
- package/dist/{insight-report-08F022xN.d.ts.map → insight-report-DETqPc_A.d.ts.map} +1 -1
- package/dist/{integrity-B_EDELom.d.ts → integrity-BKTcA-HP.d.ts} +3 -3
- package/dist/{integrity-B_EDELom.d.ts.map → integrity-BKTcA-HP.d.ts.map} +1 -1
- package/dist/{kind-factory-DMeEoMQZ.js → kind-factory-gP6lDySe.js} +164 -149
- package/dist/kind-factory-gP6lDySe.js.map +1 -0
- package/dist/{llm-client-BFMRpmqb.js → llm-client-CxQtdtd6.js} +12 -5
- package/dist/llm-client-CxQtdtd6.js.map +1 -0
- package/dist/{llm-judge-aQHIk5_-.js → llm-judge-B2YxbAJb.js} +81 -7
- package/dist/{llm-judge-aQHIk5_-.js.map → llm-judge-B2YxbAJb.js.map} +1 -1
- package/dist/{matrix-Ch8JO1pG.d.ts → matrix-DGu8KhSs.d.ts} +2 -2
- package/dist/{matrix-Ch8JO1pG.d.ts.map → matrix-DGu8KhSs.d.ts.map} +1 -1
- package/dist/meta-eval/index.d.ts +100 -5
- package/dist/meta-eval/index.d.ts.map +1 -1
- package/dist/meta-eval/index.js +200 -2
- package/dist/meta-eval/index.js.map +1 -1
- package/dist/{mint-DjfDUMHr.js → mint-vWOdD8Ae.js} +2 -2
- package/dist/{mint-DjfDUMHr.js.map → mint-vWOdD8Ae.js.map} +1 -1
- package/dist/multishot/golden/index.d.ts +1 -1
- package/dist/multishot/index.d.ts +2 -2
- package/dist/openapi.json +1 -1
- package/dist/pipelines/index.d.ts +5 -5
- package/dist/pipelines/index.js +3 -3
- package/dist/{pre-registration-DHz6P_6f.d.ts → pre-registration-BoI4ucR3.d.ts} +2 -2
- package/dist/{pre-registration-DHz6P_6f.d.ts.map → pre-registration-BoI4ucR3.d.ts.map} +1 -1
- package/dist/{produced-state-CxmbFxFd.js → produced-state-7VYDwtkk.js} +3 -3
- package/dist/{produced-state-CxmbFxFd.js.map → produced-state-7VYDwtkk.js.map} +1 -1
- package/dist/{promotion-policy-BBBcz5_3.d.ts → promotion-policy-CvMda3kU.d.ts} +2 -2
- package/dist/{promotion-policy-BBBcz5_3.d.ts.map → promotion-policy-CvMda3kU.d.ts.map} +1 -1
- package/dist/{provenance-Dp-vvyrU.d.ts → provenance-CRY67X50.d.ts} +39 -165
- package/dist/provenance-CRY67X50.d.ts.map +1 -0
- package/dist/{query-BPGMVlbM.js → query-D1nLIKt7.js} +2 -2
- package/dist/{query-BPGMVlbM.js.map → query-D1nLIKt7.js.map} +1 -1
- package/dist/{query-Na5gEIGd.d.ts → query-D6W6MaGx.d.ts} +3 -3
- package/dist/{query-Na5gEIGd.d.ts.map → query-D6W6MaGx.d.ts.map} +1 -1
- package/dist/{registry-xEb_xfns.d.ts → registry-7pOUBrtX.d.ts} +4 -4
- package/dist/{registry-xEb_xfns.d.ts.map → registry-7pOUBrtX.d.ts.map} +1 -1
- package/dist/{release-confidence-D6lQw_o7.d.ts → release-confidence-BAcNYOf1.d.ts} +4 -4
- package/dist/{release-confidence-D6lQw_o7.d.ts.map → release-confidence-BAcNYOf1.d.ts.map} +1 -1
- package/dist/{release-confidence-CzUHc4z4.js → release-confidence-BsGEg_xg.js} +3 -3
- package/dist/{release-confidence-CzUHc4z4.js.map → release-confidence-BsGEg_xg.js.map} +1 -1
- package/dist/reporting.d.ts +3 -3
- package/dist/reporting.js +1 -1
- package/dist/{researcher-CMUTQXD7.d.ts → researcher-jsW1X94L.d.ts} +7 -8
- package/dist/researcher-jsW1X94L.d.ts.map +1 -0
- package/dist/{reward-hacking-SkxYgT0x.js → reward-hacking-CKW4teig.js} +2 -2
- package/dist/{reward-hacking-SkxYgT0x.js.map → reward-hacking-CKW4teig.js.map} +1 -1
- package/dist/{reward-hacking-CgPRUesA.d.ts → reward-hacking-ZXEi9VCq.d.ts} +2 -2
- package/dist/{reward-hacking-CgPRUesA.d.ts.map → reward-hacking-ZXEi9VCq.d.ts.map} +1 -1
- package/dist/rl.d.ts +7 -7
- package/dist/rl.js +4 -4
- package/dist/rollout/index.d.ts +1 -1
- package/dist/rollout/index.js +2 -2
- package/dist/{rollout-Crypdx8s.js → rollout-C-znbbYg.js} +2 -2
- package/dist/{rollout-Crypdx8s.js.map → rollout-C-znbbYg.js.map} +1 -1
- package/dist/{rubric-predictive-validity-DluJLCKQ.d.ts → rubric-predictive-validity-Dl1dvKCv.d.ts} +2 -2
- package/dist/{rubric-predictive-validity-DluJLCKQ.d.ts.map → rubric-predictive-validity-Dl1dvKCv.d.ts.map} +1 -1
- package/dist/{run-record-DQjRcYwA.d.ts → run-record-DTv1MdjK.d.ts} +2 -2
- package/dist/{run-record-DQjRcYwA.d.ts.map → run-record-DTv1MdjK.d.ts.map} +1 -1
- package/dist/{run-record-DLORoL7t.js → run-record-ZIsR9Fif.js} +2 -2
- package/dist/{run-record-DLORoL7t.js.map → run-record-ZIsR9Fif.js.map} +1 -1
- package/dist/{schema-DID1Cqct.d.ts → schema-CR5cpjQ3.d.ts} +57 -2
- package/dist/{schema-DID1Cqct.d.ts.map → schema-CR5cpjQ3.d.ts.map} +1 -1
- package/dist/{schema-CdIX2aHu.js → schema-CSf6qWgZ.js} +35 -1
- package/dist/{schema-CdIX2aHu.js.map → schema-CSf6qWgZ.js.map} +1 -1
- package/dist/semantic-concept-judge-Ct3QU7t5.js +780 -0
- package/dist/semantic-concept-judge-Ct3QU7t5.js.map +1 -0
- package/dist/{series-convergence-D9WgpXGi.d.ts → series-convergence-DeG33RpC.d.ts} +2 -2
- package/dist/{series-convergence-D9WgpXGi.d.ts.map → series-convergence-DeG33RpC.d.ts.map} +1 -1
- package/dist/{server-CCEnywOR.js → server-BR6onwZB.js} +2 -2
- package/dist/{server-CCEnywOR.js.map → server-BR6onwZB.js.map} +1 -1
- package/dist/{skillopt-optimization-method-LHi02MzH.js → skillopt-optimization-method-BzdphODy.js} +6 -6
- package/dist/{skillopt-optimization-method-LHi02MzH.js.map → skillopt-optimization-method-BzdphODy.js.map} +1 -1
- package/dist/{statistical-heldout-Yldkntvy.d.ts → statistical-heldout-DTyB_6-1.d.ts} +3 -3
- package/dist/{statistical-heldout-Yldkntvy.d.ts.map → statistical-heldout-DTyB_6-1.d.ts.map} +1 -1
- package/dist/{store-Cq9oOrI1.d.ts → store-BErPvYBr.d.ts} +2 -2
- package/dist/{store-Cq9oOrI1.d.ts.map → store-BErPvYBr.d.ts.map} +1 -1
- package/dist/{store-otlp-CHjBvWQY.js → store-otlp-Dow0pk_5.js} +2 -2
- package/dist/{store-otlp-CHjBvWQY.js.map → store-otlp-Dow0pk_5.js.map} +1 -1
- package/dist/{store-tool-spans-BvdUbeOB.d.ts → store-tool-spans-CCZNsihA.d.ts} +8 -8
- package/dist/{store-tool-spans-BvdUbeOB.d.ts.map → store-tool-spans-CCZNsihA.d.ts.map} +1 -1
- package/dist/{store-tool-spans-B9o6tU8f.js → store-tool-spans-CeNj_m2L.js} +3 -3
- package/dist/{store-tool-spans-B9o6tU8f.js.map → store-tool-spans-CeNj_m2L.js.map} +1 -1
- package/dist/storyboard/index.d.ts +1 -1
- package/dist/{summary-report-DRstQNBX.d.ts → summary-report-gMrbYawB.d.ts} +3 -3
- package/dist/{summary-report-DRstQNBX.d.ts.map → summary-report-gMrbYawB.d.ts.map} +1 -1
- package/dist/{task-failure-attributes-CBGtLS_H.js → task-failure-attributes-CZjZeBsY.js} +3 -3
- package/dist/{task-failure-attributes-CBGtLS_H.js.map → task-failure-attributes-CZjZeBsY.js.map} +1 -1
- package/dist/{tool-groups-DjwlMBvW.d.ts → tool-groups-Cp4Xdzrp.d.ts} +3 -3
- package/dist/tool-groups-Cp4Xdzrp.d.ts.map +1 -0
- package/dist/{tool-waste-CwGHzBzX.js → tool-waste-B9tdWV6g.js} +253 -6
- package/dist/tool-waste-B9tdWV6g.js.map +1 -0
- package/dist/{tool-waste-BrmLKxMw.d.ts → tool-waste-D23I0zWm.d.ts} +4 -4
- package/dist/{tool-waste-BrmLKxMw.d.ts.map → tool-waste-D23I0zWm.d.ts.map} +1 -1
- package/dist/trace-repair/index.d.ts +2 -2
- package/dist/traces.d.ts +10 -10
- package/dist/traces.js +7 -7
- package/dist/{trajectory-r1bQqvBQ.d.ts → trajectory-D7qrNvaN.d.ts} +3 -3
- package/dist/{trajectory-r1bQqvBQ.d.ts.map → trajectory-D7qrNvaN.d.ts.map} +1 -1
- package/dist/trajectory-replay/index.d.ts +3 -3
- package/dist/{types-CCZ34qmV.d.ts → types-BDV4PiMR.d.ts} +3 -3
- package/dist/{types-CCZ34qmV.d.ts.map → types-BDV4PiMR.d.ts.map} +1 -1
- package/dist/{types-nokrtr7M.d.ts → types-Ba5UQyVD.d.ts} +4 -4
- package/dist/{types-nokrtr7M.d.ts.map → types-Ba5UQyVD.d.ts.map} +1 -1
- package/dist/{types-DMoNFDWi.d.ts → types-DN2WdT5S.d.ts} +3 -3
- package/dist/{types-DMoNFDWi.d.ts.map → types-DN2WdT5S.d.ts.map} +1 -1
- package/dist/types-gvRsyJLh.d.ts +831 -0
- package/dist/types-gvRsyJLh.d.ts.map +1 -0
- package/dist/wire/index.d.ts +3 -3
- package/dist/wire/index.js +1 -1
- package/docs/plants.md +69 -1
- package/docs/public-api.md +6 -4
- package/docs/trace-analysis.md +55 -8
- package/package.json +1 -1
- package/dist/backend-integrity-e79K3UPD.d.ts.map +0 -1
- package/dist/bounded-process-CVOC_D3H.js.map +0 -1
- package/dist/chat-client-DI79OPye.js.map +0 -1
- package/dist/chat-json-call-5Jxna-aV.js.map +0 -1
- package/dist/dspy-rlm-engine-CS3qcCEk.js.map +0 -1
- package/dist/failure-cluster-6YSvsKlp.d.ts +0 -58
- package/dist/failure-cluster-6YSvsKlp.d.ts.map +0 -1
- package/dist/index-DDAPhUJJ.d.ts.map +0 -1
- package/dist/index-DnglhM0A.d.ts.map +0 -1
- package/dist/kind-factory-DMeEoMQZ.js.map +0 -1
- package/dist/llm-client-BFMRpmqb.js.map +0 -1
- package/dist/provenance-Dp-vvyrU.d.ts.map +0 -1
- package/dist/raw-provider-sink-BU29Sh8h.d.ts +0 -134
- package/dist/raw-provider-sink-BU29Sh8h.d.ts.map +0 -1
- package/dist/researcher-CMUTQXD7.d.ts.map +0 -1
- package/dist/semantic-concept-judge-I36eejJx.js +0 -382
- package/dist/semantic-concept-judge-I36eejJx.js.map +0 -1
- package/dist/tool-groups-DjwlMBvW.d.ts.map +0 -1
- package/dist/tool-waste-CwGHzBzX.js.map +0 -1
- package/dist/types-Bfk0uxRj.d.ts +0 -443
- package/dist/types-Bfk0uxRj.d.ts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rollout-Crypdx8s.js","names":[],"sources":["../src/rollout/interchange/harbor.ts"],"sourcesContent":["/**\n * Harbor ATIF-v1.7 interchange — `tangle.rollout.v1` ⇄ Agent Trajectory\n * Interchange Format.\n *\n * ATIF is the portability format (spec:\n * https://www.harborframework.com/docs/agents/trajectory-format, normative\n * RFC: harbor-framework/harbor `rfcs/0001-trajectory-format.md`). It sits\n * BELOW the waist of the rollout hourglass in both directions — export reads\n * `RolloutLine[]`, import writes `RolloutLine[]` — and it is never a source\n * of training labels:\n *\n * ATIF models NO reward, NO judge verdict, NO task/split coordinates.\n *\n * Consequences, both deliberate:\n * - EXPORT drops `outcome.reward`, `outcome.reward_source` and\n * `outcome.verdict` entirely. They are not smuggled into `extra`: a\n * third-party reading our ATIF file must not be able to mistake an\n * agent-eval judge score for something ATIF sanctioned.\n * - IMPORT therefore mints UNLABELED lines: `reward: null` (the existing\n * \"null reward is a labeled gap, never 0\" semantics), `verdict: null`,\n * and a `provenance.gap` naming the missing label. An imported\n * trajectory is not a training example until a judge scores it.\n *\n * Everything else we own that ATIF has no field for travels in a namespaced\n * escrow at `extra.tangle.*`, so our own round-trip is exact while a foreign\n * reader can ignore it. Fields that neither ATIF nor the escrow can carry\n * come back explicitly null / fail-closed, never invented.\n *\n * THE ESCROW IS NAMESPACED, NOT AUTHENTICATED. Anyone can write\n * `extra.tangle.*` into a file. So the escrow may restore what a value IS, but\n * never what a line is ALLOWED to do: `task.split` is forced to `holdout` on\n * every import regardless of what the document claims, and promoting an\n * imported trajectory to a trainable split is an explicit, greppable act\n * (`relabelImportedSplit`) rather than a property of the file. The document\n * keeps its claim — the claim just is not authority.\n *\n * Multi-agent shape differs on purpose. ATIF EMBEDS children in\n * `subagent_trajectories`; we keep a flat ledger with a normalized\n * `parent_rollout_id` edge. Export assembles the tree, import flattens it.\n * `session_id` is RUN-scoped in ATIF, so it carries `run_id` — the coordinate\n * that is shared by every invocation of one run — not `rollout_id`, which\n * identifies a single invocation and would split one run across session ids.\n *\n * ROUND-TRIPPING IS IDEMPOTENT: `import(export(import(export(x))))` is\n * byte-identical to `import(export(x))`. Import composes `provenance.gap` as a\n * de-duplicated ordered set rather than appending, and it emits every\n * `ChatMessage` with keys in the canonical schema order (role, content,\n * reasoning_content, tool_calls, tool_call_id, name, is_copied_context), so a\n * ledger hashed on serialized bytes sees no diff across further passes. The\n * FIRST import may re-order a producer's keys — that is the canonicalization.\n *\n * NOT building a Letta converter. Letta's trajectory-v1 is a strict subset of\n * what we need from ATIF here — no per-step or aggregate cost, no\n * multi-agent/subagent structure, no token-id or logprob channel — so a Letta\n * sink would carry less than this one and add a second format to keep\n * correct. Decision recorded in docs/rollout.md; do not re-litigate without a\n * concrete consumer that reads Letta and cannot read ATIF.\n */\n\nimport {\n assertRolloutLine,\n type ChatMessage,\n type ChatRole,\n type ChatToolCall,\n type GatedEvidence,\n ROLLOUT_CAPTURES,\n ROLLOUT_ROLES,\n ROLLOUT_SCHEMA,\n ROLLOUT_SPLITS,\n type RolloutArtifacts,\n type RolloutCapture,\n type RolloutCostBlock,\n type RolloutLine,\n type RolloutPolicy,\n type RolloutRole,\n type RolloutSplit,\n type RolloutStep,\n type RolloutTask,\n type ToolDef,\n} from '../schema'\n\nexport const ATIF_SCHEMA_VERSION = 'ATIF-v1.7'\n\n/** Gap note on every imported line — ATIF carries no verdict, so nothing is scored. */\nexport const HARBOR_IMPORT_GAP = 'imported from Harbor ATIF; no verdict'\n\n/** Namespaced escrow key for everything ATIF does not model but we must not lose. */\nconst ESCROW = 'tangle'\n\n/**\n * Marks a step we synthesized purely to hold tool results that answered no\n * assistant turn IN THIS DOCUMENT. ATIF has no `tool` source, so such results\n * need a carrier step; the marker lets import drop the carrier instead of\n * inventing a turn.\n *\n * A carrier's results carry NO `source_call_id`. RFC 0001 rule 2 requires every\n * `source_call_id` to match a `tool_call_id` in the same step's `tool_calls`,\n * and a carrier declares no calls (a `system` step cannot legally make one), so\n * emitting the id there would produce an invalid document. The id is escrowed\n * instead and restored verbatim on import — the link survives without the\n * document lying about who made the call.\n */\nconst TOOL_RESULTS_ONLY = 'tool-results-only'\n\n// ---------------------------------------------------------------------------\n// ATIF-v1.7 wire types (RFC 0001). Optional fields are optional here too.\n// ---------------------------------------------------------------------------\n\nexport type HarborStepSource = 'system' | 'user' | 'agent'\n\nexport interface HarborImageSource {\n media_type: string\n path: string\n}\n\nexport interface HarborContentPart {\n type: 'text' | 'image'\n text?: string\n source?: HarborImageSource\n}\n\nexport interface HarborToolCall {\n tool_call_id: string\n function_name: string\n /** ATIF requires a decoded JSON object here, unlike our raw argument string. */\n arguments: Record<string, unknown>\n extra?: Record<string, unknown>\n}\n\nexport interface HarborSubagentTrajectoryRef {\n trajectory_id?: string\n trajectory_path?: string\n /** Informational only since v1.7 — never a resolution key. */\n session_id?: string\n extra?: Record<string, unknown>\n}\n\nexport interface HarborObservationResult {\n source_call_id?: string\n content?: string | HarborContentPart[]\n subagent_trajectory_ref?: HarborSubagentTrajectoryRef[]\n extra?: Record<string, unknown>\n}\n\nexport interface HarborObservation {\n results: HarborObservationResult[]\n}\n\nexport interface HarborMetrics {\n prompt_tokens?: number\n completion_tokens?: number\n cached_tokens?: number\n cost_usd?: number\n prompt_token_ids?: number[]\n completion_token_ids?: number[]\n logprobs?: number[]\n extra?: Record<string, unknown>\n}\n\nexport interface HarborStep {\n /** Ordinal, sequential from 1. */\n step_id: number\n timestamp?: string\n source: HarborStepSource\n model_name?: string\n reasoning_effort?: string | number\n message: string | HarborContentPart[]\n reasoning_content?: string\n tool_calls?: HarborToolCall[]\n observation?: HarborObservation\n metrics?: HarborMetrics\n llm_call_count?: number\n is_copied_context?: boolean\n extra?: Record<string, unknown>\n}\n\nexport interface HarborAgent {\n name: string\n version: string\n model_name?: string\n /** OpenAI function-calling schema — byte-identical to our `ToolDef`. */\n tool_definitions?: ToolDef[]\n extra?: Record<string, unknown>\n}\n\nexport interface HarborFinalMetrics {\n total_prompt_tokens?: number\n total_completion_tokens?: number\n total_cached_tokens?: number\n total_cost_usd?: number\n total_steps?: number\n extra?: Record<string, unknown>\n}\n\nexport interface HarborTrajectory {\n schema_version: string\n session_id?: string\n /** Required on embedded subagents; we always set it so lines stay joinable. */\n trajectory_id?: string\n agent: HarborAgent\n steps: HarborStep[]\n notes?: string\n final_metrics?: HarborFinalMetrics\n continued_trajectory_ref?: string\n subagent_trajectories?: HarborTrajectory[]\n extra?: Record<string, unknown>\n}\n\n// ---------------------------------------------------------------------------\n// Shared helpers\n// ---------------------------------------------------------------------------\n\nconst isRecord = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v)\n\nconst asString = (v: unknown): string | undefined => (typeof v === 'string' ? v : undefined)\n\nconst asNumberOrNull = (v: unknown): number | null =>\n typeof v === 'number' && Number.isFinite(v) ? v : null\n\nconst asIntegerOrUndefined = (v: unknown): number | undefined =>\n Number.isInteger(v) ? (v as number) : undefined\n\nconst asNumberArray = (v: unknown): number[] | undefined =>\n Array.isArray(v) && v.every((n) => typeof n === 'number' && Number.isFinite(n))\n ? (v as number[])\n : undefined\n\nconst asIntegerArray = (v: unknown): number[] | undefined =>\n Array.isArray(v) && v.every((n) => Number.isInteger(n)) ? (v as number[]) : undefined\n\n/**\n * Builds a `ChatMessage` with keys in the schema's declaration order.\n *\n * Object key order is insertion order in JS, so a message assembled\n * conditionally field-by-field serializes differently depending on which\n * optional fields were present — which makes a byte-hashed ledger see a diff\n * across an import that changed nothing. One builder, one order, stable bytes.\n */\nfunction canonicalChatMessage(parts: {\n role: ChatRole\n content: string | null\n reasoning_content?: string\n tool_calls?: ChatToolCall[]\n tool_call_id?: string\n name?: string\n is_copied_context?: boolean\n}): ChatMessage {\n const message: ChatMessage = { role: parts.role, content: parts.content }\n if (parts.reasoning_content !== undefined) message.reasoning_content = parts.reasoning_content\n if (parts.tool_calls !== undefined) message.tool_calls = parts.tool_calls\n if (parts.tool_call_id !== undefined) message.tool_call_id = parts.tool_call_id\n if (parts.name !== undefined) message.name = parts.name\n if (parts.is_copied_context === true) message.is_copied_context = true\n return message\n}\n\n/** Reads the `extra.tangle` escrow, tolerating a foreign file that has none. */\nfunction escrowOf(extra: Record<string, unknown> | undefined): Record<string, unknown> | undefined {\n if (!isRecord(extra)) return undefined\n const value = extra[ESCROW]\n return isRecord(value) ? value : undefined\n}\n\nfunction escrowSection(\n escrow: Record<string, unknown> | undefined,\n key: string,\n): Record<string, unknown> | undefined {\n if (escrow === undefined) return undefined\n const value = escrow[key]\n return isRecord(value) ? value : undefined\n}\n\n// ---------------------------------------------------------------------------\n// Export: RolloutLine[] → ATIF trajectory tree\n// ---------------------------------------------------------------------------\n\nfunction toHarborToolCall(call: ChatToolCall): HarborToolCall {\n // ATIF requires `arguments` to be a JSON object; ours is the raw\n // JSON-encoded string the model emitted, and models really do emit\n // malformed ones. Keep the exact bytes in `extra` so import restores the\n // string verbatim instead of re-serializing a normalized parse.\n let parsed: Record<string, unknown> | undefined\n try {\n const decoded: unknown = JSON.parse(call.function.arguments)\n if (isRecord(decoded)) parsed = decoded\n } catch {\n parsed = undefined\n }\n return {\n tool_call_id: call.id,\n function_name: call.function.name,\n arguments: parsed ?? {},\n extra: { [ESCROW]: { arguments_raw: call.function.arguments } },\n }\n}\n\n/**\n * `linked` = this result is attached to the step that actually declared the\n * call, so `source_call_id` is legal (RFC 0001 rule 2). When it is not, the id\n * goes to escrow instead of onto the wire.\n */\nfunction toObservationResult(message: ChatMessage, linked: boolean): HarborObservationResult {\n const result: HarborObservationResult = {}\n if (linked && message.tool_call_id !== undefined) result.source_call_id = message.tool_call_id\n if (message.content !== null) result.content = message.content\n const escrow: Record<string, unknown> = {}\n if (!linked && message.tool_call_id !== undefined) escrow.source_call_id = message.tool_call_id\n if (message.name !== undefined) escrow.name = message.name\n // `content: null` on a tool turn is meaningful (a tool that returned\n // nothing) and is not the same as the empty string ATIF would round-trip it to.\n if (message.content === null) escrow.content_null = true\n if (message.reasoning_content !== undefined) escrow.reasoning_content = message.reasoning_content\n if (message.is_copied_context === true) escrow.is_copied_context = true\n if (Object.keys(escrow).length > 0) result.extra = { [ESCROW]: escrow }\n return result\n}\n\n/** True when `step` is the agent turn that declared `callId` — the rule-2 test. */\nfunction declaresCall(step: HarborStep, callId: string | undefined): boolean {\n if (callId === undefined) return false\n return step.tool_calls?.some((call) => call.tool_call_id === callId) === true\n}\n\n/**\n * Attaches the four RL fields lifted from ATIF onto the agent step the span\n * describes. They are ALSO escrowed with the whole span under `extra.tangle`,\n * on purpose: the escrow is how our own round-trip stays exact, and these\n * native fields are how a foreign consumer — which never reads our escrow —\n * gets the logprobs and token ids at all. A field carried only in the escrow is\n * not an interchange field.\n */\nfunction applySpanMetrics(step: HarborStep, span: RolloutStep | undefined): void {\n if (span === undefined) return\n if (span.llm_call_count !== undefined) step.llm_call_count = span.llm_call_count\n const metrics: HarborMetrics = {}\n if (span.prompt_token_ids !== undefined) metrics.prompt_token_ids = span.prompt_token_ids\n if (span.completion_token_ids !== undefined) {\n metrics.completion_token_ids = span.completion_token_ids\n }\n if (span.logprobs !== undefined) metrics.logprobs = span.logprobs\n if (Object.keys(metrics).length > 0) step.metrics = metrics\n}\n\n/**\n * Coalescing fold, not a 1:1 map: ATIF has no `tool` source, so a tool result\n * becomes an `observation.results[]` entry on the agent step THAT DECLARED ITS\n * `tool_call_id`.\n *\n * Linking by id, not by adjacency. Adjacency emitted invalid documents in three\n * shapes the RFC forbids — an assistant turn with no `tool_calls` swallowing the\n * results that followed it, a result whose id matched none of the preceding\n * step's calls, and an unanswered result riding a `system` step that carried a\n * `source_call_id` it could never declare. Attaching only to the step that owns\n * the id also preserves message order exactly: a result either joins the step\n * immediately before it or becomes its own carrier at its own position.\n *\n * `line.steps` span projections are matched to agent steps in order (k-th llm\n * span → k-th agent step) purely to fill ATIF's native per-step `metrics`;\n * extra spans on either side are simply not matched, never invented.\n */\nfunction messagesToSteps(line: RolloutLine): HarborStep[] {\n const steps: HarborStep[] = []\n const llmSpans = (line.steps ?? []).filter((span) => span.kind === 'llm')\n let nextSpan = 0\n for (const message of line.messages) {\n if (message.role === 'tool') {\n const previous = steps[steps.length - 1]\n if (previous !== undefined && declaresCall(previous, message.tool_call_id)) {\n if (previous.observation === undefined) previous.observation = { results: [] }\n previous.observation.results.push(toObservationResult(message, true))\n continue\n }\n // A tool result answering no assistant turn in this document (truncated or\n // reconstructed transcript). It still has to survive, so it rides a marked\n // carrier step whose observation states no call id.\n const carrier: HarborStep = {\n step_id: steps.length + 1,\n source: 'system',\n message: '',\n observation: { results: [toObservationResult(message, false)] },\n extra: { [ESCROW]: { synthetic: TOOL_RESULTS_ONLY } },\n }\n if (message.is_copied_context === true) carrier.is_copied_context = true\n steps.push(carrier)\n continue\n }\n const step: HarborStep = {\n step_id: steps.length + 1,\n source: message.role === 'assistant' ? 'agent' : message.role,\n message: message.content ?? '',\n }\n const escrow: Record<string, unknown> = {}\n if (message.content === null) escrow.content_null = true\n if (message.name !== undefined) escrow.name = message.name\n if (message.role === 'assistant') {\n if (line.policy.model !== null) step.model_name = line.policy.model\n if (message.reasoning_content !== undefined) {\n step.reasoning_content = message.reasoning_content\n }\n if (message.tool_calls !== undefined && message.tool_calls.length > 0) {\n step.tool_calls = message.tool_calls.map(toHarborToolCall)\n }\n applySpanMetrics(step, llmSpans[nextSpan])\n nextSpan += 1\n } else if (message.reasoning_content !== undefined) {\n // ATIF confines `reasoning_content` to agent steps; ours is not confined.\n escrow.reasoning_content = message.reasoning_content\n }\n // RFC 0001 rule 7: a copied-context turn was not authored by this agent, and\n // an SFT pipeline MUST exclude it. Native ATIF field, both directions.\n if (message.is_copied_context === true) step.is_copied_context = true\n if (Object.keys(escrow).length > 0) step.extra = { [ESCROW]: escrow }\n steps.push(step)\n }\n return steps\n}\n\nfunction finalMetricsOf(line: RolloutLine, stepCount: number): HarborFinalMetrics {\n const metrics: HarborFinalMetrics = {}\n if (line.cost.tokens_in !== null) metrics.total_prompt_tokens = line.cost.tokens_in\n if (line.cost.tokens_out !== null) metrics.total_completion_tokens = line.cost.tokens_out\n if (line.cost.cache_read !== null) metrics.total_cached_tokens = line.cost.cache_read\n // Omitted, never 0, when cost was not captured — a fake 0 is a lie about spend.\n if (line.cost.usd !== null) metrics.total_cost_usd = line.cost.usd\n metrics.total_steps = stepCount\n // ATIF has no aggregate field for these three; `reasoning_tokens` under\n // `extra` is the key the RFC's own worked example uses.\n const extra: Record<string, unknown> = {}\n if (line.cost.tokens_reasoning !== null) extra.reasoning_tokens = line.cost.tokens_reasoning\n if (line.cost.cache_write !== null) extra.cache_write_tokens = line.cost.cache_write\n if (line.cost.wall_s !== null) extra.wall_s = line.cost.wall_s\n if (line.cost.llm_call_count !== undefined && line.cost.llm_call_count !== null) {\n extra.llm_call_count = line.cost.llm_call_count\n }\n if (Object.keys(extra).length > 0) metrics.extra = extra\n return metrics\n}\n\nfunction notesOf(line: RolloutLine): string | undefined {\n const parts: string[] = []\n if (line.provenance.gap !== undefined) parts.push(line.provenance.gap)\n if (line.outcome.realness_gated === true) {\n // ATIF has no gate field. A third-party consumer that ignores `extra`\n // would otherwise see a gamed trajectory with nothing marking it, so the\n // flag is stated in prose as well. This export carries no reward at all,\n // so it is not a training-data door — but it is an audit record.\n parts.push('realness-gated: this run faked its success signal (anti-Goodhart gate fired)')\n }\n return parts.length > 0 ? parts.join(' | ') : undefined\n}\n\nfunction toTrajectoryNode(line: RolloutLine): HarborTrajectory {\n const steps = messagesToSteps(line)\n const trajectory: HarborTrajectory = {\n schema_version: ATIF_SCHEMA_VERSION,\n // RUN-scoped, per the spec — so it is `run_id`, the coordinate every\n // invocation of one run shares. `rollout_id` identifies a single\n // invocation: using it gave two roots of the same run different session\n // ids, and foreign tooling that groups by session_id would split the run.\n session_id: line.run_id,\n trajectory_id: line.rollout_id,\n agent: {\n // ATIF requires both; ours are nullable, so a null is substituted here\n // and restored on import from the escrowed policy — never guessed back.\n name: line.policy.harness ?? 'unknown',\n version: line.policy.harness_version ?? '0.0.0',\n ...(line.policy.model !== null ? { model_name: line.policy.model } : {}),\n ...(line.tool_defs.length > 0 ? { tool_definitions: line.tool_defs } : {}),\n },\n steps,\n final_metrics: finalMetricsOf(line, steps.length),\n extra: {\n [ESCROW]: {\n schema: line.schema,\n rollout_id: line.rollout_id,\n parent_rollout_id: line.parent_rollout_id,\n run_id: line.run_id,\n ...(line.experiment_id !== undefined ? { experiment_id: line.experiment_id } : {}),\n ...(line.candidate_id !== undefined ? { candidate_id: line.candidate_id } : {}),\n generation: line.generation,\n candidate_index: line.candidate_index,\n role: line.role,\n task: line.task,\n policy: line.policy,\n // Span projections overlap the same turns as `steps[]`; folding them\n // into ATIF steps would double-count the run, so they stay escrowed.\n ...(line.steps !== undefined ? { spans: line.steps } : {}),\n outcome: {\n // reward / reward_source / verdict are deliberately absent — see the\n // module header. Only the non-scalar outcome fields travel.\n metrics: line.outcome.metrics,\n is_completed: line.outcome.is_completed,\n is_truncated: line.outcome.is_truncated,\n error: line.outcome.error,\n ...(line.outcome.realness_gated !== undefined\n ? { realness_gated: line.outcome.realness_gated }\n : {}),\n },\n artifacts: line.artifacts,\n provenance: line.provenance,\n },\n },\n }\n const notes = notesOf(line)\n if (notes !== undefined) trajectory.notes = notes\n return trajectory\n}\n\ninterface Forest {\n roots: RolloutLine[]\n childrenOf: Map<string, RolloutLine[]>\n}\n\nfunction buildForest(lines: RolloutLine[]): Forest {\n const byId = new Map<string, RolloutLine>()\n for (const line of lines) {\n if (byId.has(line.rollout_id)) {\n throw new Error(`duplicate rollout_id in input: ${line.rollout_id}`)\n }\n byId.set(line.rollout_id, line)\n }\n const roots: RolloutLine[] = []\n const childrenOf = new Map<string, RolloutLine[]>()\n for (const line of lines) {\n const parent = line.parent_rollout_id\n // A parent outside this set is a root OF WHAT WE HAVE: the edge is kept in\n // escrow so a later import restores the dangling pointer instead of nulling it.\n if (parent === null || !byId.has(parent)) {\n roots.push(line)\n continue\n }\n const siblings = childrenOf.get(parent)\n if (siblings === undefined) childrenOf.set(parent, [line])\n else siblings.push(line)\n }\n // Every line has a parent inside the set: the edges form a cycle with no\n // root. Returning zero documents would drop the whole episode silently.\n if (lines.length > 0 && roots.length === 0) {\n throw new Error(\n `parent_rollout_id cycle: no root among ${lines.length} lines (${lines.map((l) => l.rollout_id).join(', ')})`,\n )\n }\n return { roots, childrenOf }\n}\n\nfunction assemble(line: RolloutLine, forest: Forest, onPath: Set<string>): HarborTrajectory {\n if (onPath.has(line.rollout_id)) {\n throw new Error(`parent_rollout_id cycle through rollout_id ${line.rollout_id}`)\n }\n onPath.add(line.rollout_id)\n const node = toTrajectoryNode(line)\n const children = forest.childrenOf.get(line.rollout_id)\n if (children !== undefined && children.length > 0) {\n node.subagent_trajectories = children.map((child) => assemble(child, forest, onPath))\n }\n onPath.delete(line.rollout_id)\n return node\n}\n\n/**\n * Assemble one episode's flat lines into a single ATIF trajectory tree,\n * linked by `parent_rollout_id`.\n *\n * Reward, verdict and split are NOT emitted (ATIF models none of them); the\n * split and the rest of the task coordinates survive only in `extra.tangle`.\n *\n * We deliberately do NOT synthesize an `observation.subagent_trajectory_ref`\n * pointing at each child: our ledger records WHICH invocation spawned a\n * worker, not which STEP did, and attaching the ref to a guessed step would\n * fabricate a causal claim. Children are embedded in `subagent_trajectories`\n * (each with the `trajectory_id` the spec requires) and the edge is stated in\n * the child's escrowed `parent_rollout_id`.\n *\n * Throws when the lines are not one tree — use `toHarborTrajectories` for a forest.\n */\nexport function toHarborTrajectory(lines: RolloutLine[]): HarborTrajectory {\n const trees = toHarborTrajectories(lines)\n if (trees.length === 0) throw new Error('toHarborTrajectory: no lines')\n if (trees.length > 1) {\n const ids = trees.map((t) => t.trajectory_id ?? '?').join(', ')\n throw new Error(\n `toHarborTrajectory: ${trees.length} roots (${ids}) — ATIF is one tree per document; use toHarborTrajectories`,\n )\n }\n return trees[0]!\n}\n\n/** Every independent tree in the input, one ATIF document each. */\nexport function toHarborTrajectories(lines: RolloutLine[]): HarborTrajectory[] {\n const forest = buildForest(lines)\n return forest.roots.map((root) => assemble(root, forest, new Set()))\n}\n\n// ---------------------------------------------------------------------------\n// Import: ATIF trajectory tree → RolloutLine[]\n// ---------------------------------------------------------------------------\n\nfunction contentToString(message: string | HarborContentPart[]): string {\n if (typeof message === 'string') return message\n return message\n .map((part) =>\n part.type === 'image'\n ? // Our chat content is text-only. Describing the image is honest about\n // what the source held; dropping it silently would not be.\n `[image ${part.source?.media_type ?? 'unknown'} ${part.source?.path ?? ''}]`.trim()\n : (part.text ?? ''),\n )\n .join('\\n')\n}\n\nfunction fromHarborToolCall(call: HarborToolCall): ChatToolCall {\n const raw = asString(escrowOf(call.extra)?.arguments_raw)\n return {\n id: call.tool_call_id,\n type: 'function',\n function: { name: call.function_name, arguments: raw ?? JSON.stringify(call.arguments ?? {}) },\n }\n}\n\nfunction fromObservationResult(\n result: HarborObservationResult,\n callId: string | undefined,\n): ChatMessage {\n const escrow = escrowOf(result.extra)\n return canonicalChatMessage({\n role: 'tool',\n content:\n escrow?.content_null === true\n ? null\n : result.content === undefined\n ? ''\n : contentToString(result.content),\n reasoning_content: asString(escrow?.reasoning_content),\n tool_call_id: callId,\n name: asString(escrow?.name),\n is_copied_context: escrow?.is_copied_context === true,\n })\n}\n\nfunction stepsToMessages(steps: HarborStep[]): ChatMessage[] {\n const messages: ChatMessage[] = []\n for (const step of steps) {\n const escrow = escrowOf(step.extra)\n const carrierOnly = escrow?.synthetic === TOOL_RESULTS_ONLY\n if (!carrierOnly) {\n messages.push(\n canonicalChatMessage({\n role: step.source === 'agent' ? 'assistant' : step.source,\n content: escrow?.content_null === true ? null : contentToString(step.message),\n reasoning_content: step.reasoning_content ?? asString(escrow?.reasoning_content),\n tool_calls:\n step.tool_calls !== undefined && step.tool_calls.length > 0\n ? step.tool_calls.map(fromHarborToolCall)\n : undefined,\n name: asString(escrow?.name),\n is_copied_context: step.is_copied_context === true,\n }),\n )\n }\n for (const result of step.observation?.results ?? []) {\n const resultEscrow = escrowOf(result.extra)\n const callId = result.source_call_id ?? asString(resultEscrow?.source_call_id)\n if (carrierOnly) {\n // Our own carrier: every result on it was a tool turn, and its call id\n // (if the transcript had one) is in escrow, not on the wire.\n messages.push(fromObservationResult(result, callId))\n continue\n }\n if (typeof callId === 'string') {\n messages.push(fromObservationResult(result, callId))\n continue\n }\n // ATIF allows a result from a non-tool-calling action. Our chat schema\n // requires `tool_call_id` on a tool turn, so inventing one would forge a\n // link; the text is preserved as a system observation instead.\n if (result.content !== undefined) {\n messages.push(\n canonicalChatMessage({ role: 'system', content: contentToString(result.content) }),\n )\n }\n }\n }\n return messages\n}\n\nfunction taskFrom(escrow: Record<string, unknown> | undefined, fallbackId: string): RolloutTask {\n const task = escrowSection(escrow, 'task')\n return {\n suite: asString(task?.suite) ?? 'harbor-atif-import',\n instance_id: asString(task?.instance_id) ?? fallbackId,\n // ALWAYS holdout — the escrowed claim is read for nothing here.\n //\n // `extra.tangle.task.split` is a namespaced key, not an authenticated one:\n // a hand-written or third-party document can set `split: 'search'` as\n // easily as our own exporter can, and honouring it made \"this file says so\"\n // sufficient to walk into a training export. Trainability is a decision\n // about a file, so it is made by an operator through\n // `relabelImportedSplit`, never by the file about itself. The claim is not\n // destroyed — it stays readable in the source document.\n split: 'holdout',\n seed: asNumberOrNull(task?.seed),\n rep: asIntegerOrUndefined(task?.rep) ?? 0,\n }\n}\n\nfunction policyFrom(\n escrow: Record<string, unknown> | undefined,\n agent: HarborAgent,\n): RolloutPolicy {\n const escrowed = escrowSection(escrow, 'policy')\n if (escrowed !== undefined) {\n // Our own export: restore verbatim, including the nulls ATIF forced us to\n // substitute placeholders for in `agent.name` / `agent.version`.\n return {\n harness: asString(escrowed.harness) ?? null,\n harness_version: asString(escrowed.harness_version) ?? null,\n model: asString(escrowed.model) ?? null,\n provider: asString(escrowed.provider) ?? null,\n profile_commit: asString(escrowed.profile_commit) ?? null,\n ...(escrowed.prompt_hash !== undefined\n ? { prompt_hash: asString(escrowed.prompt_hash) ?? null }\n : {}),\n ...(escrowed.config_hash !== undefined\n ? { config_hash: asString(escrowed.config_hash) ?? null }\n : {}),\n ...(escrowed.agent_profile_cell_id !== undefined\n ? { agent_profile_cell_id: asString(escrowed.agent_profile_cell_id) ?? null }\n : {}),\n sampling: isRecord(escrowed.sampling) ? escrowed.sampling : null,\n }\n }\n return {\n harness: agent.name,\n harness_version: agent.version,\n model: agent.model_name ?? null,\n provider: null,\n profile_commit: null,\n sampling: null,\n }\n}\n\nfunction artifactsFrom(escrow: Record<string, unknown> | undefined): RolloutArtifacts {\n const artifacts = escrowSection(escrow, 'artifacts')\n return {\n patch_path: asString(artifacts?.patch_path) ?? null,\n run_dir: asString(artifacts?.run_dir) ?? null,\n transcript_ref: asString(artifacts?.transcript_ref) ?? null,\n }\n}\n\nfunction costFrom(final: HarborFinalMetrics | undefined): RolloutCostBlock {\n const rawExtra = final?.extra\n const extra = isRecord(rawExtra) ? rawExtra : undefined\n const calls = asIntegerOrUndefined(extra?.llm_call_count)\n return {\n usd: asNumberOrNull(final?.total_cost_usd),\n tokens_in: asNumberOrNull(final?.total_prompt_tokens),\n tokens_out: asNumberOrNull(final?.total_completion_tokens),\n tokens_reasoning: asNumberOrNull(extra?.reasoning_tokens),\n cache_read: asNumberOrNull(final?.total_cached_tokens),\n cache_write: asNumberOrNull(extra?.cache_write_tokens),\n wall_s: asNumberOrNull(extra?.wall_s),\n ...(calls !== undefined ? { llm_call_count: calls } : {}),\n }\n}\n\n/**\n * Recovers span projections from ATIF's NATIVE per-step channel, for documents\n * with no `extra.tangle.spans` escrow — i.e. everything a foreign producer\n * writes. Without this the logprobs and token ids a Harbor-native trainer\n * records would be read, validated, and then dropped on the floor.\n *\n * Only steps that actually carry one of the four fields produce a span: an\n * agent step with no metrics means \"not captured\", and inventing an empty span\n * for it would claim the run had a shape we did not observe.\n */\nfunction spansFromSteps(steps: HarborStep[]): RolloutStep[] {\n const spans: RolloutStep[] = []\n for (const step of steps) {\n if (step.source !== 'agent') continue\n const calls = asIntegerOrUndefined(step.llm_call_count)\n const promptIds = asIntegerArray(step.metrics?.prompt_token_ids)\n const completionIds = asIntegerArray(step.metrics?.completion_token_ids)\n const logprobs = asNumberArray(step.metrics?.logprobs)\n if (\n calls === undefined &&\n promptIds === undefined &&\n completionIds === undefined &&\n logprobs === undefined\n ) {\n continue\n }\n spans.push({\n kind: 'llm',\n name: step.model_name ?? 'chat',\n ...(calls !== undefined ? { llm_call_count: calls } : {}),\n ...(promptIds !== undefined ? { prompt_token_ids: promptIds } : {}),\n ...(completionIds !== undefined ? { completion_token_ids: completionIds } : {}),\n ...(logprobs !== undefined ? { logprobs } : {}),\n })\n }\n return spans\n}\n\n/**\n * Composes `provenance.gap` as an ordered SET of reasons.\n *\n * Appending made the note accrete on every pass (\"…no verdict | …no verdict\"),\n * which both grows without bound and breaks byte-level idempotency for a ledger\n * hashed on its serialized lines.\n */\nfunction composeGap(escrowedGap: string | undefined, added: readonly string[]): string {\n const parts: string[] = []\n const seen = new Set<string>()\n for (const raw of [...(escrowedGap?.split(' | ') ?? []), ...added]) {\n const reason = raw.trim()\n if (reason.length === 0 || seen.has(reason)) continue\n seen.add(reason)\n parts.push(reason)\n }\n return parts.join(' | ')\n}\n\nexport interface FromHarborOptions {\n /** Injected clock for deterministic output when the source carries no capture time. */\n now?: () => Date\n}\n\nfunction nodeToLine(\n trajectory: HarborTrajectory,\n parentId: string | null,\n capturedAt: string,\n): RolloutLine {\n const escrow = escrowOf(trajectory.extra)\n const rolloutId =\n asString(escrow?.rollout_id) ?? trajectory.trajectory_id ?? trajectory.session_id\n if (rolloutId === undefined || rolloutId.length === 0) {\n throw new Error(\n 'fromHarborTrajectory: trajectory has no trajectory_id or session_id — cannot mint a joinable rollout_id without inventing one',\n )\n }\n const outcome = escrowSection(escrow, 'outcome')\n const provenance = escrowSection(escrow, 'provenance')\n const capture = provenance?.capture\n const escrowedGap = asString(provenance?.gap)\n const role = escrow?.role\n const escrowedSpans = escrow?.spans\n // The escrow wins when it exists (our own export: exact, including an empty\n // array, which claims \"captured, none\" rather than \"not captured\"), and the\n // native per-step channel is the fallback (a foreign export: still signal).\n const nativeSpans = spansFromSteps(trajectory.steps)\n const spans: RolloutStep[] | undefined = Array.isArray(escrowedSpans)\n ? (escrowedSpans as RolloutStep[])\n : nativeSpans.length > 0\n ? nativeSpans\n : undefined\n const messages = stepsToMessages(trajectory.steps)\n const line: RolloutLine = {\n schema: ROLLOUT_SCHEMA,\n rollout_id: rolloutId,\n // The tree edge wins for embedded children; for a root, the escrowed\n // pointer may reference a line outside this document and is preserved.\n parent_rollout_id: parentId ?? asString(escrow?.parent_rollout_id) ?? null,\n run_id: asString(escrow?.run_id) ?? trajectory.session_id ?? rolloutId,\n // Required keys on the wire (0.127.0): a foreign document that never\n // stated them imports as explicit `null`, not as an absent field.\n experiment_id: asString(escrow?.experiment_id) ?? null,\n candidate_id: asString(escrow?.candidate_id) ?? null,\n generation: asIntegerOrUndefined(escrow?.generation) ?? null,\n candidate_index: asIntegerOrUndefined(escrow?.candidate_index) ?? null,\n role: ROLLOUT_ROLES.includes(role as RolloutRole) ? (role as RolloutRole) : 'agent',\n task: taskFrom(escrow, rolloutId),\n policy: policyFrom(escrow, trajectory.agent),\n messages,\n tool_defs: trajectory.agent.tool_definitions ?? [],\n ...(spans !== undefined ? { steps: spans } : {}),\n outcome: {\n // ATIF carries no label. Null is the labeled gap; a 0 here would be a\n // fabricated failure and a 1 a fabricated success.\n reward: null,\n reward_source: null,\n verdict: null,\n metrics: isRecord(outcome?.metrics) ? outcome.metrics : {},\n is_completed: typeof outcome?.is_completed === 'boolean' ? outcome.is_completed : true,\n is_truncated:\n typeof outcome?.is_truncated === 'boolean'\n ? outcome.is_truncated\n : trajectory.continued_trajectory_ref !== undefined,\n error: asString(outcome?.error) ?? null,\n // The anti-Goodhart flag is restored when the source document stated\n // it; the wire schema requires the field, so a document that never did\n // imports as `false`. That is safe here because the reward is already\n // forced to `null` (not trainable) and `realness_screened` stays\n // absent = unknown rather than claiming a screen ran.\n realness_gated: outcome?.realness_gated === true,\n },\n cost: costFrom(trajectory.final_metrics),\n artifacts: artifactsFrom(escrow),\n provenance: {\n captured_at: asString(provenance?.captured_at) ?? capturedAt,\n capture: ROLLOUT_CAPTURES.includes(capture as RolloutCapture)\n ? (capture as RolloutCapture)\n : 'backfill',\n gap: composeGap(escrowedGap, [HARBOR_IMPORT_GAP]),\n // Restored for the same reason `realness_gated` is, and with the opposite\n // risk profile from the reward: this is the gated run's own measurement\n // bag, moved off `outcome` by `gateGamedOutcome` so no exporter reads it\n // as training input. Dropping it here would silently destroy the audit\n // trail that says WHY the run was flagged and what it claimed, on the one\n // population an auditor most wants to inspect. It cannot be fail-open —\n // nothing projects `provenance` into a training row.\n ...(isRecord(provenance?.gated_evidence)\n ? { gated_evidence: provenance.gated_evidence as GatedEvidence }\n : {}),\n },\n }\n assertRolloutLine(line, `rollout line imported from ATIF trajectory ${rolloutId}`)\n return line\n}\n\n/**\n * Flatten an ATIF trajectory tree back into `tangle.rollout.v1` lines, parent\n * first, each child carrying `parent_rollout_id`.\n *\n * Every line comes back UNLABELED: `reward`, `reward_source` and `verdict` are\n * null and `provenance.gap` says why. ATIF models no verdict, so scoring an\n * imported trajectory is a judge's job, not this function's. Every line lands\n * on `holdout` whatever the document claims — see `relabelImportedSplit`.\n */\nexport function fromHarborTrajectory(\n trajectory: HarborTrajectory,\n options: FromHarborOptions = {},\n): RolloutLine[] {\n const capturedAt = (options.now?.() ?? new Date()).toISOString()\n const lines: RolloutLine[] = []\n const walk = (node: HarborTrajectory, parentId: string | null, onPath: Set<string>): void => {\n const line = nodeToLine(node, parentId, capturedAt)\n if (onPath.has(line.rollout_id)) {\n throw new Error(`subagent_trajectories cycle through trajectory_id ${line.rollout_id}`)\n }\n onPath.add(line.rollout_id)\n lines.push(line)\n for (const child of node.subagent_trajectories ?? []) {\n walk(child, line.rollout_id, onPath)\n }\n onPath.delete(line.rollout_id)\n }\n walk(trajectory, null, new Set())\n return lines\n}\n\n/**\n * THE explicit door out of `holdout` for imported lines.\n *\n * Import forces `holdout` because a document's own claim about its split is not\n * evidence — anyone can write `extra.tangle.task.split`. Promoting a file to a\n * trainable split is an operator's decision about provenance they verified, so\n * it is a separate, greppable call: `grep relabelImportedSplit` enumerates\n * every place foreign data was declared trainable, which is exactly the audit\n * the trusted-escrow version made impossible.\n *\n * Returns plain `RolloutLine`s. They still have to pass `assertMinted` (and its\n * anti-Goodhart check) to reach an exporter — re-labeling a split is not\n * minting a reward.\n */\nexport function relabelImportedSplit(\n lines: readonly RolloutLine[],\n split: RolloutSplit,\n): RolloutLine[] {\n if (!ROLLOUT_SPLITS.includes(split)) {\n throw new Error(`relabelImportedSplit: unknown split ${String(split)}`)\n }\n return lines.map((line) => ({ ...line,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AAK,MAAM,SAAS,KAAK,yBAAyB,CAAC,GACjD,KAAK,OAAO,KAAK,YAAY,MAAM;EAErC,OAAO,OAAO,KAAK,UAAU;CAC/B;CACA,KAAK,YAAY,sBAAM,IAAI,IAAI,CAAC;CAChC,OAAO;AACT;;;;;;;;;;;;;;;AAgBA,SAAgB,qBACd,OACA,OACe;CACf,IAAI,CAAC,eAAe,SAAS,KAAK,GAChC,MAAM,IAAI,MAAM,uCAAuC,OAAO,KAAK,GAAG;CAExE,OAAO,MAAM,KAAK,UAAU;EAAE,GAAG;EAAM,MAAM;GAAE,GAAG,KAAK;GAAM;EAAM;CAAE,EAAE;AACzE"}
|
|
1
|
+
{"version":3,"file":"rollout-C-znbbYg.js","names":[],"sources":["../src/rollout/interchange/harbor.ts"],"sourcesContent":["/**\n * Harbor ATIF-v1.7 interchange — `tangle.rollout.v1` ⇄ Agent Trajectory\n * Interchange Format.\n *\n * ATIF is the portability format (spec:\n * https://www.harborframework.com/docs/agents/trajectory-format, normative\n * RFC: harbor-framework/harbor `rfcs/0001-trajectory-format.md`). It sits\n * BELOW the waist of the rollout hourglass in both directions — export reads\n * `RolloutLine[]`, import writes `RolloutLine[]` — and it is never a source\n * of training labels:\n *\n * ATIF models NO reward, NO judge verdict, NO task/split coordinates.\n *\n * Consequences, both deliberate:\n * - EXPORT drops `outcome.reward`, `outcome.reward_source` and\n * `outcome.verdict` entirely. They are not smuggled into `extra`: a\n * third-party reading our ATIF file must not be able to mistake an\n * agent-eval judge score for something ATIF sanctioned.\n * - IMPORT therefore mints UNLABELED lines: `reward: null` (the existing\n * \"null reward is a labeled gap, never 0\" semantics), `verdict: null`,\n * and a `provenance.gap` naming the missing label. An imported\n * trajectory is not a training example until a judge scores it.\n *\n * Everything else we own that ATIF has no field for travels in a namespaced\n * escrow at `extra.tangle.*`, so our own round-trip is exact while a foreign\n * reader can ignore it. Fields that neither ATIF nor the escrow can carry\n * come back explicitly null / fail-closed, never invented.\n *\n * THE ESCROW IS NAMESPACED, NOT AUTHENTICATED. Anyone can write\n * `extra.tangle.*` into a file. So the escrow may restore what a value IS, but\n * never what a line is ALLOWED to do: `task.split` is forced to `holdout` on\n * every import regardless of what the document claims, and promoting an\n * imported trajectory to a trainable split is an explicit, greppable act\n * (`relabelImportedSplit`) rather than a property of the file. The document\n * keeps its claim — the claim just is not authority.\n *\n * Multi-agent shape differs on purpose. ATIF EMBEDS children in\n * `subagent_trajectories`; we keep a flat ledger with a normalized\n * `parent_rollout_id` edge. Export assembles the tree, import flattens it.\n * `session_id` is RUN-scoped in ATIF, so it carries `run_id` — the coordinate\n * that is shared by every invocation of one run — not `rollout_id`, which\n * identifies a single invocation and would split one run across session ids.\n *\n * ROUND-TRIPPING IS IDEMPOTENT: `import(export(import(export(x))))` is\n * byte-identical to `import(export(x))`. Import composes `provenance.gap` as a\n * de-duplicated ordered set rather than appending, and it emits every\n * `ChatMessage` with keys in the canonical schema order (role, content,\n * reasoning_content, tool_calls, tool_call_id, name, is_copied_context), so a\n * ledger hashed on serialized bytes sees no diff across further passes. The\n * FIRST import may re-order a producer's keys — that is the canonicalization.\n *\n * NOT building a Letta converter. Letta's trajectory-v1 is a strict subset of\n * what we need from ATIF here — no per-step or aggregate cost, no\n * multi-agent/subagent structure, no token-id or logprob channel — so a Letta\n * sink would carry less than this one and add a second format to keep\n * correct. Decision recorded in docs/rollout.md; do not re-litigate without a\n * concrete consumer that reads Letta and cannot read ATIF.\n */\n\nimport {\n assertRolloutLine,\n type ChatMessage,\n type ChatRole,\n type ChatToolCall,\n type GatedEvidence,\n ROLLOUT_CAPTURES,\n ROLLOUT_ROLES,\n ROLLOUT_SCHEMA,\n ROLLOUT_SPLITS,\n type RolloutArtifacts,\n type RolloutCapture,\n type RolloutCostBlock,\n type RolloutLine,\n type RolloutPolicy,\n type RolloutRole,\n type RolloutSplit,\n type RolloutStep,\n type RolloutTask,\n type ToolDef,\n} from '../schema'\n\nexport const ATIF_SCHEMA_VERSION = 'ATIF-v1.7'\n\n/** Gap note on every imported line — ATIF carries no verdict, so nothing is scored. */\nexport const HARBOR_IMPORT_GAP = 'imported from Harbor ATIF; no verdict'\n\n/** Namespaced escrow key for everything ATIF does not model but we must not lose. */\nconst ESCROW = 'tangle'\n\n/**\n * Marks a step we synthesized purely to hold tool results that answered no\n * assistant turn IN THIS DOCUMENT. ATIF has no `tool` source, so such results\n * need a carrier step; the marker lets import drop the carrier instead of\n * inventing a turn.\n *\n * A carrier's results carry NO `source_call_id`. RFC 0001 rule 2 requires every\n * `source_call_id` to match a `tool_call_id` in the same step's `tool_calls`,\n * and a carrier declares no calls (a `system` step cannot legally make one), so\n * emitting the id there would produce an invalid document. The id is escrowed\n * instead and restored verbatim on import — the link survives without the\n * document lying about who made the call.\n */\nconst TOOL_RESULTS_ONLY = 'tool-results-only'\n\n// ---------------------------------------------------------------------------\n// ATIF-v1.7 wire types (RFC 0001). Optional fields are optional here too.\n// ---------------------------------------------------------------------------\n\nexport type HarborStepSource = 'system' | 'user' | 'agent'\n\nexport interface HarborImageSource {\n media_type: string\n path: string\n}\n\nexport interface HarborContentPart {\n type: 'text' | 'image'\n text?: string\n source?: HarborImageSource\n}\n\nexport interface HarborToolCall {\n tool_call_id: string\n function_name: string\n /** ATIF requires a decoded JSON object here, unlike our raw argument string. */\n arguments: Record<string, unknown>\n extra?: Record<string, unknown>\n}\n\nexport interface HarborSubagentTrajectoryRef {\n trajectory_id?: string\n trajectory_path?: string\n /** Informational only since v1.7 — never a resolution key. */\n session_id?: string\n extra?: Record<string, unknown>\n}\n\nexport interface HarborObservationResult {\n source_call_id?: string\n content?: string | HarborContentPart[]\n subagent_trajectory_ref?: HarborSubagentTrajectoryRef[]\n extra?: Record<string, unknown>\n}\n\nexport interface HarborObservation {\n results: HarborObservationResult[]\n}\n\nexport interface HarborMetrics {\n prompt_tokens?: number\n completion_tokens?: number\n cached_tokens?: number\n cost_usd?: number\n prompt_token_ids?: number[]\n completion_token_ids?: number[]\n logprobs?: number[]\n extra?: Record<string, unknown>\n}\n\nexport interface HarborStep {\n /** Ordinal, sequential from 1. */\n step_id: number\n timestamp?: string\n source: HarborStepSource\n model_name?: string\n reasoning_effort?: string | number\n message: string | HarborContentPart[]\n reasoning_content?: string\n tool_calls?: HarborToolCall[]\n observation?: HarborObservation\n metrics?: HarborMetrics\n llm_call_count?: number\n is_copied_context?: boolean\n extra?: Record<string, unknown>\n}\n\nexport interface HarborAgent {\n name: string\n version: string\n model_name?: string\n /** OpenAI function-calling schema — byte-identical to our `ToolDef`. */\n tool_definitions?: ToolDef[]\n extra?: Record<string, unknown>\n}\n\nexport interface HarborFinalMetrics {\n total_prompt_tokens?: number\n total_completion_tokens?: number\n total_cached_tokens?: number\n total_cost_usd?: number\n total_steps?: number\n extra?: Record<string, unknown>\n}\n\nexport interface HarborTrajectory {\n schema_version: string\n session_id?: string\n /** Required on embedded subagents; we always set it so lines stay joinable. */\n trajectory_id?: string\n agent: HarborAgent\n steps: HarborStep[]\n notes?: string\n final_metrics?: HarborFinalMetrics\n continued_trajectory_ref?: string\n subagent_trajectories?: HarborTrajectory[]\n extra?: Record<string, unknown>\n}\n\n// ---------------------------------------------------------------------------\n// Shared helpers\n// ---------------------------------------------------------------------------\n\nconst isRecord = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v)\n\nconst asString = (v: unknown): string | undefined => (typeof v === 'string' ? v : undefined)\n\nconst asNumberOrNull = (v: unknown): number | null =>\n typeof v === 'number' && Number.isFinite(v) ? v : null\n\nconst asIntegerOrUndefined = (v: unknown): number | undefined =>\n Number.isInteger(v) ? (v as number) : undefined\n\nconst asNumberArray = (v: unknown): number[] | undefined =>\n Array.isArray(v) && v.every((n) => typeof n === 'number' && Number.isFinite(n))\n ? (v as number[])\n : undefined\n\nconst asIntegerArray = (v: unknown): number[] | undefined =>\n Array.isArray(v) && v.every((n) => Number.isInteger(n)) ? (v as number[]) : undefined\n\n/**\n * Builds a `ChatMessage` with keys in the schema's declaration order.\n *\n * Object key order is insertion order in JS, so a message assembled\n * conditionally field-by-field serializes differently depending on which\n * optional fields were present — which makes a byte-hashed ledger see a diff\n * across an import that changed nothing. One builder, one order, stable bytes.\n */\nfunction canonicalChatMessage(parts: {\n role: ChatRole\n content: string | null\n reasoning_content?: string\n tool_calls?: ChatToolCall[]\n tool_call_id?: string\n name?: string\n is_copied_context?: boolean\n}): ChatMessage {\n const message: ChatMessage = { role: parts.role, content: parts.content }\n if (parts.reasoning_content !== undefined) message.reasoning_content = parts.reasoning_content\n if (parts.tool_calls !== undefined) message.tool_calls = parts.tool_calls\n if (parts.tool_call_id !== undefined) message.tool_call_id = parts.tool_call_id\n if (parts.name !== undefined) message.name = parts.name\n if (parts.is_copied_context === true) message.is_copied_context = true\n return message\n}\n\n/** Reads the `extra.tangle` escrow, tolerating a foreign file that has none. */\nfunction escrowOf(extra: Record<string, unknown> | undefined): Record<string, unknown> | undefined {\n if (!isRecord(extra)) return undefined\n const value = extra[ESCROW]\n return isRecord(value) ? value : undefined\n}\n\nfunction escrowSection(\n escrow: Record<string, unknown> | undefined,\n key: string,\n): Record<string, unknown> | undefined {\n if (escrow === undefined) return undefined\n const value = escrow[key]\n return isRecord(value) ? value : undefined\n}\n\n// ---------------------------------------------------------------------------\n// Export: RolloutLine[] → ATIF trajectory tree\n// ---------------------------------------------------------------------------\n\nfunction toHarborToolCall(call: ChatToolCall): HarborToolCall {\n // ATIF requires `arguments` to be a JSON object; ours is the raw\n // JSON-encoded string the model emitted, and models really do emit\n // malformed ones. Keep the exact bytes in `extra` so import restores the\n // string verbatim instead of re-serializing a normalized parse.\n let parsed: Record<string, unknown> | undefined\n try {\n const decoded: unknown = JSON.parse(call.function.arguments)\n if (isRecord(decoded)) parsed = decoded\n } catch {\n parsed = undefined\n }\n return {\n tool_call_id: call.id,\n function_name: call.function.name,\n arguments: parsed ?? {},\n extra: { [ESCROW]: { arguments_raw: call.function.arguments } },\n }\n}\n\n/**\n * `linked` = this result is attached to the step that actually declared the\n * call, so `source_call_id` is legal (RFC 0001 rule 2). When it is not, the id\n * goes to escrow instead of onto the wire.\n */\nfunction toObservationResult(message: ChatMessage, linked: boolean): HarborObservationResult {\n const result: HarborObservationResult = {}\n if (linked && message.tool_call_id !== undefined) result.source_call_id = message.tool_call_id\n if (message.content !== null) result.content = message.content\n const escrow: Record<string, unknown> = {}\n if (!linked && message.tool_call_id !== undefined) escrow.source_call_id = message.tool_call_id\n if (message.name !== undefined) escrow.name = message.name\n // `content: null` on a tool turn is meaningful (a tool that returned\n // nothing) and is not the same as the empty string ATIF would round-trip it to.\n if (message.content === null) escrow.content_null = true\n if (message.reasoning_content !== undefined) escrow.reasoning_content = message.reasoning_content\n if (message.is_copied_context === true) escrow.is_copied_context = true\n if (Object.keys(escrow).length > 0) result.extra = { [ESCROW]: escrow }\n return result\n}\n\n/** True when `step` is the agent turn that declared `callId` — the rule-2 test. */\nfunction declaresCall(step: HarborStep, callId: string | undefined): boolean {\n if (callId === undefined) return false\n return step.tool_calls?.some((call) => call.tool_call_id === callId) === true\n}\n\n/**\n * Attaches the four RL fields lifted from ATIF onto the agent step the span\n * describes. They are ALSO escrowed with the whole span under `extra.tangle`,\n * on purpose: the escrow is how our own round-trip stays exact, and these\n * native fields are how a foreign consumer — which never reads our escrow —\n * gets the logprobs and token ids at all. A field carried only in the escrow is\n * not an interchange field.\n */\nfunction applySpanMetrics(step: HarborStep, span: RolloutStep | undefined): void {\n if (span === undefined) return\n if (span.llm_call_count !== undefined) step.llm_call_count = span.llm_call_count\n const metrics: HarborMetrics = {}\n if (span.prompt_token_ids !== undefined) metrics.prompt_token_ids = span.prompt_token_ids\n if (span.completion_token_ids !== undefined) {\n metrics.completion_token_ids = span.completion_token_ids\n }\n if (span.logprobs !== undefined) metrics.logprobs = span.logprobs\n if (Object.keys(metrics).length > 0) step.metrics = metrics\n}\n\n/**\n * Coalescing fold, not a 1:1 map: ATIF has no `tool` source, so a tool result\n * becomes an `observation.results[]` entry on the agent step THAT DECLARED ITS\n * `tool_call_id`.\n *\n * Linking by id, not by adjacency. Adjacency emitted invalid documents in three\n * shapes the RFC forbids — an assistant turn with no `tool_calls` swallowing the\n * results that followed it, a result whose id matched none of the preceding\n * step's calls, and an unanswered result riding a `system` step that carried a\n * `source_call_id` it could never declare. Attaching only to the step that owns\n * the id also preserves message order exactly: a result either joins the step\n * immediately before it or becomes its own carrier at its own position.\n *\n * `line.steps` span projections are matched to agent steps in order (k-th llm\n * span → k-th agent step) purely to fill ATIF's native per-step `metrics`;\n * extra spans on either side are simply not matched, never invented.\n */\nfunction messagesToSteps(line: RolloutLine): HarborStep[] {\n const steps: HarborStep[] = []\n const llmSpans = (line.steps ?? []).filter((span) => span.kind === 'llm')\n let nextSpan = 0\n for (const message of line.messages) {\n if (message.role === 'tool') {\n const previous = steps[steps.length - 1]\n if (previous !== undefined && declaresCall(previous, message.tool_call_id)) {\n if (previous.observation === undefined) previous.observation = { results: [] }\n previous.observation.results.push(toObservationResult(message, true))\n continue\n }\n // A tool result answering no assistant turn in this document (truncated or\n // reconstructed transcript). It still has to survive, so it rides a marked\n // carrier step whose observation states no call id.\n const carrier: HarborStep = {\n step_id: steps.length + 1,\n source: 'system',\n message: '',\n observation: { results: [toObservationResult(message, false)] },\n extra: { [ESCROW]: { synthetic: TOOL_RESULTS_ONLY } },\n }\n if (message.is_copied_context === true) carrier.is_copied_context = true\n steps.push(carrier)\n continue\n }\n const step: HarborStep = {\n step_id: steps.length + 1,\n source: message.role === 'assistant' ? 'agent' : message.role,\n message: message.content ?? '',\n }\n const escrow: Record<string, unknown> = {}\n if (message.content === null) escrow.content_null = true\n if (message.name !== undefined) escrow.name = message.name\n if (message.role === 'assistant') {\n if (line.policy.model !== null) step.model_name = line.policy.model\n if (message.reasoning_content !== undefined) {\n step.reasoning_content = message.reasoning_content\n }\n if (message.tool_calls !== undefined && message.tool_calls.length > 0) {\n step.tool_calls = message.tool_calls.map(toHarborToolCall)\n }\n applySpanMetrics(step, llmSpans[nextSpan])\n nextSpan += 1\n } else if (message.reasoning_content !== undefined) {\n // ATIF confines `reasoning_content` to agent steps; ours is not confined.\n escrow.reasoning_content = message.reasoning_content\n }\n // RFC 0001 rule 7: a copied-context turn was not authored by this agent, and\n // an SFT pipeline MUST exclude it. Native ATIF field, both directions.\n if (message.is_copied_context === true) step.is_copied_context = true\n if (Object.keys(escrow).length > 0) step.extra = { [ESCROW]: escrow }\n steps.push(step)\n }\n return steps\n}\n\nfunction finalMetricsOf(line: RolloutLine, stepCount: number): HarborFinalMetrics {\n const metrics: HarborFinalMetrics = {}\n if (line.cost.tokens_in !== null) metrics.total_prompt_tokens = line.cost.tokens_in\n if (line.cost.tokens_out !== null) metrics.total_completion_tokens = line.cost.tokens_out\n if (line.cost.cache_read !== null) metrics.total_cached_tokens = line.cost.cache_read\n // Omitted, never 0, when cost was not captured — a fake 0 is a lie about spend.\n if (line.cost.usd !== null) metrics.total_cost_usd = line.cost.usd\n metrics.total_steps = stepCount\n // ATIF has no aggregate field for these three; `reasoning_tokens` under\n // `extra` is the key the RFC's own worked example uses.\n const extra: Record<string, unknown> = {}\n if (line.cost.tokens_reasoning !== null) extra.reasoning_tokens = line.cost.tokens_reasoning\n if (line.cost.cache_write !== null) extra.cache_write_tokens = line.cost.cache_write\n if (line.cost.wall_s !== null) extra.wall_s = line.cost.wall_s\n if (line.cost.llm_call_count !== undefined && line.cost.llm_call_count !== null) {\n extra.llm_call_count = line.cost.llm_call_count\n }\n if (Object.keys(extra).length > 0) metrics.extra = extra\n return metrics\n}\n\nfunction notesOf(line: RolloutLine): string | undefined {\n const parts: string[] = []\n if (line.provenance.gap !== undefined) parts.push(line.provenance.gap)\n if (line.outcome.realness_gated === true) {\n // ATIF has no gate field. A third-party consumer that ignores `extra`\n // would otherwise see a gamed trajectory with nothing marking it, so the\n // flag is stated in prose as well. This export carries no reward at all,\n // so it is not a training-data door — but it is an audit record.\n parts.push('realness-gated: this run faked its success signal (anti-Goodhart gate fired)')\n }\n return parts.length > 0 ? parts.join(' | ') : undefined\n}\n\nfunction toTrajectoryNode(line: RolloutLine): HarborTrajectory {\n const steps = messagesToSteps(line)\n const trajectory: HarborTrajectory = {\n schema_version: ATIF_SCHEMA_VERSION,\n // RUN-scoped, per the spec — so it is `run_id`, the coordinate every\n // invocation of one run shares. `rollout_id` identifies a single\n // invocation: using it gave two roots of the same run different session\n // ids, and foreign tooling that groups by session_id would split the run.\n session_id: line.run_id,\n trajectory_id: line.rollout_id,\n agent: {\n // ATIF requires both; ours are nullable, so a null is substituted here\n // and restored on import from the escrowed policy — never guessed back.\n name: line.policy.harness ?? 'unknown',\n version: line.policy.harness_version ?? '0.0.0',\n ...(line.policy.model !== null ? { model_name: line.policy.model } : {}),\n ...(line.tool_defs.length > 0 ? { tool_definitions: line.tool_defs } : {}),\n },\n steps,\n final_metrics: finalMetricsOf(line, steps.length),\n extra: {\n [ESCROW]: {\n schema: line.schema,\n rollout_id: line.rollout_id,\n parent_rollout_id: line.parent_rollout_id,\n run_id: line.run_id,\n ...(line.experiment_id !== undefined ? { experiment_id: line.experiment_id } : {}),\n ...(line.candidate_id !== undefined ? { candidate_id: line.candidate_id } : {}),\n generation: line.generation,\n candidate_index: line.candidate_index,\n role: line.role,\n task: line.task,\n policy: line.policy,\n // Span projections overlap the same turns as `steps[]`; folding them\n // into ATIF steps would double-count the run, so they stay escrowed.\n ...(line.steps !== undefined ? { spans: line.steps } : {}),\n outcome: {\n // reward / reward_source / verdict are deliberately absent — see the\n // module header. Only the non-scalar outcome fields travel.\n metrics: line.outcome.metrics,\n is_completed: line.outcome.is_completed,\n is_truncated: line.outcome.is_truncated,\n error: line.outcome.error,\n ...(line.outcome.realness_gated !== undefined\n ? { realness_gated: line.outcome.realness_gated }\n : {}),\n },\n artifacts: line.artifacts,\n provenance: line.provenance,\n },\n },\n }\n const notes = notesOf(line)\n if (notes !== undefined) trajectory.notes = notes\n return trajectory\n}\n\ninterface Forest {\n roots: RolloutLine[]\n childrenOf: Map<string, RolloutLine[]>\n}\n\nfunction buildForest(lines: RolloutLine[]): Forest {\n const byId = new Map<string, RolloutLine>()\n for (const line of lines) {\n if (byId.has(line.rollout_id)) {\n throw new Error(`duplicate rollout_id in input: ${line.rollout_id}`)\n }\n byId.set(line.rollout_id, line)\n }\n const roots: RolloutLine[] = []\n const childrenOf = new Map<string, RolloutLine[]>()\n for (const line of lines) {\n const parent = line.parent_rollout_id\n // A parent outside this set is a root OF WHAT WE HAVE: the edge is kept in\n // escrow so a later import restores the dangling pointer instead of nulling it.\n if (parent === null || !byId.has(parent)) {\n roots.push(line)\n continue\n }\n const siblings = childrenOf.get(parent)\n if (siblings === undefined) childrenOf.set(parent, [line])\n else siblings.push(line)\n }\n // Every line has a parent inside the set: the edges form a cycle with no\n // root. Returning zero documents would drop the whole episode silently.\n if (lines.length > 0 && roots.length === 0) {\n throw new Error(\n `parent_rollout_id cycle: no root among ${lines.length} lines (${lines.map((l) => l.rollout_id).join(', ')})`,\n )\n }\n return { roots, childrenOf }\n}\n\nfunction assemble(line: RolloutLine, forest: Forest, onPath: Set<string>): HarborTrajectory {\n if (onPath.has(line.rollout_id)) {\n throw new Error(`parent_rollout_id cycle through rollout_id ${line.rollout_id}`)\n }\n onPath.add(line.rollout_id)\n const node = toTrajectoryNode(line)\n const children = forest.childrenOf.get(line.rollout_id)\n if (children !== undefined && children.length > 0) {\n node.subagent_trajectories = children.map((child) => assemble(child, forest, onPath))\n }\n onPath.delete(line.rollout_id)\n return node\n}\n\n/**\n * Assemble one episode's flat lines into a single ATIF trajectory tree,\n * linked by `parent_rollout_id`.\n *\n * Reward, verdict and split are NOT emitted (ATIF models none of them); the\n * split and the rest of the task coordinates survive only in `extra.tangle`.\n *\n * We deliberately do NOT synthesize an `observation.subagent_trajectory_ref`\n * pointing at each child: our ledger records WHICH invocation spawned a\n * worker, not which STEP did, and attaching the ref to a guessed step would\n * fabricate a causal claim. Children are embedded in `subagent_trajectories`\n * (each with the `trajectory_id` the spec requires) and the edge is stated in\n * the child's escrowed `parent_rollout_id`.\n *\n * Throws when the lines are not one tree — use `toHarborTrajectories` for a forest.\n */\nexport function toHarborTrajectory(lines: RolloutLine[]): HarborTrajectory {\n const trees = toHarborTrajectories(lines)\n if (trees.length === 0) throw new Error('toHarborTrajectory: no lines')\n if (trees.length > 1) {\n const ids = trees.map((t) => t.trajectory_id ?? '?').join(', ')\n throw new Error(\n `toHarborTrajectory: ${trees.length} roots (${ids}) — ATIF is one tree per document; use toHarborTrajectories`,\n )\n }\n return trees[0]!\n}\n\n/** Every independent tree in the input, one ATIF document each. */\nexport function toHarborTrajectories(lines: RolloutLine[]): HarborTrajectory[] {\n const forest = buildForest(lines)\n return forest.roots.map((root) => assemble(root, forest, new Set()))\n}\n\n// ---------------------------------------------------------------------------\n// Import: ATIF trajectory tree → RolloutLine[]\n// ---------------------------------------------------------------------------\n\nfunction contentToString(message: string | HarborContentPart[]): string {\n if (typeof message === 'string') return message\n return message\n .map((part) =>\n part.type === 'image'\n ? // Our chat content is text-only. Describing the image is honest about\n // what the source held; dropping it silently would not be.\n `[image ${part.source?.media_type ?? 'unknown'} ${part.source?.path ?? ''}]`.trim()\n : (part.text ?? ''),\n )\n .join('\\n')\n}\n\nfunction fromHarborToolCall(call: HarborToolCall): ChatToolCall {\n const raw = asString(escrowOf(call.extra)?.arguments_raw)\n return {\n id: call.tool_call_id,\n type: 'function',\n function: { name: call.function_name, arguments: raw ?? JSON.stringify(call.arguments ?? {}) },\n }\n}\n\nfunction fromObservationResult(\n result: HarborObservationResult,\n callId: string | undefined,\n): ChatMessage {\n const escrow = escrowOf(result.extra)\n return canonicalChatMessage({\n role: 'tool',\n content:\n escrow?.content_null === true\n ? null\n : result.content === undefined\n ? ''\n : contentToString(result.content),\n reasoning_content: asString(escrow?.reasoning_content),\n tool_call_id: callId,\n name: asString(escrow?.name),\n is_copied_context: escrow?.is_copied_context === true,\n })\n}\n\nfunction stepsToMessages(steps: HarborStep[]): ChatMessage[] {\n const messages: ChatMessage[] = []\n for (const step of steps) {\n const escrow = escrowOf(step.extra)\n const carrierOnly = escrow?.synthetic === TOOL_RESULTS_ONLY\n if (!carrierOnly) {\n messages.push(\n canonicalChatMessage({\n role: step.source === 'agent' ? 'assistant' : step.source,\n content: escrow?.content_null === true ? null : contentToString(step.message),\n reasoning_content: step.reasoning_content ?? asString(escrow?.reasoning_content),\n tool_calls:\n step.tool_calls !== undefined && step.tool_calls.length > 0\n ? step.tool_calls.map(fromHarborToolCall)\n : undefined,\n name: asString(escrow?.name),\n is_copied_context: step.is_copied_context === true,\n }),\n )\n }\n for (const result of step.observation?.results ?? []) {\n const resultEscrow = escrowOf(result.extra)\n const callId = result.source_call_id ?? asString(resultEscrow?.source_call_id)\n if (carrierOnly) {\n // Our own carrier: every result on it was a tool turn, and its call id\n // (if the transcript had one) is in escrow, not on the wire.\n messages.push(fromObservationResult(result, callId))\n continue\n }\n if (typeof callId === 'string') {\n messages.push(fromObservationResult(result, callId))\n continue\n }\n // ATIF allows a result from a non-tool-calling action. Our chat schema\n // requires `tool_call_id` on a tool turn, so inventing one would forge a\n // link; the text is preserved as a system observation instead.\n if (result.content !== undefined) {\n messages.push(\n canonicalChatMessage({ role: 'system', content: contentToString(result.content) }),\n )\n }\n }\n }\n return messages\n}\n\nfunction taskFrom(escrow: Record<string, unknown> | undefined, fallbackId: string): RolloutTask {\n const task = escrowSection(escrow, 'task')\n return {\n suite: asString(task?.suite) ?? 'harbor-atif-import',\n instance_id: asString(task?.instance_id) ?? fallbackId,\n // ALWAYS holdout — the escrowed claim is read for nothing here.\n //\n // `extra.tangle.task.split` is a namespaced key, not an authenticated one:\n // a hand-written or third-party document can set `split: 'search'` as\n // easily as our own exporter can, and honouring it made \"this file says so\"\n // sufficient to walk into a training export. Trainability is a decision\n // about a file, so it is made by an operator through\n // `relabelImportedSplit`, never by the file about itself. The claim is not\n // destroyed — it stays readable in the source document.\n split: 'holdout',\n seed: asNumberOrNull(task?.seed),\n rep: asIntegerOrUndefined(task?.rep) ?? 0,\n }\n}\n\nfunction policyFrom(\n escrow: Record<string, unknown> | undefined,\n agent: HarborAgent,\n): RolloutPolicy {\n const escrowed = escrowSection(escrow, 'policy')\n if (escrowed !== undefined) {\n // Our own export: restore verbatim, including the nulls ATIF forced us to\n // substitute placeholders for in `agent.name` / `agent.version`.\n return {\n harness: asString(escrowed.harness) ?? null,\n harness_version: asString(escrowed.harness_version) ?? null,\n model: asString(escrowed.model) ?? null,\n provider: asString(escrowed.provider) ?? null,\n profile_commit: asString(escrowed.profile_commit) ?? null,\n ...(escrowed.prompt_hash !== undefined\n ? { prompt_hash: asString(escrowed.prompt_hash) ?? null }\n : {}),\n ...(escrowed.config_hash !== undefined\n ? { config_hash: asString(escrowed.config_hash) ?? null }\n : {}),\n ...(escrowed.agent_profile_cell_id !== undefined\n ? { agent_profile_cell_id: asString(escrowed.agent_profile_cell_id) ?? null }\n : {}),\n sampling: isRecord(escrowed.sampling) ? escrowed.sampling : null,\n }\n }\n return {\n harness: agent.name,\n harness_version: agent.version,\n model: agent.model_name ?? null,\n provider: null,\n profile_commit: null,\n sampling: null,\n }\n}\n\nfunction artifactsFrom(escrow: Record<string, unknown> | undefined): RolloutArtifacts {\n const artifacts = escrowSection(escrow, 'artifacts')\n return {\n patch_path: asString(artifacts?.patch_path) ?? null,\n run_dir: asString(artifacts?.run_dir) ?? null,\n transcript_ref: asString(artifacts?.transcript_ref) ?? null,\n }\n}\n\nfunction costFrom(final: HarborFinalMetrics | undefined): RolloutCostBlock {\n const rawExtra = final?.extra\n const extra = isRecord(rawExtra) ? rawExtra : undefined\n const calls = asIntegerOrUndefined(extra?.llm_call_count)\n return {\n usd: asNumberOrNull(final?.total_cost_usd),\n tokens_in: asNumberOrNull(final?.total_prompt_tokens),\n tokens_out: asNumberOrNull(final?.total_completion_tokens),\n tokens_reasoning: asNumberOrNull(extra?.reasoning_tokens),\n cache_read: asNumberOrNull(final?.total_cached_tokens),\n cache_write: asNumberOrNull(extra?.cache_write_tokens),\n wall_s: asNumberOrNull(extra?.wall_s),\n ...(calls !== undefined ? { llm_call_count: calls } : {}),\n }\n}\n\n/**\n * Recovers span projections from ATIF's NATIVE per-step channel, for documents\n * with no `extra.tangle.spans` escrow — i.e. everything a foreign producer\n * writes. Without this the logprobs and token ids a Harbor-native trainer\n * records would be read, validated, and then dropped on the floor.\n *\n * Only steps that actually carry one of the four fields produce a span: an\n * agent step with no metrics means \"not captured\", and inventing an empty span\n * for it would claim the run had a shape we did not observe.\n */\nfunction spansFromSteps(steps: HarborStep[]): RolloutStep[] {\n const spans: RolloutStep[] = []\n for (const step of steps) {\n if (step.source !== 'agent') continue\n const calls = asIntegerOrUndefined(step.llm_call_count)\n const promptIds = asIntegerArray(step.metrics?.prompt_token_ids)\n const completionIds = asIntegerArray(step.metrics?.completion_token_ids)\n const logprobs = asNumberArray(step.metrics?.logprobs)\n if (\n calls === undefined &&\n promptIds === undefined &&\n completionIds === undefined &&\n logprobs === undefined\n ) {\n continue\n }\n spans.push({\n kind: 'llm',\n name: step.model_name ?? 'chat',\n ...(calls !== undefined ? { llm_call_count: calls } : {}),\n ...(promptIds !== undefined ? { prompt_token_ids: promptIds } : {}),\n ...(completionIds !== undefined ? { completion_token_ids: completionIds } : {}),\n ...(logprobs !== undefined ? { logprobs } : {}),\n })\n }\n return spans\n}\n\n/**\n * Composes `provenance.gap` as an ordered SET of reasons.\n *\n * Appending made the note accrete on every pass (\"…no verdict | …no verdict\"),\n * which both grows without bound and breaks byte-level idempotency for a ledger\n * hashed on its serialized lines.\n */\nfunction composeGap(escrowedGap: string | undefined, added: readonly string[]): string {\n const parts: string[] = []\n const seen = new Set<string>()\n for (const raw of [...(escrowedGap?.split(' | ') ?? []), ...added]) {\n const reason = raw.trim()\n if (reason.length === 0 || seen.has(reason)) continue\n seen.add(reason)\n parts.push(reason)\n }\n return parts.join(' | ')\n}\n\nexport interface FromHarborOptions {\n /** Injected clock for deterministic output when the source carries no capture time. */\n now?: () => Date\n}\n\nfunction nodeToLine(\n trajectory: HarborTrajectory,\n parentId: string | null,\n capturedAt: string,\n): RolloutLine {\n const escrow = escrowOf(trajectory.extra)\n const rolloutId =\n asString(escrow?.rollout_id) ?? trajectory.trajectory_id ?? trajectory.session_id\n if (rolloutId === undefined || rolloutId.length === 0) {\n throw new Error(\n 'fromHarborTrajectory: trajectory has no trajectory_id or session_id — cannot mint a joinable rollout_id without inventing one',\n )\n }\n const outcome = escrowSection(escrow, 'outcome')\n const provenance = escrowSection(escrow, 'provenance')\n const capture = provenance?.capture\n const escrowedGap = asString(provenance?.gap)\n const role = escrow?.role\n const escrowedSpans = escrow?.spans\n // The escrow wins when it exists (our own export: exact, including an empty\n // array, which claims \"captured, none\" rather than \"not captured\"), and the\n // native per-step channel is the fallback (a foreign export: still signal).\n const nativeSpans = spansFromSteps(trajectory.steps)\n const spans: RolloutStep[] | undefined = Array.isArray(escrowedSpans)\n ? (escrowedSpans as RolloutStep[])\n : nativeSpans.length > 0\n ? nativeSpans\n : undefined\n const messages = stepsToMessages(trajectory.steps)\n const line: RolloutLine = {\n schema: ROLLOUT_SCHEMA,\n rollout_id: rolloutId,\n // The tree edge wins for embedded children; for a root, the escrowed\n // pointer may reference a line outside this document and is preserved.\n parent_rollout_id: parentId ?? asString(escrow?.parent_rollout_id) ?? null,\n run_id: asString(escrow?.run_id) ?? trajectory.session_id ?? rolloutId,\n // Required keys on the wire (0.127.0): a foreign document that never\n // stated them imports as explicit `null`, not as an absent field.\n experiment_id: asString(escrow?.experiment_id) ?? null,\n candidate_id: asString(escrow?.candidate_id) ?? null,\n generation: asIntegerOrUndefined(escrow?.generation) ?? null,\n candidate_index: asIntegerOrUndefined(escrow?.candidate_index) ?? null,\n role: ROLLOUT_ROLES.includes(role as RolloutRole) ? (role as RolloutRole) : 'agent',\n task: taskFrom(escrow, rolloutId),\n policy: policyFrom(escrow, trajectory.agent),\n messages,\n tool_defs: trajectory.agent.tool_definitions ?? [],\n ...(spans !== undefined ? { steps: spans } : {}),\n outcome: {\n // ATIF carries no label. Null is the labeled gap; a 0 here would be a\n // fabricated failure and a 1 a fabricated success.\n reward: null,\n reward_source: null,\n verdict: null,\n metrics: isRecord(outcome?.metrics) ? outcome.metrics : {},\n is_completed: typeof outcome?.is_completed === 'boolean' ? outcome.is_completed : true,\n is_truncated:\n typeof outcome?.is_truncated === 'boolean'\n ? outcome.is_truncated\n : trajectory.continued_trajectory_ref !== undefined,\n error: asString(outcome?.error) ?? null,\n // The anti-Goodhart flag is restored when the source document stated\n // it; the wire schema requires the field, so a document that never did\n // imports as `false`. That is safe here because the reward is already\n // forced to `null` (not trainable) and `realness_screened` stays\n // absent = unknown rather than claiming a screen ran.\n realness_gated: outcome?.realness_gated === true,\n },\n cost: costFrom(trajectory.final_metrics),\n artifacts: artifactsFrom(escrow),\n provenance: {\n captured_at: asString(provenance?.captured_at) ?? capturedAt,\n capture: ROLLOUT_CAPTURES.includes(capture as RolloutCapture)\n ? (capture as RolloutCapture)\n : 'backfill',\n gap: composeGap(escrowedGap, [HARBOR_IMPORT_GAP]),\n // Restored for the same reason `realness_gated` is, and with the opposite\n // risk profile from the reward: this is the gated run's own measurement\n // bag, moved off `outcome` by `gateGamedOutcome` so no exporter reads it\n // as training input. Dropping it here would silently destroy the audit\n // trail that says WHY the run was flagged and what it claimed, on the one\n // population an auditor most wants to inspect. It cannot be fail-open —\n // nothing projects `provenance` into a training row.\n ...(isRecord(provenance?.gated_evidence)\n ? { gated_evidence: provenance.gated_evidence as GatedEvidence }\n : {}),\n },\n }\n assertRolloutLine(line, `rollout line imported from ATIF trajectory ${rolloutId}`)\n return line\n}\n\n/**\n * Flatten an ATIF trajectory tree back into `tangle.rollout.v1` lines, parent\n * first, each child carrying `parent_rollout_id`.\n *\n * Every line comes back UNLABELED: `reward`, `reward_source` and `verdict` are\n * null and `provenance.gap` says why. ATIF models no verdict, so scoring an\n * imported trajectory is a judge's job, not this function's. Every line lands\n * on `holdout` whatever the document claims — see `relabelImportedSplit`.\n */\nexport function fromHarborTrajectory(\n trajectory: HarborTrajectory,\n options: FromHarborOptions = {},\n): RolloutLine[] {\n const capturedAt = (options.now?.() ?? new Date()).toISOString()\n const lines: RolloutLine[] = []\n const walk = (node: HarborTrajectory, parentId: string | null, onPath: Set<string>): void => {\n const line = nodeToLine(node, parentId, capturedAt)\n if (onPath.has(line.rollout_id)) {\n throw new Error(`subagent_trajectories cycle through trajectory_id ${line.rollout_id}`)\n }\n onPath.add(line.rollout_id)\n lines.push(line)\n for (const child of node.subagent_trajectories ?? []) {\n walk(child, line.rollout_id, onPath)\n }\n onPath.delete(line.rollout_id)\n }\n walk(trajectory, null, new Set())\n return lines\n}\n\n/**\n * THE explicit door out of `holdout` for imported lines.\n *\n * Import forces `holdout` because a document's own claim about its split is not\n * evidence — anyone can write `extra.tangle.task.split`. Promoting a file to a\n * trainable split is an operator's decision about provenance they verified, so\n * it is a separate, greppable call: `grep relabelImportedSplit` enumerates\n * every place foreign data was declared trainable, which is exactly the audit\n * the trusted-escrow version made impossible.\n *\n * Returns plain `RolloutLine`s. They still have to pass `assertMinted` (and its\n * anti-Goodhart check) to reach an exporter — re-labeling a split is not\n * minting a reward.\n */\nexport function relabelImportedSplit(\n lines: readonly RolloutLine[],\n split: RolloutSplit,\n): RolloutLine[] {\n if (!ROLLOUT_SPLITS.includes(split)) {\n throw new Error(`relabelImportedSplit: unknown split ${String(split)}`)\n }\n return lines.map((line) => ({ ...line, task: { ...line.task, split } }))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiFA,MAAa,sBAAsB;;AAGnC,MAAa,oBAAoB;;AAGjC,MAAM,SAAS;;;;;;;;;;;;;;AAef,MAAM,oBAAoB;AA8G1B,MAAM,YAAY,MAChB,OAAO,MAAM,YAAY,MAAM,QAAQ,CAAC,MAAM,QAAQ,CAAC;AAEzD,MAAM,YAAY,MAAoC,OAAO,MAAM,WAAW,IAAI,KAAA;AAElF,MAAM,kBAAkB,MACtB,OAAO,M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EAAM;CAAE,EAAE;AACzE"}
|
package/dist/{rubric-predictive-validity-DluJLCKQ.d.ts → rubric-predictive-validity-Dl1dvKCv.d.ts}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as RunRecord } from "./run-record-
|
|
1
|
+
import { a as RunRecord } from "./run-record-DTv1MdjK.js";
|
|
2
2
|
import { o as OutcomeStore } from "./outcome-store-BYHIuO0e.js";
|
|
3
3
|
//#region src/meta-eval/rubric-predictive-validity.d.ts
|
|
4
4
|
interface RubricPredictiveValidityInput {
|
|
@@ -72,4 +72,4 @@ interface RubricPredictiveValidityReport {
|
|
|
72
72
|
declare function rubricPredictiveValidity(input: RubricPredictiveValidityInput): Promise<RubricPredictiveValidityReport>;
|
|
73
73
|
//#endregion
|
|
74
74
|
export { rubricPredictiveValidity as a, RubricRanking as i, RubricPredictiveValidityInput as n, RubricPredictiveValidityReport as r, RubricOutcomePair as t };
|
|
75
|
-
//# sourceMappingURL=rubric-predictive-validity-
|
|
75
|
+
//# sourceMappingURL=rubric-predictive-validity-Dl1dvKCv.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rubric-predictive-validity-
|
|
1
|
+
{"version":3,"file":"rubric-predictive-validity-Dl1dvKCv.d.ts","names":[],"sources":["../src/meta-eval/rubric-predictive-validity.ts"],"mappings":";;;UAqCiB;;;;;EAKf,MAAM;EACN,UAAU;;;;;;EAMV;;;;;;EAMA;;EAEA;;EAEA;;;EAGA;;;;;EAKA;;UAGe;EACf;EACA;EACA;EACA;EACA;EACA;IAAQ;IAAa;;;;;;;;EAOrB;;UAGe;EACf;;EAEA;EACA;EACA;EACA;EACA,SAAS;;UAGM;EACf,OAAO;;EAEP,QAAQ;EACR;EACA;;EAEA;;iBAGoB,yBACpB,OAAO,gCACN,QAAQ"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { c as ValidationError } from "./errors-DEE6u6ot.js";
|
|
2
2
|
import { p as CostProvenance } from "./cost-ledger-DbQdN3nO.js";
|
|
3
3
|
import { r as AgentProfileCell } from "./agent-profile-cell-CTOZJUuE.js";
|
|
4
|
-
import { o as FailureClass } from "./schema-
|
|
4
|
+
import { o as FailureClass } from "./schema-CR5cpjQ3.js";
|
|
5
5
|
//#region src/run-record.d.ts
|
|
6
6
|
/** Search/dev/holdout split tag. 'search' is the paper-grade alias for the
|
|
7
7
|
* combined train+test pool that the optimizer is allowed to read. */
|
|
@@ -244,4 +244,4 @@ declare function roundTripRunRecord(record: RunRecord): RunRecord;
|
|
|
244
244
|
declare function modelHasSnapshot(model: string): boolean;
|
|
245
245
|
//#endregion
|
|
246
246
|
export { validateRunRecord as _, RunRecord as a, RunTaskFailure as c, UNKNOWN_MODEL as d, isRunRecord as f, runTaskScore as g, roundTripRunRecord as h, RunOutcome as i, RunTerminalOutcome as l, parseRunRecordSafe as m, RunCostProvenance as n, RunRecordValidationError as o, modelHasSnapshot as p, RunJudgeMetadata as r, RunSplitTag as s, JudgeScoresRecord as t, RunTokenUsage as u };
|
|
247
|
-
//# sourceMappingURL=run-record-
|
|
247
|
+
//# sourceMappingURL=run-record-DTv1MdjK.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-record-
|
|
1
|
+
{"version":3,"file":"run-record-DTv1MdjK.d.ts","names":[],"sources":["../src/run-record.ts"],"mappings":";;;;;;;KAsCY;;;;;;;KAQA;;cAGC;UAEI;EACf;;EAEA;;;EAGA;;EAEA;;EAEA;;EAEA;;;KAIU,oBAAoB;UAEf;EACf;EACA;;;EAGA;;;EAGA;;;;;;;;;;;;;;;;;;;;;UAsBe;;EAEf,UAAU,eAAe;;EAEzB,YAAY;;;EAGZ;;;;EAIA;;;EAGA;;UAGe;;;EAGf;;;EAGA;;;;EAIA,KAAK;;;;;;EAML,cAAc;;;;;;;EAOd;IAAa;IAAe;IAAgB;;;;;;;;;;;;;;;;;;;;;;UAsB7B;;EAEf;;;EAGA;;;EAGA;;;EAGA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA,gBAAgB;;EAEhB,YAAY;;EAEZ,iBAAiB;;;EAGjB;;EAEA,gBAAgB;;EAEhB,SAAS;;;;;EAKT,eAAe;;;EAGf;;EAEA,UAAU;;;;;EAKV;;;;;;;;EAQA,eAAe;;;;;;;;;KAUL;EACN;EAA0B;;EAC1B;EAAyB;;EAEzB,cAAc,QAAQ;EACtB;;;;;;;;;;iBAWU,aAAa,QAAQ;cAmCxB,iCAAiC;WACnC;EACT,YAAY,iBAAiB;;;;;;;iBAWf,kBAAkB,iBAAiB;;iBAgPnC,YAAY,iBAAiB,SAAS;;iBAUtC,mBACd;EACG;EAAU,OAAO;;EAAgB;EAAW,OAAO;;;iBAUxC,mBAAmB,QAAQ,YAAY;;;;;;;iBAuFvC,iBAAiB"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { s as ValidationError } from "./errors-Dngq5h35.js";
|
|
2
2
|
import { validateAgentProfileCell } from "./profile-cell.js";
|
|
3
|
-
import { t as FAILURE_CLASSES } from "./schema-
|
|
3
|
+
import { t as FAILURE_CLASSES } from "./schema-CSf6qWgZ.js";
|
|
4
4
|
import { n as observedScore } from "./reward-nw2xZGZG.js";
|
|
5
5
|
//#region src/run-record.ts
|
|
6
6
|
/** Explicit model value for a row that never produced a served model snapshot. */
|
|
@@ -255,4 +255,4 @@ function validSnapshotDate(year, month, day) {
|
|
|
255
255
|
//#endregion
|
|
256
256
|
export { parseRunRecordSafe as a, validateRunRecord as c, modelHasSnapshot as i, UNKNOWN_MODEL as n, roundTripRunRecord as o, isRunRecord as r, runTaskScore as s, RunRecordValidationError as t };
|
|
257
257
|
|
|
258
|
-
//# sourceMappingURL=run-record-
|
|
258
|
+
//# sourceMappingURL=run-record-ZIsR9Fif.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-record-DLORoL7t.js","names":[],"sources":["../src/run-record.ts"],"sourcesContent":["/**\n * Paper-grade RunRecord schema + runtime validator.\n *\n * Every run that participates in a promotion gate, paper table, or\n * researcher loop SHOULD be recorded as a `RunRecord`. The mandatory\n * fields are exactly those the paper \"Two Loops, Three Roles\" requires\n * for reproducibility: who/what/when/cost/seed/hash, plus the search vs\n * holdout split tag. A task score is optional because execution-only records\n * must preserve missing labels instead of converting errors into zero quality.\n *\n * This is intentionally NOT a replacement for the rich `Run` /\n * `ProposeReviewReport` / `ScenarioResult` types already in the\n * package. Those are runtime structures with full provenance. A\n * `RunRecord` is the analysis-time projection — the JSON-friendly\n * row you'd put in a parquet file or paste into a notebook.\n *\n * Validate at the boundary:\n *\n * const rec = validateRunRecord(rawJson) // throws on missing\n * const ok = isRunRecord(rawJson) // boolean check\n * const rec = parseRunRecordSafe(rawJson) // { ok, value | error }\n *\n * The validator runs in pure TS — zod is intentionally NOT a\n * dependency. Round-trip tested in `tests/run-record.test.ts`.\n */\n\nimport type { AgentProfileCell } from './agent-profile-cell'\nimport { validateAgentProfileCell } from './agent-profile-cell'\nimport type { CostProvenance } from './cost-ledger'\nimport { ValidationError } from './errors'\n// Value import of a leaf module that itself imports only this file's TYPES —\n// no runtime cycle. It keeps the raw split-score derivation spelled in exactly\n// one place (see `rollout/score-derivation-guard`).\nimport { observedScore } from './rollout/reward'\nimport { FAILURE_CLASSES, type FailureClass } from './trace/schema'\n\n/** Search/dev/holdout split tag. 'search' is the paper-grade alias for the\n * combined train+test pool that the optimizer is allowed to read. */\nexport type RunSplitTag = 'search' | 'dev' | 'holdout'\n\n/**\n * Explicit execution-lifecycle result for a run.\n *\n * This is separate from task quality (`outcome`) and failure classification.\n * Producers set it only from root-run or process evidence.\n */\nexport type RunTerminalOutcome = 'succeeded' | 'failed' | 'cancelled' | 'incomplete' | 'unknown'\n\n/** Explicit model value for a row that never produced a served model snapshot. */\nexport const UNKNOWN_MODEL = 'unknown'\n\nexport interface RunTokenUsage {\n input: number\n /** All generated tokens charged as output, including reasoning tokens. */\n output: number\n /** Present only when one or more paid calls did not report token usage.\n * In that case, every numeric field is a known subtotal, not a measured total. */\n tokensKnown?: false\n /** Reasoning-token subset of `output`, when the provider reports it. */\n reasoning?: number\n /** Prompt tokens served from a provider cache. */\n cached?: number\n /** Prompt tokens written into a provider cache. */\n cacheWrite?: number\n}\n\n/** How a run's USD amount was obtained. */\nexport type RunCostProvenance = CostProvenance\n\nexport interface RunJudgeMetadata {\n model: string\n promptVersion: string\n /** [0,1] confidence the judge declared. Constant judge confidence\n * across many runs is a fallback signal (see `canary.ts`). */\n confidence: number\n /** True if the judge degraded to a fallback path (rules-only,\n * prior-call cache, etc.). The canary uses this to alert. */\n fallback: boolean\n}\n\n/**\n * Per-judge / per-dimension breakdown for runs scored by an ensemble of\n * judges over a multi-dimensional rubric.\n *\n * The collapsed `outcome.searchScore` / `holdoutScore` carries the\n * composite the gate uses. The full breakdown belongs here so consumers\n * can answer \"which judge disagreed?\", \"which dimension dragged the\n * composite down?\", and \"did half the panel fail?\" without re-running.\n *\n * `perJudge[judgeId][dim]` is the canonical source; `perDimMean` and\n * `composite` are convenience projections — derivable but precomputed so\n * downstream IRR primitives (`interRaterReliability`,\n * `corpusInterRaterAgreement`) and reporters don't pay the same\n * aggregation twice.\n *\n * Fail-loud discipline: judges that errored out land in `failedJudges`\n * by id. A missing key in `perJudge` is ambiguous (silent zero vs not\n * run); the explicit list makes a partial-failure recorded as such.\n */\nexport interface JudgeScoresRecord {\n /** Per-judge per-dimension scores. `{ \"kimi-k2.6\": { helpfulness: 0.8, clarity: 0.7 }, ... }`. */\n perJudge: Record<string, Record<string, number>>\n /** Per-dim mean across judges. Convenience — derivable from `perJudge`. */\n perDimMean: Record<string, number>\n /** Composite mean across successful judges. Mirrors the task score only\n * when `failedJudges` is empty. */\n composite: number\n /** Judges that errored or returned an unparseable verdict. Recorded\n * by id (e.g. `['glm-5.1']`) so a partial-failure case is explicit,\n * not inferred from missing keys in `perJudge`. */\n failedJudges?: string[]\n /** Free-form notes the judges emitted (joined across judges or\n * first-judge only — consumer's choice). */\n notes?: string\n}\n\nexport interface RunOutcome {\n /** Score on the search/optimization split. Optional for holdout-only and\n * execution-only records. */\n searchScore?: number\n /** Score on the held-out split. Optional for search-only and execution-only\n * records. When both scores are absent, the run is explicitly unlabeled. */\n holdoutScore?: number\n /** Bag of any other metric the run produced — judge dimensions,\n * pass/fail counters, latency stats, etc. Numeric only — keeps\n * reporters honest. */\n raw: Record<string, number>\n /** Per-judge / per-dim breakdown. Consumers writing ensemble\n * judgements populate this; substrate primitives like\n * `interRaterReliability` and `corpusInterRaterAgreement` accept\n * these records as input. Optional — single-judge or scalar-only\n * runs leave it unset. */\n judgeScores?: JudgeScoresRecord\n /** Authenticity / realness verdict — did the run build the REAL thing on the\n * intended infra, or fake it (see `./authenticity`)? Optional: only domains\n * with an authenticity config populate it. Carried in the corpus so the\n * flywheel / off-policy learning can optimize for real completion, not gamed\n * pass-rate. `score` is 0-1; `gated` is the anti-Goodhart flag — a gated run\n * must not count as a real success regardless of `score`. */\n realness?: { score: number; gated: boolean; reason?: string }\n}\n\n/**\n * Mandatory paper-grade fields for a single evaluation run. Optional\n * fields are extension points; mandatory fields throw if missing.\n *\n * Hash discipline:\n * - `promptHash` is the sha256 of the EFFECTIVE prompt sent to the\n * model (after any steering bundle merge).\n * - `configHash` is the sha256 of the effective run config (model,\n * temperature, tools, judges, splits). The pair (promptHash,\n * configHash) uniquely identifies an experiment cell.\n *\n * Model snapshot discipline:\n * - successful rows MUST encode a snapshot version. Bare aliases like\n * `claude-sonnet-4` or `gpt-4o` are banned — they remap silently.\n * Use `claude-sonnet-4-6@2025-04-15` or `gpt-4o-2024-11-20`.\n * - a failed, cancelled, incomplete, or otherwise unknown row may use\n * `UNKNOWN_MODEL` when no served model was observed. This is an explicit\n * absence marker, not a fabricated snapshot.\n */\nexport interface RunRecord {\n /** UUID for the run. */\n runId: string\n /** Logical experiment grouping (a treatment vs a baseline within\n * the same sweep should share `experimentId`). */\n experimentId: string\n /** Stable identifier for the candidate (variant) being run. The\n * promotion gate compares two `candidateId`s on matched items. */\n candidateId: string\n /** RNG seed for the run. Always recorded — silent re-seeding is\n * the most common cause of non-reproducible numbers. */\n seed: number\n /** Model identifier WITH snapshot version. */\n model: string\n /** sha256 of the effective prompt (post-steering). */\n promptHash: string\n /** sha256 of the effective config. */\n configHash: string\n /** Git SHA the harness was run from. */\n commitSha: string\n /** End-to-end wall-clock duration in milliseconds. */\n wallMs: number\n /** Time spent queued before execution started, if known. */\n queueMs?: number\n /** Total USD cost, or null when the producer could not capture one. */\n costUsd: number | null\n /** Whether `costUsd` came from billing data, a price calculation, or is unavailable. */\n costProvenance: RunCostProvenance\n /** Token usage breakdown. */\n tokenUsage: RunTokenUsage\n /** Root-run or process terminal result. Never inferred from a child span. */\n terminalOutcome: RunTerminalOutcome\n /** Root-run or process failure reason. Valid only for a failed, cancelled,\n * or incomplete terminal result; never populated from a child span. */\n terminalFailureReason?: string\n /** Judge-side metadata, if a judge was used. */\n judgeMetadata?: RunJudgeMetadata\n /** Per-split scores + raw bag. */\n outcome: RunOutcome\n /** Canonical task-failure class drawn from the shared\n * `FAILURE_CLASSES` taxonomy. Producers set it only from task-result\n * evidence. Execution errors belong in\n * `outcome.raw.execution_error_count`. */\n failureClass?: FailureClass\n /** Free-form task-failure detail scoped under a non-success\n * `failureClass`. It is invalid without that class. */\n failureMode?: string\n /** Which split this run was drawn from. */\n splitTag: RunSplitTag\n /**\n * Stable scenario identifier the run observed or was scored against.\n * Comparison primitives match this identity rather than input order.\n */\n scenarioId: string\n /**\n * Canonical identity for the agent profile cell that produced this row:\n * profile artifact hash plus optional harness/model/prompt/reporting\n * dimensions. Use `agentProfile.cellId` to group persona sweeps and\n * longitudinal reports by the complete source profile, not by a loose\n * candidate label or opaque config hash.\n */\n agentProfile?: AgentProfileCell\n}\n\n/**\n * Canonical task-result classification.\n *\n * A producer may omit classification, record explicit success, or attach\n * domain-specific detail to a non-success class. Detail can never stand alone.\n * Execution errors belong in `outcome.raw.execution_error_count`.\n */\nexport type RunTaskFailure =\n | { failureClass?: undefined; failureMode?: undefined }\n | { failureClass: 'success'; failureMode?: undefined }\n | {\n failureClass: Exclude<FailureClass, 'success'>\n failureMode?: string\n }\n\n/**\n * Return task quality, preferring held-out evidence when both scores exist.\n *\n * RAW: no realness protection is applied. Built on `observedScore` rather\n * than repeating the split derivation, so only `rollout/reward.ts` reads the\n * raw fields. Anything that becomes training data must use `trainingScore` or\n * `trainingReward` instead.\n */\nexport function runTaskScore(record: RunRecord): number | undefined {\n const score = observedScore(record)\n return typeof score === 'number' && Number.isFinite(score) ? score : undefined\n}\n\n// ── Validation ───────────────────────────────────────────────────────\n\nconst MANDATORY_TOP_LEVEL = [\n 'runId',\n 'experimentId',\n 'candidateId',\n 'seed',\n 'model',\n 'promptHash',\n 'configHash',\n 'commitSha',\n 'wallMs',\n 'costUsd',\n 'costProvenance',\n 'tokenUsage',\n 'terminalOutcome',\n 'outcome',\n 'splitTag',\n 'scenarioId',\n] as const\n\nconst SPLIT_TAGS: ReadonlyArray<RunSplitTag> = ['search', 'dev', 'holdout']\nconst TERMINAL_OUTCOMES: ReadonlyArray<RunTerminalOutcome> = [\n 'succeeded',\n 'failed',\n 'cancelled',\n 'incomplete',\n 'unknown',\n]\n\nexport class RunRecordValidationError extends ValidationError {\n readonly path: string\n constructor(message: string, path = '') {\n super(path ? `${message} (at ${path})` : message)\n this.path = path\n }\n}\n\n/**\n * Strict validator. Throws `RunRecordValidationError` on the first\n * missing or wrongly-typed field. Returns the input cast to\n * `RunRecord` on success — the validator does not coerce.\n */\nexport function validateRunRecord(input: unknown): RunRecord {\n if (input === null || typeof input !== 'object') {\n throw new RunRecordValidationError('expected object')\n }\n const obj = input as Record<string, unknown>\n\n for (const key of MANDATORY_TOP_LEVEL) {\n if (!(key in obj)) {\n throw new RunRecordValidationError(`missing mandatory field \"${key}\"`)\n }\n }\n\n expectString(obj.runId, 'runId')\n expectString(obj.experimentId, 'experimentId')\n expectString(obj.candidateId, 'candidateId')\n expectFiniteNumber(obj.seed, 'seed')\n expectString(obj.model, 'model')\n expectString(obj.promptHash, 'promptHash')\n expectString(obj.configHash, 'configHash')\n expectString(obj.commitSha, 'commitSha')\n expectNonNegativeNumber(obj.wallMs, 'wallMs')\n if (obj.queueMs !== undefined) expectNonNegativeNumber(obj.queueMs, 'queueMs')\n validateCost(obj.costUsd, obj.costProvenance)\n\n // Snapshot discipline: successful rows require a served model snapshot.\n // Non-success rows may carry the explicit absence marker when execution\n // stopped before a model identity was observed.\n if (\n !modelHasSnapshot(obj.model as string) &&\n !(obj.model === UNKNOWN_MODEL && obj.terminalOutcome !== 'succeeded')\n ) {\n throw new RunRecordValidationError(\n `model \"${obj.model}\" lacks a snapshot version (use 'name@YYYY-MM-DD' or 'name-YYYYMMDD', or '${UNKNOWN_MODEL}' for a non-success row without a served model)`,\n 'model',\n )\n }\n\n // Token usage.\n const tu = obj.tokenUsage\n if (tu === null || typeof tu !== 'object') {\n throw new RunRecordValidationError('tokenUsage must be an object', 'tokenUsage')\n }\n const tuRec = tu as Record<string, unknown>\n expectNonNegativeNumber(tuRec.input, 'tokenUsage.input')\n expectNonNegativeNumber(tuRec.output, 'tokenUsage.output')\n if (tuRec.tokensKnown !== undefined && tuRec.tokensKnown !== false) {\n throw new RunRecordValidationError(\n 'tokensKnown must be false when present; omit it when token usage is complete',\n 'tokenUsage.tokensKnown',\n )\n }\n if (tuRec.reasoning !== undefined) {\n expectNonNegativeNumber(tuRec.reasoning, 'tokenUsage.reasoning')\n if ((tuRec.reasoning as number) > (tuRec.output as number)) {\n throw new RunRecordValidationError(\n 'reasoning tokens must be a subset of output tokens',\n 'tokenUsage.reasoning',\n )\n }\n }\n if (tuRec.cached !== undefined) expectNonNegativeNumber(tuRec.cached, 'tokenUsage.cached')\n if (tuRec.cacheWrite !== undefined) {\n expectNonNegativeNumber(tuRec.cacheWrite, 'tokenUsage.cacheWrite')\n }\n\n // Judge metadata, optional.\n if (obj.judgeMetadata !== undefined) {\n const jm = obj.judgeMetadata\n if (jm === null || typeof jm !== 'object') {\n throw new RunRecordValidationError('judgeMetadata must be an object', 'judgeMetadata')\n }\n const jmRec = jm as Record<string, unknown>\n expectString(jmRec.model, 'judgeMetadata.model')\n expectString(jmRec.promptVersion, 'judgeMetadata.promptVersion')\n expectFiniteNumber(jmRec.confidence, 'judgeMetadata.confidence')\n if (typeof jmRec.fallback !== 'boolean') {\n throw new RunRecordValidationError(\n 'judgeMetadata.fallback must be boolean',\n 'judgeMetadata.fallback',\n )\n }\n }\n\n // Outcome.\n const out = obj.outcome\n if (out === null || typeof out !== 'object') {\n throw new RunRecordValidationError('outcome must be an object', 'outcome')\n }\n const outRec = out as Record<string, unknown>\n if (outRec.searchScore !== undefined)\n expectFiniteNumber(outRec.searchScore, 'outcome.searchScore')\n if (outRec.holdoutScore !== undefined)\n expectFiniteNumber(outRec.holdoutScore, 'outcome.holdoutScore')\n const raw = outRec.raw\n if (raw === null || typeof raw !== 'object') {\n throw new RunRecordValidationError('outcome.raw must be an object', 'outcome.raw')\n }\n for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {\n expectFiniteNumber(v, `outcome.raw.${k}`)\n }\n // Realness verdict, optional.\n if (outRec.realness !== undefined) {\n const r = outRec.realness\n if (r === null || typeof r !== 'object') {\n throw new RunRecordValidationError('outcome.realness must be an object', 'outcome.realness')\n }\n const rr = r as Record<string, unknown>\n expectFiniteNumber(rr.score, 'outcome.realness.score')\n if (typeof rr.gated !== 'boolean') {\n throw new RunRecordValidationError(\n 'outcome.realness.gated must be a boolean',\n 'outcome.realness.gated',\n )\n }\n }\n\n // Per-judge / per-dim breakdown, optional.\n if (outRec.judgeScores !== undefined) {\n validateJudgeScores(outRec.judgeScores, 'outcome.judgeScores')\n }\n\n // Failure mode optional.\n if (\n obj.failureClass !== undefined &&\n (typeof obj.failureClass !== 'string' ||\n !FAILURE_CLASSES.includes(obj.failureClass as FailureClass))\n ) {\n throw new RunRecordValidationError(\n `failureClass must be one of ${FAILURE_CLASSES.join(', ')}`,\n 'failureClass',\n )\n }\n if (obj.failureMode !== undefined) {\n expectString(obj.failureMode, 'failureMode')\n if (obj.failureClass === undefined || obj.failureClass === 'success') {\n throw new RunRecordValidationError(\n 'failureMode requires a non-success failureClass',\n 'failureMode',\n )\n }\n }\n\n if (\n typeof obj.terminalOutcome !== 'string' ||\n !TERMINAL_OUTCOMES.includes(obj.terminalOutcome as RunTerminalOutcome)\n ) {\n throw new RunRecordValidationError(\n `terminalOutcome must be one of ${TERMINAL_OUTCOMES.join(', ')}`,\n 'terminalOutcome',\n )\n }\n if (obj.terminalFailureReason !== undefined) {\n expectString(obj.terminalFailureReason, 'terminalFailureReason')\n if (\n obj.terminalOutcome !== 'failed' &&\n obj.terminalOutcome !== 'cancelled' &&\n obj.terminalOutcome !== 'incomplete'\n ) {\n throw new RunRecordValidationError(\n 'terminalFailureReason requires terminalOutcome failed, cancelled, or incomplete',\n 'terminalFailureReason',\n )\n }\n }\n\n if (obj.agentProfile !== undefined) {\n try {\n const profile = validateAgentProfileCell(obj.agentProfile)\n if (profile.model !== undefined && profile.model !== obj.model) {\n throw new RunRecordValidationError(\n `agentProfile.model \"${profile.model}\" does not match model \"${obj.model}\"`,\n 'agentProfile.model',\n )\n }\n if (profile.promptHash !== undefined && profile.promptHash !== obj.promptHash) {\n throw new RunRecordValidationError(\n `agentProfile.promptHash \"${profile.promptHash}\" does not match promptHash \"${obj.promptHash}\"`,\n 'agentProfile.promptHash',\n )\n }\n } catch (error) {\n if (error instanceof RunRecordValidationError) throw error\n if (error instanceof Error) {\n throw new RunRecordValidationError(error.message, 'agentProfile')\n }\n throw error\n }\n }\n\n expectString(obj.scenarioId, 'scenarioId')\n\n // Split tag.\n if (typeof obj.splitTag !== 'string' || !SPLIT_TAGS.includes(obj.splitTag as RunSplitTag)) {\n throw new RunRecordValidationError(\n `splitTag must be one of ${SPLIT_TAGS.join(', ')}, got ${String(obj.splitTag)}`,\n 'splitTag',\n )\n }\n\n return input as RunRecord\n}\n\nfunction validateCost(costUsd: unknown, provenance: unknown): void {\n if (provenance === null || typeof provenance !== 'object') {\n throw new RunRecordValidationError('costProvenance must be an object', 'costProvenance')\n }\n const value = provenance as Record<string, unknown>\n if (value.kind !== 'observed' && value.kind !== 'estimated' && value.kind !== 'uncaptured') {\n throw new RunRecordValidationError(\n 'costProvenance.kind must be observed, estimated, or uncaptured',\n 'costProvenance.kind',\n )\n }\n // A record must never read as a total it cannot support, so an uncaptured\n // cost carries no number at all. A matrix `CellResult` keeps its known\n // subtotal instead, because a cost ceiling must charge the part it can see;\n // converting one to the other drops that subtotal.\n if (value.kind === 'uncaptured') {\n if (value.usd !== null) {\n throw new RunRecordValidationError(\n 'uncaptured costProvenance.usd must be null',\n 'costProvenance.usd',\n )\n }\n if (costUsd !== null) {\n throw new RunRecordValidationError('uncaptured cost requires costUsd to be null', 'costUsd')\n }\n return\n }\n expectNonNegativeNumber(costUsd, 'costUsd')\n expectNonNegativeNumber(value.usd, 'costProvenance.usd')\n if (value.usd !== costUsd) {\n throw new RunRecordValidationError(\n 'costProvenance.usd must equal costUsd',\n 'costProvenance.usd',\n )\n }\n}\n\n/** Boolean validator — convenience for filtering arrays. */\nexport function isRunRecord(input: unknown): input is RunRecord {\n try {\n validateRunRecord(input)\n return true\n } catch {\n return false\n }\n}\n\n/** Non-throwing validator — returns a discriminated union. */\nexport function parseRunRecordSafe(\n input: unknown,\n): { ok: true; value: RunRecord } | { ok: false; error: RunRecordValidationError } {\n try {\n return { ok: true, value: validateRunRecord(input) }\n } catch (e) {\n if (e instanceof RunRecordValidationError) return { ok: false, error: e }\n throw e\n }\n}\n\n/** Round-trip helper — `JSON.parse(JSON.stringify(record))` then validate. */\nexport function roundTripRunRecord(record: RunRecord): RunRecord {\n const json = JSON.stringify(record)\n return validateRunRecord(JSON.parse(json))\n}\n\n// ── Internals ────────────────────────────────────────────────────────\n\nfunction expectString(value: unknown, path: string): void {\n if (typeof value !== 'string' || value.length === 0) {\n throw new RunRecordValidationError(`expected non-empty string`, path)\n }\n}\n\nfunction expectFiniteNumber(value: unknown, path: string): void {\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new RunRecordValidationError(`expected finite number`, path)\n }\n}\n\nfunction expectNonNegativeNumber(value: unknown, path: string): void {\n expectFiniteNumber(value, path)\n if ((value as number) < 0) {\n throw new RunRecordValidationError('expected non-negative number', path)\n }\n}\n\nfunction validateJudgeScores(value: unknown, path: string): void {\n if (value === null || typeof value !== 'object') {\n throw new RunRecordValidationError('judgeScores must be an object', path)\n }\n const rec = value as Record<string, unknown>\n\n const perJudge = rec.perJudge\n if (perJudge === null || typeof perJudge !== 'object') {\n throw new RunRecordValidationError('perJudge must be an object', `${path}.perJudge`)\n }\n for (const [judgeId, dims] of Object.entries(perJudge as Record<string, unknown>)) {\n if (dims === null || typeof dims !== 'object') {\n throw new RunRecordValidationError(\n 'per-judge entry must be an object of dimension scores',\n `${path}.perJudge.${judgeId}`,\n )\n }\n for (const [dim, score] of Object.entries(dims as Record<string, unknown>)) {\n expectFiniteNumber(score, `${path}.perJudge.${judgeId}.${dim}`)\n }\n }\n\n const perDimMean = rec.perDimMean\n if (perDimMean === null || typeof perDimMean !== 'object') {\n throw new RunRecordValidationError('perDimMean must be an object', `${path}.perDimMean`)\n }\n for (const [dim, mean] of Object.entries(perDimMean as Record<string, unknown>)) {\n expectFiniteNumber(mean, `${path}.perDimMean.${dim}`)\n }\n\n expectFiniteNumber(rec.composite, `${path}.composite`)\n\n if (rec.failedJudges !== undefined) {\n if (!Array.isArray(rec.failedJudges)) {\n throw new RunRecordValidationError(\n 'failedJudges must be an array of strings',\n `${path}.failedJudges`,\n )\n }\n for (let i = 0; i < rec.failedJudges.length; i++) {\n const id = rec.failedJudges[i]\n if (typeof id !== 'string' || id.length === 0) {\n throw new RunRecordValidationError(\n 'failedJudges entry must be a non-empty string',\n `${path}.failedJudges[${i}]`,\n )\n }\n }\n }\n\n if (rec.notes !== undefined && typeof rec.notes !== 'string') {\n throw new RunRecordValidationError('notes must be a string', `${path}.notes`)\n }\n}\n\n/**\n * Snapshot check for provider model identifiers. Accepts ISO and compact\n * dates, Router's `-MMDD` snapshots, one opaque `@token`, and Vertex-style\n * `:date-token` suffixes. Routing selectors such as `@preset/name` are not\n * immutable model identities.\n */\nexport function modelHasSnapshot(model: string): boolean {\n if (model.length === 0 || model.trim() !== model) return false\n\n const opaqueAt = model.lastIndexOf('@')\n if (opaqueAt > 0) {\n const base = model.slice(0, opaqueAt)\n const token = model.slice(opaqueAt + 1)\n if (!base.includes('@') && /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/u.test(token)) {\n return true\n }\n }\n\n const isoDate = model.match(/-(\\d{4})-(\\d{2})-(\\d{2})$/u)\n if (isoDate && validSnapshotDate(isoDate[1]!, isoDate[2]!, isoDate[3]!)) return true\n\n const compactDate = model.match(/-(\\d{4})(\\d{2})(\\d{2})$/u)\n if (compactDate && validSnapshotDate(compactDate[1]!, compactDate[2]!, compactDate[3]!)) {\n return true\n }\n\n const routerDate = model.match(/-(\\d{2})(\\d{2})$/u)\n if (routerDate && validSnapshotDate(undefined, routerDate[1]!, routerDate[2]!)) return true\n\n return /:date-[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/u.test(model)\n}\n\nfunction validSnapshotDate(year: string | undefined, month: string, day: string): boolean {\n const monthNumber = Number(month)\n const dayNumber = Number(day)\n if (!Number.isInteger(monthNumber) || monthNumber < 1 || monthNumber > 12) return false\n\n const yearNumber = year === undefined ? undefined : Number(year)\n const leapYear =\n yearNumber === undefined ||\n (yearNumber % 4 === 0 && (yearNumber % 100 !== 0 || yearNumber % 400 === 0))\n const daysInMonth = [31, leapYear ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n return Number.isInteger(dayNumber) && dayNumber >= 1 && dayNumber <= daysInMonth[monthNumber - 1]!\n}\n"],"mappings":";;;;;;AAiDA,MAAa,gBAAgB;;;;;;;;;AAu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IAAK,YAAY,EAAG,GACpF,OAAO;CAGT,MAAM,aAAa,MAAM,MAAM,mBAAmB;CAClD,IAAI,cAAc,kBAAkB,KAAA,GAAW,WAAW,IAAK,WAAW,EAAG,GAAG,OAAO;CAEvF,OAAO,qDAAqD,KAAK,KAAK;AACxE;AAEA,SAAS,kBAAkB,MAA0B,OAAe,KAAsB;CACxF,MAAM,cAAc,OAAO,KAAK;CAChC,MAAM,YAAY,OAAO,GAAG;CAC5B,IAAI,CAAC,OAAO,UAAU,WAAW,KAAK,cAAc,KAAK,cAAc,IAAI,OAAO;CAElF,MAAM,aAAa,SAAS,KAAA,IAAY,KAAA,IAAY,OAAO,IAAI;CAI/D,MAAM,cAAc;EAAC;EAFnB,eAAe,KAAA,KACd,aAAa,MAAM,MAAM,aAAa,QAAQ,KAAK,aAAa,QAAQ,KACvC,KAAK;EAAI;EAAI;EAAI;EAAI;EAAI;EAAI;EAAI;EAAI;EAAI;EAAI;CAAE;CACnF,OAAO,OAAO,UAAU,SAAS,KAAK,aAAa,KAAK,aAAa,YAAY,cAAc;AACjG"}
|
|
1
|
+
{"version":3,"file":"run-record-ZIsR9Fif.js","names":[],"sources":["../src/run-record.ts"],"sourcesContent":["/**\n * Paper-grade RunRecord schema + runtime validator.\n *\n * Every run that participates in a promotion gate, paper table, or\n * researcher loop SHOULD be recorded as a `RunRecord`. The mandatory\n * fields are exactly those the paper \"Two Loops, Three Roles\" requires\n * for reproducibility: who/what/when/cost/seed/hash, plus the search vs\n * holdout split tag. A task score is optional because execution-only records\n * must preserve missing labels instead of converting errors into zero quality.\n *\n * This is intentionally NOT a replacement for the rich `Run` /\n * `ProposeReviewReport` / `ScenarioResult` types already in the\n * package. Those are runtime structures with full provenance. A\n * `RunRecord` is the analysis-time projection — the JSON-friendly\n * row you'd put in a parquet file or paste into a notebook.\n *\n * Validate at the boundary:\n *\n * const rec = validateRunRecord(rawJson) // throws on missing\n * const ok = isRunRecord(rawJson) // boolean check\n * const rec = parseRunRecordSafe(rawJson) // { ok, value | error }\n *\n * The validator runs in pure TS — zod is intentionally NOT a\n * dependency. Round-trip tested in `tests/run-record.test.ts`.\n */\n\nimport type { AgentProfileCell } from './agent-profile-cell'\nimport { validateAgentProfileCell } from './agent-profile-cell'\nimport type { CostProvenance } from './cost-ledger'\nimport { ValidationError } from './errors'\n// Value import of a leaf module that itself imports only this file's TYPES —\n// no runtime cycle. It keeps the raw split-score derivation spelled in exactly\n// one place (see `rollout/score-derivation-guard`).\nimport { observedScore } from './rollout/reward'\nimport { FAILURE_CLASSES, type FailureClass } from './trace/schema'\n\n/** Search/dev/holdout split tag. 'search' is the paper-grade alias for the\n * combined train+test pool that the optimizer is allowed to read. */\nexport type RunSplitTag = 'search' | 'dev' | 'holdout'\n\n/**\n * Explicit execution-lifecycle result for a run.\n *\n * This is separate from task quality (`outcome`) and failure classification.\n * Producers set it only from root-run or process evidence.\n */\nexport type RunTerminalOutcome = 'succeeded' | 'failed' | 'cancelled' | 'incomplete' | 'unknown'\n\n/** Explicit model value for a row that never produced a served model snapshot. */\nexport const UNKNOWN_MODEL = 'unknown'\n\nexport interface RunTokenUsage {\n input: number\n /** All generated tokens charged as output, including reasoning tokens. */\n output: number\n /** Present only when one or more paid calls did not report token usage.\n * In that case, every numeric field is a known subtotal, not a measured total. */\n tokensKnown?: false\n /** Reasoning-token subset of `output`, when the provider reports it. */\n reasoning?: number\n /** Prompt tokens served from a provider cache. */\n cached?: number\n /** Prompt tokens written into a provider cache. */\n cacheWrite?: number\n}\n\n/** How a run's USD amount was obtained. */\nexport type RunCostProvenance = CostProvenance\n\nexport interface RunJudgeMetadata {\n model: string\n promptVersion: string\n /** [0,1] confidence the judge declared. Constant judge confidence\n * across many runs is a fallback signal (see `canary.ts`). */\n confidence: number\n /** True if the judge degraded to a fallback path (rules-only,\n * prior-call cache, etc.). The canary uses this to alert. */\n fallback: boolean\n}\n\n/**\n * Per-judge / per-dimension breakdown for runs scored by an ensemble of\n * judges over a multi-dimensional rubric.\n *\n * The collapsed `outcome.searchScore` / `holdoutScore` carries the\n * composite the gate uses. The full breakdown belongs here so consumers\n * can answer \"which judge disagreed?\", \"which dimension dragged the\n * composite down?\", and \"did half the panel fail?\" without re-running.\n *\n * `perJudge[judgeId][dim]` is the canonical source; `perDimMean` and\n * `composite` are convenience projections — derivable but precomputed so\n * downstream IRR primitives (`interRaterReliability`,\n * `corpusInterRaterAgreement`) and reporters don't pay the same\n * aggregation twice.\n *\n * Fail-loud discipline: judges that errored out land in `failedJudges`\n * by id. A missing key in `perJudge` is ambiguous (silent zero vs not\n * run); the explicit list makes a partial-failure recorded as such.\n */\nexport interface JudgeScoresRecord {\n /** Per-judge per-dimension scores. `{ \"kimi-k2.6\": { helpfulness: 0.8, clarity: 0.7 }, ... }`. */\n perJudge: Record<string, Record<string, number>>\n /** Per-dim mean across judges. Convenience — derivable from `perJudge`. */\n perDimMean: Record<string, number>\n /** Composite mean across successful judges. Mirrors the task score only\n * when `failedJudges` is empty. */\n composite: number\n /** Judges that errored or returned an unparseable verdict. Recorded\n * by id (e.g. `['glm-5.1']`) so a partial-failure case is explicit,\n * not inferred from missing keys in `perJudge`. */\n failedJudges?: string[]\n /** Free-form notes the judges emitted (joined across judges or\n * first-judge only — consumer's choice). */\n notes?: string\n}\n\nexport interface RunOutcome {\n /** Score on the search/optimization split. Optional for holdout-only and\n * execution-only records. */\n searchScore?: number\n /** Score on the held-out split. Optional for search-only and execution-only\n * records. When both scores are absent, the run is explicitly unlabeled. */\n holdoutScore?: number\n /** Bag of any other metric the run produced — judge dimensions,\n * pass/fail counters, latency stats, etc. Numeric only — keeps\n * reporters honest. */\n raw: Record<string, number>\n /** Per-judge / per-dim breakdown. Consumers writing ensemble\n * judgements populate this; substrate primitives like\n * `interRaterReliability` and `corpusInterRaterAgreement` accept\n * these records as input. Optional — single-judge or scalar-only\n * runs leave it unset. */\n judgeScores?: JudgeScoresRecord\n /** Authenticity / realness verdict — did the run build the REAL thing on the\n * intended infra, or fake it (see `./authenticity`)? Optional: only domains\n * with an authenticity config populate it. Carried in the corpus so the\n * flywheel / off-policy learning can optimize for real completion, not gamed\n * pass-rate. `score` is 0-1; `gated` is the anti-Goodhart flag — a gated run\n * must not count as a real success regardless of `score`. */\n realness?: { score: number; gated: boolean; reason?: string }\n}\n\n/**\n * Mandatory paper-grade fields for a single evaluation run. Optional\n * fields are extension points; mandatory fields throw if missing.\n *\n * Hash discipline:\n * - `promptHash` is the sha256 of the EFFECTIVE prompt sent to the\n * model (after any steering bundle merge).\n * - `configHash` is the sha256 of the effective run config (model,\n * temperature, tools, judges, splits). The pair (promptHash,\n * configHash) uniquely identifies an experiment cell.\n *\n * Model snapshot discipline:\n * - successful rows MUST encode a snapshot version. Bare aliases like\n * `claude-sonnet-4` or `gpt-4o` are banned — they remap silently.\n * Use `claude-sonnet-4-6@2025-04-15` or `gpt-4o-2024-11-20`.\n * - a failed, cancelled, incomplete, or otherwise unknown row may use\n * `UNKNOWN_MODEL` when no served model was observed. This is an explicit\n * absence marker, not a fabricated snapshot.\n */\nexport interface RunRecord {\n /** UUID for the run. */\n runId: string\n /** Logical experiment grouping (a treatment vs a baseline within\n * the same sweep should share `experimentId`). */\n experimentId: string\n /** Stable identifier for the candidate (variant) being run. The\n * promotion gate compares two `candidateId`s on matched items. */\n candidateId: string\n /** RNG seed for the run. Always recorded — silent re-seeding is\n * the most common cause of non-reproducible numbers. */\n seed: number\n /** Model identifier WITH snapshot version. */\n model: string\n /** sha256 of the effective prompt (post-steering). */\n promptHash: string\n /** sha256 of the effective config. */\n configHash: string\n /** Git SHA the harness was run from. */\n commitSha: string\n /** End-to-end wall-clock duration in milliseconds. */\n wallMs: number\n /** Time spent queued before execution started, if known. */\n queueMs?: number\n /** Total USD cost, or null when the producer could not capture one. */\n costUsd: number | null\n /** Whether `costUsd` came from billing data, a price calculation, or is unavailable. */\n costProvenance: RunCostProvenance\n /** Token usage breakdown. */\n tokenUsage: RunTokenUsage\n /** Root-run or process terminal result. Never inferred from a child span. */\n terminalOutcome: RunTerminalOutcome\n /** Root-run or process failure reason. Valid only for a failed, cancelled,\n * or incomplete terminal result; never populated from a child span. */\n terminalFailureReason?: string\n /** Judge-side metadata, if a judge was used. */\n judgeMetadata?: RunJudgeMetadata\n /** Per-split scores + raw bag. */\n outcome: RunOutcome\n /** Canonical task-failure class drawn from the shared\n * `FAILURE_CLASSES` taxonomy. Producers set it only from task-result\n * evidence. Execution errors belong in\n * `outcome.raw.execution_error_count`. */\n failureClass?: FailureClass\n /** Free-form task-failure detail scoped under a non-success\n * `failureClass`. It is invalid without that class. */\n failureMode?: string\n /** Which split this run was drawn from. */\n splitTag: RunSplitTag\n /**\n * Stable scenario identifier the run observed or was scored against.\n * Comparison primitives match this identity rather than input order.\n */\n scenarioId: string\n /**\n * Canonical identity for the agent profile cell that produced this row:\n * profile artifact hash plus optional harness/model/prompt/reporting\n * dimensions. Use `agentProfile.cellId` to group persona sweeps and\n * longitudinal reports by the complete source profile, not by a loose\n * candidate label or opaque config hash.\n */\n agentProfile?: AgentProfileCell\n}\n\n/**\n * Canonical task-result classification.\n *\n * A producer may omit classification, record explicit success, or attach\n * domain-specific detail to a non-success class. Detail can never stand alone.\n * Execution errors belong in `outcome.raw.execution_error_count`.\n */\nexport type RunTaskFailure =\n | { failureClass?: undefined; failureMode?: undefined }\n | { failureClass: 'success'; failureMode?: undefined }\n | {\n failureClass: Exclude<FailureClass, 'success'>\n failureMode?: string\n }\n\n/**\n * Return task quality, preferring held-out evidence when both scores exist.\n *\n * RAW: no realness protection is applied. Built on `observedScore` rather\n * than repeating the split derivation, so only `rollout/reward.ts` reads the\n * raw fields. Anything that becomes training data must use `trainingScore` or\n * `trainingReward` instead.\n */\nexport function runTaskScore(record: RunRecord): number | undefined {\n const score = observedScore(record)\n return typeof score === 'number' && Number.isFinite(score) ? score : undefined\n}\n\n// ── Validation ───────────────────────────────────────────────────────\n\nconst MANDATORY_TOP_LEVEL = [\n 'runId',\n 'experimentId',\n 'candidateId',\n 'seed',\n 'model',\n 'promptHash',\n 'configHash',\n 'commitSha',\n 'wallMs',\n 'costUsd',\n 'costProvenance',\n 'tokenUsage',\n 'terminalOutcome',\n 'outcome',\n 'splitTag',\n 'scenarioId',\n] as const\n\nconst SPLIT_TAGS: ReadonlyArray<RunSplitTag> = ['search', 'dev', 'holdout']\nconst TERMINAL_OUTCOMES: ReadonlyArray<RunTerminalOutcome> = [\n 'succeeded',\n 'failed',\n 'cancelled',\n 'incomplete',\n 'unknown',\n]\n\nexport class RunRecordValidationError extends ValidationError {\n readonly path: string\n constructor(message: string, path = '') {\n super(path ? `${message} (at ${path})` : message)\n this.path = path\n }\n}\n\n/**\n * Strict validator. Throws `RunRecordValidationError` on the first\n * missing or wrongly-typed field. Returns the input cast to\n * `RunRecord` on success — the validator does not coerce.\n */\nexport function validateRunRecord(input: unknown): RunRecord {\n if (input === null || typeof input !== 'object') {\n throw new RunRecordValidationError('expected object')\n }\n const obj = input as Record<string, unknown>\n\n for (const key of MANDATORY_TOP_LEVEL) {\n if (!(key in obj)) {\n throw new RunRecordValidationError(`missing mandatory field \"${key}\"`)\n }\n }\n\n expectString(obj.runId, 'runId')\n expectString(obj.experimentId, 'experimentId')\n expectString(obj.candidateId, 'candidateId')\n expectFiniteNumber(obj.seed, 'seed')\n expectString(obj.model, 'model')\n expectString(obj.promptHash, 'promptHash')\n expectString(obj.configHash, 'configHash')\n expectString(obj.commitSha, 'commitSha')\n expectNonNegativeNumber(obj.wallMs, 'wallMs')\n if (obj.queueMs !== undefined) expectNonNegativeNumber(obj.queueMs, 'queueMs')\n validateCost(obj.costUsd, obj.costProvenance)\n\n // Snapshot discipline: successful rows require a served model snapshot.\n // Non-success rows may carry the explicit absence marker when execution\n // stopped before a model identity was observed.\n if (\n !modelHasSnapshot(obj.model as string) &&\n !(obj.model === UNKNOWN_MODEL && obj.terminalOutcome !== 'succeeded')\n ) {\n throw new RunRecordValidationError(\n `model \"${obj.model}\" lacks a snapshot version (use 'name@YYYY-MM-DD' or 'name-YYYYMMDD', or '${UNKNOWN_MODEL}' for a non-success row without a served model)`,\n 'model',\n )\n }\n\n // Token usage.\n const tu = obj.tokenUsage\n if (tu === null || typeof tu !== 'object') {\n throw new RunRecordValidationError('tokenUsage must be an object', 'tokenUsage')\n }\n const tuRec = tu as Record<string, unknown>\n expectNonNegativeNumber(tuRec.input, 'tokenUsage.input')\n expectNonNegativeNumber(tuRec.output, 'tokenUsage.output')\n if (tuRec.tokensKnown !== undefined && tuRec.tokensKnown !== false) {\n throw new RunRecordValidationError(\n 'tokensKnown must be false when present; omit it when token usage is complete',\n 'tokenUsage.tokensKnown',\n )\n }\n if (tuRec.reasoning !== undefined) {\n expectNonNegativeNumber(tuRec.reasoning, 'tokenUsage.reasoning')\n if ((tuRec.reasoning as number) > (tuRec.output as number)) {\n throw new RunRecordValidationError(\n 'reasoning tokens must be a subset of output tokens',\n 'tokenUsage.reasoning',\n )\n }\n }\n if (tuRec.cached !== undefined) expectNonNegativeNumber(tuRec.cached, 'tokenUsage.cached')\n if (tuRec.cacheWrite !== undefined) {\n expectNonNegativeNumber(tuRec.cacheWrite, 'tokenUsage.cacheWrite')\n }\n\n // Judge metadata, optional.\n if (obj.judgeMetadata !== undefined) {\n const jm = obj.judgeMetadata\n if (jm === null || typeof jm !== 'object') {\n throw new RunRecordValidationError('judgeMetadata must be an object', 'judgeMetadata')\n }\n const jmRec = jm as Record<string, unknown>\n expectString(jmRec.model, 'judgeMetadata.model')\n expectString(jmRec.promptVersion, 'judgeMetadata.promptVersion')\n expectFiniteNumber(jmRec.confidence, 'judgeMetadata.confidence')\n if (typeof jmRec.fallback !== 'boolean') {\n throw new RunRecordValidationError(\n 'judgeMetadata.fallback must be boolean',\n 'judgeMetadata.fallback',\n )\n }\n }\n\n // Outcome.\n const out = obj.outcome\n if (out === null || typeof out !== 'object') {\n throw new RunRecordValidationError('outcome must be an object', 'outcome')\n }\n const outRec = out as Record<string, unknown>\n if (outRec.searchScore !== undefined)\n expectFiniteNumber(outRec.searchScore, 'outcome.searchScore')\n if (outRec.holdoutScore !== undefined)\n expectFiniteNumber(outRec.holdoutScore, 'outcome.holdoutScore')\n const raw = outRec.raw\n if (raw === null || typeof raw !== 'object') {\n throw new RunRecordValidationError('outcome.raw must be an object', 'outcome.raw')\n }\n for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {\n expectFiniteNumber(v, `outcome.raw.${k}`)\n }\n // Realness verdict, optional.\n if (outRec.realness !== undefined) {\n const r = outRec.realness\n if (r === null || typeof r !== 'object') {\n throw new RunRecordValidationError('outcome.realness must be an object', 'outcome.realness')\n }\n const rr = r as Record<string, unknown>\n expectFiniteNumber(rr.score, 'outcome.realness.score')\n if (typeof rr.gated !== 'boolean') {\n throw new RunRecordValidationError(\n 'outcome.realness.gated must be a boolean',\n 'outcome.realness.gated',\n )\n }\n }\n\n // Per-judge / per-dim breakdown, optional.\n if (outRec.judgeScores !== undefined) {\n validateJudgeScores(outRec.judgeScores, 'outcome.judgeScores')\n }\n\n // Failure mode optional.\n if (\n obj.failureClass !== undefined &&\n (typeof obj.failureClass !== 'string' ||\n !FAILURE_CLASSES.includes(obj.failureClass as FailureClass))\n ) {\n throw new RunRecordValidationError(\n `failureClass must be one of ${FAILURE_CLASSES.join(', ')}`,\n 'failureClass',\n )\n }\n if (obj.failureMode !== undefined) {\n expectString(obj.failureMode, 'failureMode')\n if (obj.failureClass === undefined || obj.failureClass === 'success') {\n throw new RunRecordValidationError(\n 'failureMode requires a non-success failureClass',\n 'failureMode',\n )\n }\n }\n\n if (\n typeof obj.terminalOutcome !== 'string' ||\n !TERMINAL_OUTCOMES.includes(obj.terminalOutcome as RunTerminalOutcome)\n ) {\n throw new RunRecordValidationError(\n `terminalOutcome must be one of ${TERMINAL_OUTCOMES.join(', ')}`,\n 'terminalOutcome',\n )\n }\n if (obj.terminalFailureReason !== undefined) {\n expectString(obj.terminalFailureReason, 'terminalFailureReason')\n if (\n obj.terminalOutcome !== 'failed' &&\n obj.terminalOutcome !== 'cancelled' &&\n obj.terminalOutcome !== 'incomplete'\n ) {\n throw new RunRecordValidationError(\n 'terminalFailureReason requires terminalOutcome failed, cancelled, or incomplete',\n 'terminalFailureReason',\n )\n }\n }\n\n if (obj.agentProfile !== undefined) {\n try {\n const profile = validateAgentProfileCell(obj.agentProfile)\n if (profile.model !== undefined && profile.model !== obj.model) {\n throw new RunRecordValidationError(\n `agentProfile.model \"${profile.model}\" does not match model \"${obj.model}\"`,\n 'agentProfile.model',\n )\n }\n if (profile.promptHash !== undefined && profile.promptHash !== obj.promptHash) {\n throw new RunRecordValidationError(\n `agentProfile.promptHash \"${profile.promptHash}\" does not match promptHash \"${obj.promptHash}\"`,\n 'agentProfile.promptHash',\n )\n }\n } catch (error) {\n if (error instanceof RunRecordValidationError) throw error\n if (error instanceof Error) {\n throw new RunRecordValidationError(error.message, 'agentProfile')\n }\n throw error\n }\n }\n\n expectString(obj.scenarioId, 'scenarioId')\n\n // Split tag.\n if (typeof obj.splitTag !== 'string' || !SPLIT_TAGS.includes(obj.splitTag as RunSplitTag)) {\n throw new RunRecordValidationError(\n `splitTag must be one of ${SPLIT_TAGS.join(', ')}, got ${String(obj.splitTag)}`,\n 'splitTag',\n )\n }\n\n return input as RunRecord\n}\n\nfunction validateCost(costUsd: unknown, provenance: unknown): void {\n if (provenance === null || typeof provenance !== 'object') {\n throw new RunRecordValidationError('costProvenance must be an object', 'costProvenance')\n }\n const value = provenance as Record<string, unknown>\n if (value.kind !== 'observed' && value.kind !== 'estimated' && value.kind !== 'uncaptured') {\n throw new RunRecordValidationError(\n 'costProvenance.kind must be observed, estimated, or uncaptured',\n 'costProvenance.kind',\n )\n }\n // A record must never read as a total it cannot support, so an uncaptured\n // cost carries no number at all. A matrix `CellResult` keeps its known\n // subtotal instead, because a cost ceiling must charge the part it can see;\n // converting one to the other drops that subtotal.\n if (value.kind === 'uncaptured') {\n if (value.usd !== null) {\n throw new RunRecordValidationError(\n 'uncaptured costProvenance.usd must be null',\n 'costProvenance.usd',\n )\n }\n if (costUsd !== null) {\n throw new RunRecordValidationError('uncaptured cost requires costUsd to be null', 'costUsd')\n }\n return\n }\n expectNonNegativeNumber(costUsd, 'costUsd')\n expectNonNegativeNumber(value.usd, 'costProvenance.usd')\n if (value.usd !== costUsd) {\n throw new RunRecordValidationError(\n 'costProvenance.usd must equal costUsd',\n 'costProvenance.usd',\n )\n }\n}\n\n/** Boolean validator — convenience for filtering arrays. */\nexport function isRunRecord(input: unknown): input is RunRecord {\n try {\n validateRunRecord(input)\n return true\n } catch {\n return false\n }\n}\n\n/** Non-throwing validator — returns a discriminated union. */\nexport function parseRunRecordSafe(\n input: unknown,\n): { ok: true; value: RunRecord } | { ok: false; error: RunRecordValidationError } {\n try {\n return { ok: true, value: validateRunRecord(input) }\n } catch (e) {\n if (e instanceof RunRecordValidationError) return { ok: false, error: e }\n throw e\n }\n}\n\n/** Round-trip helper — `JSON.parse(JSON.stringify(record))` then validate. */\nexport function roundTripRunRecord(record: RunRecord): RunRecord {\n const json = JSON.stringify(record)\n return validateRunRecord(JSON.parse(json))\n}\n\n// ── Internals ────────────────────────────────────────────────────────\n\nfunction expectString(value: unknown, path: string): void {\n if (typeof value !== 'string' || value.length === 0) {\n throw new RunRecordValidationError(`expected non-empty string`, path)\n }\n}\n\nfunction expectFiniteNumber(value: unknown, path: string): void {\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new RunRecordValidationError(`expected finite number`, path)\n }\n}\n\nfunction expectNonNegativeNumber(value: unknown, path: string): void {\n expectFiniteNumber(value, path)\n if ((value as number) < 0) {\n throw new RunRecordValidationError('expected non-negative number', path)\n }\n}\n\nfunction validateJudgeScores(value: unknown, path: string): void {\n if (value === null || typeof value !== 'object') {\n throw new RunRecordValidationError('judgeScores must be an object', path)\n }\n const rec = value as Record<string, unknown>\n\n const perJudge = rec.perJudge\n if (perJudge === null || typeof perJudge !== 'object') {\n throw new RunRecordValidationError('perJudge must be an object', `${path}.perJudge`)\n }\n for (const [judgeId, dims] of Object.entries(perJudge as Record<string, unknown>)) {\n if (dims === null || typeof dims !== 'object') {\n throw new RunRecordValidationError(\n 'per-judge entry must be an object of dimension scores',\n `${path}.perJudge.${judgeId}`,\n )\n }\n for (const [dim, score] of Object.entries(dims as Record<string, unknown>)) {\n expectFiniteNumber(score, `${path}.perJudge.${judgeId}.${dim}`)\n }\n }\n\n const perDimMean = rec.perDimMean\n if (perDimMean === null || typeof perDimMean !== 'object') {\n throw new RunRecordValidationError('perDimMean must be an object', `${path}.perDimMean`)\n }\n for (const [dim, mean] of Object.entries(perDimMean as Record<string, unknown>)) {\n expectFiniteNumber(mean, `${path}.perDimMean.${dim}`)\n }\n\n expectFiniteNumber(rec.composite, `${path}.composite`)\n\n if (rec.failedJudges !== undefined) {\n if (!Array.isArray(rec.failedJudges)) {\n throw new RunRecordValidationError(\n 'failedJudges must be an array of strings',\n `${path}.failedJudges`,\n )\n }\n for (let i = 0; i < rec.failedJudges.length; i++) {\n const id = rec.failedJudges[i]\n if (typeof id !== 'string' || id.length === 0) {\n throw new RunRecordValidationError(\n 'failedJudges entry must be a non-empty string',\n `${path}.failedJudges[${i}]`,\n )\n }\n }\n }\n\n if (rec.notes !== undefined && typeof rec.notes !== 'string') {\n throw new RunRecordValidationError('notes must be a string', `${path}.notes`)\n }\n}\n\n/**\n * Snapshot check for provider model identifiers. Accepts ISO and compact\n * dates, Router's `-MMDD` snapshots, one opaque `@token`, and Vertex-style\n * `:date-token` suffixes. Routing selectors such as `@preset/name` are not\n * immutable model identities.\n */\nexport function modelHasSnapshot(model: string): boolean {\n if (model.length === 0 || model.trim() !== model) return false\n\n const opaqueAt = model.lastIndexOf('@')\n if (opaqueAt > 0) {\n const base = model.slice(0, opaqueAt)\n const token = model.slice(opaqueAt + 1)\n if (!base.includes('@') && /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/u.test(token)) {\n return true\n }\n }\n\n const isoDate = model.match(/-(\\d{4})-(\\d{2})-(\\d{2})$/u)\n if (isoDate && validSnapshotDate(isoDate[1]!, isoDate[2]!, isoDate[3]!)) return true\n\n const compactDate = model.match(/-(\\d{4})(\\d{2})(\\d{2})$/u)\n if (compactDate && validSnapshotDate(compactDate[1]!, compactDate[2]!, compactDate[3]!)) {\n return true\n }\n\n const routerDate = model.match(/-(\\d{2})(\\d{2})$/u)\n if (routerDate && validSnapshotDate(undefined, routerDate[1]!, routerDate[2]!)) return true\n\n return /:date-[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/u.test(model)\n}\n\nfunction validSnapshotDate(year: string | undefined, month: string, day: string): boolean {\n const monthNumber = Number(month)\n const dayNumber = Number(day)\n if (!Number.isInteger(monthNumber) || monthNumber < 1 || monthNumber > 12) return false\n\n const yearNumber = year === undefined ? undefined : Number(year)\n const leapYear =\n yearNumber === undefined ||\n (yearNumber % 4 === 0 && (yearNumber % 100 !== 0 || yearNumber % 400 === 0))\n const daysInMonth = [31, leapYear ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n return Number.isInteger(dayNumber) && dayNumber >= 1 && dayNumber <= daysInMonth[monthNumber - 1]!\n}\n"],"mappings":";;;;;;AAiDA,MAAa,gBAAgB;;;;;;;;;AAuM7B,SAAgB,aAAa,QAAuC;CAClE,MAAM,QAAQ,cAAc,MAAM;CAClC,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ,KAAA;AACvE;AAIA,MAAM,sBAAsB;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,aAAyC;CAAC;CAAU;CAAO;AAAS;AAC1E,MAAM,oBAAuD;CAC3D;CACA;CACA;CACA;CACA;AACF;AAEA,IAAa,2BAAb,cAA8C,gBAAgB;CAC5D;CACA,YAAY,SAAiB,OAAO,IAAI;EACtC,MAAM,OAAO,GAAG,QAAQ,OAAO,KAAK,KAAK,OAAO;EAChD,KAAK,OAAO;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M,MAAM,aAAa,QAAQ,KAAK,aAAa,QAAQ,KACvC,KAAK;EAAI;EAAI;EAAI;EAAI;EAAI;EAAI;EAAI;EAAI;EAAI;EAAI;CAAE;CACnF,OAAO,OAAO,UAAU,SAAS,KAAK,aAAa,KAAK,aAAa,YAAY,cAAc;AACjG"}
|
|
@@ -197,12 +197,67 @@ interface Artifact {
|
|
|
197
197
|
/**
|
|
198
198
|
* The failure taxonomy. `FailureClass` derives from this array, so the type
|
|
199
199
|
* and the runtime list cannot name different sets.
|
|
200
|
+
*
|
|
201
|
+
* Two layers, and the split is what `FAILURE_BLAME` reads
|
|
202
|
+
* (`src/failure-taxonomy.ts`):
|
|
203
|
+
* - behaviour classes name what the agent did wrong, and a run that ends in
|
|
204
|
+
* one is evidence about the agent;
|
|
205
|
+
* - transport classes name a death before or around the model turn — the
|
|
206
|
+
* bridge refused, the box never provisioned, the stream tore — and a run
|
|
207
|
+
* that ends in one of the machine-blamed members is not evidence about the
|
|
208
|
+
* agent at all.
|
|
209
|
+
*
|
|
210
|
+
* The transport layer exists because a taxonomy with no name for "the run
|
|
211
|
+
* never reached a model" charges an infrastructure outage to the agent under
|
|
212
|
+
* test. Measured: six director cells settled with the runtime journal's own
|
|
213
|
+
* `infra` flag reading FALSE while the real reason was
|
|
214
|
+
* `host-executor: acquire timeout after 900000ms (in_flight=10/10)` — the
|
|
215
|
+
* bridge's host lane had saturated.
|
|
200
216
|
*/
|
|
201
|
-
declare const FAILURE_CLASSES: readonly ['success', 'reasoning_error', 'tool_selection_error', 'tool_argument_error', 'tool_recovery_failure', 'hallucination', 'instruction_following', 'safety_refusal_miss', 'policy_violation', 'budget_exceeded', 'format_drift', 'permission_escalation', 'pii_leak', 'cost_overrun', 'timeout', 'sandbox_failure', 'missing_user_data', 'missing_domain_data', 'missing_codebase_context', 'missing_runtime_context', 'missing_credentials', 'missing_integration_connection', 'missing_integration_scope', 'integration_approval_required', 'integration_auth_expired', 'integration_provider_failure', 'bad_integration_manifest', 'unsafe_integration_write_denied', 'stale_external_data', 'bad_retrieval', 'insufficient_evidence', 'contradictory_evidence', 'ambiguous_user_intent', 'knowledge_readiness_blocked',
|
|
217
|
+
declare const FAILURE_CLASSES: readonly ['success', 'reasoning_error', 'tool_selection_error', 'tool_argument_error', 'tool_recovery_failure', 'hallucination', 'instruction_following', 'safety_refusal_miss', 'policy_violation', 'budget_exceeded', 'format_drift', 'permission_escalation', 'pii_leak', 'cost_overrun', 'timeout', 'sandbox_failure', 'missing_user_data', 'missing_domain_data', 'missing_codebase_context', 'missing_runtime_context', 'missing_credentials', 'missing_integration_connection', 'missing_integration_scope', 'integration_approval_required', 'integration_auth_expired', 'integration_provider_failure', 'bad_integration_manifest', 'unsafe_integration_write_denied', 'stale_external_data', 'bad_retrieval', 'insufficient_evidence', 'contradictory_evidence', 'ambiguous_user_intent', 'knowledge_readiness_blocked',
|
|
218
|
+
/** The bridge refused the connection or dropped it before a terminal event. */
|
|
219
|
+
'bridge_unreachable',
|
|
220
|
+
/** The bridge accepted the request and its execution lane was already full. */
|
|
221
|
+
'bridge_lane_saturated',
|
|
222
|
+
/** The router could not reconcile a completion with its own recorded usage. */
|
|
223
|
+
'router_usage_mismatch',
|
|
224
|
+
/** A session was bound to one AgentProfile and asked to serve another. */
|
|
225
|
+
'session_profile_conflict',
|
|
226
|
+
/** The agent runtime restarted underneath a live run. */
|
|
227
|
+
'runtime_restart',
|
|
228
|
+
/** The root driver of a recursive run failed before it could dispatch work. */
|
|
229
|
+
'root_driver_failed',
|
|
230
|
+
/** A sandbox box never finished provisioning. Distinct from `sandbox_failure`,
|
|
231
|
+
* which is a command the agent ran exiting non-zero inside a live box. */
|
|
232
|
+
'box_provision_failure',
|
|
233
|
+
/** A sandbox box did not confirm destruction after the run. */
|
|
234
|
+
'box_teardown_failure',
|
|
235
|
+
/** The harness refused an agent-authored profile: an unknown model, a
|
|
236
|
+
* workspace file it may not overwrite, a system prompt it may not replace. */
|
|
237
|
+
'profile_refused',
|
|
238
|
+
/** The model was reached and returned no visible output. */
|
|
239
|
+
'empty_completion',
|
|
240
|
+
/** The response stream carried malformed protocol content. */
|
|
241
|
+
'stream_protocol_error',
|
|
242
|
+
/** The response stream ended before a terminal event. */
|
|
243
|
+
'stream_incomplete',
|
|
244
|
+
/** A message was appended to a conversation the provider had already sealed. */
|
|
245
|
+
'message_sealed',
|
|
246
|
+
/** The model process was killed by a signal or exited with no code. */
|
|
247
|
+
'process_killed',
|
|
248
|
+
/** The run was cancelled by an operator. */
|
|
249
|
+
'cancelled',
|
|
250
|
+
/** The run was terminated without a more specific reason. */
|
|
251
|
+
'terminated',
|
|
252
|
+
/** The agent exhausted its traversal or iteration cap. */
|
|
253
|
+
'traversal_cap_exhausted',
|
|
254
|
+
/** No reason was recorded at all. Distinct from `unknown`, which means a
|
|
255
|
+
* reason exists and no rule matched it. */
|
|
256
|
+
'unreported', 'unknown'];
|
|
202
257
|
type FailureClass = (typeof FAILURE_CLASSES)[number];
|
|
203
258
|
declare function isLlmSpan(s: Span): s is LlmSpan;
|
|
204
259
|
declare function isToolSpan(s: Span): s is ToolSpan;
|
|
205
260
|
declare function isJudgeSpan(s: Span): s is JudgeSpan;
|
|
206
261
|
//#endregion
|
|
207
262
|
export { TraceEvent as C, isToolSpan as E, ToolSpan as S, isLlmSpan as T, Span as _, FAILURE_CLASSES as a, SpanStatus as b, JudgeSpan as c, RetrievalSpan as d, Run as f, SandboxSpan as g, RunStatus as h, EventKind as i, LlmSpan as l, RunOutcome as m, BudgetLedgerEntry as n, FailureClass as o, RunLayer as p, BudgetSpec as r, GenericSpan as s, Artifact as t, Message as u, SpanBase as v, isJudgeSpan as w, TRACE_SCHEMA_VERSION as x, SpanKind as y };
|
|
208
|
-
//# sourceMappingURL=schema-
|
|
263
|
+
//# sourceMappingURL=schema-CR5cpjQ3.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema-
|
|
1
|
+
{"version":3,"file":"schema-CR5cpjQ3.d.ts","names":[],"sources":["../src/trace/schema.ts"],"mappings":";;;;;;;;;;;;cAYa;KAID;UAEK;EACf;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA,eAAe;EACf;;;;;;;;;KAUU;UAEK;EACf;;;;;;;;;;;EAWA;EACA;EACA;;EAEA;;EAEA;;EAEA;EACA;;EAEA,iBAAiB;;EAEjB;;;EAGA;;EAEA;;EAEA;;EAEA,QAAQ;EACR;EACA;EACA,QAAQ;EACR,UAAU;EACV,SAAS;;EAET,OAAO;;KAKG;KAEA;UAEK;EACf;EACA;EACA;EACA,MAAM;EACN;EACA;EACA;EACA,SAAS;EACT;;EAEA,aAAa;;UAGE;EACf;EACA;EACA;;EAEA,SAAS;IAAQ;IAAqB;IAAc;;;UAGrC,gBAAgB;EAC/B;EACA;EACA,UAAU;EACV;EACA;;EAEA;EACA;EACA;;EAEA;EACA;EACA;;UAGe,iBAAiB;EAChC;EACA;EACA;;EAEA;EACA;EACA;;UAGe,sBAAsB;EACrC;EACA;EACA,MAAM;IAAQ;IAAe;IAAe;;;UAG7B,kBAAkB;EACjC;EACA;;EAEA;EACA;;EAEA;EACA;EACA;;UAGe,oBAAoB;EACnC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA;;UAGe,oBAAoB;EACnC;;KAGU,OAAO,UAAU,WAAW,gBAAgB,YAAY,cAAc;KAItE;UAUK;EACf;EACA;EACA;EACA,MAAM;EACN;EACA,SAAS;;UAKM;EACf;EACA,iBAAiB;EACjB;EACA;EACA;EACA;EACA;;EAEA;;UAKe;EACf;EACA;EACA;EACA;EACA;;EAEA;;EAEA;;EAEA;;;;;;;;;;;;;;;;;;;;;;cAyBW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAgFD,uBAAuB;iBAInB,UAAU,GAAG,OAAO,KAAK;iBAGzB,WAAW,GAAG,OAAO,KAAK;iBAG1B,YAAY,GAAG,OAAO,KAAK"}
|