@tangle-network/agent-eval 0.138.0 → 0.139.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +2 -1
  3. package/dist/analyst/index.d.ts +41 -94
  4. package/dist/analyst/index.d.ts.map +1 -1
  5. package/dist/analyst/index.js +9 -24
  6. package/dist/analyst/index.js.map +1 -1
  7. package/dist/{benchmark-D8dkki-J.js → benchmark-CYtcIF2V.js} +2 -2
  8. package/dist/{benchmark-D8dkki-J.js.map → benchmark-CYtcIF2V.js.map} +1 -1
  9. package/dist/{benchmark-DlQgU_XI.d.ts → benchmark-DDVdWcwA.d.ts} +3 -3
  10. package/dist/{benchmark-DlQgU_XI.d.ts.map → benchmark-DDVdWcwA.d.ts.map} +1 -1
  11. package/dist/{benchmark-command-CMqVqReF.js → benchmark-command-BKfjOBJ5.js} +243 -38
  12. package/dist/benchmark-command-BKfjOBJ5.js.map +1 -0
  13. package/dist/benchmarks/index.d.ts +1 -1
  14. package/dist/benchmarks/index.js +1 -1
  15. package/dist/{benchmarks-BJ_xK5rQ.js → benchmarks-zxhy1QV3.js} +4 -4
  16. package/dist/{benchmarks-BJ_xK5rQ.js.map → benchmarks-zxhy1QV3.js.map} +1 -1
  17. package/dist/campaign/index.d.ts +5 -5
  18. package/dist/campaign/index.js +4 -3
  19. package/dist/{campaign-BIBS-NHV.js → campaign-DrS6_hLd.js} +10 -9
  20. package/dist/campaign-DrS6_hLd.js.map +1 -0
  21. package/dist/canonical-D011XM8r.js +86 -0
  22. package/dist/canonical-D011XM8r.js.map +1 -0
  23. package/dist/cli.js +3 -3
  24. package/dist/{client-BwPKohkJ.d.ts → client-BohnDFBq.d.ts} +4 -4
  25. package/dist/{client-BwPKohkJ.d.ts.map → client-BohnDFBq.d.ts.map} +1 -1
  26. package/dist/{completion-verifier-B4-IMYcS.d.ts → completion-verifier-IPoP4fQO.d.ts} +178 -4
  27. package/dist/completion-verifier-IPoP4fQO.d.ts.map +1 -0
  28. package/dist/contract/index.d.ts +10 -10
  29. package/dist/contract/index.js +8 -7
  30. package/dist/contract/index.js.map +1 -1
  31. package/dist/control.d.ts +2 -2
  32. package/dist/{cost-ledger-CHDLA0Ss.js → cost-ledger-CZ9diLxY.js} +7 -7
  33. package/dist/cost-ledger-CZ9diLxY.js.map +1 -0
  34. package/dist/{cost-ledger-B1D3COAc.d.ts → cost-ledger-DKgyIWRj.d.ts} +5 -2
  35. package/dist/cost-ledger-DKgyIWRj.d.ts.map +1 -0
  36. package/dist/default-registry-B8vf7Rmf.d.ts +118 -0
  37. package/dist/default-registry-B8vf7Rmf.d.ts.map +1 -0
  38. package/dist/{default-registry-lp5R0lve.js → default-registry-BgJJItGr.js} +57 -1532
  39. package/dist/default-registry-BgJJItGr.js.map +1 -0
  40. package/dist/dspy-rlm-engine-DTkVyDX-.js +344 -0
  41. package/dist/dspy-rlm-engine-DTkVyDX-.js.map +1 -0
  42. package/dist/{eval-campaign-9MozgKL7.js → eval-campaign-BmptJj50.js} +2 -2
  43. package/dist/{eval-campaign-9MozgKL7.js.map → eval-campaign-BmptJj50.js.map} +1 -1
  44. package/dist/{exact-types-Dpw2LeHA.d.ts → exact-types-MaaFcllV.d.ts} +2 -2
  45. package/dist/{exact-types-Dpw2LeHA.d.ts.map → exact-types-MaaFcllV.d.ts.map} +1 -1
  46. package/dist/external-optimizer-contracts-BrxY2Sli.d.ts +32 -0
  47. package/dist/external-optimizer-contracts-BrxY2Sli.d.ts.map +1 -0
  48. package/dist/{extract-usage-CS391dOE.js → extract-usage-DZs601Va.js} +2 -2
  49. package/dist/{extract-usage-CS391dOE.js.map → extract-usage-DZs601Va.js.map} +1 -1
  50. package/dist/{feedback-trajectory-CoNep7rl.d.ts → feedback-trajectory-BJUWOkJM.d.ts} +3 -3
  51. package/dist/{feedback-trajectory-CoNep7rl.d.ts.map → feedback-trajectory-BJUWOkJM.d.ts.map} +1 -1
  52. package/dist/fuzz.d.ts +1 -1
  53. package/dist/fuzz.js +1 -1
  54. package/dist/{hf-dataset-DBJXXoY1.js → hf-dataset-XggBupCr.js} +2 -2
  55. package/dist/{hf-dataset-DBJXXoY1.js.map → hf-dataset-XggBupCr.js.map} +1 -1
  56. package/dist/hosted/index.d.ts +3 -3
  57. package/dist/{index-D0cxAdaV.d.ts → index-BTm_P9aC.d.ts} +11 -11
  58. package/dist/{index-D0cxAdaV.d.ts.map → index-BTm_P9aC.d.ts.map} +1 -1
  59. package/dist/{index-B2-IxCMB.d.ts → index-CWOPCJiw.d.ts} +2 -2
  60. package/dist/{index-B2-IxCMB.d.ts.map → index-CWOPCJiw.d.ts.map} +1 -1
  61. package/dist/{index-sMN_hI4E.d.ts → index-CtR1xh4V.d.ts} +3 -3
  62. package/dist/{index-sMN_hI4E.d.ts.map → index-CtR1xh4V.d.ts.map} +1 -1
  63. package/dist/{index-CjVYlVBK.d.ts → index-_66rVpwN.d.ts} +5 -5
  64. package/dist/{index-CjVYlVBK.d.ts.map → index-_66rVpwN.d.ts.map} +1 -1
  65. package/dist/index.d.ts +35 -56
  66. package/dist/index.d.ts.map +1 -1
  67. package/dist/index.js +51 -176
  68. package/dist/index.js.map +1 -1
  69. package/dist/{insight-report-CXd8VBDR.d.ts → insight-report-Bu5Wi9tG.d.ts} +4 -4
  70. package/dist/{insight-report-CXd8VBDR.d.ts.map → insight-report-Bu5Wi9tG.d.ts.map} +1 -1
  71. package/dist/{integrity-B-MLFz0I.d.ts → integrity-COTh3DTH.d.ts} +2 -2
  72. package/dist/{integrity-B-MLFz0I.d.ts.map → integrity-COTh3DTH.d.ts.map} +1 -1
  73. package/dist/kind-factory-CFxA0JQX.js +2133 -0
  74. package/dist/kind-factory-CFxA0JQX.js.map +1 -0
  75. package/dist/ledger-core/index.js +2 -1
  76. package/dist/{ledger-core-C0Yx1I14.js → ledger-core-Dxz0Rkwa.js} +3 -85
  77. package/dist/ledger-core-Dxz0Rkwa.js.map +1 -0
  78. package/dist/{llm-client-Cj3c7PEm.js → llm-client-bkztEfIx.js} +2 -2
  79. package/dist/{llm-client-Cj3c7PEm.js.map → llm-client-bkztEfIx.js.map} +1 -1
  80. package/dist/meta-eval/index.d.ts +2 -2
  81. package/dist/multishot/index.d.ts +2 -2
  82. package/dist/openapi.json +1 -1
  83. package/dist/{release-report-CoyvyLBs.d.ts → release-report-fZarvIm-.d.ts} +3 -3
  84. package/dist/{release-report-CoyvyLBs.d.ts.map → release-report-fZarvIm-.d.ts.map} +1 -1
  85. package/dist/{replay-DbIYwso6.d.ts → replay-DjG4IG60.d.ts} +34 -143
  86. package/dist/replay-DjG4IG60.d.ts.map +1 -0
  87. package/dist/{replay-Cb-4Vf0k.js → replay-SA4OB7O7.js} +48 -137
  88. package/dist/replay-SA4OB7O7.js.map +1 -0
  89. package/dist/reporting.d.ts +4 -4
  90. package/dist/{researcher-BCeOEjtR.d.ts → researcher-BxhtGfKa.d.ts} +5 -5
  91. package/dist/{researcher-BCeOEjtR.d.ts.map → researcher-BxhtGfKa.d.ts.map} +1 -1
  92. package/dist/{reward-hacking-sE2l_NV6.d.ts → reward-hacking-CqSLiV51.d.ts} +2 -2
  93. package/dist/{reward-hacking-sE2l_NV6.d.ts.map → reward-hacking-CqSLiV51.d.ts.map} +1 -1
  94. package/dist/rl.d.ts +5 -5
  95. package/dist/rl.js +1 -1
  96. package/dist/rollout/index.d.ts +1 -1
  97. package/dist/rollout/index.js +2 -2
  98. package/dist/{rollout-DQFl0UXA.js → rollout-8nj3mYvx.js} +2 -2
  99. package/dist/{rollout-DQFl0UXA.js.map → rollout-8nj3mYvx.js.map} +1 -1
  100. package/dist/{rubric-predictive-validity-w2klGv1u.d.ts → rubric-predictive-validity-DQBQj6uV.d.ts} +2 -2
  101. package/dist/{rubric-predictive-validity-w2klGv1u.d.ts.map → rubric-predictive-validity-DQBQj6uV.d.ts.map} +1 -1
  102. package/dist/{run-evidence-CbE0A8Xg.d.ts → run-evidence-C4RcRQT5.d.ts} +3 -3
  103. package/dist/{run-evidence-CbE0A8Xg.d.ts.map → run-evidence-C4RcRQT5.d.ts.map} +1 -1
  104. package/dist/{run-record-DwHMk1Ai.d.ts → run-record-CztDMXVF.d.ts} +2 -2
  105. package/dist/{run-record-DwHMk1Ai.d.ts.map → run-record-CztDMXVF.d.ts.map} +1 -1
  106. package/dist/{semantic-concept-judge-DYXDPZW0.js → semantic-concept-judge-BuIJ9IfB.js} +43 -6
  107. package/dist/semantic-concept-judge-BuIJ9IfB.js.map +1 -0
  108. package/dist/{server-DLEvyW2z.js → server-DaCpLfi0.js} +3 -3
  109. package/dist/{server-DLEvyW2z.js.map → server-DaCpLfi0.js.map} +1 -1
  110. package/dist/single-run-lock-BTTtPZ9N.js +989 -0
  111. package/dist/single-run-lock-BTTtPZ9N.js.map +1 -0
  112. package/dist/{skill-usage-Bv3G4VkA.d.ts → skill-usage-B-BFS8M2.d.ts} +54 -39
  113. package/dist/skill-usage-B-BFS8M2.d.ts.map +1 -0
  114. package/dist/{skillopt-optimization-method-CjKMZy0d.js → skillopt-optimization-method-BbGnCC53.js} +18 -802
  115. package/dist/skillopt-optimization-method-BbGnCC53.js.map +1 -0
  116. package/dist/{skillopt-optimization-method-CzfnA8O-.d.ts → skillopt-optimization-method-_s0Tub7Y.d.ts} +11 -39
  117. package/dist/skillopt-optimization-method-_s0Tub7Y.d.ts.map +1 -0
  118. package/dist/{statistics-mf70aXKp.d.ts → statistics-B5d0Zd-z.d.ts} +2 -2
  119. package/dist/{statistics-mf70aXKp.d.ts.map → statistics-B5d0Zd-z.d.ts.map} +1 -1
  120. package/dist/store-otlp-DX4fGIcf.js +757 -0
  121. package/dist/store-otlp-DX4fGIcf.js.map +1 -0
  122. package/dist/{summary-report-BKinV4yD.d.ts → summary-report-Cg7BifAM.d.ts} +3 -3
  123. package/dist/{summary-report-BKinV4yD.d.ts.map → summary-report-Cg7BifAM.d.ts.map} +1 -1
  124. package/dist/tool-groups-CdYq22lX.d.ts +258 -0
  125. package/dist/tool-groups-CdYq22lX.d.ts.map +1 -0
  126. package/dist/traces.d.ts +7 -6
  127. package/dist/traces.js +5 -5
  128. package/dist/{types-zFYez3PK.d.ts → types-BBFNHxSK.d.ts} +5 -5
  129. package/dist/{types-zFYez3PK.d.ts.map → types-BBFNHxSK.d.ts.map} +1 -1
  130. package/dist/{types-BtJhn8v6.d.ts → types-DoEYskCd.d.ts} +5 -5
  131. package/dist/{types-BtJhn8v6.d.ts.map → types-DoEYskCd.d.ts.map} +1 -1
  132. package/dist/{types-5q2T25iW.d.ts → types-uPrS6mD-.d.ts} +2 -2
  133. package/dist/{types-5q2T25iW.d.ts.map → types-uPrS6mD-.d.ts.map} +1 -1
  134. package/dist/usage-receipt-CgxMEBZq.js +134 -0
  135. package/dist/usage-receipt-CgxMEBZq.js.map +1 -0
  136. package/dist/wire/index.d.ts +3 -3
  137. package/dist/wire/index.js +1 -1
  138. package/docs/trace-analysis.md +170 -484
  139. package/package.json +1 -2
  140. package/dist/analyze-runs-CPYxfPWT.d.ts +0 -72
  141. package/dist/analyze-runs-CPYxfPWT.d.ts.map +0 -1
  142. package/dist/benchmark-command-CMqVqReF.js.map +0 -1
  143. package/dist/campaign-BIBS-NHV.js.map +0 -1
  144. package/dist/completion-verifier-B4-IMYcS.d.ts.map +0 -1
  145. package/dist/cost-ledger-B1D3COAc.d.ts.map +0 -1
  146. package/dist/cost-ledger-CHDLA0Ss.js.map +0 -1
  147. package/dist/default-registry-PUhIVRWz.d.ts +0 -215
  148. package/dist/default-registry-PUhIVRWz.d.ts.map +0 -1
  149. package/dist/default-registry-lp5R0lve.js.map +0 -1
  150. package/dist/ledger-core-C0Yx1I14.js.map +0 -1
  151. package/dist/registry-C4yJTza7.d.ts +0 -178
  152. package/dist/registry-C4yJTza7.d.ts.map +0 -1
  153. package/dist/replay-Cb-4Vf0k.js.map +0 -1
  154. package/dist/replay-DbIYwso6.d.ts.map +0 -1
  155. package/dist/semantic-concept-judge-DYXDPZW0.js.map +0 -1
  156. package/dist/single-run-lock-D_bS5xhj.js +0 -318
  157. package/dist/single-run-lock-D_bS5xhj.js.map +0 -1
  158. package/dist/skill-usage-Bv3G4VkA.d.ts.map +0 -1
  159. package/dist/skillopt-optimization-method-CjKMZy0d.js.map +0 -1
  160. package/dist/skillopt-optimization-method-CzfnA8O-.d.ts.map +0 -1
  161. package/dist/store-otlp-BenKynPE.js +0 -1688
  162. package/dist/store-otlp-BenKynPE.js.map +0 -1
  163. package/dist/tools-DZGdROtG.js +0 -255
  164. package/dist/tools-DZGdROtG.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"rollout-DQFl0UXA.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,MAAM,YAAY,OAAO,SAAS,CAAC,IAAI,IAAI;AAEpD,M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nj3mYvx.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,MAAM,YAAY,OAAO,SAAS,CAAC,IAAI,IAAI;AAEpD,MAAM,wBAAwB,MAC5B,OAAO,UAAU,CAAC,IAAK,IAAe,KAAA;AAExC,MAAM,iBAAiB,MACrB,MAAM,QAAQ,CAAC,KAAK,EAAE,OAAO,MAAM,OAAO,MAAM,YAAY,OAAO,SAAS,CAAC,CAAC,IACzE,IACD,KAAA;AAEN,MAAM,kBAAkB,MACtB,MAAM,QAAQ,CAAC,KAAK,EAAE,OAAO,MAAM,OAAO,UAAU,CAAC,CAAC,IAAK,IAAiB,KAAA;;;;;;;;;AAU9E,SAAS,qBAAqB,OAQd;CACd,MAAM,UAAuB;EAAE,MAAM,MAAM;EAAM,SAAS,MA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kB,MAAM,8CAA8C,WAAW;CACjF,OAAO;AACT;;;;;;;;;;AAWA,SAAgB,qBACd,YACA,UAA6B,CAAC,GACf;CACf,MAAM,cAAc,QAAQ,MAAM,qBAAK,IAAI,KAAK,EAAA,CAAG,YAAY;CAC/D,MAAM,QAAuB,CAAC;CAC9B,MAAM,QAAQ,MAAwB,UAAyB,WAA8B;EAC3F,MAAM,OAAO,WAAW,MAAM,UAAU,UAAU;EAClD,IAAI,OAAO,IAAI,KAAK,UAAU,GAC5B,MAAM,IAAI,MAAM,qDAAqD,KAAK,YAAY;EAExF,OAAO,IAAI,KAAK,UAAU;EAC1B,MAAM,KAAK,IAAI;EACf,KAAK,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,4 +1,4 @@
1
- import { a as RunRecord } from "./run-record-DwHMk1Ai.js";
1
+ import { a as RunRecord } from "./run-record-CztDMXVF.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 {
@@ -71,4 +71,4 @@ interface RubricPredictiveValidityReport {
71
71
  declare function rubricPredictiveValidity(input: RubricPredictiveValidityInput): Promise<RubricPredictiveValidityReport>;
72
72
  //#endregion
73
73
  export { rubricPredictiveValidity as a, RubricRanking as i, RubricPredictiveValidityInput as n, RubricPredictiveValidityReport as r, RubricOutcomePair as t };
74
- //# sourceMappingURL=rubric-predictive-validity-w2klGv1u.d.ts.map
74
+ //# sourceMappingURL=rubric-predictive-validity-DQBQj6uV.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"rubric-predictive-validity-w2klGv1u.d.ts","names":[],"sources":["../src/meta-eval/rubric-predictive-validity.ts"],"mappings":";;;UAoCiB;;;;;EAKf,MAAM;EACN,UAAU;;;;;;EAMV;;;;;;EAMA;;EAEA;;EAEA;;EAEA;;;;;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
+ {"version":3,"file":"rubric-predictive-validity-DQBQj6uV.d.ts","names":[],"sources":["../src/meta-eval/rubric-predictive-validity.ts"],"mappings":";;;UAoCiB;;;;;EAKf,MAAM;EACN,UAAU;;;;;;EAMV;;;;;;EAMA;;EAEA;;EAEA;;EAEA;;;;;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,8 +1,8 @@
1
1
  import { o as FailureClass } from "./schema-BtVldJ3T.js";
2
- import { a as RunRecord, c as RunTaskFailure, s as RunSplitTag, u as RunTokenUsage } from "./run-record-DwHMk1Ai.js";
2
+ import { a as RunRecord, c as RunTaskFailure, s as RunSplitTag, u as RunTokenUsage } from "./run-record-CztDMXVF.js";
3
3
  import { s as TraceStore } from "./store-CT9YIIve.js";
4
4
  import { i as TraceEmitter } from "./emitter-DGQGoLyj.js";
5
- import { $ as ControlRunResult, Q as ControlEvalResult, a as FeedbackLabel, et as ControlRuntimeConfig, x as ProposedSideEffect } from "./feedback-trajectory-CoNep7rl.js";
5
+ import { $ as ControlRunResult, Q as ControlEvalResult, a as FeedbackLabel, et as ControlRuntimeConfig, x as ProposedSideEffect } from "./feedback-trajectory-BJUWOkJM.js";
6
6
  //#region src/action-policy.d.ts
7
7
  interface ActionExecutionPolicy {
8
8
  allowedTypes?: string[];
@@ -222,4 +222,4 @@ declare function controlRunToRunRecord<TState, TAction, TActionResult, TEval ext
222
222
  declare function scoreFromEvals(evals: readonly ControlEvalResult[]): number | undefined;
223
223
  //#endregion
224
224
  export { ActionExecutionPolicy as A, ReviewMemoryStore as C, inMemoryReviewStore as D, createLlmReviewer as E, evaluateActionPolicy as M, jsonlReviewStore as O, ReviewMemoryEntry as S, VerifyFn as T, ProposeReviewReport as _, ProposeReviewControlAction as a, ReviewFn as b, ProposeReviewControlState as c, LlmJsonCall as d, LlmReviewerConfig as f, ProposeReviewConfig as g, ProposeOutput as h, scoreFromEvals as i, ActionPolicyDecision as j, runProposeReview as k, controlFailureClassFromVerification as l, ProposeInput as m, RunEvidenceMetadata as n, ProposeReviewControlConfig as o, ProposeFn as p, controlRunToRunRecord as r, ProposeReviewControlResult as s, ControlRunToRunRecordOptions as t, runProposeReviewAsControlLoop as u, ProposeReviewShot as v, Verification as w, ReviewInput as x, Review as y };
225
- //# sourceMappingURL=run-evidence-CbE0A8Xg.d.ts.map
225
+ //# sourceMappingURL=run-evidence-C4RcRQT5.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"run-evidence-CbE0A8Xg.d.ts","names":[],"sources":["../src/action-policy.ts","../src/propose-review.ts","../src/propose-review-control.ts","../src/run-evidence.ts"],"mappings":";;;;;;UAEiB;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA,QAAQ;;iBAGM,qBACd,QAAQ,oBACR,SAAQ,uBACR;EAAW;IACV;;;UCmBc;EACf;EACA;EACA;EACA;;U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a;EACb,cAAc;EACd,eAAe;EACf,QAAQ;EACR;EACA;EACA;;UAGe;EACf;EACA;;UAGe,2BAA2B,OAAO;EACjD,OAAO;EACP,cAAc;EACd,eAAe;EACf,QAAQ;EACR;EACA;;UAGe,2BAA2B,OAAO;EACjD;EACA,cAAc;EACd,SAAS,UAAU,OAAO;EAC1B,QAAQ,SAAS;EACjB,QAAQ,SAAS,OAAO;EACxB;EACA;EACA,SAAS;EACT,QAAQ;EACR;EACA;EACA;EACA;EACA;EACA;EACA,gCAAgC,cAAc,iBAAiB;EAC/D,gBAAgB,qBACd,0BAA0B,OAAO,UACjC,4BACA,2BAA2B,OAAO;;iBAOhB,8BAA8B,OAAO,mBACzD,QAAQ,2BAA2B,OAAO,WACzC,QACD,iBACE,0BAA0B,OAAO,UACjC,4BACA,2BAA2B,OAAO;iBAwKtB,oCACd,cAAc,eACb;;;UChPc;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,UAAU;EACV,YAAY;EACZ,gBAAgB;EAChB;EACA,gBAAgB;EAChB,MAAM;;KAGI,+BAA+B,sBACzC;EACE;EACA;;;;;;;;;;iBAWY,sBACd,QACA,SACA,eACA,cAAc,oBAAoB,mBAElC,KAAK,iBAAiB,QAAQ,SAAS,eAAe,QACtD,SAAS,+BACR;iBAwDa,eAAe,gBAAgB"}
1
+ {"version":3,"file":"run-evidence-C4RcRQT5.d.ts","names":[],"sources":["../src/action-policy.ts","../src/propose-review.ts","../src/propose-review-control.ts","../src/run-evidence.ts"],"mappings":";;;;;;UAEiB;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA,QAAQ;;iBAGM,qBACd,QAAQ,oBACR,SAAQ,uBACR;EAAW;IACV;;;UCmBc;EACf;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA;;UAGe,0BAA0B;EACzC;EACA;EACA;IACE;IACA;IACA;;;UAIa,aAAa;EAC5B;EACA;EACA,O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AAc;EACd,eAAe;EACf,QAAQ;EACR;EACA;;UAGe,2BAA2B,OAAO;EACjD;EACA,cAAc;EACd,SAAS,UAAU,OAAO;EAC1B,QAAQ,SAAS;EACjB,QAAQ,SAAS,OAAO;EACxB;EACA;EACA,SAAS;EACT,QAAQ;EACR;EACA;EACA;EACA;EACA;EACA;EACA,gCAAgC,cAAc,iBAAiB;EAC/D,gBAAgB,qBACd,0BAA0B,OAAO,UACjC,4BACA,2BAA2B,OAAO;;iBAOhB,8BAA8B,OAAO,mBACzD,QAAQ,2BAA2B,OAAO,WACzC,QACD,iBACE,0BAA0B,OAAO,UACjC,4BACA,2BAA2B,OAAO;iBAwKtB,oCACd,cAAc,eACb;;;UChPc;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,UAAU;EACV,YAAY;EACZ,gBAAgB;EAChB;EACA,gBAAgB;EAChB,MAAM;;KAGI,+BAA+B,sBACzC;EACE;EACA;;;;;;;;;;iBAWY,sBACd,QACA,SACA,eACA,cAAc,oBAAoB,mBAElC,KAAK,iBAAiB,QAAQ,SAAS,eAAe,QACtD,SAAS,+BACR;iBAwDa,eAAe,gBAAgB"}
@@ -1,6 +1,6 @@
1
1
  import { l as ValidationError } from "./errors-DkfjIDvD.js";
2
2
  import { r as AgentProfileCell } from "./agent-profile-cell-Cw0PVwDr.js";
3
- import { p as CostProvenance } from "./cost-ledger-B1D3COAc.js";
3
+ import { p as CostProvenance } from "./cost-ledger-DKgyIWRj.js";
4
4
  import { o as FailureClass } from "./schema-BtVldJ3T.js";
5
5
  //#region src/run-record.d.ts
6
6
  /** Search/dev/holdout split tag. 'search' is the paper-grade alias for the
@@ -240,4 +240,4 @@ declare function roundTripRunRecord(record: RunRecord): RunRecord;
240
240
  declare function modelHasSnapshot(model: string): boolean;
241
241
  //#endregion
242
242
  export { RunRecord as a, RunTaskFailure as c, isRunRecord as d, modelHasSnapshot as f, validateRunRecord as g, runTaskScore as h, RunOutcome as i, RunTerminalOutcome as l, roundTripRunRecord as m, RunCostProvenance as n, RunRecordValidationError as o, parseRunRecordSafe as p, RunJudgeMetadata as r, RunSplitTag as s, JudgeScoresRecord as t, RunTokenUsage as u };
243
- //# sourceMappingURL=run-record-DwHMk1Ai.d.ts.map
243
+ //# sourceMappingURL=run-record-CztDMXVF.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"run-record-DwHMk1Ai.d.ts","names":[],"sources":["../src/run-record.ts"],"mappings":";;;;;;;KAsCY;;;;;;;KAQA;UAEK;EACf;;EAEA;;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;;;;;;;;;;;;;;;;;;;UAmB7B;;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;;iBAiOnC,YAAY,iBAAiB,SAAS;;iBAUtC,mBACd;EACG;EAAU,OAAO;;EAAgB;EAAW,OAAO;;;iBAUxC,mBAAmB,QAAQ,YAAY;;;;;;;;;;;iBA2FvC,iBAAiB"}
1
+ {"version":3,"file":"run-record-CztDMXVF.d.ts","names":[],"sources":["../src/run-record.ts"],"mappings":";;;;;;;KAsCY;;;;;;;KAQA;UAEK;EACf;;EAEA;;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;;;;;;;;;;;;;;;;;;;UAmB7B;;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;;iBAiOnC,YAAY,iBAAiB,SAAS;;iBAUtC,mBACd;EACG;EAAU,OAAO;;EAAgB;EAAW,OAAO;;;iBAUxC,mBAAmB,QAAQ,YAAY;;;;;;;;;;;iBA2FvC,iBAAiB"}
@@ -1,11 +1,48 @@
1
1
  import { o as NotFoundError } from "./errors-D-LKuDhb.js";
2
- import { i as CostLedger } from "./cost-ledger-CHDLA0Ss.js";
3
- import { c as callLlmJson, f as maximumChargeForLlmRequest, l as costReceiptFromLlm, u as costReceiptFromLlmError } from "./llm-client-Cj3c7PEm.js";
4
- import { p as computeFindingId } from "./single-run-lock-D_bS5xhj.js";
5
- import { f as Mutex } from "./ledger-core-C0Yx1I14.js";
2
+ import { i as CostLedger } from "./cost-ledger-CZ9diLxY.js";
3
+ import { c as callLlmJson, f as maximumChargeForLlmRequest, l as costReceiptFromLlm, u as costReceiptFromLlmError } from "./llm-client-bkztEfIx.js";
4
+ import { a as computeFindingId } from "./usage-receipt-CgxMEBZq.js";
6
5
  import { a as clamp01, i as aggregateRunScore } from "./proposal-findings-2GIUo1et.js";
6
+ import { f as Mutex } from "./ledger-core-Dxz0Rkwa.js";
7
7
  import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync } from "node:fs";
8
8
  import { dirname, join } from "node:path";
9
+ //#region src/analyst/define.ts
10
+ /**
11
+ * Define a reusable trace-research question.
12
+ *
13
+ * The returned value contains no model, credentials, or execution state. Bind
14
+ * it to any TraceAnalysisEngine with `runTraceAnalyst` or
15
+ * `createTraceAnalyst`.
16
+ */
17
+ function defineTraceAnalyst(definition) {
18
+ for (const [name, value] of [
19
+ ["id", definition.id],
20
+ ["description", definition.description],
21
+ ["area", definition.area],
22
+ ["version", definition.version],
23
+ ["instructions", definition.instructions]
24
+ ]) if (typeof value !== "string" || !value.trim()) throw new TypeError(`defineTraceAnalyst: ${name} must be a non-empty string`);
25
+ return {
26
+ ...definition,
27
+ limits: definition.limits ? { ...definition.limits } : void 0
28
+ };
29
+ }
30
+ function defineCustomAnalyst(options) {
31
+ if (!options.id.trim()) throw new TypeError("defineCustomAnalyst: id must not be empty");
32
+ if (!options.description.trim()) throw new TypeError("defineCustomAnalyst: description must not be empty");
33
+ if (options.cost === void 0) throw new TypeError("defineCustomAnalyst: cost must be declared");
34
+ if ("executionConfig" in options && (!options.executionConfig || typeof options.executionConfig !== "object" || Array.isArray(options.executionConfig))) throw new TypeError("defineCustomAnalyst: executionConfig must be an object");
35
+ return {
36
+ id: options.id,
37
+ description: options.description,
38
+ version: options.version ?? "1.0.0",
39
+ inputKind: "trace-store",
40
+ cost: options.cost,
41
+ analyze: options.analyze,
42
+ ..."executionConfig" in options ? { executionConfig: options.executionConfig } : {}
43
+ };
44
+ }
45
+ //#endregion
9
46
  //#region src/locked-jsonl-appender.ts
10
47
  /**
11
48
  * LockedJsonlAppender — mutex-serialized JSONL append helper for arbitrary
@@ -725,6 +762,6 @@ function createSemanticConceptJudge(options = {}) {
725
762
  return (input) => runSemanticConceptJudge(input, options);
726
763
  }
727
764
  //#endregion
728
- export { RunCritic as a, buildSkillUsageReport as c, defaultIsMaterial as d, diffFindings as f, runSemanticConceptJudge as i, emitSkillUsageFindings as l, SEMANTIC_CONCEPT_JUDGE_VERSION as n, SKILL_USAGE_ANALYST as o, LockedJsonlAppender as p, createSemanticConceptJudge as r, SkillUsageAnalyst as s, DEFAULT_COMPLEXITY_WEIGHTS as t, FindingsStore as u };
765
+ export { RunCritic as a, buildSkillUsageReport as c, defaultIsMaterial as d, diffFindings as f, defineTraceAnalyst as h, runSemanticConceptJudge as i, emitSkillUsageFindings as l, defineCustomAnalyst as m, SEMANTIC_CONCEPT_JUDGE_VERSION as n, SKILL_USAGE_ANALYST as o, LockedJsonlAppender as p, createSemanticConceptJudge as r, SkillUsageAnalyst as s, DEFAULT_COMPLEXITY_WEIGHTS as t, FindingsStore as u };
729
766
 
730
- //# sourceMappingURL=semantic-concept-judge-DYXDPZW0.js.map
767
+ //# sourceMappingURL=semantic-concept-judge-BuIJ9IfB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"semantic-concept-judge-BuIJ9IfB.js","names":[],"sources":["../src/analyst/define.ts","../src/locked-jsonl-appender.ts","../src/analyst/findings-store.ts","../src/analyst/kinds/skill-usage.ts","../src/run-critic.ts","../src/semantic-concept-judge.ts"],"sourcesContent":["import type { TraceAnalysisStore } from '../trace-analyst/store'\nimport type { ExactCapableAnalyst } from './exact-types'\nimport type { TraceAnalystDefinition } from './kind-factory'\nimport type { Analyst, AnalystCost } from './types'\n\n/**\n * Define a reusable trace-research question.\n *\n * The returned value contains no model, credentials, or execution state. Bind\n * it to any TraceAnalysisEngine with `runTraceAnalyst` or\n * `createTraceAnalyst`.\n */\nexport function defineTraceAnalyst(definition: TraceAnalystDefinition): TraceAnalystDefinition {\n for (const [name, value] of [\n ['id', definition.id],\n ['description', definition.description],\n ['area', definition.area],\n ['version', definition.version],\n ['instructions', definition.instructions],\n ] as const) {\n if (typeof value !== 'string' || !value.trim()) {\n throw new TypeError(`defineTraceAnalyst: ${name} must be a non-empty string`)\n }\n }\n return {\n ...definition,\n limits: definition.limits ? { ...definition.limits } : undefined,\n }\n}\n\nexport interface DefineCustomAnalystOptions {\n id: string\n description: string\n version?: string\n cost: AnalystCost\n analyze: Analyst<TraceAnalysisStore>['analyze']\n}\n\nexport interface DefineExactCustomAnalystOptions extends DefineCustomAnalystOptions {\n /** Canonical JSON for behavior knobs not already bound by `version`. */\n executionConfig: Readonly<Record<string, unknown>>\n}\n\n/** Construct a registrable analyst from a hand-written analyze function. */\nexport function defineCustomAnalyst(\n options: DefineExactCustomAnalystOptions,\n): ExactCapableAnalyst<TraceAnalysisStore>\nexport function defineCustomAnalyst(\n options: DefineCustomAnalystOptions,\n): Analyst<TraceAnalysisStore>\nexport function defineCustomAnalyst(\n options: DefineCustomAnalystOptions | DefineExactCustomAnalystOptions,\n): Analyst<TraceAnalysisStore> | ExactCapableAnalyst<TraceAnalysisStore> {\n if (!options.id.trim()) throw new TypeError('defineCustomAnalyst: id must not be empty')\n if (!options.description.trim()) {\n throw new TypeError('defineCustomAnalyst: description must not be empty')\n }\n if (options.cost === undefined) {\n throw new TypeError('defineCustomAnalyst: cost must be declared')\n }\n if (\n 'executionConfig' in options &&\n (!options.executionConfig ||\n typeof options.executionConfig !== 'object' ||\n Array.isArray(options.executionConfig))\n ) {\n throw new TypeError('defineCustomAnalyst: executionConfig must be an object')\n }\n return {\n id: options.id,\n description: options.description,\n version: options.version ?? '1.0.0',\n inputKind: 'trace-store',\n cost: options.cost,\n analyze: options.analyze,\n ...('executionConfig' in options ? { executionConfig: options.executionConfig } : {}),\n }\n}\n","/**\n * LockedJsonlAppender — mutex-serialized JSONL append helper for arbitrary\n * payloads. The reference-replay store does the same thing for typed\n * `ReferenceReplayRun` rows; this is the generic version used by\n * `MutationTelemetry`, `TrialTelemetry`, and any other consumer that wants\n * append-only durable telemetry without rolling its own lock.\n *\n * Locks are per absolute file path (process-local). Cross-process\n * concurrency is NOT addressed — that's an fcntl/flock problem.\n */\n\nimport { appendFileSync, existsSync, mkdirSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport { Mutex } from './concurrency'\n\nconst mutexes = new Map<string, Mutex>()\n\nfunction getMutex(path: string): Mutex {\n let m = mutexes.get(path)\n if (!m) {\n m = new Mutex()\n mutexes.set(path, m)\n }\n return m\n}\n\nexport class LockedJsonlAppender {\n private readonly mutex: Mutex\n constructor(public readonly path: string) {\n this.mutex = getMutex(path)\n if (!existsSync(dirname(path))) {\n mkdirSync(dirname(path), { recursive: true })\n }\n }\n\n async append(entry: unknown): Promise<void> {\n const line = `${JSON.stringify(entry)}\\n`\n await this.mutex.runExclusive(() => {\n appendFileSync(this.path, line)\n })\n }\n}\n\n/** Reset all internal mutex state — tests only. */\nexport function resetLockedAppendersForTesting(): void {\n mutexes.clear()\n}\n","/**\n * FindingsStore — durable persistence for AnalystFinding rows + a diff\n * helper so we can answer \"what changed since the last run?\" without\n * recomputing analysts.\n *\n * On-disk shape is JSONL: one finding per line, append-only, locked via\n * LockedJsonlAppender. Operators get crash-safety (no partial JSON),\n * cheap reads (sequential parse), and trivial backup (rsync the file).\n *\n * Reads are non-locking: a reader sees a consistent snapshot of all\n * fully-written lines and skips an incomplete trailing line if the\n * writer is mid-append. Cross-process locking is intentionally out of\n * scope (see locked-jsonl-appender.ts).\n *\n * The store is run-scoped: callers pass `runId` on append and on load,\n * which keeps multi-run files cleanly partitioned. The `diffFindings`\n * helper compares two run-id sets using stable `finding_id` semantics —\n * the diff is the cross-run signal the regression dashboard renders.\n */\n\nimport { existsSync, readFileSync } from 'node:fs'\n\nimport { LockedJsonlAppender } from '../locked-jsonl-appender'\nimport type { AnalystFinding } from './types'\n\n/**\n * One persisted row. We attach `run_id` on disk so a single file can\n * hold multiple runs and the diff helper can query without re-walking\n * separate files.\n */\nexport interface PersistedFinding extends AnalystFinding {\n run_id: string\n}\n\nexport class FindingsStore {\n private readonly appender: LockedJsonlAppender\n\n constructor(public readonly path: string) {\n this.appender = new LockedJsonlAppender(path)\n }\n\n async append(runId: string, findings: AnalystFinding[]): Promise<void> {\n for (const f of findings) {\n const row: PersistedFinding = { ...f, run_id: runId }\n await this.appender.append(row)\n }\n }\n\n /** Load every persisted finding. Discards malformed trailing lines silently. */\n loadAll(): PersistedFinding[] {\n if (!existsSync(this.path)) return []\n const raw = readFileSync(this.path, 'utf8')\n if (!raw) return []\n const out: PersistedFinding[] = []\n for (const line of raw.split('\\n')) {\n if (!line) continue\n try {\n out.push(JSON.parse(line) as PersistedFinding)\n } catch {\n // Skip torn trailing line — the lock guarantees no torn lines\n // mid-file, only at EOF when a writer is in-flight.\n }\n }\n return out\n }\n\n /** Filter to a single run. */\n loadRun(runId: string): PersistedFinding[] {\n return this.loadAll().filter((r) => r.run_id === runId)\n }\n}\n\n// ── Cross-run diff ──────────────────────────────────────────────────\n\nexport interface FindingsDiff {\n /** New finding ids in `current` that weren't in `previous`. */\n appeared: PersistedFinding[]\n /** Finding ids in `previous` that aren't in `current`. */\n disappeared: PersistedFinding[]\n /** Same finding id present in both runs and unchanged per the materiality test. */\n persisted: PersistedFinding[]\n /**\n * Same finding id in both runs but at least one non-identity field\n * shifted per `DiffPolicy.isMaterial`. Reported as [previous, current].\n */\n changed: Array<{ previous: PersistedFinding; current: PersistedFinding }>\n}\n\nexport interface DiffPolicy {\n /**\n * Predicate that decides whether two findings (same finding_id) count\n * as a material change. Defaults to {@link defaultIsMaterial}: severity\n * shift, confidence Δ > 0.05, or evidence count change. Compliance /\n * perf consumers MAY supply a stricter predicate (e.g. rationale text\n * diff, metric Δ thresholds).\n */\n isMaterial?: (previous: AnalystFinding, current: AnalystFinding) => boolean\n}\n\n/**\n * Default materiality test. Deliberately narrow so LLM-reword churn\n * doesn't flood the diff. Stricter tests are opt-in via DiffPolicy.\n */\nexport function defaultIsMaterial(a: AnalystFinding, b: AnalystFinding): boolean {\n if (a.severity !== b.severity) return true\n if (Math.abs((a.confidence ?? 0) - (b.confidence ?? 0)) > 0.05) return true\n if (a.evidence_refs.length !== b.evidence_refs.length) return true\n return false\n}\n\n/**\n * Diff two findings sets by stable finding_id. Callers typically load\n * the two run-id slices from the same store and pass them in.\n */\nexport function diffFindings(\n previous: PersistedFinding[],\n current: PersistedFinding[],\n policy: DiffPolicy = {},\n): FindingsDiff {\n const isMaterial = policy.isMaterial ?? defaultIsMaterial\n const prevById = new Map(previous.map((f) => [f.finding_id, f]))\n const curById = new Map(current.map((f) => [f.finding_id, f]))\n\n const appeared: PersistedFinding[] = []\n const disappeared: PersistedFinding[] = []\n const persisted: PersistedFinding[] = []\n const changed: FindingsDiff['changed'] = []\n\n for (const [id, cur] of curById) {\n const prev = prevById.get(id)\n if (!prev) {\n appeared.push(cur)\n continue\n }\n if (isMaterial(prev, cur)) {\n changed.push({ previous: prev, current: cur })\n } else {\n persisted.push(cur)\n }\n }\n for (const [id, prev] of prevById) {\n if (!curById.has(id)) disappeared.push(prev)\n }\n return { appeared, disappeared, persisted, changed }\n}\n","/**\n * Skill-usage analyst — a DETERMINISTIC `Analyst` over a Claude/Codex skill\n * library + its trace corpus. Unlike the trace-store kinds (failure-mode,\n * improvement, ...) this kind calls no LLM: it mines real usage and skill\n * structure and emits findings by rule.\n *\n * It exists because the naive \"Skill-tool invocation count\" lies low — it\n * misses orchestrated sub-dispatch (a leaf skill run BY /pursue or /governor\n * logs under the parent), slash-command entry, local-script bypass, and\n * on-disk artifacts. The 2026-05-30 skill audit found 39/53 skills at zero\n * direct invocations, yet only one was a genuine cut: the rest were\n * measurement-invisible or discovery-limited. This analyst encodes that\n * lesson as a multi-signal usage model so a cheap repeatable pass can keep\n * the library honest, and so the expensive audit workflow's verdicts can\n * GEPA-distill it toward agreement (see `gold/skill-verdicts.gold.jsonl`).\n *\n * Report-building (`buildSkillUsageReport`, an fs scan) is separated from\n * finding emission (`SkillUsageAnalyst.analyze`, pure) so the slow scan runs\n * once at the registry boundary and the rule logic stays unit-testable.\n */\n\nimport { type Dirent, existsSync, readdirSync, readFileSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { ExactCapableAnalyst } from '../exact-types'\nimport type { AnalystContext, AnalystFinding, AnalystSeverity } from '../types'\nimport { computeFindingId } from '../types'\n\n// ── Input model ──────────────────────────────────────────────────────\n\nexport type SkillKind = 'public' | 'private'\n\n/** One skill's multi-signal usage + structure. All counts are deterministic. */\nexport interface SkillUsageRecord {\n name: string\n kind: SkillKind\n /** Absolute path to the skill's SKILL.md. */\n path: string\n lines: number\n /** `\"skill\":\"<name>\"` Skill-tool invocations across the trace corpus. */\n directInvocations: number\n /** `<command-name>/<name>` slash invocations across the trace corpus. */\n slashInvocations: number\n /** Sibling skills whose SKILL.md dispatches to this one (`/<name>`). Proxy\n * for orchestrated sub-dispatch the per-skill counter cannot see. */\n inboundRefs: number\n /** On-disk artifacts attributable to the skill (e.g. `.evolve/<name>/**`). */\n artifactCount: number\n /** Tangle-private reference count in the body (leak signal for public skills). */\n tanglePrivateRefs: number\n hasReferencesDir: boolean\n hasEvalsDir: boolean\n /** Body mentions `skill-runs.jsonl` (visible to /reflect + /governor). */\n logsRuns: boolean\n /** Description carries an explicit `Triggers:` clause / trigger phrases. */\n hasTriggerPhrases: boolean\n}\n\nexport interface SkillUsageReport {\n generatedFromTraces: number\n records: SkillUsageRecord[]\n}\n\nexport interface SkillUsageScanConfig {\n /** Dirs holding `*.jsonl` transcripts (Claude `~/.claude/projects`, Codex sessions). */\n transcriptDirs: string[]\n /** Skill roots to scan; each dir directly under `root` with a `SKILL.md` is a skill. */\n skillRoots: { root: string; kind: SkillKind }[]\n /** Roots scanned for `<root>/.evolve/<skill>` artifact dirs. */\n artifactRoots?: string[]\n /** Token-prefixed mappings: skill name → extra artifact subpaths under an artifactRoot\n * (e.g. reflect → `.evolve/reflections`). Catches non-eponymous artifact dirs. */\n artifactAliases?: Record<string, string[]>\n /** Cap files read per transcript dir (bounds a huge corpus); 0 = unbounded. */\n maxTranscriptsPerDir?: number\n}\n\n// ── Deterministic thresholds ─────────────────────────────────────────\n\n/** Anthropic's authoring guidance keeps SKILL.md short; past this with no\n * `references/` split the body burns context budget every session. */\nconst BLOAT_LINE_THRESHOLD = 300\n\nconst TANGLE_PRIVATE_RE =\n /\\b(cli-bridge|tangletools|ops-board|drew-gtr-pro|@tangle-network\\/|~\\/company|tangle\\.tools|gtm-agent)\\b|\\bkimi\\b|\\btcloud\\b/gi\nconst TRIGGER_RE = /triggers?\\s*[:-]/i\n\n// ── Report builder (fs scan — slow, runs once at the registry boundary) ──\n\nfunction listSkillDirs(root: string): { name: string; path: string }[] {\n if (!existsSync(root)) return []\n const out: { name: string; path: string }[] = []\n for (const entry of readdirSync(root, { withFileTypes: true })) {\n if (!entry.isDirectory() && !entry.isSymbolicLink()) continue\n const skillMd = join(root, entry.name, 'SKILL.md')\n if (existsSync(skillMd)) out.push({ name: entry.name, path: skillMd })\n }\n return out\n}\n\nfunction walkJsonl(dir: string, cap: number): string[] {\n if (!existsSync(dir)) return []\n const files: string[] = []\n const stack = [dir]\n while (stack.length) {\n const cur = stack.pop()!\n let entries: Dirent[]\n try {\n entries = readdirSync(cur, { withFileTypes: true })\n } catch {\n continue\n }\n for (const e of entries) {\n const full = join(cur, e.name)\n if (e.isDirectory()) stack.push(full)\n else if (e.name.endsWith('.jsonl')) {\n files.push(full)\n if (cap > 0 && files.length >= cap) return files\n }\n }\n }\n return files\n}\n\nfunction frontmatterDescription(body: string): string {\n const fm = /^---\\n([\\s\\S]*?)\\n---/.exec(body)\n const block = fm?.[1] ?? ''\n const m = /description:\\s*(.+)/i.exec(block)\n return m?.[1] ?? ''\n}\n\nfunction countArtifacts(roots: string[], name: string, aliases: string[]): number {\n let n = 0\n for (const root of roots) {\n const candidates = [join(root, '.evolve', name), ...aliases.map((a) => join(root, a))]\n for (const dir of candidates) {\n if (!existsSync(dir)) continue\n try {\n if (statSync(dir).isDirectory()) n += readdirSync(dir).length\n else n += 1\n } catch {\n /* unreadable — skip */\n }\n }\n }\n return n\n}\n\n/** Scan the corpus + skill roots into a {@link SkillUsageReport}. Deterministic. */\nexport function buildSkillUsageReport(config: SkillUsageScanConfig): SkillUsageReport {\n const skills = config.skillRoots.flatMap(({ root, kind }) =>\n listSkillDirs(root).map((s) => ({ ...s, kind })),\n )\n const names = skills.map((s) => s.name)\n\n // One pass over the corpus accumulating direct + slash counts per skill.\n const direct = new Map<string, number>(names.map((n) => [n, 0]))\n const slash = new Map<string, number>(names.map((n) => [n, 0]))\n const skillRe = /\"skill\"\\s*:\\s*\"([a-z0-9_:-]+)\"/g\n const cmdRe = /<command-name>\\/?([a-z0-9_:-]+)<\\/command-name>/g\n let transcripts = 0\n for (const dir of config.transcriptDirs) {\n for (const file of walkJsonl(dir, config.maxTranscriptsPerDir ?? 0)) {\n transcripts += 1\n let data: string\n try {\n data = readFileSync(file, 'utf8')\n } catch {\n continue\n }\n for (const m of data.matchAll(skillRe)) {\n const g = m[1]\n if (!g) continue\n const n = g.split(':').pop() ?? g\n const prev = direct.get(n)\n if (prev !== undefined) direct.set(n, prev + 1)\n }\n for (const m of data.matchAll(cmdRe)) {\n const g = m[1]\n if (g === undefined) continue\n const prev = slash.get(g)\n if (prev !== undefined) slash.set(g, prev + 1)\n }\n }\n }\n\n // Read each skill body once; compute structure + inbound refs across siblings.\n const bodies = new Map<string, string>()\n for (const s of skills) {\n try {\n bodies.set(s.name, readFileSync(s.path, 'utf8'))\n } catch {\n bodies.set(s.name, '')\n }\n }\n const inbound = new Map<string, number>(names.map((n) => [n, 0]))\n for (const target of names) {\n const ref = new RegExp(`/${target}\\\\b|\\\\[\\\\[${target}\\\\]\\\\]`)\n for (const s of skills) {\n if (s.name === target) continue\n if (ref.test(bodies.get(s.name) ?? '')) inbound.set(target, inbound.get(target)! + 1)\n }\n }\n\n const records: SkillUsageRecord[] = skills.map((s) => {\n const body = bodies.get(s.name) ?? ''\n const dir = s.path.replace(/\\/SKILL\\.md$/, '')\n return {\n name: s.name,\n kind: s.kind,\n path: s.path,\n lines: body ? body.split('\\n').length : 0,\n directInvocations: direct.get(s.name) ?? 0,\n slashInvocations: slash.get(s.name) ?? 0,\n inboundRefs: inbound.get(s.name) ?? 0,\n artifactCount: countArtifacts(\n config.artifactRoots ?? [],\n s.name,\n config.artifactAliases?.[s.name] ?? [],\n ),\n tanglePrivateRefs: (body.match(TANGLE_PRIVATE_RE) ?? []).length,\n hasReferencesDir: existsSync(join(dir, 'references')),\n hasEvalsDir: existsSync(join(dir, 'evals')),\n logsRuns: body.includes('skill-runs.jsonl'),\n hasTriggerPhrases: TRIGGER_RE.test(frontmatterDescription(body) || body.slice(0, 600)),\n }\n })\n return { generatedFromTraces: transcripts, records }\n}\n\n// ── Finding emission (pure — unit-testable, no LLM, no fs) ────────────\n\nconst ANALYST_ID = 'skill-usage'\n\nfunction finding(\n area: string,\n subject: string,\n claim: string,\n severity: AnalystSeverity,\n confidence: number,\n producedAt: string,\n recommended: string,\n evidenceUri: string,\n rationale?: string,\n): AnalystFinding {\n return {\n schema_version: '1.0.0',\n finding_id: computeFindingId({ analyst_id: ANALYST_ID, area, subject, claim }),\n analyst_id: ANALYST_ID,\n produced_at: producedAt,\n severity,\n area,\n claim,\n rationale,\n evidence_refs: [{ kind: 'artifact', uri: evidenceUri }],\n recommended_action: recommended,\n confidence,\n subject,\n }\n}\n\n/** Pure rule pass over a report → findings. Exported for direct/unit use. */\nexport function emitSkillUsageFindings(\n report: SkillUsageReport,\n producedAt: string,\n): AnalystFinding[] {\n const out: AnalystFinding[] = []\n for (const r of report.records) {\n const directTotal = r.directInvocations + r.slashInvocations\n const trueUsage = directTotal + r.inboundRefs + r.artifactCount\n\n // 1. Dead: no usage signal of ANY kind. The only real deprecation candidate.\n if (trueUsage === 0) {\n out.push(\n finding(\n 'skill-usage',\n r.name,\n `Skill '${r.name}' has zero usage across all signals (direct, slash, inbound-refs, artifacts)`,\n 'high',\n 0.6,\n producedAt,\n 'Confirm the skill covers a real recurring job; if not, deprecate. Zero true usage is the only deterministic deprecation candidate.',\n r.path,\n 'No Skill-tool call, no slash invocation, no sibling dispatches to it, and no on-disk artifacts.',\n ),\n )\n } else if (directTotal === 0 && r.inboundRefs + r.artifactCount > 0) {\n // 2. Measurement-invisible: real use via orchestration/artifacts, never invoked directly.\n out.push(\n finding(\n 'skill-usage',\n r.name,\n `Skill '${r.name}' shows 0 direct invocations but is used via orchestration/artifacts (inbound=${r.inboundRefs}, artifacts=${r.artifactCount})`,\n 'info',\n 0.8,\n producedAt,\n 'Do NOT treat as unused — usage is real but logged under parent skills or on disk. Strengthen direct-invocation discovery only if direct use is desired.',\n r.path,\n 'The Skill-tool counter undercounts orchestrated/chained leaf skills.',\n ),\n )\n }\n\n // 3. Discovery gap: low direct use AND weak trigger surface.\n if (directTotal <= 2 && !r.hasTriggerPhrases) {\n out.push(\n finding(\n 'discoverability',\n r.name,\n `Skill '${r.name}' is rarely invoked directly and its description has no explicit trigger phrases`,\n 'medium',\n 0.7,\n producedAt,\n 'Add a `Triggers:` clause with verbatim user phrases to the frontmatter description so the model auto-invokes it.',\n r.path,\n ),\n )\n }\n\n // 4. Public-repo leak.\n if (r.kind === 'public' && r.tanglePrivateRefs > 0) {\n out.push(\n finding(\n 'safety',\n r.name,\n `Public skill '${r.name}' carries ${r.tanglePrivateRefs} Tangle-private reference(s)`,\n 'high',\n 0.75,\n producedAt,\n 'Sanitize incidental internal refs (cli-bridge/kimi/tcloud/~company/private repos) or relocate to a private repo. Verify @tangle-network/* refs are to PUBLISHED packages before treating as a leak.',\n r.path,\n ),\n )\n }\n\n // 5. Bloat / no progressive disclosure.\n if (r.lines > BLOAT_LINE_THRESHOLD && !r.hasReferencesDir) {\n out.push(\n finding(\n 'maintainability',\n r.name,\n `Skill '${r.name}' is ${r.lines} lines with no references/ split (progressive disclosure)`,\n 'medium',\n 0.8,\n producedAt,\n `Split detail into references/ loaded on demand; keep SKILL.md a short overview. ${r.lines} lines load into every session's context budget.`,\n r.path,\n ),\n )\n }\n\n // 6. No evals (Anthropic's \">=3 evals before docs\" rule).\n if (!r.hasEvalsDir) {\n out.push(\n finding(\n 'data-quality',\n r.name,\n `Skill '${r.name}' ships no evals/`,\n 'low',\n 0.6,\n producedAt,\n 'Add evals/evals.json with >=3 scenarios proving the skill beats baseline; gives regression coverage.',\n r.path,\n ),\n )\n }\n\n // 7. No run logging → invisible to /reflect and /governor.\n if (!r.logsRuns) {\n out.push(\n finding(\n 'observability',\n r.name,\n `Skill '${r.name}' never appends to .evolve/skill-runs.jsonl`,\n 'low',\n 0.55,\n producedAt,\n 'Append one run line to .evolve/skill-runs.jsonl on completion, or declare it a non-logging leaf, so the self-improvement loop can see it ran.',\n r.path,\n ),\n )\n }\n }\n return out\n}\n\n// ── The Analyst ──────────────────────────────────────────────────────\n\nexport class SkillUsageAnalyst implements ExactCapableAnalyst<SkillUsageReport> {\n readonly id = ANALYST_ID\n readonly description =\n 'Deterministic multi-signal skill-usage analysis: flags dead skills, measurement-invisible (orchestrated) usage, discovery gaps, public-repo leaks, bloat, missing evals, and missing run-logging.'\n readonly inputKind = 'custom' as const\n readonly cost = { kind: 'deterministic' as const, est_usd_per_run: 0 }\n readonly version = '1.0.0'\n readonly executionConfig = {\n kind: 'skill-usage',\n bloat_line_threshold: BLOAT_LINE_THRESHOLD,\n produced_at_source: 'tags.producedAt-or-system-clock',\n } as const\n\n async analyze(input: SkillUsageReport, ctx: AnalystContext): Promise<AnalystFinding[]> {\n const producedAt = ctx.tags?.producedAt ?? new Date().toISOString()\n ctx.log?.(\n `skill-usage: ${input.records.length} skills over ${input.generatedFromTraces} transcripts`,\n )\n return emitSkillUsageFindings(input, producedAt)\n }\n}\n\nexport const SKILL_USAGE_ANALYST = new SkillUsageAnalyst()\n","import { NotFoundError } from './errors'\nimport { aggregateRunScore, clamp01, type RunScore, type RunScoreWeights } from './run-score'\nimport type { Artifact, BudgetLedgerEntry, Run, Span, TraceEvent, TraceStore } from './trace'\n\nexport interface RunTrace {\n run: Run\n spans: Span[]\n events: TraceEvent[]\n artifacts: Artifact[]\n budget: BudgetLedgerEntry[]\n}\n\nexport interface RunCriticOptions {\n weights?: Partial<RunScoreWeights>\n driftPatterns?: RegExp[]\n}\n\nconst DEFAULT_DRIFT_PATTERNS = [\n /https?:\\/\\//i,\n /\\btitle:\\s/i,\n /\\bsummary:\\s/i,\n /\\burl:\\s/i,\n /\\bnpm package usage\\b/i,\n /\\bnews\\b/i,\n]\n\nexport class RunCritic {\n private readonly weights?: Partial<RunScoreWeights>\n private readonly driftPatterns: RegExp[]\n\n constructor(options: RunCriticOptions = {}) {\n this.weights = options.weights\n this.driftPatterns = options.driftPatterns ?? DEFAULT_DRIFT_PATTERNS\n }\n\n async score(store: TraceStore, runId: string): Promise<RunScore> {\n const run = await store.getRun(runId)\n if (!run) throw new NotFoundError(`run ${runId} not found`)\n const [spans, events, artifacts, budget] = await Promise.all([\n store.spans({ runId }),\n store.events({ runId }),\n store.artifacts(runId),\n store.budget(runId),\n ])\n return this.scoreTrace({ run, spans, events, artifacts, budget })\n }\n\n scoreTrace(trace: RunTrace): RunScore {\n const notes: string[] = []\n const llmSpans = trace.spans.filter(\n (s): s is Extract<Span, { kind: 'llm' }> => s.kind === 'llm',\n )\n const toolSpans = trace.spans.filter(\n (s): s is Extract<Span, { kind: 'tool' }> => s.kind === 'tool',\n )\n const judgeSpans = trace.spans.filter(\n (s): s is Extract<Span, { kind: 'judge' }> => s.kind === 'judge',\n )\n const sandboxSpans = trace.spans.filter(\n (s): s is Extract<Span, { kind: 'sandbox' }> => s.kind === 'sandbox',\n )\n const finalGateSpans = judgeSpans.filter(\n (span) => span.dimension === 'final_gate' || span.attributes?.finalGate === true,\n )\n\n const success =\n trace.run.outcome?.pass === true ? 1 : trace.run.status === 'completed' ? 0.5 : 0\n if (!success) notes.push('run did not complete with pass=true')\n\n const judgeAverage = judgeSpans.length\n ? judgeSpans.reduce((sum, span) => sum + normalizeJudgeScore(span.score), 0) /\n judgeSpans.length\n : undefined\n const outcomeScore =\n typeof trace.run.outcome?.score === 'number'\n ? clamp01(\n trace.run.outcome.score > 1 ? trace.run.outcome.score / 100 : trace.run.outcome.score,\n )\n : undefined\n const goalProgress = outcomeScore ?? judgeAverage ?? success\n\n const successfulTools = toolSpans.filter((span) => span.status !== 'error').length\n const toolUseQuality = toolSpans.length === 0 ? 0 : successfulTools / toolSpans.length\n if (toolSpans.length === 0) notes.push('no tool spans recorded')\n\n const patchEvidence =\n trace.artifacts.length +\n toolSpans.filter((span) => /write|edit|patch|apply/i.test(span.toolName)).length\n const patchQuality = patchEvidence > 0 ? clamp01(patchEvidence / 4) : 0\n if (!patchQuality) notes.push('no artifact or edit evidence recorded')\n\n const sandboxTests = sandboxSpans.filter(\n (span) => typeof span.testsTotal === 'number' && span.testsTotal > 0,\n )\n const testReality = sandboxTests.length\n ? sandboxTests.reduce(\n (sum, span) => sum + (span.testsPassed ?? 0) / Math.max(1, span.testsTotal ?? 1),\n 0,\n ) / sandboxTests.length\n : toolSpans.some((span) =>\n /\\btest|vitest|pytest|jest|build|tsc\\b/i.test(JSON.stringify(span.args)),\n )\n ? 0.4\n : 0\n if (!testReality) notes.push('no real test/build evidence recorded')\n\n const blockerSpans = judgeSpans.filter((span) => isBlockingJudge(span))\n const finalGateBlockers = finalGateSpans.filter((span) => isBlockingJudge(span))\n const finalGate = finalGateSpans.length ? (finalGateBlockers.length ? 0 : 1) : success\n if (finalGateBlockers.length)\n notes.push(`final gate blocked by ${finalGateBlockers.length} reviewer(s)`)\n else if (!finalGateSpans.length) notes.push('no final gate judgment recorded')\n\n const reviewerBlockers = judgeSpans.length ? blockerSpans.length / judgeSpans.length : 0\n if (reviewerBlockers) notes.push(`detected ${blockerSpans.length} blocking reviewer signal(s)`)\n\n const positiveGroundingSignals =\n patchEvidence +\n sandboxSpans.length +\n llmSpans.filter((span) => looksRepoGrounded(span.output ?? '')).length\n const driftSignals =\n llmSpans.filter((span) => this.isDrift(span.output ?? '')).length +\n trace.events.filter((event) => this.isDrift(JSON.stringify(event.payload))).length\n const repoGroundedness =\n positiveGroundingSignals + driftSignals === 0\n ? 0\n : positiveGroundingSignals / (positiveGroundingSignals + driftSignals)\n const driftPenalty =\n positiveGroundingSignals + driftSignals === 0\n ? 0\n : driftSignals / (positiveGroundingSignals + driftSignals)\n if (driftSignals > 0) notes.push(`detected ${driftSignals} drift signal(s)`)\n\n const costUsd = trace.budget.length\n ? Math.max(\n ...trace.budget\n .filter((entry: BudgetLedgerEntry) => entry.dimension === 'usd')\n .map((entry: BudgetLedgerEntry) => entry.consumed),\n 0,\n )\n : llmSpans.reduce((sum, span) => sum + (span.costUsd ?? 0), 0)\n const wallSeconds =\n trace.run.endedAt && trace.run.startedAt\n ? Math.max(0, (trace.run.endedAt - trace.run.startedAt) / 1000)\n : 0\n\n return {\n success,\n goalProgress,\n repoGroundedness,\n driftPenalty,\n toolUseQuality,\n patchQuality,\n testReality,\n finalGate,\n reviewerBlockers,\n costUsd,\n wallSeconds,\n notes,\n }\n }\n\n rank(score: RunScore): number {\n return aggregateRunScore(score, this.weights)\n }\n\n private isDrift(text: string): boolean {\n return this.driftPatterns.some((pattern) => pattern.test(text))\n }\n}\n\nfunction normalizeJudgeScore(score: number): number {\n return score > 1 ? clamp01(score / 10) : clamp01(score)\n}\n\nfunction looksRepoGrounded(text: string): boolean {\n return /(?:src\\/|tests?\\/|package\\.json|tsconfig|\\.ts\\b|\\.tsx\\b|git status|pnpm |npm |vitest|pytest|jest)/i.test(\n text,\n )\n}\n\nfunction isBlockingJudge(span: Extract<Span, { kind: 'judge' }>): boolean {\n return (\n span.attributes?.blocking === true ||\n span.attributes?.verdict === 'BLOCKING' ||\n positiveNumber(span.attributes?.blockingFindings) ||\n positiveNumber(span.attributes?.highFindings) ||\n span.score <= 2\n )\n}\n\nfunction positiveNumber(value: unknown): boolean {\n return typeof value === 'number' && value > 0\n}\n","/**\n * Semantic concept judge — \"does the built artifact actually implement\n * the features the user asked for?\"\n *\n * Distinct from the domain/code/coherence judges in `judges.ts`:\n * - those judges score free-form conversational agent outputs along\n * quality dimensions (accuracy, depth, etc.)\n * - this judge scores a *built artifact* (served HTML + source files)\n * against an explicit list of expected concepts, returning per-concept\n * {present, score 0-10, evidence, severity}.\n *\n * The judge is strict about distinguishing (a) a working implementation\n * from (b) a keyword-present stub. \"// TODO: mint button\" is NOT present.\n * Only real, functional, wired-up code counts.\n *\n * Use via {@link createSemanticConceptJudge} or directly via\n * {@link runSemanticConceptJudge}. Soft-fails (available=false) on LLM\n * or JSON-parse errors so the caller can treat that as \"layer skipped\"\n * rather than \"layer failed\" in a multi-layer pipeline.\n */\n\nimport { CostLedger, type CostLedgerHandle, type CostReceipt } from './cost-ledger'\nimport {\n callLlmJson,\n costReceiptFromLlm,\n costReceiptFromLlmError,\n type LlmCallRequest,\n type LlmClientOptions,\n maximumChargeForLlmRequest,\n} from './llm-client'\nimport type { Severity } from './multi-layer-verifier'\n\n// ─── Types ──────────────────────────────────────────────────────────────\n\n/**\n * Implementation complexity class for weighted scoring.\n *\n * - `render` (default): the concept is a UI surface that displays static\n * data — render a list, show a counter, lay out a button. Single-file\n * work, no external integration.\n * - `integrate`: the concept requires wiring a real external system —\n * wallet connect (wagmi + RainbowKit + chain config), payment provider\n * (Stripe Elements + intent + webhook), an API client with auth.\n * Multi-file, library-knowledge, runtime correctness matters.\n * - `compute`: the concept requires algorithmic work — solver, simulator,\n * constraint propagation, ML inference. Correctness > UI polish.\n *\n * Default weights (when applied via `weightConcepts: 'complexity'`):\n * render=1.0, integrate=2.0, compute=2.5\n *\n * Cross-vertical scoring without complexity weighting silently inflates\n * the rate of UI-heavy verticals (healthcare, fintech dashboards) vs\n * integration-heavy verticals (DeFi, wallets) — all concepts treated\n * equally even though the agent does 2-3x the work for `integrate`.\n */\nexport type ConceptComplexity = 'render' | 'integrate' | 'compute'\n\nexport interface ConceptSpec {\n name: string\n /** Short hints that help the judge; not used for matching. */\n keywords?: string[]\n /** Optional explicit weight; default 1.0. Overrides complexity-derived weight. */\n weight?: number\n /** Implementation complexity class. Default `render`. */\n complexity?: ConceptComplexity\n}\n\nexport interface ConceptFinding {\n concept: string\n present: boolean\n /** 0..10. 10 = production-ready; 7 = functional thin; 4 = partial; 0 = absent. */\n score: number\n evidence: string\n severity: Severity\n}\n\nexport interface SemanticConceptJudgeInput {\n /** Full natural-language prompt the agent was handed. */\n userRequest: string\n /** Rendered HTML the preview returns (UI artifacts). Optional. */\n servedHtml?: string\n /** Top-level source files from the agent's workdir. */\n sourceFiles: Array<{ path: string; content: string }>\n /** The expected concept list. */\n expectedConcepts: ConceptSpec[]\n /** Free-form metadata (id, difficulty) to inject into the prompt. */\n artifactLabel?: string\n artifactDescription?: string\n}\n\nexport interface SemanticConceptJudgeResult {\n kind: 'semantic-concept'\n version: string\n /** Normalized 0..1 score — mean of per-concept scores / 10. */\n score: number\n presentCount: number\n totalCount: number\n findings: ConceptFinding[]\n summary: string\n durationMs: number\n costUsd: number | null\n /** False on LLM/JSON error — treat as \"skipped / unable to judge\" in pipelines. */\n available: boolean\n error?: string\n}\n\n/**\n * Score-aggregation strategy. `mean` averages 0-10 scores uniformly.\n * `complexity` applies the default weight table (render=1, integrate=2,\n * compute=2.5) unless a concept has an explicit `weight`. `explicit`\n * honors only `weight` (defaulting to 1 for unspecified).\n */\nexport type ConceptWeightStrategy = 'mean' | 'complexity' | 'explicit'\n\nexport const DEFAULT_COMPLEXITY_WEIGHTS: Record<ConceptComplexity, number> = {\n render: 1.0,\n integrate: 2.0,\n compute: 2.5,\n}\n\nexport interface SemanticConceptJudgeOptions {\n /** Model id to call. Default 'claude-sonnet-4-6' via agent-eval defaults. */\n model?: string\n /** Per-call timeout. Default 300s. */\n timeoutMs?: number\n /** Provider-enforced output limit. Default 16000. */\n maxTokens?: number\n /** Pipeline budget for the prompt (source blob truncation). Default 45000. */\n maxSourceChars?: number\n /** Per-file cap before inclusion. Default 20000. */\n maxPerFileChars?: number\n /** HTML cap. Default 30000. */\n maxHtmlChars?: number\n /** LlmClient config (baseUrl, apiKey, authHeader, …). */\n llm?: LlmClientOptions\n costLedger?: CostLedgerHandle\n costPhase?: string\n costTags?: Record<string, string>\n signal?: AbortSignal\n /**\n * Score aggregation strategy. Default `mean` — uniform average across\n * concepts. Cross-vertical comparisons should use `complexity` to\n * neutralize the integrate-vs-render asymmetry.\n */\n weightConcepts?: ConceptWeightStrategy\n /** Override the default complexity → weight table. */\n complexityWeights?: Partial<Record<ConceptComplexity, number>>\n}\n\n// ─── Prompt assembly ────────────────────────────────────────────────────\n\nexport const SEMANTIC_CONCEPT_JUDGE_VERSION = 'semantic-concept-judge-v1-2026-04-24'\n\nconst DEFAULT_MAX_SOURCE = 45_000\nconst DEFAULT_MAX_HTML = 30_000\nconst DEFAULT_MAX_PER_FILE = 20_000\nconst DEFAULT_TIMEOUT = 300_000\nconst DEFAULT_MAX_TOKENS = 16_000\nconst DEFAULT_MODEL = 'claude-sonnet-4-6'\n\nconst SEMANTIC_SCHEMA = {\n type: 'object',\n additionalProperties: false,\n required: ['summary', 'concepts'],\n properties: {\n summary: { type: 'string', minLength: 20, maxLength: 600 },\n concepts: {\n type: 'array',\n minItems: 1,\n items: {\n type: 'object',\n additionalProperties: false,\n required: ['concept', 'present', 'score', 'evidence', 'severity'],\n properties: {\n concept: { type: 'string', minLength: 1, maxLength: 120 },\n present: { type: 'boolean' },\n score: { type: 'number', minimum: 0, maximum: 10 },\n evidence: { type: 'string', minLength: 5, maxLength: 400 },\n severity: { type: 'string', enum: ['critical', 'major', 'minor', 'info'] },\n },\n },\n },\n },\n}\n\nfunction truncate(body: string, cap: number, label: string): string {\n if (body.length <= cap) return body\n return `${body.slice(0, cap)}\\n… [truncated ${body.length - cap} chars of ${label}]`\n}\n\nfunction buildPrompt(\n input: SemanticConceptJudgeInput,\n opts: Required<SemanticConceptJudgeOptions>,\n): string {\n const sourceBlob = input.sourceFiles\n .filter((f) => f.content.length <= opts.maxPerFileChars)\n .map((f) => `--- FILE: ${f.path} ---\\n${f.content}`)\n .join('\\n\\n')\n\n const html = input.servedHtml ?? ''\n\n return `You are a strict code-review judge evaluating whether an agent's 0-to-1 build actually implements the features the user asked for.\n\nYou MUST distinguish:\n (a) WORKING code that implements the concept (rendered UI, wired handler, real API call),\n (b) KEYWORD-PRESENT stub (comments mentioning the concept, variable names, TODOs),\n (c) ABSENT (concept nowhere).\n\nA comment like \"// TODO: add mint button\" is NOT present — score 2-3. Only count a concept as present if there is real functional code: a rendered component, a call handler wired to state or a network call, a computed value actually used.\n\nUSER REQUEST (what the agent was asked to build):\n${input.userRequest}\n\n${input.artifactLabel ? `ARTIFACT METADATA:\\n name: ${input.artifactLabel}\\n description: ${input.artifactDescription ?? ''}\\n\\n` : ''}EXPECTED CONCEPTS (each must be graded independently):\n${input.expectedConcepts\n .map(\n (c, i) =>\n ` ${i + 1}. \"${c.name}\"${c.keywords?.length ? ` — hints: [${c.keywords.slice(0, 6).join(' | ')}]` : ''}`,\n )\n .join('\\n')}\n\n${html ? `SERVED HTML (what the preview returns when hit):\\n${truncate(html, opts.maxHtmlChars, 'HTML')}\\n\\n` : ''}SOURCE FILES (the agent's workdir):\n${truncate(sourceBlob, opts.maxSourceChars, 'source')}\n\nFor EACH concept, return:\n - concept: the concept name as given (match exactly)\n - present: boolean — does a working implementation exist?\n - score: 0-10 — 10 = production-ready; 7 = functional but thin; 4 = partial/stubbed; 2 = keyword-only comment; 0 = absent\n - evidence: cite \"<file>:<line>\" or \"served-html:<selector>\" pointing at the strongest supporting code. If the concept is absent or stubbed, explain what's missing.\n - severity:\n \"info\" when present: true AND score >= 7\n \"minor\" when present: true AND 4 <= score < 7\n \"major\" when present: false OR score < 4\n \"critical\" when the concept is not only absent but a core user flow depends on it\n\nAlso produce a \"summary\" (one sentence, 20-600 chars): overall verdict on whether this is a shippable implementation of the user request vs a keyword-dense placeholder.\n\nBE SKEPTICAL. Keyword matching already passed — your job is to catch what keyword matching misses. If the agent shipped a working build, say so. If it shipped a stub, say so. Don't grade on effort.\n\nReturn STRICT JSON. No prose outside the JSON.`\n}\n\n// ─── Runner ─────────────────────────────────────────────────────────────\n\n/**\n * Run the semantic concept judge. Soft-fails to available=false on\n * LLM/JSON errors — callers in a MultiLayerVerifier pipeline can treat\n * that as \"skip\" rather than \"fail.\"\n */\nexport async function runSemanticConceptJudge(\n input: SemanticConceptJudgeInput,\n options: SemanticConceptJudgeOptions = {},\n): Promise<SemanticConceptJudgeResult> {\n const start = Date.now()\n const totalCount = input.expectedConcepts.length\n\n if (totalCount === 0) {\n return {\n kind: 'semantic-concept',\n version: SEMANTIC_CONCEPT_JUDGE_VERSION,\n score: 0,\n presentCount: 0,\n totalCount: 0,\n findings: [],\n summary: 'no expected concepts declared',\n durationMs: 0,\n costUsd: null,\n available: false,\n error: 'no expected concepts declared',\n }\n }\n\n const opts: Required<SemanticConceptJudgeOptions> = {\n model: options.model ?? DEFAULT_MODEL,\n timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT,\n maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS,\n maxSourceChars: options.maxSourceChars ?? DEFAULT_MAX_SOURCE,\n maxPerFileChars: options.maxPerFileChars ?? DEFAULT_MAX_PER_FILE,\n maxHtmlChars: options.maxHtmlChars ?? DEFAULT_MAX_HTML,\n llm: options.llm ?? {},\n costLedger: options.costLedger ?? new CostLedger(),\n costPhase: options.costPhase ?? 'judge.semantic-concept',\n costTags: options.costTags ?? {},\n signal: options.signal ?? new AbortController().signal,\n weightConcepts: options.weightConcepts ?? 'mean',\n complexityWeights: { ...DEFAULT_COMPLEXITY_WEIGHTS, ...(options.complexityWeights ?? {}) },\n }\n\n // Build a name → weight map for aggregation. Mean strategy keeps every\n // weight at 1 (uniform average). Complexity strategy reads the table\n // and lets an explicit `weight` override. Explicit strategy uses ONLY\n // the spec's `weight` (defaulting to 1).\n const weightForConcept = (spec: ConceptSpec): number => {\n if (opts.weightConcepts === 'mean') return 1\n if (spec.weight != null) return spec.weight\n if (opts.weightConcepts === 'complexity') {\n return opts.complexityWeights[spec.complexity ?? 'render'] ?? 1\n }\n return 1\n }\n const weightByName = new Map<string, number>(\n input.expectedConcepts.map((c) => [c.name, weightForConcept(c)]),\n )\n\n let receipt: CostReceipt | undefined\n try {\n const request = {\n model: opts.model,\n messages: [\n {\n role: 'system' as const,\n content:\n 'You are a strict code-review judge. Return strict JSON only. No prose outside the JSON. A keyword in a comment is NOT a working implementation.',\n },\n { role: 'user' as const, content: buildPrompt(input, opts) },\n ],\n jsonSchema: { name: 'semantic_concept_judge', schema: SEMANTIC_SCHEMA },\n temperature: 0,\n maxTokens: opts.maxTokens,\n timeoutMs: opts.timeoutMs,\n } satisfies LlmCallRequest\n const paid = await opts.costLedger.runPaidCall({\n channel: 'judge',\n phase: opts.costPhase,\n actor: 'semantic-concept',\n model: opts.model,\n ...(Object.keys(opts.costTags).length > 0 ? { tags: opts.costTags } : {}),\n maximumCharge: maximumChargeForLlmRequest(request, opts.llm),\n signal: opts.signal,\n execute: (signal, callId) =>\n callLlmJson<{ summary: string; concepts: ConceptFinding[] }>(request, {\n ...opts.llm,\n signal,\n idempotencyKey: callId,\n }),\n receipt: ({ result }) => costReceiptFromLlm(result),\n receiptFromError: costReceiptFromLlmError,\n })\n receipt = paid.receipt\n if (!paid.succeeded) throw paid.error\n const { value } = paid.value\n\n if (!value?.concepts || !Array.isArray(value.concepts)) {\n throw new Error('judge returned malformed response — expected array under \"concepts\"')\n }\n\n const findings: ConceptFinding[] = value.concepts.map((c) => ({\n concept: String(c.concept),\n present: Boolean(c.present),\n score: Math.max(0, Math.min(10, Number(c.score ?? 0))),\n evidence: String(c.evidence ?? ''),\n severity: (['critical', 'major', 'minor', 'info'] as const).includes(c.severity)\n ? c.severity\n : 'info',\n }))\n\n const presentCount = findings.filter((f) => f.present && f.score >= 7).length\n let weightSum = 0\n let weightedScoreSum = 0\n for (const f of findings) {\n const w = weightByName.get(f.concept) ?? 1\n weightSum += w\n weightedScoreSum += w * f.score\n }\n const scoreAvg =\n weightSum > 0\n ? weightedScoreSum / weightSum\n : findings.reduce((a, f) => a + f.score, 0) / Math.max(1, findings.length)\n\n return {\n kind: 'semantic-concept',\n version: SEMANTIC_CONCEPT_JUDGE_VERSION,\n score: Number((scoreAvg / 10).toFixed(3)),\n presentCount,\n totalCount,\n findings,\n summary: String(value.summary ?? ''),\n durationMs: Date.now() - start,\n costUsd: paid.receipt.costUnknown ? null : paid.receipt.costUsd,\n available: true,\n }\n } catch (err) {\n return {\n kind: 'semantic-concept',\n version: SEMANTIC_CONCEPT_JUDGE_VERSION,\n score: 0,\n presentCount: 0,\n totalCount,\n findings: [],\n summary: '',\n durationMs: Date.now() - start,\n costUsd: receipt && !receipt.costUnknown ? receipt.costUsd : null,\n available: false,\n error: err instanceof Error ? err.message : String(err),\n }\n }\n}\n\n/**\n * Factory: pin LLM options once, return a closure that accepts inputs.\n * Convenient for pipelines that want to share a single LlmClient config.\n */\nexport function createSemanticConceptJudge(\n options: SemanticConceptJudgeOptions = {},\n): (input: SemanticConceptJudgeInput) => Promise<SemanticConceptJudgeResult> {\n return (input) => runSemanticConceptJudge(input, options)\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAYA,SAAgB,mBAAmB,YAA4D;CAC7F,KAAK,MAAM,CAAC,MAAM,UAAU;EAC1B,CAAC,MAAM,WAAW,EAAE;EACpB,CAAC,eAAe,WAAW,WAAW;EACtC,CAAC,QAAQ,WAAW,IAAI;EACxB,CAAC,WAAW,WAAW,OAAO;EAC9B,CAAC,gBAAgB,WAAW,YAAY;CAC1C,GACE,IAAI,OAAO,UAAU,YAAY,CAAC,MAAM,KAAK,GAC3C,MAAM,IAAI,UAAU,uBAAuB,KAAK,4BAA4B;CAGhF,OAAO;EACL,GAAG;EACH,QAAQ,WAAW,SAAS,EAAE,GAAG,WAAW,OAAO,IAAI,KAAA;CACzD;AACF;AA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AAY,KAAK,IAAI,IAAI;GACzB,SAAS,KAAK,QAAQ,cAAc,OAAO,KAAK,QAAQ;GACxD,WAAW;EACb;CACF,SAAS,KAAK;EACZ,OAAO;GACL,MAAM;GACN,SAAS;GACT,OAAO;GACP,cAAc;GACd;GACA,UAAU,CAAC;GACX,SAAS;GACT,YAAY,KAAK,IAAI,IAAI;GACzB,SAAS,WAAW,CAAC,QAAQ,cAAc,QAAQ,UAAU;GAC7D,WAAW;GACX,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;EACxD;CACF;AACF;;;;;AAMA,SAAgB,2BACd,UAAuC,CAAC,GACmC;CAC3E,QAAQ,UAAU,wBAAwB,OAAO,OAAO;AAC1D"}
@@ -1,5 +1,5 @@
1
- import { i as CostLedger } from "./cost-ledger-CHDLA0Ss.js";
2
- import { a as assertLlmRoute, c as callLlmJson, f as maximumChargeForLlmRequest, i as LlmRouteAssertionError, l as costReceiptFromLlm, u as costReceiptFromLlmError } from "./llm-client-Cj3c7PEm.js";
1
+ import { i as CostLedger } from "./cost-ledger-CZ9diLxY.js";
2
+ import { a as assertLlmRoute, c as callLlmJson, f as maximumChargeForLlmRequest, i as LlmRouteAssertionError, l as costReceiptFromLlm, u as costReceiptFromLlmError } from "./llm-client-bkztEfIx.js";
3
3
  import { z } from "zod";
4
4
  import { readFileSync } from "node:fs";
5
5
  import { dirname, resolve } from "node:path";
@@ -1037,4 +1037,4 @@ function startServerAsync(opts = {}) {
1037
1037
  //#endregion
1038
1038
  export { TraceEventSchema as A, HealthResponseSchema as C, RubricDimensionSchema as D, ListRubricsResponseSchema as E, hashRubric as F, TracesIngestResponseSchema as M, VersionResponseSchema as N, RubricInfoSchema as O, WIRE_VERSION as P, FeedbackTrajectorySchema as S, JudgeResultSchema as T, ErrorResponseSchema as _, runRpcBatch as a, FeedbackIngestResponseSchema as b, WireError as c, handleListRubrics as d, handleTracesIngest as f, listBuiltinRubrics as g, getBuiltinRubric as h, dispatchRpc as i, TracesIngestRequestSchema as j, RubricSchema as k, handleFeedbackIngest as l, BUILTIN_RUBRICS as m, startServer as n, runRpcOnce as o, handleVersion as p, startServerAsync as r, buildOpenApi as s, createApp as t, handleJudge as u, FailureModeSchema as v, JudgeRequestSchema as w, FeedbackLabelSchema as x, FeedbackAttemptSchema as y };
1039
1039
 
1040
- //# sourceMappingURL=server-DLEvyW2z.js.map
1040
+ //# sourceMappingURL=server-DaCpLfi0.js.map