@tangle-network/agent-eval 0.144.8 → 0.144.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +3 -0
  3. package/dist/{agent-profile-CgDTo40f.d.ts → agent-profile-DPi7IZg7.d.ts} +3 -3
  4. package/dist/{agent-profile-CgDTo40f.d.ts.map → agent-profile-DPi7IZg7.d.ts.map} +1 -1
  5. package/dist/analyst/index.d.ts +9 -9
  6. package/dist/analyst/index.js +7 -7
  7. package/dist/{analyze-runs-BNNK7irB.js → analyze-runs-C30yljDJ.js} +2 -2
  8. package/dist/{analyze-runs-BNNK7irB.js.map → analyze-runs-C30yljDJ.js.map} +1 -1
  9. package/dist/{benchmark-B181aMF9.js → benchmark-CWeqGl7x.js} +2 -2
  10. package/dist/{benchmark-B181aMF9.js.map → benchmark-CWeqGl7x.js.map} +1 -1
  11. package/dist/{benchmark-command-BKENp2s5.js → benchmark-command-D3fEnKdf.js} +8 -8
  12. package/dist/{benchmark-command-BKENp2s5.js.map → benchmark-command-D3fEnKdf.js.map} +1 -1
  13. package/dist/benchmarks/index.d.ts +1 -1
  14. package/dist/benchmarks/index.js +1 -1
  15. package/dist/{benchmarks-BlPmjd88.js → benchmarks-BzqyTvAr.js} +4 -4
  16. package/dist/{benchmarks-BlPmjd88.js.map → benchmarks-BzqyTvAr.js.map} +1 -1
  17. package/dist/campaign/index.d.ts +8 -8
  18. package/dist/campaign/index.js +5 -5
  19. package/dist/{campaign--HVSuvV0.js → campaign-ccOrVCuR.js} +6 -6
  20. package/dist/{campaign--HVSuvV0.js.map → campaign-ccOrVCuR.js.map} +1 -1
  21. package/dist/cli.js +1 -1
  22. package/dist/{client-DjXROWpx.d.ts → client-C9gzZE59.d.ts} +4 -4
  23. package/dist/{client-DjXROWpx.d.ts.map → client-C9gzZE59.d.ts.map} +1 -1
  24. package/dist/{completion-verifier-foUCLif_.d.ts → completion-verifier-DJA5BhPb.d.ts} +3 -3
  25. package/dist/{completion-verifier-foUCLif_.d.ts.map → completion-verifier-DJA5BhPb.d.ts.map} +1 -1
  26. package/dist/contract/index.d.ts +9 -9
  27. package/dist/contract/index.js +9 -9
  28. package/dist/contract/index.js.map +1 -1
  29. package/dist/control.d.ts +2 -2
  30. package/dist/control.js +1 -1
  31. package/dist/{default-registry-BZhStdjl.d.ts → default-registry-Bf8Woqmq.d.ts} +6 -6
  32. package/dist/{default-registry-BZhStdjl.d.ts.map → default-registry-Bf8Woqmq.d.ts.map} +1 -1
  33. package/dist/{default-registry-BaQXW1Ow.js → default-registry-BmktKy8r.js} +3 -3
  34. package/dist/{default-registry-BaQXW1Ow.js.map → default-registry-BmktKy8r.js.map} +1 -1
  35. package/dist/{dspy-rlm-engine-BiN49gK6.js → dspy-rlm-engine-DbTk4JdR.js} +3 -3
  36. package/dist/{dspy-rlm-engine-BiN49gK6.js.map → dspy-rlm-engine-DbTk4JdR.js.map} +1 -1
  37. package/dist/{engine-nB64f48I.d.ts → engine-3hL-XqwJ.d.ts} +7 -7
  38. package/dist/{engine-nB64f48I.d.ts.map → engine-3hL-XqwJ.d.ts.map} +1 -1
  39. package/dist/{eval-campaign-DNjCvAm-.js → eval-campaign-B_7wcnav.js} +2 -2
  40. package/dist/{eval-campaign-DNjCvAm-.js.map → eval-campaign-B_7wcnav.js.map} +1 -1
  41. package/dist/{exact-types-Djvzosly.d.ts → exact-types-DSFFpLLI.d.ts} +2 -2
  42. package/dist/{exact-types-Djvzosly.d.ts.map → exact-types-DSFFpLLI.d.ts.map} +1 -1
  43. package/dist/experiment/index.d.ts +2 -2
  44. package/dist/{extract-usage-BW27f3XW.js → extract-usage-CdZdoj1s.js} +2 -2
  45. package/dist/{extract-usage-BW27f3XW.js.map → extract-usage-CdZdoj1s.js.map} +1 -1
  46. package/dist/{feedback-trajectory-Rh280oXo.d.ts → feedback-trajectory-CacHpxsp.d.ts} +3 -3
  47. package/dist/{feedback-trajectory-Rh280oXo.d.ts.map → feedback-trajectory-CacHpxsp.d.ts.map} +1 -1
  48. package/dist/hosted/index.d.ts +3 -3
  49. package/dist/{index-CvXXlyz7.d.ts → index-BnEuDAK2.d.ts} +2 -2
  50. package/dist/{index-CvXXlyz7.d.ts.map → index-BnEuDAK2.d.ts.map} +1 -1
  51. package/dist/{index-CwDrUMe0.d.ts → index-CQTZ-4XN.d.ts} +2 -2
  52. package/dist/{index-CwDrUMe0.d.ts.map → index-CQTZ-4XN.d.ts.map} +1 -1
  53. package/dist/{index-C5HOo4ZF2.d.ts → index-CwYZNzMD2.d.ts} +5 -5
  54. package/dist/{index-C5HOo4ZF2.d.ts.map → index-CwYZNzMD2.d.ts.map} +1 -1
  55. package/dist/{index-Sh2I0DRc.d.ts → index-DvvvSho7.d.ts} +9 -9
  56. package/dist/{index-Sh2I0DRc.d.ts.map → index-DvvvSho7.d.ts.map} +1 -1
  57. package/dist/index.d.ts +22 -22
  58. package/dist/index.js +18 -18
  59. package/dist/{insight-report-C6h6F_4L.d.ts → insight-report-CgX_s0Ez.d.ts} +3 -3
  60. package/dist/{insight-report-C6h6F_4L.d.ts.map → insight-report-CgX_s0Ez.d.ts.map} +1 -1
  61. package/dist/{kind-factory-BHIgPmzS.js → kind-factory-B8-r8-y8.js} +3 -16
  62. package/dist/kind-factory-B8-r8-y8.js.map +1 -0
  63. package/dist/meta-eval/index.d.ts +1 -1
  64. package/dist/{mint-CGEkzPLf.js → mint-B2O60ACG.js} +2 -2
  65. package/dist/{mint-CGEkzPLf.js.map → mint-B2O60ACG.js.map} +1 -1
  66. package/dist/multishot/index.d.ts +1 -1
  67. package/dist/openapi.json +1 -1
  68. package/dist/{promotion-policy-ChWhTDBH.d.ts → promotion-policy-Ckjhzg_4.d.ts} +2 -2
  69. package/dist/{promotion-policy-ChWhTDBH.d.ts.map → promotion-policy-Ckjhzg_4.d.ts.map} +1 -1
  70. package/dist/{propose-review-control-qgWLA6E9.js → propose-review-control-dSNPjFUH.js} +2 -2
  71. package/dist/{propose-review-control-qgWLA6E9.js.map → propose-review-control-dSNPjFUH.js.map} +1 -1
  72. package/dist/{release-report-Dy39cbFF.js → release-report-BUYmoKo2.js} +2 -2
  73. package/dist/{release-report-Dy39cbFF.js.map → release-report-BUYmoKo2.js.map} +1 -1
  74. package/dist/{release-report-CI8uisI1.d.ts → release-report-DA2BCu5a.d.ts} +3 -3
  75. package/dist/{release-report-CI8uisI1.d.ts.map → release-report-DA2BCu5a.d.ts.map} +1 -1
  76. package/dist/{replay-DyBLaKFc.js → replay-CohS93nE.js} +5 -5
  77. package/dist/{replay-DyBLaKFc.js.map → replay-CohS93nE.js.map} +1 -1
  78. package/dist/{replay-DFf-teiC.d.ts → replay-DbhZ4Ked.d.ts} +5 -5
  79. package/dist/{replay-DFf-teiC.d.ts.map → replay-DbhZ4Ked.d.ts.map} +1 -1
  80. package/dist/reporting.d.ts +3 -3
  81. package/dist/reporting.js +1 -1
  82. package/dist/{researcher-BoaxeCzP.d.ts → researcher-BchpD55R.d.ts} +3 -3
  83. package/dist/{researcher-BoaxeCzP.d.ts.map → researcher-BchpD55R.d.ts.map} +1 -1
  84. package/dist/{reward-hacking-B2tPL9a3.js → reward-hacking-BDToousL.js} +4 -3
  85. package/dist/reward-hacking-BDToousL.js.map +1 -0
  86. package/dist/{reward-hacking-Cf1PtEOz.d.ts → reward-hacking-BI0OMAlo.d.ts} +2 -2
  87. package/dist/{reward-hacking-Cf1PtEOz.d.ts.map → reward-hacking-BI0OMAlo.d.ts.map} +1 -1
  88. package/dist/rl.d.ts +5 -5
  89. package/dist/rl.js +4 -4
  90. package/dist/rollout/index.d.ts +1 -1
  91. package/dist/rollout/index.js +2 -2
  92. package/dist/{rollout-2ECTXb2N.js → rollout-DRrksrcV.js} +2 -2
  93. package/dist/{rollout-2ECTXb2N.js.map → rollout-DRrksrcV.js.map} +1 -1
  94. package/dist/{rubric-predictive-validity-9qAwzkZm.d.ts → rubric-predictive-validity-DvkjPYCe.d.ts} +2 -2
  95. package/dist/{rubric-predictive-validity-9qAwzkZm.d.ts.map → rubric-predictive-validity-DvkjPYCe.d.ts.map} +1 -1
  96. package/dist/{run-evidence-BDFFai9R.d.ts → run-evidence-Dhi3C81V.d.ts} +3 -3
  97. package/dist/{run-evidence-BDFFai9R.d.ts.map → run-evidence-Dhi3C81V.d.ts.map} +1 -1
  98. package/dist/{run-record-DqOw5X6_.js → run-record-BmSPWXJR.js} +2 -1
  99. package/dist/run-record-BmSPWXJR.js.map +1 -0
  100. package/dist/{run-record-DdSa93_W.d.ts → run-record-CF4Dwpxr.d.ts} +4 -1
  101. package/dist/run-record-CF4Dwpxr.d.ts.map +1 -0
  102. package/dist/{semantic-concept-judge-Bmrq6yqU.js → semantic-concept-judge-D1z-KepS.js} +2 -2
  103. package/dist/{semantic-concept-judge-Bmrq6yqU.js.map → semantic-concept-judge-D1z-KepS.js.map} +1 -1
  104. package/dist/{single-run-lock-BMQEv1wG.js → single-run-lock-DFWHEB09.js} +123 -123
  105. package/dist/{single-run-lock-BMQEv1wG.js.map → single-run-lock-DFWHEB09.js.map} +1 -1
  106. package/dist/{skill-usage-CJlWEUFt.d.ts → skill-usage-CO9OLRBx.d.ts} +6 -6
  107. package/dist/{skill-usage-CJlWEUFt.d.ts.map → skill-usage-CO9OLRBx.d.ts.map} +1 -1
  108. package/dist/{skillopt-optimization-method-BO7NAl3b.d.ts → skillopt-optimization-method-9J8dJbrM.d.ts} +40 -8
  109. package/dist/skillopt-optimization-method-9J8dJbrM.d.ts.map +1 -0
  110. package/dist/{skillopt-optimization-method-CkaI2ly4.js → skillopt-optimization-method-D6Q4dLbh.js} +301 -133
  111. package/dist/skillopt-optimization-method-D6Q4dLbh.js.map +1 -0
  112. package/dist/{statistical-heldout-Dn9ruizm.d.ts → statistical-heldout-TQ-4CYiN.d.ts} +3 -3
  113. package/dist/{statistical-heldout-Dn9ruizm.d.ts.map → statistical-heldout-TQ-4CYiN.d.ts.map} +1 -1
  114. package/dist/{store-otlp-CKtTpRhv.js → store-otlp-Dw8PPIlL.js} +2 -2
  115. package/dist/{store-otlp-CKtTpRhv.js.map → store-otlp-Dw8PPIlL.js.map} +1 -1
  116. package/dist/{summary-report-DuUS_i7W.d.ts → summary-report-BNR7DWTj.d.ts} +2 -2
  117. package/dist/{summary-report-DuUS_i7W.d.ts.map → summary-report-BNR7DWTj.d.ts.map} +1 -1
  118. package/dist/{tool-groups-DIVBnJyl.d.ts → tool-groups-CZPGGlHf.d.ts} +3 -3
  119. package/dist/tool-groups-CZPGGlHf.d.ts.map +1 -0
  120. package/dist/trace-repair/index.d.ts +2 -2
  121. package/dist/traces.d.ts +4 -4
  122. package/dist/traces.js +4 -4
  123. package/dist/{types-DYuNHo9R.d.ts → types-BnjdJ70P.d.ts} +3 -3
  124. package/dist/{types-DYuNHo9R.d.ts.map → types-BnjdJ70P.d.ts.map} +1 -1
  125. package/dist/{types-DF_Udrp-.d.ts → types-BvDKaULh.d.ts} +2 -2
  126. package/dist/{types-DF_Udrp-.d.ts.map → types-BvDKaULh.d.ts.map} +1 -1
  127. package/dist/{usage-receipt-EVI8B8Xu.js → usage-receipt-t7vAzCRQ.js} +15 -2
  128. package/dist/usage-receipt-t7vAzCRQ.js.map +1 -0
  129. package/dist/wire/index.d.ts +1 -1
  130. package/docs/concepts.md +1 -0
  131. package/package.json +1 -1
  132. package/dist/kind-factory-BHIgPmzS.js.map +0 -1
  133. package/dist/reward-hacking-B2tPL9a3.js.map +0 -1
  134. package/dist/run-record-DdSa93_W.d.ts.map +0 -1
  135. package/dist/run-record-DqOw5X6_.js.map +0 -1
  136. package/dist/skillopt-optimization-method-BO7NAl3b.d.ts.map +0 -1
  137. package/dist/skillopt-optimization-method-CkaI2ly4.js.map +0 -1
  138. package/dist/tool-groups-DIVBnJyl.d.ts.map +0 -1
  139. package/dist/usage-receipt-EVI8B8Xu.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["hashString","ANALYSIS_ARTIFACT","isRecord","sessionIdFromEntries","fallbackSessionId","stringField","record","numberField"],"sources":["../../src/contract/self-improve.ts","../../src/contract/define-agent-eval.ts","../../src/contract/fixed-spend.ts","../../src/contract/concurrent-map.ts","../../src/contract/paid-paired-measurement.ts","../../src/contract/measured-comparison.ts","../../src/contract/profile-measured-comparison.ts","../../src/contract/intake/run-record-dir.ts","../../src/contract/eval-reporting-suite.ts","../../src/contract/diff.ts","../../src/contract/intake/agent-trace.ts","../../src/contract/intake/code-agent-observation.ts","../../src/contract/intake/code-agent-session.ts","../../src/contract/intake/feedback-table.ts","../../src/contract/intake/otel-spans.ts"],"sourcesContent":["/**\n * Run one complete improvement job.\n *\n * A caller-owned `proposer` can generate candidates across local generations.\n * An external `method`, such as official GEPA or SkillOpt, owns its complete\n * search and returns one candidate. Both paths remeasure the selected candidate\n * against cases that candidate generation never receives.\n */\n\nimport type { ProposalFinding } from '../analyst/types'\nimport { defaultProductionGate } from '../campaign/gates/default-production-gate'\nimport { type PowerPreflight, powerPreflight } from '../campaign/gates/power-preflight'\nimport {\n assertOptimizationResult,\n type OptimizationMethod,\n type OptimizationMethodProvenance,\n type OptimizationMethodResult,\n} from '../campaign/presets/compare-optimization-methods'\nimport {\n type RunImprovementLoopResult,\n runImprovementLoop,\n} from '../campaign/presets/run-improvement-loop'\nimport type {\n PremeasuredOptimizationBaseline,\n RunOptimizationOptions,\n} from '../campaign/presets/run-optimization'\nimport {\n emitLoopProvenance,\n type LoopProvenanceRecord,\n loopProvenanceArgsFromResult,\n} from '../campaign/provenance'\nimport { resolveRunDir } from '../campaign/run-dir'\nimport {\n campaignCellExecutionEvidence,\n campaignCellJudgeDimensions,\n campaignCellTaskScore,\n campaignCellToRunRecord,\n} from '../campaign/run-record'\nimport {\n type CampaignStorage,\n createRunCostLedger,\n fsCampaignStorage,\n inMemoryCampaignStorage,\n} from '../campaign/storage'\nimport { surfaceContentHash, surfaceHash } from '../campaign/surface-identity'\nimport type {\n CampaignCellResult,\n DispatchContext,\n Gate,\n JudgeConfig,\n LabeledScenarioStore,\n MutableSurface,\n Scenario,\n SurfaceProposer,\n} from '../campaign/types'\nimport type { CostLedgerHandle, CostLedgerSummary, CostReceipt } from '../cost-ledger'\nimport { ValidationError } from '../errors'\nimport { createHostedClient, type HostedTenant } from '../hosted/client'\nimport type { EvalRunCellScore, EvalRunEvent, EvalRunGenerationSnapshot } from '../hosted/types'\nimport { modelHasSnapshot, type RunRecord, type RunSplitTag } from '../run-record'\nimport { analyzeRuns } from './analyze-runs'\nimport type { InsightReport } from './insight-report'\n\nexport interface SelfImproveBudget {\n /** Hard spend cap across the full run. Each paid call reserves its enforced\n * maximum before dispatch, so completed spend cannot cross this amount. */\n dollars?: number\n /** Proposer generations. Default: 3. External methods own their rounds and\n * require this value to be omitted or set to 1. Set 0 only for a\n * proposer-free baseline run. */\n generations?: number\n /** Candidates the proposer emits per generation. Default 2. */\n populationSize?: number\n /** Max concurrent cells across the loop. Default 2. */\n maxConcurrency?: number\n /** Candidate campaigns scored in parallel. Default 1. Total concurrent\n * cells are bounded by `candidateConcurrency * maxConcurrency`. */\n candidateConcurrency?: number\n /** Fraction of `scenarios` held out from training, used for the gate.\n * Default 0.25. Ignored when `holdoutScenarios` is set explicitly. */\n holdoutFraction?: number\n /** Fraction of the non-final cases reserved for method selection.\n * Default 0.25. Used only with `method` and ignored when\n * `selectionScenarios` is supplied explicitly. */\n selectionFraction?: number\n /** Explicit held-out scenarios; overrides `holdoutFraction`. */\n holdoutScenarios?: Scenario[]\n /** Holdout policy. Default `'measured'`: split, re-score baseline vs winner\n * on the held-out set, gate on that comparison. `'deferred'`: run the\n * improvement-set campaigns + search promotion, dispatch ZERO holdout cells,\n * force the gate to `'hold'`, return `lift: undefined`, and record\n * `holdout: 'deferred'` in the provenance record — for callers that measure\n * the held-out comparison in a separate later run instead of faking a\n * static holdout scenario and recording a meaningless lift. Unless\n * `holdoutScenarios` reserves an explicit set, ALL scenarios train. */\n holdout?: 'measured' | 'deferred'\n /** Per-scenario replicates per cell — raises bootstrap-CI tightness. Default 1. */\n reps?: number\n /** DEPTH dial forwarded to the proposer's `propose()` as\n * `ctx.maxImprovementShots` — max iterations an agentic candidate generator\n * may take per candidate (verify-in-session retries). Unset ⇒ the\n * proposer's own default. */\n maxImprovementShots?: number\n}\n\nexport type SelfImproveProgressEvent =\n | { kind: 'baseline.started'; scenarios: number }\n | { kind: 'baseline.completed'; compositeMean: number; durationMs: number }\n | { kind: 'generation.started'; index: number; populationSize: number }\n | { kind: 'generation.completed'; index: number; bestComposite: number; durationMs: number }\n // `lift` is absent when `budget.holdout === 'deferred'` — no held-out\n // measurement ran, and the search-split delta must not masquerade as one.\n | { kind: 'gate.decided'; decision: string; lift?: number }\n | { kind: 'power.estimated'; n: number; sd: number; mde: number; underpowered: boolean }\n\nexport interface SelfImproveOptions<TScenario extends Scenario, TArtifact> {\n /**\n * Your agent — a function that takes the current `MutableSurface`\n * (typically a system prompt the loop is optimizing) plus the\n * scenario + cell ctx, and returns the artifact your judge scores.\n *\n * Same shape as `RunOptimizationOptions.dispatchWithSurface`. Wrap a\n * plain `Dispatch` if you don't have a surface seam:\n *\n * agent: (_surface, scenario, ctx) => yourPlainDispatch(scenario, ctx)\n *\n * That mode evaluates without mutating any surface — useful as a\n * baseline-only run (set `budget.generations = 0`).\n */\n agent: (surface: MutableSurface, scenario: TScenario, ctx: DispatchContext) => Promise<TArtifact>\n\n /**\n * Snapshot-bearing model identity for agents that do not report a paid-call\n * receipt through `ctx.cost.runPaidCall()`.\n *\n * Omit this when every cell reports its concrete model in a receipt.\n */\n model?: string\n\n /** Scenarios to evaluate against. Train/holdout split is computed from\n * these unless `budget.holdoutScenarios` is set explicitly. */\n scenarios: TScenario[]\n\n /** Judge that scores artifacts. Bring your own; use `langchainJudge`\n * from `/adapters/langchain` for a Runnable-shaped one. */\n judge: JudgeConfig<TArtifact, TScenario>\n\n /** Starting surface — system prompt, JSON config, anything `MutableSurface`\n * accepts. The proposer mutates this each generation. */\n baselineSurface: MutableSurface\n\n /** Budget + loop shape. All fields optional. */\n budget?: SelfImproveBudget\n\n /**\n * Complete prior measurement of `baselineSurface` over the TRAIN split.\n * Forwarded to the loop body, which validates its surface hash, scenario\n * split, seed (42), reps, and coverage, then skips the baseline search\n * campaign entirely — no baseline dispatch, no resumability lookup. The\n * train split is `scenarios` minus the holdout split, so premeasure with\n * exactly that scenario set (explicit `budget.holdoutScenarios`, or\n * `budget.holdout: 'deferred'` with no reserved set, makes the train split\n * deterministic). Prior spend stays in the imported campaign aggregates and\n * is not re-added to this run's cost ledger.\n */\n premeasuredBaseline?: PremeasuredOptimizationBaseline<TArtifact, TScenario>\n\n /**\n * Candidate generator for this local generation loop.\n * Required when `budget.generations` is greater than zero.\n */\n proposer?: SurfaceProposer<ProposalFinding>\n\n /**\n * Complete optimization method, such as official GEPA or SkillOpt.\n * The method receives disjoint train and selection cases and never receives\n * the final comparison cases. Mutually exclusive with `proposer`.\n */\n method?: OptimizationMethod<TScenario, TArtifact>\n\n /** Explicit method-selection cases. They must also appear in `scenarios`\n * and must not overlap the final comparison cases. */\n selectionScenarios?: TScenario[]\n\n /** Custom gate. Default is `defaultProductionGate` with\n * `deltaThreshold: 0.05` on the held-out split. */\n gate?: Gate<TArtifact, TScenario>\n\n /** Placebo control. When supplied AND the winner differs from baseline, the\n * loop scores a THIRD held-out arm: the winner surface with its content\n * footprint-matched-blanked by this fn (typically via `neutralizeText`). Its\n * scores reach the gate as `ctx.neutralizedJudgeScores`, letting a\n * `neutralizationGate` reject a win whose lift survives blanking the content\n * (decorative — driven by footprint, not content). Costs one extra held-out\n * campaign; omit to skip. Compose `neutralizationGate` into `gate` to act on it. */\n neutralize?: (winnerSurface: MutableSurface, baselineSurface: MutableSurface) => MutableSurface\n\n /** Storage backend. A filesystem run directory uses `fsCampaignStorage()`;\n * a `mem://` directory uses in-memory storage. External methods default to\n * a filesystem directory because their official state must survive. */\n storage?: CampaignStorage\n\n /** Run directory. Proposer mode defaults to\n * `mem://selfImprove-<timestamp>`. External method mode defaults to\n * `.agent-eval/runs/self-improve-<timestamp>`. */\n runDir?: string\n\n /** Fires once the durable provenance record + OTel spans are emitted.\n * Receives the structured record for inline assertions / custom routing. */\n onProvenance?: (record: LoopProvenanceRecord) => void\n\n /** Distributed execution seam — same as `RunCampaignOptions.cellPlacement`.\n * Returns an opaque placement key the substrate forwards to your agent\n * as `ctx.placement`. Combined with `httpDispatch` from\n * `/adapters/http`, fans cells across regions. */\n cellPlacement?: (input: {\n scenario: TScenario\n rep: number\n generation?: number\n }) => string | undefined\n\n /** Per-cell agent dispatch deadline, applied to baseline, candidate, and\n * held-out campaigns. Default 600_000 ms. Set 0 to disable. */\n dispatchTimeoutMs?: number\n\n /** Streaming hook — fires on baseline + each generation + gate decision.\n * Consumer routes events wherever (UI, dashboard, logs). */\n onProgress?: (event: SelfImproveProgressEvent) => void\n\n /** Auto-promotion behavior on a ship decision. Default `'none'` — we\n * return the winner; you ship it however you ship. `'pr'` opens a\n * GitHub PR via `openAutoPr`; requires `ghOwner` + `ghRepo`. */\n autoOnPromote?: 'pr' | 'none'\n ghOwner?: string\n ghRepo?: string\n\n /**\n * Opt-in: ship eval-run events to a hosted orchestrator (ours, your\n * self-hosted one, or any compatible implementation of the\n * `docs/hosted-ingest-spec.md` wire format). When set, the substrate\n * POSTs the final `EvalRunEvent` to `${endpoint}/v1/ingest/eval-runs`\n * after the loop completes. Failures are logged but do not fail the\n * loop — local result is always returned.\n *\n * For our orchestrator: `{ endpoint: 'https://orchestrator.tangle.tools/v1', apiKey, tenantId }`.\n *\n * For your self-hosted: any URL serving the wire format. See\n * `examples/hosted-ingest-server/` for the reference receiver.\n */\n hostedTenant?: HostedTenant\n\n /** Free-form labels attached to the hosted event (env, branch, model id,\n * etc.). Ignored when `hostedTenant` is unset. */\n hostedLabels?: Record<string, string>\n\n /** Capture every search artifact and judge score to this store.\n * The store is output only and is never exposed to candidate generation.\n * Pass `'off'` to disable. Default: off. */\n labeledStore?: LabeledScenarioStore | 'off'\n\n /** Capture-source tag for `labeledStore`. Default `'eval-run'`. */\n captureSource?: 'production-trace' | 'eval-run' | 'manual' | 'red-team' | 'synthetic'\n\n /**\n * Per-cell backend-integrity expectation — the fail-loud guard. A cell that\n * produced an artifact but reported `costUsd === 0` AND zero tokens is a\n * stub. Modes: `'assert'` throws on the first such cell, `'warn'` logs it,\n * `'off'` skips the check (offline/replay). Default `'assert'` — `selfImprove`\n * is the real-run path, so a stub fails loud rather than scoring a clean 0.\n */\n expectUsage?: 'assert' | 'warn' | 'off'\n\n /**\n * Per-generation findings producer. Runs once on the baseline campaign (as\n * `generation: -1`) before generation 0 proposes — so single-generation runs\n * propose with trace context — and again after each generation is scored;\n * whatever it returns REPLACES the proposer's `findings` for the next\n * `propose()`. Plug a trace-analyst registry / HALO here. When absent,\n * findings stay `opts.findings`.\n */\n analyzeGeneration?: RunOptimizationOptions<TScenario, TArtifact>['analyzeGeneration']\n\n /** Static findings forwarded to the proposer's `propose()` as `ctx.findings`\n * (a findings-grounded proposer consumes them). Default: none. */\n findings?: ProposalFinding[]\n\n /** Override how the WINNER is selected among coverage-complete candidates.\n * Defaults to the scalar mean composite (historical behavior). A binary-with-\n * replicates consumer whose ship-gate counts an instance resolved only when\n * every replicate resolved passes a fail-closed lexicographic key here so that\n * winner-selection and the ship-gate rank on the identical metric and cannot\n * invert. See `RunOptimizationOptions.selectionRankKey`. */\n selectionRankKey?: RunOptimizationOptions<TScenario, TArtifact>['selectionRankKey']\n}\n\nexport interface SelfImproveResult<TScenario extends Scenario, TArtifact> {\n /** Composite mean across all scenarios, baseline run. When\n * `budget.holdout === 'deferred'` this is measured on the improvement\n * (search) split — no holdout campaign ran. */\n baseline: {\n compositeMean: number\n perScenario: Record<string, number>\n }\n /** Composite mean on the held-out set, winner run. When\n * `budget.holdout === 'deferred'` this is the winner's improvement-set\n * (search) measurement — no holdout campaign ran. */\n winner: {\n compositeMean: number\n perScenario: Record<string, number>\n surface: MutableSurface\n /** Proposer label for the promoted change. Absent ⇒ winner == baseline or\n * a bare-surface mutator. */\n label?: string\n /** Proposer rationale — the \"because Z\" that motivated the promoted change.\n * Threaded from the proposer's `ProposedCandidate` through the loop.\n * Absent ⇒ winner == baseline. */\n rationale?: string\n }\n /** `winner.compositeMean - baselineOnHoldout.compositeMean`. Positive\n * means the gate observed improvement. Absent iff\n * `budget.holdout === 'deferred'` — no held-out measurement ran, so there\n * is no lift to report (never a fabricated 0). */\n lift?: number\n /** The explicit baseline→winner unified diff. Always present (empty string\n * when winner == baseline). */\n diff: string\n /** Durable, queryable provenance record: candidate→cell→gate→promote chain +\n * rationale + diff + backend provenance. The artifact the hosted ingest\n * path stores; the +lift RECOMPUTES from `record.heldOutLift`. */\n provenance: LoopProvenanceRecord\n /** `defaultProductionGate.decide()` result. */\n gateDecision: 'ship' | 'hold' | 'need_more_work' | 'model_ceiling' | 'arch_ceiling'\n /** Number of generations actually explored (may be less than the\n * budget if the proposer gave up early). */\n generationsExplored: number\n /** Wall-clock total. */\n durationMs: number\n /** Total newly observed cost across the full run. */\n totalCostUsd: number\n /** Canonical run-wide spend summary. */\n cost: CostLedgerSummary\n /** Run-wide receipts across proposal, search, holdout, judging, analysis,\n * and promotion work, with phase and actor attribution. */\n receipts: CostReceipt[]\n /** Exact external method and source identity, when `method` was used. */\n optimization?: {\n name: string\n cost: OptimizationMethodResult['cost']\n durationMs?: number\n provenance?: OptimizationMethodProvenance\n }\n /**\n * Rigor packet: distributional summary, paired-bootstrap lift CI,\n * judge stats, contamination check, recommendations. Wired through\n * `analyzeRuns()` on the baseline + winner cells of the campaign.\n * Hosted-tier dashboards render this as the v3-vs-v4 decision view.\n */\n insight: InsightReport\n /** Minimum-detectable-lift analysis from the baseline holdout cells: could this\n * budget have shipped ANY plausible effect? Absent when the baseline produced\n * fewer than 3 scored holdout cells. See `powerPreflight` for the standalone\n * pre-run version (run `gate: 'none'` first, budget the real search after). */\n power?: PowerPreflight\n /**\n * Raw substrate result for advanced inspection — full per-generation\n * candidates, full campaign artifacts, all judge scores. Useful for\n * debugging or reporting beyond the summary.\n */\n raw: RunImprovementLoopResult<TArtifact, TScenario>\n}\n\n/** Failed self-improvement run with an immutable receipt snapshot. */\nexport class SelfImproveRunError extends Error {\n readonly cost: CostLedgerSummary\n readonly receipts: CostReceipt[]\n\n constructor(cause: unknown, ledger: CostLedgerHandle) {\n const original = cause instanceof Error ? cause : new Error(String(cause))\n super(original.message, { cause: original })\n this.name = 'SelfImproveRunError'\n this.cost = ledger.summary()\n this.receipts = ledger.list()\n }\n}\n\nfunction assertSelfImproveSearchMode<TScenario extends Scenario, TArtifact>(\n opts: SelfImproveOptions<TScenario, TArtifact>,\n): void {\n if (opts.method && opts.proposer) {\n throw new Error('selfImprove: method and proposer are mutually exclusive')\n }\n if (!opts.method) {\n if (opts.selectionScenarios !== undefined) {\n throw new Error('selfImprove: selectionScenarios requires method')\n }\n return\n }\n if (\n typeof opts.method.name !== 'string' ||\n !opts.method.name.trim() ||\n opts.method.name.trim() !== opts.method.name ||\n typeof opts.method.optimize !== 'function'\n ) {\n throw new Error('selfImprove: method must have a trimmed name and optimize(input)')\n }\n const budget = opts.budget\n if (budget?.generations !== undefined && budget.generations !== 1) {\n throw new Error('selfImprove: method owns its rounds; budget.generations must be 1 when set')\n }\n if (budget?.populationSize !== undefined && budget.populationSize !== 1) {\n throw new Error(\n 'selfImprove: method owns its candidates; budget.populationSize must be 1 when set',\n )\n }\n if (\n budget?.candidateConcurrency !== undefined ||\n budget?.maxImprovementShots !== undefined ||\n opts.analyzeGeneration !== undefined ||\n opts.findings !== undefined\n ) {\n throw new Error(\n 'selfImprove: candidateConcurrency, maxImprovementShots, analyzeGeneration, and findings apply only to proposer mode',\n )\n }\n}\n\nfunction splitMethodPartitions<TScenario extends Scenario>(\n searchScenarios: TScenario[],\n explicitSelection: TScenario[] | undefined,\n fraction: number,\n): { train: TScenario[]; selection: TScenario[] } {\n if (!Number.isFinite(fraction) || fraction <= 0 || fraction >= 1) {\n throw new Error('selfImprove: budget.selectionFraction must be in (0, 1)')\n }\n const byId = new Map<string, TScenario>()\n for (const scenario of searchScenarios) {\n if (byId.has(scenario.id)) {\n throw new Error(`selfImprove: duplicate scenario id '${scenario.id}'`)\n }\n byId.set(scenario.id, scenario)\n }\n if (explicitSelection) {\n if (explicitSelection.length === 0) {\n throw new Error('selfImprove: selectionScenarios must not be empty')\n }\n const selectionIds = new Set<string>()\n for (const scenario of explicitSelection) {\n if (!byId.has(scenario.id)) {\n throw new Error(\n `selfImprove: selection scenario '${scenario.id}' is absent from the non-final cases`,\n )\n }\n if (selectionIds.has(scenario.id)) {\n throw new Error(`selfImprove: duplicate selection scenario id '${scenario.id}'`)\n }\n selectionIds.add(scenario.id)\n }\n const train = searchScenarios.filter((scenario) => !selectionIds.has(scenario.id))\n if (train.length === 0) {\n throw new Error('selfImprove: method train split is empty')\n }\n return {\n train,\n selection: explicitSelection.map((scenario) => byId.get(scenario.id)!),\n }\n }\n if (searchScenarios.length < 2) {\n throw new Error('selfImprove: method requires at least two non-final scenarios')\n }\n const sorted = [...searchScenarios].sort(\n (a, b) => stableScenarioHash(a.id) - stableScenarioHash(b.id),\n )\n const count = Math.max(1, Math.min(sorted.length - 1, Math.round(sorted.length * fraction)))\n return {\n selection: sorted.slice(0, count),\n train: sorted.slice(count),\n }\n}\n\nfunction safeRunComponent(value: string): string {\n return value.replace(/[^a-zA-Z0-9._-]/g, '_')\n}\n\nfunction stableScenarioHash(value: string): number {\n let hash = 2166136261 >>> 0\n for (let index = 0; index < value.length; index++) {\n hash ^= value.charCodeAt(index)\n hash = Math.imul(hash, 16777619) >>> 0\n }\n return hash\n}\n\n/**\n * Deterministic train/holdout split by a stable hash of `scenario.id`,\n * so the same scenario set always splits the same way across runs.\n */\nfunction splitTrainHoldout<TScenario extends Scenario>(\n scenarios: TScenario[],\n fraction: number,\n): { train: TScenario[]; holdout: TScenario[] } {\n const sorted = [...scenarios].sort((a, b) => stableScenarioHash(a.id) - stableScenarioHash(b.id))\n const nHoldout = Math.max(1, Math.min(sorted.length - 1, Math.round(sorted.length * fraction)))\n return {\n holdout: sorted.slice(0, nHoldout),\n train: sorted.slice(nHoldout),\n }\n}\n\nfunction meanComposite(byScenario: Record<string, { meanComposite: number }>): {\n compositeMean: number\n perScenario: Record<string, number>\n} {\n const perScenario: Record<string, number> = {}\n const values: number[] = []\n for (const [id, agg] of Object.entries(byScenario)) {\n perScenario[id] = agg.meanComposite\n values.push(agg.meanComposite)\n }\n return {\n compositeMean: values.length === 0 ? 0 : values.reduce((s, v) => s + v, 0) / values.length,\n perScenario,\n }\n}\n\n/**\n * Latest search campaign measured for the winner surface; the baseline search\n * campaign when the winner IS the baseline. Used by the deferred-holdout\n * summary, where no holdout campaign exists to summarize.\n */\nfunction winnerSearchCampaign<TScenario extends Scenario, TArtifact>(\n result: RunImprovementLoopResult<TArtifact, TScenario>,\n): RunImprovementLoopResult<TArtifact, TScenario>['baselineCampaign'] {\n for (let i = result.generations.length - 1; i >= 0; i--) {\n const measured = result.generations[i]?.surfaces.find(\n (s) => s.surfaceHash === result.winnerSurfaceHash,\n )\n if (measured) return measured.campaign\n }\n return result.baselineCampaign\n}\n\n/**\n * One-shot self-improvement loop. See module docstring for defaults +\n * extension points.\n *\n * @example Minimum:\n *\n * const result = await selfImprove({\n * agent: (surface, scenario, ctx) => myAgent(surface, scenario, ctx.signal),\n * scenarios,\n * judge,\n * baselineSurface: DEFAULT_PROMPT,\n * proposer,\n * })\n * console.log(`lift: ${result.lift.toFixed(3)} (${result.gateDecision})`)\n *\n * @example Distributed (workers in three regions):\n *\n * await selfImprove({\n * agent: httpDispatch({ resolveUrl: ({ placement }) => REGION_URLS[placement!] }),\n * scenarios,\n * judge,\n * baselineSurface: DEFAULT_PROMPT,\n * cellPlacement: ({ scenario }) => scenario.region,\n * budget: { maxConcurrency: 12 },\n * })\n */\nexport async function selfImprove<TScenario extends Scenario, TArtifact>(\n opts: SelfImproveOptions<TScenario, TArtifact>,\n): Promise<SelfImproveResult<TScenario, TArtifact>> {\n const startedAt = Date.now()\n const requestedRunDir =\n opts.runDir ??\n (opts.method ? `.agent-eval/runs/self-improve-${startedAt}` : `mem://selfImprove-${startedAt}`)\n const runDir = resolveRunDir(requestedRunDir)\n const storage =\n opts.storage ?? (runDir.startsWith('mem://') ? inMemoryCampaignStorage() : fsCampaignStorage())\n const costLedger = createRunCostLedger({\n storage,\n runDir,\n costCeilingUsd: opts.budget?.dollars,\n })\n try {\n return await runSelfImprove(opts, costLedger, startedAt, runDir, storage)\n } catch (error) {\n throw new SelfImproveRunError(error, costLedger)\n }\n}\n\nasync function runSelfImprove<TScenario extends Scenario, TArtifact>(\n opts: SelfImproveOptions<TScenario, TArtifact>,\n costLedger: CostLedgerHandle,\n startedAt: number,\n runDir: string,\n storage: CampaignStorage,\n): Promise<SelfImproveResult<TScenario, TArtifact>> {\n const budget = opts.budget ?? {}\n assertSelfImproveSearchMode(opts)\n const generations = opts.method ? 1 : (budget.generations ?? 3)\n const populationSize = opts.method ? 1 : (budget.populationSize ?? 2)\n const maxConcurrency = budget.maxConcurrency ?? 2\n const holdoutFraction = budget.holdoutFraction ?? 0.25\n const holdoutMode = budget.holdout ?? 'measured'\n const holdoutDeferred = holdoutMode === 'deferred'\n const expectUsage = opts.expectUsage ?? 'assert'\n\n // Deferred holdout without an explicitly reserved set trains on EVERYTHING:\n // there is no held-out measurement in this run, so carving out a fraction\n // would waste scenarios. An explicit `holdoutScenarios` set stays reserved\n // (excluded from training) even when deferred, for the later measured run.\n const explicitHoldout = budget.holdoutScenarios\n const { train, holdout } = explicitHoldout\n ? {\n train: opts.scenarios.filter((s) => !explicitHoldout.some((h) => h.id === s.id)),\n holdout: explicitHoldout as TScenario[],\n }\n : holdoutDeferred\n ? { train: opts.scenarios, holdout: [] as TScenario[] }\n : splitTrainHoldout(opts.scenarios, holdoutFraction)\n\n if (train.length === 0) {\n throw new Error(\n 'selfImprove: train split is empty. Reduce holdoutFraction or pass more scenarios.',\n )\n }\n if (holdout.length === 0 && !holdoutDeferred) {\n throw new Error('selfImprove: holdout split is empty. Pass more scenarios.')\n }\n\n if (generations > 0 && !opts.proposer && !opts.method) {\n throw new Error(\n 'selfImprove: method or proposer is required when budget.generations is greater than zero',\n )\n }\n let optimizationResult: OptimizationMethodResult | undefined\n const methodPartitions = opts.method\n ? splitMethodPartitions(train, opts.selectionScenarios, budget.selectionFraction ?? 0.25)\n : undefined\n const proposer: SurfaceProposer<ProposalFinding> = opts.method\n ? {\n kind: `method:${opts.method.name}`,\n propose: async (context) => {\n if (context.generation > 0) return []\n const result = await opts.method!.optimize(\n Object.freeze({\n baselineSurface: structuredClone(context.currentSurface),\n trainScenarios: Object.freeze(\n methodPartitions!.train.map((scenario) => structuredClone(scenario)),\n ),\n selectionScenarios: Object.freeze(\n methodPartitions!.selection.map((scenario) => structuredClone(scenario)),\n ),\n dispatchWithSurface: opts.agent,\n judges: Object.freeze([opts.judge]),\n runDir: `${runDir}/optimization/${safeRunComponent(opts.method!.name)}`,\n seed: 42,\n runOptions: Object.freeze({\n storage,\n maxConcurrency,\n reps: budget.reps,\n dispatchTimeoutMs: opts.dispatchTimeoutMs,\n expectUsage,\n costCeiling: budget.dollars,\n }),\n costLedger,\n }),\n )\n assertOptimizationResult(opts.method!.name, result)\n optimizationResult = structuredClone(result)\n return [\n {\n surface: structuredClone(result.winnerSurface),\n label: opts.method!.name,\n rationale: `${opts.method!.name} selected this surface without final cases.`,\n },\n ]\n },\n }\n : (opts.proposer ?? {\n kind: 'baseline-only',\n propose: async () => [],\n })\n\n const gate: Gate<TArtifact, TScenario> =\n opts.gate ??\n defaultProductionGate<TArtifact, TScenario>({\n holdoutScenarios: holdout,\n deltaThreshold: 0.05,\n })\n\n if (opts.onProgress) {\n opts.onProgress({ kind: 'baseline.started', scenarios: opts.scenarios.length })\n }\n\n const result = await runImprovementLoop<TScenario, TArtifact>({\n scenarios: train,\n baselineSurface: opts.baselineSurface,\n premeasuredBaseline: opts.premeasuredBaseline,\n dispatchWithSurface: opts.agent,\n proposer,\n judges: [opts.judge],\n populationSize,\n maxGenerations: generations,\n candidateConcurrency: budget.candidateConcurrency,\n reps: budget.reps,\n maxImprovementShots: budget.maxImprovementShots,\n holdoutScenarios: holdout,\n holdout: holdoutMode,\n gate,\n neutralize: opts.neutralize,\n autoOnPromote: opts.autoOnPromote ?? 'none',\n ghOwner: opts.ghOwner,\n ghRepo: opts.ghRepo,\n storage,\n runDir,\n maxConcurrency,\n cellPlacement: opts.cellPlacement,\n dispatchTimeoutMs: opts.dispatchTimeoutMs,\n costLedger,\n expectUsage,\n labeledStore: opts.labeledStore,\n captureSource: opts.captureSource,\n analyzeGeneration: opts.analyzeGeneration,\n findings: opts.findings,\n selectionRankKey: opts.selectionRankKey,\n })\n\n // Deferred holdout ran zero holdout cells, so the summary stats come from\n // the improvement-set (search) campaigns — labeled as such on the result\n // type — and `lift` is omitted rather than fabricated from empty campaigns.\n const reportSplit: RunSplitTag = holdoutDeferred ? 'search' : 'holdout'\n const reportBaselineCampaign = holdoutDeferred\n ? result.baselineCampaign\n : result.baselineOnHoldout\n const reportWinnerCampaign = holdoutDeferred\n ? winnerSearchCampaign(result)\n : result.winnerOnHoldout\n const baseline = meanComposite(reportBaselineCampaign.aggregates.byScenario)\n const winnerStats = meanComposite(reportWinnerCampaign.aggregates.byScenario)\n\n // Power analysis from the baseline holdout cells — the number that says whether\n // this budget could ship ANY effect. Attached to every result; loud when the\n // search was structurally unable to promote (that spend should not repeat).\n let power: PowerPreflight | undefined\n const baselineHoldoutComposites = result.baselineOnHoldout.cells\n .filter((cell) => !cell.error)\n .map((cell) => {\n const scores = Object.values(cell.judgeScores)\n return scores.length === 0\n ? Number.NaN\n : scores.reduce((sum, s) => sum + s.composite, 0) / scores.length\n })\n .filter((v) => Number.isFinite(v))\n if (baselineHoldoutComposites.length >= 3) {\n // selfImprove's holdout is scored by the SAME judge as the gate — the\n // shared-channel case by construction (S1c): flag it so the MDE reads as a\n // lower bound and nobody buys reps expecting them to fix judge bias.\n power = powerPreflight({\n baselineComposites: baselineHoldoutComposites,\n sharedScorerChannel: true,\n })\n if (opts.onProgress) {\n opts.onProgress({\n kind: 'power.estimated',\n n: power.n,\n sd: power.sd,\n mde: power.mde,\n underpowered: power.underpowered,\n })\n }\n if (power.underpowered && generations > 0) {\n console.warn(`[selfImprove] ${power.recommendation}`)\n }\n }\n\n if (opts.onProgress) {\n opts.onProgress({\n kind: 'baseline.completed',\n compositeMean: baseline.compositeMean,\n durationMs: Date.now() - startedAt,\n })\n opts.onProgress({\n kind: 'gate.decided',\n decision: result.gateResult.decision,\n // Deferred holdout has no held-out measurement: in that mode the summary\n // stats are search-split numbers, and emitting their delta as `lift`\n // would misreport a train-split delta as a held-out one. Omit instead.\n ...(holdoutDeferred ? {} : { lift: winnerStats.compositeMean - baseline.compositeMean }),\n })\n }\n\n const cost = result.cost\n const totalCost = cost.totalCostUsd\n\n // Rigor packet: feed baseline + winner cells through analyzeRuns().\n // The two candidates (`baseline` / `winner`) give the lift section a\n // clean paired comparison; per-judge / per-dimension / cost-quality\n // sections populate from the cells' judgeScores.\n const insight = await analyzeRuns({\n runs: [\n ...cellsToRunRecords(\n reportBaselineCampaign.cells,\n 'baseline',\n runDir,\n opts.baselineSurface,\n reportSplit,\n opts.model,\n ),\n ...cellsToRunRecords(\n reportWinnerCampaign.cells,\n 'winner',\n runDir,\n result.winnerSurface,\n reportSplit,\n opts.model,\n ),\n ],\n baselineCandidateId: 'baseline',\n candidateCandidateId: 'winner',\n })\n\n // ── Durable provenance: candidate→cell→gate→promote chain + rationale +\n // diff + backend provenance. Always emitted; the +lift recomputes from it.\n const durationMs = Date.now() - startedAt\n const { record: provenance } = await emitLoopProvenance<TArtifact, TScenario>({\n ...loopProvenanceArgsFromResult({\n runId: `${runDir}#${startedAt}`,\n runDir,\n timestamp: new Date(startedAt).toISOString(),\n baselineSurface: opts.baselineSurface,\n result,\n costReceipts: costLedger.list(),\n totalCostUsd: totalCost,\n totalDurationMs: durationMs,\n }),\n ...(optimizationResult\n ? {\n optimizationMethod: {\n name: opts.method!.name,\n cost: structuredClone(optimizationResult.cost),\n ...(optimizationResult.durationMs === undefined\n ? {}\n : { durationMs: optimizationResult.durationMs }),\n ...(optimizationResult.provenance === undefined\n ? {}\n : { provenance: structuredClone(optimizationResult.provenance) }),\n },\n }\n : {}),\n storage,\n hostedClient: opts.hostedTenant ? createHostedClient(opts.hostedTenant) : undefined,\n })\n if (opts.onProvenance) opts.onProvenance(provenance)\n\n const summary: SelfImproveResult<TScenario, TArtifact> = {\n baseline,\n winner: {\n ...winnerStats,\n surface: result.winnerSurface,\n ...(result.winnerLabel ? { label: result.winnerLabel } : {}),\n ...(result.winnerRationale ? { rationale: result.winnerRationale } : {}),\n },\n ...(holdoutDeferred ? {} : { lift: winnerStats.compositeMean - baseline.compositeMean }),\n diff: result.promotedDiff,\n provenance,\n gateDecision: result.gateResult.decision,\n generationsExplored: result.generations.length,\n durationMs,\n totalCostUsd: totalCost,\n cost,\n receipts: costLedger.list(),\n ...(optimizationResult\n ? {\n optimization: {\n name: opts.method!.name,\n cost: structuredClone(optimizationResult.cost),\n ...(optimizationResult.durationMs === undefined\n ? {}\n : { durationMs: optimizationResult.durationMs }),\n ...(optimizationResult.provenance === undefined\n ? {}\n : { provenance: structuredClone(optimizationResult.provenance) }),\n },\n }\n : {}),\n insight,\n ...(power ? { power } : {}),\n raw: result,\n }\n\n // Opt-in hosted ingest. Failures are logged but never fail the loop: the\n // local result is always returned.\n if (opts.hostedTenant) {\n try {\n await shipEvalRunToHosted(opts.hostedTenant, opts, summary, result, runDir)\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n // eslint-disable-next-line no-console -- intentional: hosted-ingest is best-effort\n console.warn(`[agent-eval] hosted ingest failed (continuing): ${msg}`)\n }\n }\n\n return summary\n}\n\nasync function shipEvalRunToHosted<TScenario extends Scenario, TArtifact>(\n tenant: HostedTenant,\n opts: SelfImproveOptions<TScenario, TArtifact>,\n summary: SelfImproveResult<TScenario, TArtifact>,\n raw: RunImprovementLoopResult<TArtifact, TScenario>,\n runDir: string,\n): Promise<void> {\n const client = createHostedClient(tenant)\n\n function snapshotFromCampaign(\n index: number,\n surface: MutableSurface,\n campaign: RunImprovementLoopResult<TArtifact, TScenario>['baselineCampaign'],\n durationMs: number,\n ): EvalRunGenerationSnapshot {\n const cells: EvalRunCellScore[] = campaign.cells.map((cell) => {\n const execution = campaignCellExecutionEvidence(cell)\n return {\n scenarioId: cell.scenarioId,\n rep: cell.rep,\n compositeMean: campaignCellTaskScore(cell) ?? null,\n dimensions: campaignCellJudgeDimensions(cell),\n terminalOutcome: execution.terminalOutcome,\n executionErrorCount: execution.executionErrorCount ?? null,\n errorMessage: cell.error ?? undefined,\n }\n })\n const scoredCells = cells.flatMap((cell) =>\n cell.compositeMean === null ? [] : [cell.compositeMean],\n )\n const compositeMean =\n scoredCells.length === 0\n ? null\n : scoredCells.reduce((sum, score) => sum + score, 0) / scoredCells.length\n return {\n index,\n surfaceHash: surfaceHash(surface),\n surface,\n cells,\n compositeMean,\n costUsd: campaign.aggregates.cost.totalCostUsd,\n durationMs,\n }\n }\n\n const generations: EvalRunGenerationSnapshot[] = []\n // Baseline as generation 0.\n generations.push(snapshotFromCampaign(0, opts.baselineSurface, raw.baselineCampaign, 0))\n // Improvement generations as 1..N. Substrate stores per-surface campaigns\n // per generation — we summarize the WINNING surface per generation here.\n for (const gen of raw.generations) {\n const winner = gen.surfaces.reduce(\n (best, s) =>\n s.campaign.aggregates.cellsExecuted > 0 &&\n (best === undefined || averageComposite(s.campaign) > averageComposite(best.campaign))\n ? s\n : best,\n gen.surfaces[0],\n )\n if (!winner) continue\n generations.push(\n snapshotFromCampaign(gen.record.generationIndex + 1, winner.surface, winner.campaign, 0),\n )\n }\n\n const event: EvalRunEvent = {\n runId: `${runDir}#${Date.now()}`,\n runDir,\n timestamp: new Date().toISOString(),\n status: 'finished',\n labels: opts.hostedLabels ?? {},\n baseline: generations[0],\n generations,\n gateDecision: summary.gateDecision,\n holdoutLift: summary.lift,\n totalCostUsd: summary.totalCostUsd,\n totalDurationMs: summary.durationMs,\n insightReport: summary.insight,\n }\n\n await client.ingestEvalRun(event)\n}\n\nfunction averageComposite(\n campaign: RunImprovementLoopResult<unknown, Scenario>['baselineCampaign'],\n): number {\n const aggs = Object.values(campaign.aggregates.byScenario)\n return aggs.length === 0 ? 0 : aggs.reduce((s, a) => s + a.meanComposite, 0) / aggs.length\n}\n\nfunction hashString(s: string): string {\n let h = 2166136261 >>> 0\n for (let i = 0; i < s.length; i++) {\n h ^= s.charCodeAt(i)\n h = Math.imul(h, 16777619) >>> 0\n }\n return h.toString(16).padStart(8, '0')\n}\n\n/**\n * Adapt campaign cells into the `RunRecord` shape `analyzeRuns()` consumes.\n * Each cell becomes one run; `candidateId` is the caller-supplied label so\n * baseline + winner pair cleanly on `(experimentId, scenarioId, seed)`.\n *\n * `promptHash` is the REAL sha256 content hash of the surface this cell ran\n * (baseline vs winner are byte-distinguishable + byte-identical-verifiable);\n * `configHash` is the sha256 of the candidate label so the two candidates'\n * config rows differ. Both were previously the literal `'sha256:cell'`, which\n * made baseline and winner indistinguishable in every downstream record.\n */\nfunction cellsToRunRecords<TArtifact>(\n cells: ReadonlyArray<CampaignCellResult<TArtifact>>,\n candidateId: 'baseline' | 'winner',\n runId: string,\n surface: MutableSurface,\n splitTag: RunSplitTag,\n fallbackModel?: string,\n): RunRecord[] {\n const promptHash = surfaceContentHash(surface)\n const configHash = surfaceContentHash(candidateId)\n return cells.map((cell) => {\n const receiptModels = cell.resolvedModels ?? (cell.resolvedModel ? [cell.resolvedModel] : [])\n if (receiptModels.length > 1) {\n throw new ValidationError(\n `selfImprove cell ${cell.cellId} used multiple agent models: ${receiptModels.join(', ')}`,\n )\n }\n const model = receiptModels[0] ?? fallbackModel\n if (!model) {\n throw new ValidationError(\n `selfImprove.model is required when cell ${cell.cellId} has no paid-call model receipt`,\n )\n }\n if (!modelHasSnapshot(model)) {\n throw new ValidationError(\n `selfImprove model \"${model}\" lacks a snapshot version for cell ${cell.cellId}`,\n )\n }\n return campaignCellToRunRecord(cell, {\n runId: `${runId}::${candidateId}::${cell.cellId}`,\n experimentId: runId,\n candidateId,\n // scenarioId is explicit; seed keeps repeated runs distinct.\n seed:\n cell.rep * 1_000_000 +\n hashString(cell.scenarioId)\n .slice(0, 6)\n .split('')\n .reduce((a, c) => (a * 31 + c.charCodeAt(0)) >>> 0, 0),\n model,\n promptHash,\n configHash,\n commitSha: 'cell',\n splitTag,\n })\n })\n}\n","import type { RunEvalOptions } from '../campaign/presets/run-eval'\nimport { runEval } from '../campaign/presets/run-eval'\nimport { inMemoryCampaignStorage } from '../campaign/storage'\nimport type {\n CampaignResult,\n DispatchContext,\n JudgeConfig,\n MutableSurface,\n Scenario,\n} from '../campaign/types'\nimport type { HostedTenant } from '../hosted/client'\nimport {\n type SelfImproveBudget,\n type SelfImproveOptions,\n type SelfImproveResult,\n selfImprove,\n} from './self-improve'\n\nexport type AgentEvalAgent<TScenario extends Scenario, TArtifact> = (\n surface: MutableSurface,\n scenario: TScenario,\n ctx: DispatchContext,\n) => Promise<TArtifact>\n\nexport type DefineAgentEvalOptions<TScenario extends Scenario, TArtifact> = SelfImproveOptions<\n TScenario,\n TArtifact\n>\n\nexport interface AgentEvalEvaluateOptions<TScenario extends Scenario, TArtifact>\n extends Omit<\n RunEvalOptions<TScenario, TArtifact>,\n 'dispatch' | 'judges' | 'runDir' | 'scenarios'\n > {\n /** Scenario set to evaluate. Defaults to the scenarios passed to `defineAgentEval`. */\n scenarios?: TScenario[]\n /** Surface to evaluate. Defaults to the baseline surface passed to `defineAgentEval`. */\n surface?: MutableSurface\n /** Agent to evaluate. Defaults to the agent passed to `defineAgentEval`. */\n agent?: AgentEvalAgent<TScenario, TArtifact>\n /** Single judge override. Ignored when `judges` is set. */\n judge?: JudgeConfig<TArtifact, TScenario>\n /** Full judge list override. Defaults to the single judge passed to `defineAgentEval`. */\n judges?: JudgeConfig<TArtifact, TScenario>[]\n /** Logical or filesystem run directory. Defaults to an in-memory run. */\n runDir?: string\n}\n\nexport type AgentEvalImproveOptions<TScenario extends Scenario, TArtifact> = Omit<\n Partial<SelfImproveOptions<TScenario, TArtifact>>,\n 'budget' | 'hostedTenant'\n> & {\n budget?: Partial<SelfImproveBudget>\n hostedTenant?: Partial<HostedTenant>\n}\n\nexport interface DefinedAgentEval<TScenario extends Scenario, TArtifact> {\n /** The default scenarios used by `evaluate()` and `improve()`. */\n readonly scenarios: readonly TScenario[]\n /** The default baseline surface used by `evaluate()` and `improve()`. */\n readonly baselineSurface: MutableSurface\n /**\n * Run one scored evaluation. Use this for a baseline score or to score one\n * candidate surface without running an improvement loop.\n */\n evaluate(\n opts?: AgentEvalEvaluateOptions<TScenario, TArtifact>,\n ): Promise<CampaignResult<TArtifact, TScenario>>\n /**\n * Run the closed improvement loop. Per-call overrides replace the definition\n * except for nested config objects (`budget`, `hostedTenant`), which\n * are merged field-by-field so callers can override one knob without\n * repeating secrets or budget defaults.\n */\n improve(\n opts?: AgentEvalImproveOptions<TScenario, TArtifact>,\n ): Promise<SelfImproveResult<TScenario, TArtifact>>\n}\n\n/**\n * Define an agent eval once, then either score a surface with `evaluate()` or\n * run the closed loop with `improve()`.\n *\n * This is a DX wrapper only: it delegates to `runEval()` and `selfImprove()` and\n * returns their native result shapes.\n */\nexport function defineAgentEval<TScenario extends Scenario, TArtifact>(\n defaults: DefineAgentEvalOptions<TScenario, TArtifact>,\n): DefinedAgentEval<TScenario, TArtifact> {\n const defaultEvaluateOptions = evaluateDefaults(defaults)\n\n return {\n scenarios: defaults.scenarios,\n baselineSurface: defaults.baselineSurface,\n\n async evaluate(opts = {}) {\n const { agent, judge, judges, runDir, scenarios, surface, ...campaignOpts } = opts\n const selectedAgent = agent ?? defaults.agent\n const selectedSurface = surface ?? defaults.baselineSurface\n const selectedRunDir = runDir ?? defaults.runDir ?? `mem://defineAgentEval-${Date.now()}`\n const selectedStorage =\n campaignOpts.storage ??\n defaultEvaluateOptions.storage ??\n (selectedRunDir.startsWith('mem://') ? inMemoryCampaignStorage() : undefined)\n const evalOptions: RunEvalOptions<TScenario, TArtifact> = {\n ...defaultEvaluateOptions,\n ...campaignOpts,\n ...(selectedStorage ? { storage: selectedStorage } : {}),\n runDir: selectedRunDir,\n scenarios: scenarios ?? defaults.scenarios,\n dispatch: (scenario, ctx) => selectedAgent(selectedSurface, scenario, ctx),\n judges: evaluateJudges(judges, judge ?? defaults.judge),\n }\n if (evalOptions.reps !== undefined)\n evalOptions.reps = requirePositiveInteger(evalOptions.reps, 'reps')\n return runEval<TScenario, TArtifact>(evalOptions)\n },\n\n async improve(opts = {}) {\n const {\n budget: budgetOverride,\n hostedTenant: hostedTenantOverride,\n ...topLevelOverrides\n } = opts\n const merged = mergeDefined(defaults, topLevelOverrides)\n const budget = mergeBudget(defaults.budget, budgetOverride)\n const hostedTenant = mergeHostedTenant(defaults.hostedTenant, hostedTenantOverride)\n return selfImprove<TScenario, TArtifact>({\n ...merged,\n ...(budget ? { budget } : {}),\n ...(hostedTenant ? { hostedTenant } : {}),\n })\n },\n }\n}\n\ntype SharedEvaluateDefaults<TScenario extends Scenario, TArtifact> = Omit<\n RunEvalOptions<TScenario, TArtifact>,\n 'dispatch' | 'judges' | 'runDir' | 'scenarios'\n>\n\nfunction evaluateDefaults<TScenario extends Scenario, TArtifact>(\n defaults: DefineAgentEvalOptions<TScenario, TArtifact>,\n): SharedEvaluateDefaults<TScenario, TArtifact> {\n const out: SharedEvaluateDefaults<TScenario, TArtifact> = {}\n if (defaults.storage) out.storage = defaults.storage\n if (defaults.labeledStore) out.labeledStore = defaults.labeledStore\n if (defaults.captureSource) out.captureSource = defaults.captureSource\n if (defaults.cellPlacement) out.cellPlacement = defaults.cellPlacement\n if (defaults.expectUsage) out.expectUsage = defaults.expectUsage\n if (defaults.budget?.dollars !== undefined) out.costCeiling = defaults.budget.dollars\n if (defaults.budget?.maxConcurrency !== undefined)\n out.maxConcurrency = defaults.budget.maxConcurrency\n if (defaults.budget?.reps !== undefined)\n out.reps = requirePositiveInteger(defaults.budget.reps, 'budget.reps')\n return out\n}\n\nfunction mergeBudget(\n defaults: SelfImproveBudget | undefined,\n overrides: Partial<SelfImproveBudget> | undefined,\n): SelfImproveBudget | undefined {\n const merged = mergeOptionalObject(defaults, overrides)\n if (merged?.reps !== undefined) merged.reps = requirePositiveInteger(merged.reps, 'budget.reps')\n return merged\n}\n\nfunction mergeHostedTenant(\n defaults: HostedTenant | undefined,\n overrides: Partial<HostedTenant> | undefined,\n): HostedTenant | undefined {\n const merged = mergeOptionalObject(defaults, overrides)\n if (!merged) return undefined\n if (!merged.endpoint?.trim() || !merged.apiKey?.trim() || !merged.tenantId?.trim()) {\n throw new Error(\n 'defineAgentEval.improve: hostedTenant requires endpoint, apiKey, and tenantId after merging defaults and overrides',\n )\n }\n return merged\n}\n\nfunction mergeDefined<T extends object>(defaults: T, overrides: Partial<T> | undefined): T {\n if (!overrides) return defaults\n const merged = { ...defaults } as Record<string, unknown>\n for (const [key, value] of Object.entries(overrides)) {\n if (value !== undefined) merged[key] = value\n }\n return merged as T\n}\n\nfunction mergeOptionalObject<T extends object>(\n defaults: T | undefined,\n overrides: Partial<T> | undefined,\n): T | undefined {\n if (!defaults && !overrides) return undefined\n return mergeDefined(defaults ?? ({} as T), overrides)\n}\n\nfunction evaluateJudges<TArtifact, TScenario extends Scenario>(\n judges: JudgeConfig<TArtifact, TScenario>[] | undefined,\n defaultJudge: JudgeConfig<TArtifact, TScenario>,\n): JudgeConfig<TArtifact, TScenario>[] {\n if (judges !== undefined) {\n if (judges.length === 0) {\n throw new Error('defineAgentEval.evaluate: judges must not be empty')\n }\n return judges\n }\n return [defaultJudge]\n}\n\nfunction requirePositiveInteger(value: number, field: string): number {\n if (!Number.isInteger(value) || value < 1) {\n throw new Error(`defineAgentEval: ${field} must be a positive integer`)\n }\n return value\n}\n","import type { AgentCandidateFixedSpend } from '@tangle-network/agent-interface'\n\nexport function addFixedSpend(\n left: AgentCandidateFixedSpend,\n right: AgentCandidateFixedSpend,\n): AgentCandidateFixedSpend {\n return {\n inputTokens: left.inputTokens + right.inputTokens,\n outputTokens: left.outputTokens + right.outputTokens,\n cachedInputTokens: left.cachedInputTokens + right.cachedInputTokens,\n reasoningTokens: left.reasoningTokens + right.reasoningTokens,\n modelCalls: left.modelCalls + right.modelCalls,\n costUsdNanos: left.costUsdNanos + right.costUsdNanos,\n costProvenance:\n left.costProvenance === 'observed' && right.costProvenance === 'observed'\n ? 'observed'\n : 'estimated',\n }\n}\n","import { mapConcurrentRange } from '../concurrency'\n\nexport interface MapPairedConcurrentOptions<T> {\n count: number\n maxConcurrency: number\n label: string\n signal?: AbortSignal\n map(index: number, arm: 'baseline' | 'candidate', signal: AbortSignal): Promise<T>\n}\n\n/** Map both arms while bounding the actual executions, not the number of pairs. */\nexport async function mapPairedConcurrent<T>(\n options: MapPairedConcurrentOptions<T>,\n): Promise<Array<{ baseline: T; candidate: T }>> {\n if (!Number.isSafeInteger(options.count) || options.count < 0) {\n throw new Error(`${options.label} pair count must be a non-negative integer`)\n }\n if (options.count > Math.floor(Number.MAX_SAFE_INTEGER / 2)) {\n throw new Error(`${options.label} pair count is too large to schedule both arms`)\n }\n const executions = await mapConcurrentRange({\n count: options.count * 2,\n maxConcurrency: options.maxConcurrency,\n label: options.label,\n ...(options.signal ? { signal: options.signal } : {}),\n map(flatIndex, signal) {\n const index = Math.floor(flatIndex / 2)\n const arm = flatIndex % 2 === 0 ? 'baseline' : 'candidate'\n return options.map(index, arm, signal)\n },\n })\n\n return Array.from({ length: options.count }, (_, index) => ({\n baseline: executions[index * 2]!,\n candidate: executions[index * 2 + 1]!,\n }))\n}\n","import {\n type CostChannel,\n CostLedger,\n type CostLedgerHandle,\n type CostProvenance,\n type CostReceiptInput,\n} from '../cost-ledger'\nimport { mapPairedConcurrent } from './concurrent-map'\n\nexport interface PaidPairedMeasurementResult<T> {\n measurements: Array<{ baseline: T; candidate: T }>\n wallDurationMs: number\n cost: Exclude<CostProvenance, { kind: 'uncaptured' }>\n}\n\nexport interface RunPaidPairedMeasurementOptions<T> {\n count: number\n maxConcurrency: number\n label: string\n budgetUsd?: number\n costLedger?: CostLedgerHandle\n maximumCostUsd: number\n call: {\n callId: string\n channel: CostChannel\n phase: string\n actor: string\n model: string\n tags?: Record<string, string>\n }\n signal?: AbortSignal\n execute(index: number, arm: 'baseline' | 'candidate', signal: AbortSignal): Promise<T>\n receipt(measurements: Array<{ baseline: T; candidate: T }>): CostReceiptInput\n}\n\n/**\n * Reserve the complete signed suite before its first cell starts.\n *\n * The host executor receives each task's signed cap through `execute`; this\n * batch reservation prevents a complete comparison from turning into a partial\n * one after earlier analysis or search has used the remaining budget.\n */\nexport async function runPaidPairedMeasurement<T>(\n options: RunPaidPairedMeasurementOptions<T>,\n): Promise<PaidPairedMeasurementResult<T>> {\n assertNonNegativeFinite(options.maximumCostUsd, 'maximumCostUsd')\n const costLedger = resolveCostLedger(options)\n const startedAt = performance.now()\n const paid = await costLedger.runPaidCall({\n callId: options.call.callId,\n channel: options.call.channel,\n phase: options.call.phase,\n actor: options.call.actor,\n model: options.call.model,\n maximumCharge: { externallyEnforcedMaximumUsd: options.maximumCostUsd },\n ...(options.call.tags ? { tags: options.call.tags } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n execute: async (signal) =>\n await mapPairedConcurrent({\n count: options.count,\n maxConcurrency: options.maxConcurrency,\n label: options.label,\n signal,\n map: options.execute,\n }),\n receipt: options.receipt,\n })\n const wallDurationMs = performance.now() - startedAt\n if (!paid.succeeded) throw paid.error\n if (paid.receipt.costUnknown) {\n throw new Error(`${options.label} did not capture the complete measurement cost`)\n }\n return {\n measurements: paid.value,\n wallDurationMs,\n cost:\n paid.receipt.actualCostUsd === undefined\n ? { kind: 'estimated', usd: paid.receipt.costUsd }\n : { kind: 'observed', usd: paid.receipt.costUsd },\n }\n}\n\nfunction resolveCostLedger(options: RunPaidPairedMeasurementOptions<unknown>): CostLedgerHandle {\n if (options.budgetUsd === undefined) return options.costLedger ?? new CostLedger()\n assertNonNegativeFinite(options.budgetUsd, 'budgetUsd')\n if (!options.costLedger) {\n throw new Error(`${options.label} with a policy budget requires one shared CostLedger`)\n }\n if (options.costLedger.costCeilingUsd !== options.budgetUsd) {\n throw new Error(`${options.label} CostLedger ceiling must equal the frozen policy budget`)\n }\n return options.costLedger\n}\n\nfunction assertNonNegativeFinite(value: number, label: string): void {\n if (!Number.isFinite(value) || value < 0) {\n throw new Error(`${label} must be a non-negative finite number`)\n }\n}\n","import {\n type AgentCandidateBenchmarkCellRef,\n type AgentCandidateBenchmarkSuiteInputs,\n type AgentCandidateBenchmarkTask,\n type AgentCandidateBenchmarkTaskMaterial,\n type AgentCandidateBundle,\n type AgentCandidateEvaluationPolicy,\n type AgentCandidateExperiment,\n type AgentCandidateExperimentMaterial,\n type AgentCandidateExperimentMeasurement,\n type AgentCandidateFixedSpend,\n type AgentImprovementCost,\n type AgentImprovementMeasuredComparison,\n agentCandidateBenchmarkSuiteSchema,\n agentCandidateBenchmarkTaskSchema,\n agentCandidateBundleSchema,\n agentCandidateEvaluationPolicySchema,\n agentCandidateExperimentSchema,\n agentImprovementMeasuredComparisonSchema,\n type CandidateExecutionEvidence,\n candidateExecutionEvidenceSchema,\n canonicalCandidateDigest,\n numbersApproximatelyEqual,\n omitTopLevelDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { heldoutSignificance } from '../campaign/gates/statistical-heldout'\nimport type { CostLedgerHandle, CostReceiptInput } from '../cost-ledger'\nimport { decidePairedPromotion } from '../paired-promotion-decision'\nimport { pairedBootstrap } from '../statistics'\nimport { addFixedSpend } from './fixed-spend'\nimport { runPaidPairedMeasurement } from './paid-paired-measurement'\n\nexport interface SealCandidateBenchmarkSuiteOptions {\n tasks: [AgentCandidateBenchmarkTask, ...AgentCandidateBenchmarkTask[]]\n reps: number\n seeds: [number, ...number[]]\n}\n\nexport interface CandidateExperimentExecutionInput {\n experiment: AgentCandidateExperiment\n arm: 'baseline' | 'candidate'\n bundle: AgentCandidateBundle\n task: AgentCandidateBenchmarkTask\n benchmarkCell: AgentCandidateBenchmarkCellRef\n seed: number\n signal?: AbortSignal\n}\n\nexport interface RunCandidateExperimentOptions {\n experiment: AgentCandidateExperiment\n execute(input: CandidateExperimentExecutionInput): Promise<CandidateExecutionEvidence>\n /** Maximum number of simultaneous execute calls across both arms. */\n maxConcurrency?: number\n /** Shared run budget that also accounts for analysis and candidate search. */\n costLedger?: CostLedgerHandle\n signal?: AbortSignal\n}\n\nexport interface CandidateExperimentRun {\n measurements: AgentCandidateExperimentMeasurement[]\n measurement: {\n wallDurationMs: number\n cost: AgentImprovementCost\n }\n}\n\nexport interface CompareCandidateExperimentOptions {\n experiment: AgentCandidateExperiment\n measurements: AgentCandidateExperimentMeasurement[]\n preparation: {\n wallDurationMs: number\n cost: AgentImprovementCost\n }\n measurement: CandidateExperimentRun['measurement']\n runId: string\n candidate?: AgentImprovementMeasuredComparison['candidate']\n generationsExplored?: number\n metadata?: AgentImprovementMeasuredComparison['metadata']\n}\n\n/** One exact baseline/candidate observation of the same held-out cell. */\nexport interface PairedMeasurement<TRun> {\n cellId: string\n baseline: TRun\n candidate: TRun\n}\n\n/** Maps a product-owned run receipt into the measurements required for a fair paired decision. */\nexport interface PairedMeasurementAdapter<TRun> {\n score(run: TRun): number\n dimensions(run: TRun): readonly { name: string; score: number }[]\n costUsd(run: TRun): number\n costProvenance(run: TRun): AgentImprovementCost['provenance']\n latencyMs(run: TRun): number\n completed(run: TRun): boolean\n passed(run: TRun): boolean\n}\n\nexport interface EvaluatePairedMeasurementsOptions<TRun> {\n measurements: readonly PairedMeasurement<TRun>[]\n policy: AgentCandidateEvaluationPolicy\n adapter: PairedMeasurementAdapter<TRun>\n /** Whether both arms use the same scorer family as the promotion decision. */\n sharedScorerChannel: boolean\n /** Analysis and candidate-search spend that belongs to the same frozen budget. */\n preparationCost?: AgentImprovementCost\n /** Settled aggregate receipt for this exact paired suite, when an executor provides one. */\n measurementCost?: AgentImprovementCost\n}\n\n/** Statistical and operational result derived from complete paired receipts. */\nexport type PairedMeasurementEvaluation = Pick<\n AgentImprovementMeasuredComparison,\n 'overall' | 'objectives' | 'decision' | 'power'\n> & {\n measurementCost: AgentImprovementCost\n totalCost: AgentImprovementCost\n measurementWorkDurationMs: number\n}\n\n/** Content-address one task before any measured execution can see it. */\nexport function sealCandidateBenchmarkTask(\n material: AgentCandidateBenchmarkTaskMaterial,\n): AgentCandidateBenchmarkTask {\n return agentCandidateBenchmarkTaskSchema.parse({\n ...material,\n digest: canonicalCandidateDigest(material),\n })\n}\n\n/** Freeze task order, repetitions, and every seed before either arm runs. */\nexport function sealCandidateBenchmarkSuite(\n options: SealCandidateBenchmarkSuiteOptions,\n): AgentCandidateBenchmarkSuiteInputs {\n for (const task of options.tasks) verifyCandidateBenchmarkTask(task)\n const material = {\n kind: 'agent-candidate-benchmark-suite' as const,\n digestAlgorithm: 'rfc8785-sha256' as const,\n taskDigests: options.tasks.map((task) => task.digest) as [Sha256Digest, ...Sha256Digest[]],\n reps: options.reps,\n seeds: options.seeds,\n }\n const suite = agentCandidateBenchmarkSuiteSchema.parse({\n ...material,\n digest: canonicalCandidateDigest(material),\n })\n return { suite, tasks: options.tasks }\n}\n\n/** Freeze both complete agent states and their exact held-out work. */\nexport function sealCandidateExperiment(\n material: AgentCandidateExperimentMaterial,\n): AgentCandidateExperiment {\n const parsed = agentCandidateExperimentSchema.parse({\n ...material,\n digest: canonicalCandidateDigest(material),\n })\n return verifyCandidateExperiment(parsed)\n}\n\nexport function verifyCandidateExperiment(input: unknown): AgentCandidateExperiment {\n const experiment = agentCandidateExperimentSchema.parse(input)\n verifySelfAddressed(experiment, 'candidate experiment')\n verifyBundle(experiment.baseline, 'baseline bundle')\n verifyBundle(experiment.candidate, 'candidate bundle')\n if (experiment.baseline.digest === experiment.candidate.digest) {\n throw new Error('candidate experiment baseline and candidate bundles are identical')\n }\n verifyCandidateBenchmarkSuiteInputs(experiment.benchmark)\n return experiment\n}\n\n/** Execute each signed cell for both arms. The callback is Runtime's one executor. */\nexport async function runCandidateExperiment(\n options: RunCandidateExperimentOptions,\n): Promise<CandidateExperimentRun> {\n const experiment = verifyCandidateExperiment(options.experiment)\n const { suite, tasks } = experiment.benchmark\n const run = await runPaidPairedMeasurement({\n count: suite.taskDigests.length * suite.reps,\n maxConcurrency: options.maxConcurrency ?? 2,\n label: 'candidate experiment',\n budgetUsd: experiment.policy.budgetUsd,\n ...(options.costLedger ? { costLedger: options.costLedger } : {}),\n maximumCostUsd: candidateMeasurementMaximumCostUsd(experiment),\n call: {\n callId: `candidate-measurement:${experiment.digest}`,\n channel: 'measurement',\n phase: 'heldout',\n actor: experiment.digest,\n model: candidateMeasurementModel(experiment),\n tags: { experimentDigest: experiment.digest },\n },\n ...(options.signal ? { signal: options.signal } : {}),\n async execute(index, arm, signal) {\n const taskIndex = Math.floor(index / suite.reps)\n const repetition = index % suite.reps\n const task = tasks[taskIndex]\n const seed = suite.seeds[index]\n if (!task || seed === undefined) {\n throw new Error(`candidate experiment cell ${index} has no signed task or seed`)\n }\n const benchmarkCell = {\n suiteDigest: suite.digest,\n taskIndex,\n repetition,\n }\n return verifyExecutionEvidence(\n await options.execute({\n experiment,\n arm,\n bundle: experiment[arm],\n task,\n benchmarkCell,\n seed,\n signal,\n }),\n )\n },\n receipt(measurements) {\n return candidateMeasurementCostReceipt(measurements, candidateMeasurementModel(experiment))\n },\n })\n return {\n measurements: run.measurements.map((measurement, index) =>\n verifyMeasurement(experiment, measurement, index),\n ),\n measurement: {\n wallDurationMs: run.wallDurationMs,\n cost: { usd: run.cost.usd, provenance: run.cost.kind },\n },\n }\n}\n\n/**\n * Calculate the shared paired decision from any complete receipt shape.\n *\n * Callers still own sealing their tasks, verifying each receipt against its\n * expected arm and state, and proving every expected cell exists. This function\n * only validates the projected measurements and derives their shared decision.\n */\nexport function evaluatePairedMeasurements<TRun>(\n options: EvaluatePairedMeasurementsOptions<TRun>,\n): PairedMeasurementEvaluation {\n if (options.measurements.length === 0) {\n throw new Error('paired measurement evaluation requires at least one paired cell')\n }\n const preparationCost = options.preparationCost ?? { usd: 0, provenance: 'observed' as const }\n if (!Number.isFinite(preparationCost.usd) || preparationCost.usd < 0) {\n throw new Error('paired measurement evaluation preparation cost must be a non-negative number')\n }\n if (typeof options.sharedScorerChannel !== 'boolean') {\n throw new Error('paired measurement evaluation sharedScorerChannel must be a boolean')\n }\n const policy = agentCandidateEvaluationPolicySchema.parse(options.policy)\n const measurements = options.measurements.map((measurement, index) =>\n projectPairedMeasurement(measurement, index, options.adapter),\n )\n const cellIds = measurements.map((measurement) => measurement.cellId)\n if (new Set(cellIds).size !== cellIds.length) {\n throw new Error('paired measurement evaluation cell ids must be unique')\n }\n const dimensions = sharedProjectedDimensions(measurements)\n const baselineScores = measurements.map((measurement) => measurement.baseline.score)\n const candidateScores = measurements.map((measurement) => measurement.candidate.score)\n const {\n confidenceLevel: confidence,\n resamples,\n bootstrapSeed,\n deltaThreshold,\n minProductiveRuns,\n budgetUsd,\n criticalDimensions,\n regressionTolerance,\n } = policy\n const significance = heldoutSignificance(\n { before: baselineScores, after: candidateScores, cellIds },\n {\n confidence,\n resamples,\n seed: bootstrapSeed,\n statistic: 'mean',\n deltaThreshold,\n minProductiveRuns,\n },\n )\n const overall = measuredEstimate(baselineScores, candidateScores, {\n confidence,\n resamples,\n seed: bootstrapSeed,\n })\n const objectives: AgentImprovementMeasuredComparison['objectives'] = [\n {\n kind: 'objective',\n name: 'benchmark-score',\n direction: 'higher-is-better',\n unit: 'score',\n availability: 'measured',\n ...overall,\n },\n ...dimensions.map((name, index) => ({\n kind: 'dimension' as const,\n objective: 'benchmark-score',\n name,\n direction: 'higher-is-better' as const,\n unit: 'score' as const,\n availability: 'measured' as const,\n ...measuredEstimate(\n measurements.map((measurement) => dimensionScore(measurement.baseline, name)),\n measurements.map((measurement) => dimensionScore(measurement.candidate, name)),\n {\n confidence,\n resamples,\n seed: bootstrapSeed + index + 1,\n },\n ),\n })),\n ]\n const cost = measuredEstimate(\n measurements.map((measurement) => measurement.baseline.costUsd),\n measurements.map((measurement) => measurement.candidate.costUsd),\n {\n confidence,\n resamples,\n seed: bootstrapSeed + dimensions.length + 1,\n },\n )\n const latency = measuredEstimate(\n measurements.map((measurement) => measurement.baseline.latencyMs),\n measurements.map((measurement) => measurement.candidate.latencyMs),\n {\n confidence,\n resamples,\n seed: bootstrapSeed + dimensions.length + 2,\n },\n )\n objectives.push(\n {\n kind: 'cost',\n name: 'cost',\n direction: 'lower-is-better',\n unit: 'usd',\n availability: 'measured',\n ...cost,\n },\n {\n kind: 'latency',\n name: 'latency',\n direction: 'lower-is-better',\n unit: 'milliseconds',\n availability: 'measured',\n ...latency,\n },\n )\n\n const power = observedPairedPrecision({\n baselineScores,\n candidateScores,\n delta: overall.delta,\n lowerBound: overall.confidenceInterval.lower,\n deltaThreshold,\n minProductiveRuns: significance.minimumRequired,\n confidence,\n sharedScorerChannel: options.sharedScorerChannel,\n })\n const powerSufficient = power.sufficient\n const guardedDimensions = new Set(criticalDimensions)\n const missingCriticalDimensions = criticalDimensions.filter(\n (dimension) => !dimensions.includes(dimension),\n )\n // The dimension floor fires on EITHER burden of proof, because the interval\n // arm alone fails OPEN on exactly the shape a safety dimension lands in.\n // `regressionTolerance` is positive, so an interval pinned at [0, 0] — which\n // is what a pass/fail dimension gives whenever its pairs are concordant, and\n // what a percentile bootstrap of the mean gives whenever every delta is\n // identical — never satisfies `lower < -tolerance`, and a real regression is\n // reported as no regression. `decidePairedPromotion` on the reversed arms\n // adds the proven-drop path: a two-point dimension is judged on Tango's score\n // interval, which is valid at the nonzero margin the tolerance creates.\n const regressionProven = new Set(\n dimensions.filter((name) => {\n if (!guardedDimensions.has(name)) return false\n const baselineDim = measurements.map((m) => dimensionScore(m.baseline, name))\n const candidateDim = measurements.map((m) => dimensionScore(m.candidate, name))\n return decidePairedPromotion(candidateDim, baselineDim, {\n confidence,\n resamples,\n statistic: 'mean',\n seed: bootstrapSeed,\n threshold: regressionTolerance,\n minPairs: minProductiveRuns,\n }).promote\n }),\n )\n const regressions = objectives.filter(\n (objective) =>\n objective.kind === 'dimension' &&\n guardedDimensions.has(objective.name) &&\n objective.availability === 'measured' &&\n (objective.confidenceInterval.lower < -regressionTolerance ||\n regressionProven.has(objective.name)),\n )\n const measurementCostUsd = measurements.reduce(\n (sum, measurement) => sum + measurement.baseline.costUsd + measurement.candidate.costUsd,\n 0,\n )\n const measurementWorkDurationMs = measurements.reduce(\n (sum, measurement) => sum + measurement.baseline.latencyMs + measurement.candidate.latencyMs,\n 0,\n )\n const completedRuns = measurements.flatMap((measurement) => [\n measurement.baseline,\n measurement.candidate,\n ])\n const incompleteRuns = completedRuns.filter((run) => !run.completed)\n // FAILED is not REGRESSED, and the gate must ship on the second one.\n //\n // The blocking bar used to be `!candidate.passed` on any cell, i.e. the\n // candidate had to pass EVERY benchmark task. On a benchmark hard enough to\n // be worth running, nothing passes everything, so the bar was unreachable.\n //\n // The demonstration is the synthetic case `repairedNotRegressed(8)` in this\n // file's tests: baseline mean 0.3339, candidate mean 0.8685, paired delta\n // +0.5346 — held with \"candidate failed 2 benchmark tasks\", where both were\n // tasks the BASELINE failed too. An improvement reported as a defect.\n //\n // Stated precisely because an earlier draft of this comment was not: that case\n // is CONSTRUCTED, not observed. No live run of this gate is on disk, and no\n // arm of the work that found this defect ever called a model. The argument for\n // the change is the unreachable bar itself, which is visible in the predicate;\n // it does not rest on a measured candidate, and none should be claimed here.\n //\n // The consequence still holds and is the reason this matters: an improvement\n // null measured through the OLD gate cannot be read as evidence that\n // improvement does not work, because the gate could reject winners.\n //\n // The honest bar is improvement WITHOUT regression. The improvement half is\n // already carried by `paired-significance` (the lift must clear the threshold\n // with statistical evidence) and the quality half by `critical-dimensions`.\n // What was missing here is the per-task regression: a cell the baseline\n // PASSED and the candidate now fails. The baseline arm is already projected\n // through the same `adapter.passed`, so the comparison needs no new evidence —\n // it was available and simply not read.\n //\n // The three-way split is retained (not just the regression count) so a future\n // reader can tell a gate artifact from a real null: `repaired` is the work the\n // candidate did, `shared` is the work neither arm can do, and only `regressed`\n // blocks.\n const regressedTasks = measurements.filter(\n (measurement) => !measurement.candidate.passed && measurement.baseline.passed,\n )\n const sharedTaskFailures = measurements.filter(\n (measurement) => !measurement.candidate.passed && !measurement.baseline.passed,\n )\n const repairedTasks = measurements.filter(\n (measurement) => measurement.candidate.passed && !measurement.baseline.passed,\n )\n const derivedMeasurementCost: AgentImprovementCost = {\n usd: measurementCostUsd,\n provenance: measurements.every(\n (measurement) =>\n measurement.baseline.costProvenance === 'observed' &&\n measurement.candidate.costProvenance === 'observed',\n )\n ? 'observed'\n : 'estimated',\n }\n const measurementCost = options.measurementCost ?? derivedMeasurementCost\n assertKnownCost(measurementCost, 'paired measurement cost')\n if (\n options.measurementCost !== undefined &&\n (measurementCost.provenance !== derivedMeasurementCost.provenance ||\n !numbersApproximatelyEqual(measurementCost.usd, derivedMeasurementCost.usd))\n ) {\n throw new Error('paired measurement cost does not match its signed receipts')\n }\n const totalCost: AgentImprovementCost = {\n usd: preparationCost.usd + measurementCost.usd,\n provenance:\n preparationCost.provenance === 'observed' && measurementCost.provenance === 'observed'\n ? 'observed'\n : 'estimated',\n }\n const budgetPassed =\n budgetUsd === undefined ||\n totalCost.usd < budgetUsd ||\n numbersApproximatelyEqual(totalCost.usd, budgetUsd)\n const checks = [\n { name: 'paired-significance', passed: significance.significant },\n { name: 'paired-precision', passed: powerSufficient },\n { name: 'all-runs-completed', passed: incompleteRuns.length === 0 },\n // Renamed from `candidate-task-pass` with the semantics. A consumer keyed on\n // the old name now sees a MISSING check rather than a silently different\n // one, which is the failure mode worth having.\n { name: 'no-task-regression', passed: regressedTasks.length === 0 },\n {\n name: 'critical-dimensions',\n passed: regressions.length === 0 && missingCriticalDimensions.length === 0,\n },\n { name: 'budget', passed: budgetPassed },\n ]\n const shipped = checks.every((check) => check.passed)\n const hardFailure =\n incompleteRuns.length > 0 ||\n regressedTasks.length > 0 ||\n regressions.length > 0 ||\n missingCriticalDimensions.length > 0 ||\n !budgetPassed\n const reasons = [\n ...(significance.significant ? [] : [significanceReason(significance, deltaThreshold)]),\n ...(powerSufficient || significance.fewRuns ? [] : [power.reason]),\n ...(regressions.length === 0\n ? []\n : [`critical dimensions regressed: ${regressions.map((entry) => entry.name).join(', ')}`]),\n ...(missingCriticalDimensions.length === 0\n ? []\n : [`critical dimensions missing: ${missingCriticalDimensions.join(', ')}`]),\n ...(incompleteRuns.length === 0\n ? []\n : [`${incompleteRuns.length} benchmark executions did not exit successfully`]),\n ...(regressedTasks.length === 0\n ? []\n : [\n `candidate regressed ${regressedTasks.length} benchmark ` +\n `${regressedTasks.length === 1 ? 'task' : 'tasks'} the baseline passed: ` +\n regressedTasks.map((measurement) => measurement.cellId).join(', '),\n ]),\n ...(budgetPassed ? [] : [`total cost ${totalCost.usd} exceeded budget ${budgetUsd}`]),\n // Non-blocking accounting, emitted on any outcome that did NOT ship and has\n // tasks both arms failed — so a `hold` (whatever caused it) and also a\n // `need_more_work`. It lets an operator reading a refusal tell \"the\n // candidate is bad\" from \"the benchmark has tasks neither arm solves\". The\n // `shipped` term is what keeps it off a ship, where it could be misread as a\n // blocking reason.\n ...(shipped || sharedTaskFailures.length === 0\n ? []\n : [\n `benchmark tasks: ${repairedTasks.length} repaired, ${regressedTasks.length} regressed, ` +\n `${sharedTaskFailures.length} still failing that the baseline also failed`,\n ]),\n ]\n\n return {\n overall: {\n name: 'composite',\n direction: 'higher-is-better',\n unit: 'score',\n ...overall,\n },\n objectives,\n decision: {\n outcome: shipped\n ? 'ship'\n : hardFailure\n ? 'hold'\n : // A degenerate paired sample is a MEASUREMENT that cannot decide, not\n // a candidate that lost. `hold` sends the operator to build a better\n // candidate; `need_more_work` sends them to the held-out set, which is\n // the only thing that can actually resolve a zero-variance sample.\n significance.fewRuns || !powerSufficient || significance.decision.indeterminate\n ? 'need_more_work'\n : 'hold',\n reasons: reasons.length > 0 ? reasons : ['all measured checks passed'],\n contributingChecks: checks,\n },\n power: {\n sufficient: powerSufficient,\n n: baselineScores.length,\n minimumDetectableDelta: power.minimumDetectableDelta,\n confidenceLevel: confidence,\n scaleAssumed: power.scaleAssumed,\n sharedScorerChannel: options.sharedScorerChannel,\n reason: power.reason,\n },\n measurementCost,\n totalCost,\n measurementWorkDurationMs,\n }\n}\n\n/**\n * Say why the paired significance check refused, reading the interval that\n * ACTUALLY decided.\n *\n * The old string always printed `significance.bootstrap.low`, which is a\n * DIAGNOSTIC bootstrap that on several paths never enters the decision at all.\n * That produced self-contradicting holds — observed live: \"paired interval lower\n * bound 0.6666666666666669 did not clear 0\", where 0.667 plainly clears 0. Three\n * paths where the old string was simply reporting the wrong number:\n *\n * - ZERO-VARIANCE sample. Every paired delta identical ⇒ the resample\n * distribution is a point mass and the interval collapses to [g, g]. The\n * refusal is correct and load-bearing, and the reason has to say so.\n * Under the bounded asymmetric null this repo documents (2 % of pairs drop\n * by 1.0, the rest gain 0.0204, true mean paired delta exactly 0), a\n * constant-positive sample is exactly a sample in which no pair drew the\n * drop, so its frequency is closed-form 0.98^n — 88.6 % at n = 6 and 66.8 %\n * at n = 20. That reconciles with the false-promotion rates measured on the\n * composable gate for the same null, 88.50 % at n = 6 and 65.65 % at n = 20\n * (see {@link decidePairedPromotion} in `src/paired-promotion-decision.ts`);\n * no number here is independently measured, and none needs to be. A\n * constant positive delta is therefore NOT the strongest evidence — it is\n * the signature of a held-out set too small or too uniform to have sampled\n * the tail, and promoting on it would false-promote a true-zero candidate\n * most of the time. No distribution-free bound rescues it either: a\n * Hoeffding 95 % lower bound on a constant +0.667 with scores in [0, 1] is\n * −0.33 at n = 6 and −0.11 at n = 10, first clearing 0 at n = 20. The\n * estimator genuinely cannot express this sample, so the gate says that and\n * routes to `need_more_work` — vary or extend the held-out cells.\n * - TWO-POINT outcome, where the score interval decided and the bootstrap was\n * never consulted.\n * - McNEMAR VETO, where no interval failed at all.\n */\nfunction significanceReason(\n significance: ReturnType<typeof heldoutSignificance>,\n deltaThreshold: number,\n): string {\n if (significance.fewRuns) {\n return `only ${significance.n} paired runs; ${significance.minimumRequired} required`\n }\n const { decision } = significance\n if (decision.indeterminate) {\n return (\n `paired ${decision.statistic} interval is degenerate at [${decision.low}, ${decision.high}] ` +\n `(${decision.indeterminateCause}); a zero-width interval carries no information about its ` +\n `own error, so no threshold can be cleared on it — vary or extend the held-out cells`\n )\n }\n if (decision.exactTestVetoes && decision.mcnemar !== null) {\n return (\n `McNemar's exact test refuses at threshold ${deltaThreshold}: ` +\n `b=${decision.mcnemar.b}, c=${decision.mcnemar.c}, p=${decision.mcnemar.pValue}`\n )\n }\n return (\n `paired ${decision.statistic} interval lower bound ${decision.low} ` +\n `did not clear ${deltaThreshold}.${decision.methodDetail}`\n )\n}\n\n/** Build the only publishable comparison: paired statistics over Runtime receipts. */\nexport function measuredComparisonFromCandidateExperiment(\n options: CompareCandidateExperimentOptions,\n): AgentImprovementMeasuredComparison {\n const experiment = verifyCandidateExperiment(options.experiment)\n const measurements = options.measurements.map((measurement, index) =>\n verifyMeasurement(experiment, measurement, index),\n )\n const expectedN = experiment.benchmark.suite.taskDigests.length * experiment.benchmark.suite.reps\n if (measurements.length !== expectedN) {\n throw new Error(\n `candidate experiment is incomplete (${measurements.length}/${expectedN} paired cells)`,\n )\n }\n verifyStableProfileMaterialization(measurements)\n if (!options.runId.trim()) throw new Error('candidate experiment runId is required')\n assertPhaseAccounting(options.preparation, 'candidate preparation')\n assertPhaseAccounting(options.measurement, 'candidate measurement')\n const evaluation = evaluatePairedMeasurements({\n measurements: measurements.map((measurement, index) => ({\n cellId: cellIds(experiment)[index]!,\n ...measurement,\n })),\n policy: experiment.policy,\n adapter: candidateExecutionEvidenceAdapter,\n sharedScorerChannel: true,\n preparationCost: options.preparation.cost,\n measurementCost: options.measurement.cost,\n })\n const diff = deriveCandidateBundleDiff(experiment)\n const provisional = agentImprovementMeasuredComparisonSchema.parse({\n kind: 'agent-improvement-measured-comparison',\n experiment,\n measurements,\n overall: evaluation.overall,\n objectives: evaluation.objectives,\n ...(options.candidate ? { candidate: options.candidate } : {}),\n decision: evaluation.decision,\n power: evaluation.power,\n provenance: {\n kind: 'agent-eval-loop',\n schema: 'agent-candidate-experiment',\n runId: options.runId,\n recordDigest: canonicalCandidateDigest({}),\n baselineContentHash: experiment.baseline.digest,\n candidateContentHash: experiment.candidate.digest,\n },\n diff,\n evaluation: {\n generationsExplored: options.generationsExplored ?? 0,\n preparation: options.preparation,\n measurement: {\n wallDurationMs: options.measurement.wallDurationMs,\n workDurationMs: evaluation.measurementWorkDurationMs,\n cost: evaluation.measurementCost,\n },\n total: {\n wallDurationMs: options.preparation.wallDurationMs + options.measurement.wallDurationMs,\n cost: evaluation.totalCost,\n },\n },\n ...(options.metadata ? { metadata: options.metadata } : {}),\n })\n const { recordDigest: _recordDigest, ...provenance } = provisional.provenance\n return agentImprovementMeasuredComparisonSchema.parse({\n ...provisional,\n provenance: {\n ...provenance,\n recordDigest: canonicalCandidateDigest({ ...provisional, provenance }),\n },\n })\n}\n\n/** Recompute every statistic and decision from the signed experiment receipts. */\nexport function verifyCandidateExperimentComparison(\n input: unknown,\n): AgentImprovementMeasuredComparison {\n const comparison = agentImprovementMeasuredComparisonSchema.parse(input)\n const recomputed = measuredComparisonFromCandidateExperiment({\n experiment: comparison.experiment,\n measurements: comparison.measurements,\n runId: comparison.provenance.runId,\n ...(comparison.candidate ? { candidate: comparison.candidate } : {}),\n generationsExplored: comparison.evaluation.generationsExplored,\n preparation: comparison.evaluation.preparation,\n measurement: {\n wallDurationMs: comparison.evaluation.measurement.wallDurationMs,\n cost: comparison.evaluation.measurement.cost,\n },\n ...(comparison.metadata ? { metadata: comparison.metadata } : {}),\n })\n if (canonicalCandidateDigest(recomputed) !== canonicalCandidateDigest(comparison)) {\n throw new Error('candidate experiment comparison does not match its Runtime receipts')\n }\n return comparison\n}\n\nfunction candidateMeasurementMaximumCostUsd(experiment: AgentCandidateExperiment): number {\n const maximum = experiment.benchmark.tasks.reduce(\n (sum, task) => sum + task.limits.maxCostUsd * experiment.benchmark.suite.reps * 2,\n 0,\n )\n if (!Number.isFinite(maximum) || maximum < 0) {\n throw new Error('candidate measurement maximum cost is invalid')\n }\n return maximum\n}\n\nfunction candidateMeasurementModel(experiment: AgentCandidateExperiment): string {\n const models = [...new Set(experiment.benchmark.tasks.map((task) => task.model.model))]\n return models.length === 1 ? models[0]! : 'multiple-models'\n}\n\nfunction candidateMeasurementCostReceipt(\n measurements: Array<{\n baseline: CandidateExecutionEvidence\n candidate: CandidateExecutionEvidence\n }>,\n model: string,\n): CostReceiptInput {\n const usage = measurements.reduce<AgentCandidateFixedSpend>(\n (sum, measurement) =>\n addFixedSpend(\n addFixedSpend(sum, combinedUsage(measurement.baseline)),\n combinedUsage(measurement.candidate),\n ),\n {\n inputTokens: 0,\n outputTokens: 0,\n cachedInputTokens: 0,\n reasoningTokens: 0,\n modelCalls: 0,\n costUsdNanos: 0,\n costProvenance: 'observed',\n },\n )\n const costUsd = usage.costUsdNanos / 1_000_000_000\n return {\n model,\n inputTokens: usage.inputTokens,\n outputTokens: usage.outputTokens,\n cachedTokens: usage.cachedInputTokens,\n reasoningTokens: usage.reasoningTokens,\n ...(usage.costProvenance === 'observed'\n ? { actualCostUsd: costUsd }\n : { estimatedCostUsd: costUsd }),\n }\n}\n\nfunction assertPhaseAccounting(\n accounting: CompareCandidateExperimentOptions['preparation'],\n label: string,\n): void {\n if (!Number.isFinite(accounting.wallDurationMs) || accounting.wallDurationMs < 0) {\n throw new Error(`${label} wall duration must be a non-negative number`)\n }\n assertKnownCost(accounting.cost, `${label} cost`)\n}\n\nfunction assertKnownCost(cost: AgentImprovementCost, label: string): void {\n if (!Number.isFinite(cost.usd) || cost.usd < 0) {\n throw new Error(`${label} must be a non-negative number`)\n }\n if (cost.provenance !== 'observed' && cost.provenance !== 'estimated') {\n throw new Error(`${label} provenance must be observed or estimated`)\n }\n}\n\nfunction deriveCandidateBundleDiff(experiment: AgentCandidateExperiment): string {\n const surfaces = ['profile', 'code', 'execution', 'knowledge', 'memory'] as const\n const changed = surfaces.flatMap((surface) => {\n const baseline = experiment.baseline[surface] ?? null\n const candidate = experiment.candidate[surface] ?? null\n const baselineDigest = canonicalCandidateDigest(baseline)\n const candidateDigest = canonicalCandidateDigest(candidate)\n if (baselineDigest === candidateDigest) return []\n return [\n [\n `--- baseline/${surface} (${baselineDigest})`,\n `+++ candidate/${surface} (${candidateDigest})`,\n JSON.stringify({ baseline, candidate }, null, 2),\n ].join('\\n'),\n ]\n })\n if (changed.length === 0) {\n throw new Error('candidate experiment has no changed candidate surface')\n }\n return changed.join('\\n\\n')\n}\n\nexport function verifyCandidateBenchmarkTask(input: unknown): AgentCandidateBenchmarkTask {\n const task = agentCandidateBenchmarkTaskSchema.parse(input)\n verifySelfAddressed(task, 'candidate benchmark task')\n return task\n}\n\nexport function verifyCandidateBenchmarkSuiteInputs(\n input: unknown,\n): AgentCandidateBenchmarkSuiteInputs {\n if (input === null || typeof input !== 'object' || Array.isArray(input)) {\n throw new Error('candidate benchmark suite inputs must be an object')\n }\n const candidate = input as AgentCandidateBenchmarkSuiteInputs\n const suite = verifyCandidateBenchmarkSuite(candidate.suite)\n if (!Array.isArray(candidate.tasks) || candidate.tasks.length !== suite.taskDigests.length) {\n throw new Error('candidate benchmark suite task count does not match its signed digests')\n }\n candidate.tasks.forEach((task, index) => {\n const verified = verifyCandidateBenchmarkTask(task)\n if (verified.digest !== suite.taskDigests[index]) {\n throw new Error(`candidate benchmark task ${index} does not match the signed suite`)\n }\n })\n return { suite, tasks: candidate.tasks }\n}\n\nexport function verifyCandidateBenchmarkSuite(input: unknown) {\n const suite = agentCandidateBenchmarkSuiteSchema.parse(input)\n verifySelfAddressed(suite, 'candidate benchmark suite')\n return suite\n}\n\nfunction verifyBundle(input: unknown, label: string): AgentCandidateBundle {\n const bundle = agentCandidateBundleSchema.parse(input)\n verifySelfAddressed(bundle, label)\n return bundle\n}\n\nfunction verifyMeasurement(\n experiment: AgentCandidateExperiment,\n input: AgentCandidateExperimentMeasurement,\n index: number,\n): AgentCandidateExperimentMeasurement {\n const suite = experiment.benchmark.suite\n const taskIndex = Math.floor(index / suite.reps)\n const repetition = index % suite.reps\n const task = experiment.benchmark.tasks[taskIndex]\n const seed = suite.seeds[index]\n if (!task || seed === undefined) {\n throw new Error(`candidate experiment measurement ${index} is outside the signed suite`)\n }\n const baseline = verifyExecutionEvidence(input.baseline)\n const candidate = verifyExecutionEvidence(input.candidate)\n for (const [arm, evidence] of [\n ['baseline', baseline],\n ['candidate', candidate],\n ] as const) {\n const bundle = experiment[arm]\n const materialization = evidence.materializationReceipt\n const plan = materialization.executionPlan.material\n const runCell = plan.runCell\n verifySelfAddressed(runCell, 'candidate run cell')\n if (\n runCell.experimentDigest !== experiment.digest ||\n runCell.arm !== arm ||\n runCell.bundleDigest !== bundle.digest ||\n runCell.suiteDigest !== suite.digest ||\n runCell.taskDigest !== task.digest ||\n runCell.taskIndex !== taskIndex ||\n runCell.repetition !== repetition ||\n runCell.seed !== seed ||\n runCell.attempt > task.attempt.maxAttempts ||\n materialization.bundleDigest !== bundle.digest ||\n materialization.benchmark.suite.digest !== suite.digest ||\n materialization.benchmark.task.digest !== task.digest ||\n materialization.codeKind !== bundle.code.kind ||\n materialization.profileActivation.profilePlan.material.sourceProfileDigest !==\n canonicalCandidateDigest(bundle.profile) ||\n evidence.receipt.runCellDigest !== runCell.digest ||\n JSON.stringify(materialization.resolvedModel) !== JSON.stringify(task.model)\n ) {\n throw new Error(`candidate experiment measurement ${index} substituted its ${arm} arm`)\n }\n verifyTaskOutcome(task, evidence, index, arm)\n }\n const baselinePlan = baseline.materializationReceipt.executionPlan.material\n const candidatePlan = candidate.materializationReceipt.executionPlan.material\n if (\n baselinePlan.executionId === candidatePlan.executionId ||\n baselinePlan.runCell.digest === candidatePlan.runCell.digest ||\n baseline.materializationReceipt.digest === candidate.materializationReceipt.digest ||\n baseline.receipt.digest === candidate.receipt.digest ||\n baseline.digest === candidate.digest\n ) {\n throw new Error(`candidate experiment measurement ${index} reused one execution across arms`)\n }\n return { baseline, candidate }\n}\n\nfunction verifyExecutionEvidence(input: unknown): CandidateExecutionEvidence {\n const evidence = candidateExecutionEvidenceSchema.parse(input)\n verifySelfAddressed(evidence, 'candidate execution evidence')\n verifySelfAddressed(evidence.materializationReceipt, 'candidate materialization receipt')\n verifySelfAddressed(\n evidence.materializationReceipt.profileActivation,\n 'candidate profile activation',\n )\n verifyMaterialAddressed(\n evidence.materializationReceipt.profileActivation.profilePlan,\n 'candidate profile plan',\n )\n verifyMaterialAddressed(evidence.materializationReceipt.executionPlan, 'candidate execution plan')\n verifySelfAddressed(evidence.receipt, 'candidate run receipt')\n verifyMaterialAddressed(evidence.receipt.modelSettlement, 'candidate model settlement')\n verifyMaterialAddressed(evidence.receipt.taskOutcome, 'candidate task outcome')\n verifyMaterialAddressed(evidence.receipt.benchmarkResult, 'candidate benchmark result')\n return evidence\n}\n\nfunction verifySelfAddressed<T extends { digest: Sha256Digest }>(document: T, label: string): void {\n if (canonicalCandidateDigest(omitTopLevelDigest(document)) !== document.digest) {\n throw new Error(`${label} digest is invalid`)\n }\n}\n\nfunction verifyTaskOutcome(\n task: AgentCandidateBenchmarkTask,\n evidence: CandidateExecutionEvidence,\n index: number,\n arm: 'baseline' | 'candidate',\n): void {\n const outcome = evidence.receipt.taskOutcome.material.outcome\n const result = evidence.receipt.benchmarkResult.material\n const prefix = `candidate experiment measurement ${index} ${arm}`\n if (result.evidence.sha256 === task.grader.artifact.sha256) {\n throw new Error(`${prefix} reused grader bytes as grading evidence`)\n }\n const usage = combinedUsage(evidence)\n const usageChecks: Array<[number, number, string]> = [\n [usage.modelCalls, task.limits.maxModelCalls, 'model calls'],\n [usage.inputTokens, task.limits.maxInputTokens, 'input tokens'],\n [usage.outputTokens, task.limits.maxOutputTokens, 'output tokens'],\n [usage.costUsdNanos, Math.round(task.limits.maxCostUsd * 1_000_000_000), 'cost'],\n ]\n for (const [actual, maximum, label] of usageChecks) {\n if (actual > maximum) {\n throw new Error(`${prefix} ${label} ${actual} exceeds the signed limit ${maximum}`)\n }\n }\n if (outcome.kind !== task.outcome.kind) {\n throw new Error(`${prefix} returned an outcome outside the signed task contract`)\n }\n if (task.outcome.kind === 'output') {\n if (\n outcome.kind !== 'output' ||\n outcome.spec.mediaType !== task.outcome.mediaType ||\n outcome.spec.maxBytes !== task.outcome.maxBytes\n ) {\n throw new Error(`${prefix} changed the signed output contract`)\n }\n return\n }\n const repository = task.repository\n if (\n outcome.kind !== 'workspace' ||\n repository === undefined ||\n outcome.baseRepository.identity !== repository.identity ||\n outcome.baseRepository.rootIdentity !== repository.rootIdentity ||\n outcome.baseRepository.commit !== repository.baseCommit ||\n outcome.baseRepository.tree !== repository.baseTree\n ) {\n throw new Error(`${prefix} did not start from the signed repository state`)\n }\n}\n\nfunction verifyStableProfileMaterialization(\n measurements: AgentCandidateExperimentMeasurement[],\n): void {\n for (const arm of ['baseline', 'candidate'] as const) {\n const expected = measurements[0]?.[arm].materializationReceipt.profileActivation\n if (!expected) throw new Error('candidate experiment contains no profile materialization')\n const expectedDigest = canonicalCandidateDigest({\n profilePlanDigest: expected.profilePlan.digest,\n files: expected.files,\n })\n for (const [index, measurement] of measurements.entries()) {\n const activation = measurement[arm].materializationReceipt.profileActivation\n if (\n canonicalCandidateDigest({\n profilePlanDigest: activation.profilePlan.digest,\n files: activation.files,\n }) !== expectedDigest\n ) {\n throw new Error(\n `candidate experiment measurement ${index} ${arm} materialized a different profile`,\n )\n }\n }\n }\n}\n\nfunction completedSuccessfully(evidence: CandidateExecutionEvidence): boolean {\n const termination = evidence.receipt.termination\n return termination.kind === 'exit' && termination.exitCode === 0\n}\n\nfunction verifyMaterialAddressed(\n evidence: { digest: Sha256Digest; material: unknown },\n label: string,\n): void {\n if (canonicalCandidateDigest(evidence.material) !== evidence.digest) {\n throw new Error(`${label} digest is invalid`)\n }\n}\n\ninterface ProjectedRun {\n score: number\n dimensions: Map<string, number>\n costUsd: number\n costProvenance: AgentImprovementCost['provenance']\n latencyMs: number\n completed: boolean\n passed: boolean\n}\n\ninterface ProjectedPairedMeasurement {\n cellId: string\n baseline: ProjectedRun\n candidate: ProjectedRun\n}\n\nfunction projectPairedMeasurement<TRun>(\n measurement: PairedMeasurement<TRun>,\n index: number,\n adapter: PairedMeasurementAdapter<TRun>,\n): ProjectedPairedMeasurement {\n if (typeof measurement.cellId !== 'string' || !measurement.cellId.trim()) {\n throw new Error(`paired measurement ${index} requires a cell id`)\n }\n return {\n cellId: measurement.cellId,\n baseline: projectRun(measurement.baseline, adapter, `paired measurement ${index} baseline`),\n candidate: projectRun(measurement.candidate, adapter, `paired measurement ${index} candidate`),\n }\n}\n\nfunction projectRun<TRun>(\n run: TRun,\n adapter: PairedMeasurementAdapter<TRun>,\n label: string,\n): ProjectedRun {\n const suppliedDimensions = adapter.dimensions(run)\n if (!Array.isArray(suppliedDimensions)) {\n throw new Error(`${label} dimensions must be an array`)\n }\n const dimensions = new Map<string, number>()\n for (const dimension of suppliedDimensions) {\n if (typeof dimension.name !== 'string' || !dimension.name.trim()) {\n throw new Error(`${label} contains an unnamed dimension`)\n }\n if (dimensions.has(dimension.name)) {\n throw new Error(`${label} repeats dimension '${dimension.name}'`)\n }\n dimensions.set(dimension.name, finiteMeasurement(dimension.score, `${label} ${dimension.name}`))\n }\n const completed = adapter.completed(run)\n const passed = adapter.passed(run)\n if (typeof completed !== 'boolean' || typeof passed !== 'boolean') {\n throw new Error(`${label} completion and pass values must be booleans`)\n }\n const costProvenance = adapter.costProvenance(run)\n if (costProvenance !== 'observed' && costProvenance !== 'estimated') {\n throw new Error(`${label} cost provenance must be observed or estimated`)\n }\n return {\n score: finiteMeasurement(adapter.score(run), `${label} score`),\n dimensions,\n costUsd: nonNegativeMeasurement(adapter.costUsd(run), `${label} cost`),\n costProvenance,\n latencyMs: nonNegativeMeasurement(adapter.latencyMs(run), `${label} latency`),\n completed,\n passed,\n }\n}\n\nfunction sharedProjectedDimensions(measurements: readonly ProjectedPairedMeasurement[]): string[] {\n const expected = [...measurements[0]!.baseline.dimensions.keys()]\n for (const [index, measurement] of measurements.entries()) {\n for (const [arm, run] of [\n ['baseline', measurement.baseline],\n ['candidate', measurement.candidate],\n ] as const) {\n const actual = [...run.dimensions.keys()]\n if (JSON.stringify(actual) !== JSON.stringify(expected)) {\n throw new Error(`paired measurement ${index} ${arm} dimensions do not match the suite`)\n }\n }\n }\n return expected\n}\n\nfunction dimensionScore(run: ProjectedRun, name: string): number {\n const value = run.dimensions.get(name)\n if (value === undefined) throw new Error(`paired measurement is missing dimension '${name}'`)\n return value\n}\n\nfunction measuredEstimate(\n baseline: number[],\n candidate: number[],\n options: { confidence: number; resamples: number; seed: number },\n): Pick<\n AgentImprovementMeasuredComparison['overall'],\n 'baseline' | 'candidate' | 'delta' | 'confidenceInterval' | 'n'\n> {\n const bootstrap = pairedBootstrap(baseline, candidate, {\n confidence: options.confidence,\n resamples: options.resamples,\n statistic: 'mean',\n seed: options.seed,\n })\n const baselineMean = mean(baseline)\n const candidateMean = mean(candidate)\n const delta = candidateMean - baselineMean\n return {\n baseline: baselineMean,\n candidate: candidateMean,\n delta,\n confidenceInterval: {\n level: bootstrap.confidence,\n lower: Math.min(bootstrap.low, delta),\n upper: Math.max(bootstrap.high, delta),\n method: 'paired-bootstrap',\n statistic: 'mean',\n resamples: bootstrap.resamples,\n },\n n: bootstrap.n,\n }\n}\n\nfunction observedPairedPrecision(options: {\n baselineScores: number[]\n candidateScores: number[]\n delta: number\n lowerBound: number\n deltaThreshold: number\n minProductiveRuns: number\n confidence: number\n sharedScorerChannel: boolean\n}): { sufficient: boolean; minimumDetectableDelta: number; scaleAssumed: boolean; reason: string } {\n const n = options.baselineScores.length\n const lowerMargin = Math.max(0, options.delta - options.lowerBound)\n const minimumDetectableDelta = options.deltaThreshold + lowerMargin\n const allScores = [...options.baselineScores, ...options.candidateScores]\n const scaleAssumed = allScores.every((score) => score >= -0.001 && score <= 1.001)\n const headroom = Math.max(0, 1 - mean(options.baselineScores))\n const enoughRuns = n >= options.minProductiveRuns\n const attainable = !scaleAssumed || minimumDetectableDelta <= headroom\n const sufficient = enoughRuns && attainable\n const scorerNote = options.sharedScorerChannel\n ? ' The same scorer evaluated both arms, so scorer bias is not measured.'\n : ''\n\n if (!enoughRuns) {\n return {\n sufficient,\n minimumDetectableDelta,\n scaleAssumed,\n reason: `only ${n} paired runs; ${options.minProductiveRuns} required.${scorerNote}`,\n }\n }\n if (!attainable) {\n return {\n sufficient,\n minimumDetectableDelta,\n scaleAssumed,\n reason:\n `observed paired uncertainty gives a minimum detectable delta of ` +\n `${minimumDetectableDelta.toFixed(3)}, above the remaining score headroom ` +\n `${headroom.toFixed(3)}.${scorerNote}`,\n }\n }\n return {\n sufficient,\n minimumDetectableDelta,\n scaleAssumed,\n reason:\n `observed paired uncertainty gives a minimum detectable delta of ` +\n `${minimumDetectableDelta.toFixed(3)} at ${options.confidence.toFixed(2)} confidence ` +\n `from ${n} runs.${scorerNote}`,\n }\n}\n\nfunction finiteMeasurement(value: number, label: string): number {\n if (!Number.isFinite(value)) throw new Error(`${label} must be finite`)\n return value\n}\n\nfunction nonNegativeMeasurement(value: number, label: string): number {\n if (!Number.isFinite(value) || value < 0) throw new Error(`${label} must be non-negative`)\n return value\n}\n\nconst candidateExecutionEvidenceAdapter: PairedMeasurementAdapter<CandidateExecutionEvidence> = {\n score: (evidence) => evidence.receipt.benchmarkResult.material.score,\n dimensions: (evidence) => evidence.receipt.benchmarkResult.material.dimensions,\n costUsd: costFromEvidence,\n costProvenance: (evidence) => combinedUsage(evidence).costProvenance,\n latencyMs: latencyFromEvidence,\n completed: completedSuccessfully,\n passed: (evidence) => evidence.receipt.benchmarkResult.material.passed,\n}\n\nfunction costFromEvidence(evidence: CandidateExecutionEvidence): number {\n return combinedUsage(evidence).costUsdNanos / 1_000_000_000\n}\n\nfunction latencyFromEvidence(evidence: CandidateExecutionEvidence): number {\n return (\n evidence.receipt.timing.durationMs +\n evidence.receipt.benchmarkResult.material.grading.timing.durationMs\n )\n}\n\nfunction combinedUsage(evidence: CandidateExecutionEvidence): AgentCandidateFixedSpend {\n const candidate = evidence.receipt.modelSettlement.material.usage\n const grader = evidence.receipt.benchmarkResult.material.grading.usage\n return addFixedSpend(candidate, grader)\n}\n\nfunction cellIds(experiment: AgentCandidateExperiment): string[] {\n const { suite, tasks } = experiment.benchmark\n return suite.seeds.map((_, index) => {\n const taskIndex = Math.floor(index / suite.reps)\n const repetition = index % suite.reps\n return `${tasks[taskIndex]?.scenario.id ?? taskIndex}:${repetition}`\n })\n}\n\nfunction mean(values: number[]): number {\n if (values.length === 0) throw new Error('candidate experiment requires measured values')\n return values.reduce((sum, value) => sum + value, 0) / values.length\n}\n","import {\n type AgentCandidateFixedSpend,\n type AgentImprovementCost,\n type AgentProfileImprovementExperiment,\n type AgentProfileImprovementExperimentMaterial,\n type AgentProfileImprovementMeasuredComparison,\n type AgentProfileImprovementMeasurement,\n type AgentProfileImprovementRunCell,\n type AgentProfileImprovementRunReceipt,\n type AgentProfileImprovementSuiteInputs,\n type AgentProfileImprovementTask,\n type AgentProfileImprovementTaskMaterial,\n agentProfileImprovementExperimentSchema,\n agentProfileImprovementMeasuredComparisonSchema,\n agentProfileImprovementRunCellSchema,\n agentProfileImprovementRunReceiptSchema,\n agentProfileImprovementSuiteInputsSchema,\n agentProfileImprovementSuiteSchema,\n agentProfileImprovementTaskSchema,\n canonicalCandidateDigest,\n canonicalCandidateJson,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport type { CostLedgerHandle, CostReceiptInput } from '../cost-ledger'\nimport { addFixedSpend } from './fixed-spend'\nimport { evaluatePairedMeasurements, type PairedMeasurementAdapter } from './measured-comparison'\nimport { runPaidPairedMeasurement } from './paid-paired-measurement'\n\nexport interface SealAgentProfileImprovementSuiteOptions {\n splitDigest: Sha256Digest\n tasks: [AgentProfileImprovementTask, ...AgentProfileImprovementTask[]]\n reps: number\n seeds: [number, ...number[]]\n}\n\nexport interface AgentProfileImprovementExperimentExecutionInput {\n experiment: AgentProfileImprovementExperiment\n arm: 'baseline' | 'candidate'\n stateDigest: Sha256Digest\n task: AgentProfileImprovementTask\n runCell: AgentProfileImprovementRunCell\n seed: number\n signal?: AbortSignal\n}\n\nexport interface RunAgentProfileImprovementExperimentOptions {\n experiment: AgentProfileImprovementExperiment\n execute(\n input: AgentProfileImprovementExperimentExecutionInput,\n ): Promise<AgentProfileImprovementRunReceipt>\n /** Maximum number of simultaneous execute calls across both arms. */\n maxConcurrency?: number\n /** Shared run budget that also accounts for analysis and candidate search. */\n costLedger?: CostLedgerHandle\n signal?: AbortSignal\n}\n\nexport interface AgentProfileImprovementExperimentRun {\n measurements: AgentProfileImprovementMeasurement[]\n measurement: {\n wallDurationMs: number\n cost: AgentImprovementCost\n }\n}\n\nexport interface CompareAgentProfileImprovementExperimentOptions {\n experiment: AgentProfileImprovementExperiment\n measurements: AgentProfileImprovementMeasurement[]\n preparation: {\n wallDurationMs: number\n cost: AgentImprovementCost\n }\n measurement: AgentProfileImprovementExperimentRun['measurement']\n runId: string\n candidate?: AgentProfileImprovementMeasuredComparison['candidate']\n generationsExplored?: number\n metadata?: AgentProfileImprovementMeasuredComparison['metadata']\n}\n\n/** Content-address one held-out profile task before either state can execute it. */\nexport function sealAgentProfileImprovementTask(\n material: AgentProfileImprovementTaskMaterial,\n): AgentProfileImprovementTask {\n return agentProfileImprovementTaskSchema.parse({\n ...material,\n digest: canonicalCandidateDigest(material),\n })\n}\n\n/** Freeze profile task order, repetitions, seeds, and the held-out split. */\nexport function sealAgentProfileImprovementSuite(\n options: SealAgentProfileImprovementSuiteOptions,\n): AgentProfileImprovementSuiteInputs {\n for (const task of options.tasks) verifyAgentProfileImprovementTask(task)\n const material = {\n kind: 'agent-profile-improvement-suite' as const,\n digestAlgorithm: 'rfc8785-sha256' as const,\n splitDigest: options.splitDigest,\n taskDigests: options.tasks.map((task) => task.digest) as [Sha256Digest, ...Sha256Digest[]],\n reps: options.reps,\n seeds: options.seeds,\n }\n const suite = agentProfileImprovementSuiteSchema.parse({\n ...material,\n digest: canonicalCandidateDigest(material),\n })\n return agentProfileImprovementSuiteInputsSchema.parse({\n suite,\n tasks: options.tasks,\n })\n}\n\n/** Freeze the two host-owned profile states and their exact held-out work. */\nexport function sealAgentProfileImprovementExperiment(\n material: AgentProfileImprovementExperimentMaterial,\n): AgentProfileImprovementExperiment {\n return verifyAgentProfileImprovementExperiment({\n ...material,\n digest: canonicalCandidateDigest(material),\n })\n}\n\nexport function verifyAgentProfileImprovementTask(input: unknown): AgentProfileImprovementTask {\n return agentProfileImprovementTaskSchema.parse(input)\n}\n\nexport function verifyAgentProfileImprovementSuiteInputs(\n input: unknown,\n): AgentProfileImprovementSuiteInputs {\n return agentProfileImprovementSuiteInputsSchema.parse(input)\n}\n\nexport function verifyAgentProfileImprovementExperiment(\n input: unknown,\n): AgentProfileImprovementExperiment {\n return agentProfileImprovementExperimentSchema.parse(input)\n}\n\n/**\n * Execute each signed profile cell through the host's one exact-state executor.\n * Eval owns only the cell schedule and receipt checks; the host resolves each\n * state digest and captures its own run, billing, trace, and grader evidence.\n */\nexport async function runAgentProfileImprovementExperiment(\n options: RunAgentProfileImprovementExperimentOptions,\n): Promise<AgentProfileImprovementExperimentRun> {\n const experiment = verifyAgentProfileImprovementExperiment(options.experiment)\n const expectedCount =\n experiment.benchmark.suite.taskDigests.length * experiment.benchmark.suite.reps\n const run = await runPaidPairedMeasurement({\n count: expectedCount,\n maxConcurrency: options.maxConcurrency ?? 2,\n label: 'profile improvement experiment',\n budgetUsd: experiment.policy.budgetUsd,\n ...(options.costLedger ? { costLedger: options.costLedger } : {}),\n maximumCostUsd: profileMeasurementMaximumCostUsd(experiment),\n call: {\n callId: `profile-improvement-measurement:${experiment.digest}`,\n channel: 'measurement',\n phase: 'heldout',\n actor: experiment.executionRef.identity,\n model: profileMeasurementModel(experiment),\n tags: { experimentDigest: experiment.digest, executorDigest: experiment.executionRef.digest },\n },\n ...(options.signal ? { signal: options.signal } : {}),\n async execute(index, arm, signal) {\n const expected = profileExecutionInput(experiment, arm, index, signal)\n const receipt = agentProfileImprovementRunReceiptSchema.parse(await options.execute(expected))\n verifyProfileReceiptContract(receipt, expected, index)\n return receipt\n },\n receipt(measurements) {\n return profileMeasurementCostReceipt(measurements, profileMeasurementModel(experiment))\n },\n })\n return {\n measurements: run.measurements.map((measurement, index) =>\n verifyProfileMeasurement(experiment, measurement, index),\n ),\n measurement: {\n wallDurationMs: run.wallDurationMs,\n cost: { usd: run.cost.usd, provenance: run.cost.kind },\n },\n }\n}\n\n/** Build the only publishable profile comparison from complete host receipts. */\nexport function measuredComparisonFromAgentProfileImprovementExperiment(\n options: CompareAgentProfileImprovementExperimentOptions,\n): AgentProfileImprovementMeasuredComparison {\n const experiment = verifyAgentProfileImprovementExperiment(options.experiment)\n const measurements = options.measurements.map((measurement, index) =>\n verifyProfileMeasurement(experiment, measurement, index),\n )\n const expectedCount =\n experiment.benchmark.suite.taskDigests.length * experiment.benchmark.suite.reps\n if (measurements.length !== expectedCount) {\n throw new Error(\n `profile improvement experiment is incomplete (${measurements.length}/${expectedCount} paired cells)`,\n )\n }\n if (!options.runId.trim()) {\n throw new Error('profile improvement experiment runId is required')\n }\n\n const evaluation = evaluatePairedMeasurements({\n measurements: measurements.map((measurement, index) => ({\n cellId: profileCellId(experiment, index),\n ...measurement,\n })),\n policy: experiment.policy,\n adapter: profileReceiptAdapter,\n sharedScorerChannel: true,\n preparationCost: options.preparation.cost,\n measurementCost: options.measurement.cost,\n })\n const provisional = agentProfileImprovementMeasuredComparisonSchema.parse({\n kind: 'agent-profile-improvement-measured-comparison',\n experiment,\n measurements,\n overall: evaluation.overall,\n objectives: evaluation.objectives,\n ...(options.candidate ? { candidate: options.candidate } : {}),\n decision: evaluation.decision,\n power: evaluation.power,\n provenance: {\n kind: 'agent-eval-loop',\n schema: 'agent-profile-improvement-experiment',\n runId: options.runId,\n recordDigest: canonicalCandidateDigest({}),\n baselineContentHash: experiment.baseline.stateDigest,\n candidateContentHash: experiment.candidate.stateDigest,\n },\n diff: canonicalCandidateJson(experiment.change),\n evaluation: {\n generationsExplored: options.generationsExplored ?? 0,\n preparation: options.preparation,\n measurement: {\n wallDurationMs: options.measurement.wallDurationMs,\n workDurationMs: evaluation.measurementWorkDurationMs,\n cost: evaluation.measurementCost,\n },\n total: {\n wallDurationMs: options.preparation.wallDurationMs + options.measurement.wallDurationMs,\n cost: evaluation.totalCost,\n },\n },\n ...(options.metadata ? { metadata: options.metadata } : {}),\n })\n const { recordDigest: _recordDigest, ...provenance } = provisional.provenance\n return agentProfileImprovementMeasuredComparisonSchema.parse({\n ...provisional,\n provenance: {\n ...provenance,\n recordDigest: canonicalCandidateDigest({ ...provisional, provenance }),\n },\n })\n}\n\n/** Recompute a profile comparison from the exact sealed experiment and receipts. */\nexport function verifyAgentProfileImprovementExperimentComparison(\n input: unknown,\n): AgentProfileImprovementMeasuredComparison {\n const comparison = agentProfileImprovementMeasuredComparisonSchema.parse(input)\n const recomputed = measuredComparisonFromAgentProfileImprovementExperiment({\n experiment: comparison.experiment,\n measurements: comparison.measurements,\n runId: comparison.provenance.runId,\n ...(comparison.candidate ? { candidate: comparison.candidate } : {}),\n generationsExplored: comparison.evaluation.generationsExplored,\n preparation: comparison.evaluation.preparation,\n measurement: {\n wallDurationMs: comparison.evaluation.measurement.wallDurationMs,\n cost: comparison.evaluation.measurement.cost,\n },\n ...(comparison.metadata ? { metadata: comparison.metadata } : {}),\n })\n if (canonicalCandidateDigest(recomputed) !== canonicalCandidateDigest(comparison)) {\n throw new Error('profile improvement comparison does not match its Runtime receipts')\n }\n return comparison\n}\n\nfunction profileMeasurementMaximumCostUsd(experiment: AgentProfileImprovementExperiment): number {\n const pairs = experiment.benchmark.suite.reps\n const maximum = experiment.benchmark.tasks.reduce(\n (sum, task) => sum + task.limits.maxCostUsd * pairs * 2,\n 0,\n )\n if (!Number.isFinite(maximum) || maximum < 0) {\n throw new Error('profile improvement measurement maximum cost is invalid')\n }\n return maximum\n}\n\nfunction profileMeasurementModel(experiment: AgentProfileImprovementExperiment): string {\n const models = [...new Set(experiment.benchmark.tasks.map((task) => task.model.model))]\n return models.length === 1 ? models[0]! : 'multiple-models'\n}\n\nfunction profileMeasurementCostReceipt(\n measurements: Array<{\n baseline: AgentProfileImprovementRunReceipt\n candidate: AgentProfileImprovementRunReceipt\n }>,\n model: string,\n): CostReceiptInput {\n const usage = measurements.reduce<AgentCandidateFixedSpend>(\n (sum, measurement) =>\n addFixedSpend(\n addFixedSpend(sum, combinedProfileUsage(measurement.baseline)),\n combinedProfileUsage(measurement.candidate),\n ),\n {\n inputTokens: 0,\n outputTokens: 0,\n cachedInputTokens: 0,\n reasoningTokens: 0,\n modelCalls: 0,\n costUsdNanos: 0,\n costProvenance: 'observed',\n },\n )\n const costUsd = usage.costUsdNanos / 1_000_000_000\n return {\n model,\n inputTokens: usage.inputTokens,\n outputTokens: usage.outputTokens,\n cachedTokens: usage.cachedInputTokens,\n reasoningTokens: usage.reasoningTokens,\n ...(usage.costProvenance === 'observed'\n ? { actualCostUsd: costUsd }\n : { estimatedCostUsd: costUsd }),\n }\n}\n\nfunction combinedProfileUsage(\n receipt: AgentProfileImprovementRunReceipt,\n): AgentCandidateFixedSpend {\n return addFixedSpend(receipt.usage, receipt.grading.usage)\n}\n\nfunction profileExecutionInput(\n experiment: AgentProfileImprovementExperiment,\n arm: 'baseline' | 'candidate',\n index: number,\n signal: AbortSignal | undefined,\n): AgentProfileImprovementExperimentExecutionInput {\n const { task, taskIndex, repetition, seed } = profileCell(experiment, index)\n const stateDigest = experiment[arm].stateDigest\n const runCellMaterial = {\n kind: 'agent-profile-improvement-run-cell' as const,\n experimentDigest: experiment.digest,\n arm,\n stateDigest,\n suiteDigest: experiment.benchmark.suite.digest,\n taskDigest: task.digest,\n taskIndex,\n repetition,\n seed,\n attempt: 1,\n }\n const runCell = agentProfileImprovementRunCellSchema.parse({\n ...runCellMaterial,\n digest: canonicalCandidateDigest(runCellMaterial),\n })\n return {\n experiment,\n arm,\n stateDigest,\n task,\n runCell,\n seed,\n ...(signal ? { signal } : {}),\n }\n}\n\nfunction verifyProfileMeasurement(\n experiment: AgentProfileImprovementExperiment,\n input: unknown,\n index: number,\n): AgentProfileImprovementMeasurement {\n if (input === null || typeof input !== 'object' || Array.isArray(input)) {\n throw new Error(`profile improvement measurement ${index} must be an object`)\n }\n const material = input as { baseline?: unknown; candidate?: unknown }\n const expectedBaseline = profileExecutionInput(experiment, 'baseline', index, undefined)\n const expectedCandidate = profileExecutionInput(experiment, 'candidate', index, undefined)\n const baseline = agentProfileImprovementRunReceiptSchema.parse(material.baseline)\n const candidate = agentProfileImprovementRunReceiptSchema.parse(material.candidate)\n if (\n baseline.runCell.digest !== expectedBaseline.runCell.digest ||\n candidate.runCell.digest !== expectedCandidate.runCell.digest\n ) {\n throw new Error(`profile improvement measurement ${index} substituted a measured arm`)\n }\n verifyProfileReceiptContract(baseline, expectedBaseline, index)\n verifyProfileReceiptContract(candidate, expectedCandidate, index)\n if (baseline.executionId === candidate.executionId || baseline.digest === candidate.digest) {\n throw new Error(`profile improvement measurement ${index} reused one execution across arms`)\n }\n return { baseline, candidate }\n}\n\nfunction verifyProfileReceiptContract(\n receipt: AgentProfileImprovementRunReceipt,\n expected: AgentProfileImprovementExperimentExecutionInput,\n index: number,\n): void {\n const task = expected.task\n if (\n canonicalCandidateDigest(receipt.resolvedModel) !== canonicalCandidateDigest(task.model) ||\n canonicalCandidateDigest(receipt.limits) !== canonicalCandidateDigest(task.limits) ||\n canonicalCandidateDigest(receipt.grading.grader) !== canonicalCandidateDigest(task.grader)\n ) {\n throw new Error(\n `profile improvement measurement ${index} substituted its ${expected.arm} task contract`,\n )\n }\n if (\n canonicalCandidateDigest(receipt.executionRef) !==\n canonicalCandidateDigest(expected.experiment.executionRef)\n ) {\n throw new Error(\n `profile improvement measurement ${index} substituted its ${expected.arm} executor`,\n )\n }\n}\n\nfunction profileCell(\n experiment: AgentProfileImprovementExperiment,\n index: number,\n): {\n task: AgentProfileImprovementTask\n taskIndex: number\n repetition: number\n seed: number\n} {\n const { suite, tasks } = experiment.benchmark\n const taskIndex = Math.floor(index / suite.reps)\n const repetition = index % suite.reps\n const task = tasks[taskIndex]\n const seed = suite.seeds[index]\n if (!task || seed === undefined) {\n throw new Error(`profile improvement experiment cell ${index} is outside the signed suite`)\n }\n return { task, taskIndex, repetition, seed }\n}\n\nfunction profileCellId(experiment: AgentProfileImprovementExperiment, index: number): string {\n return `${experiment.benchmark.suite.digest}:${index}`\n}\n\nconst profileReceiptAdapter: PairedMeasurementAdapter<AgentProfileImprovementRunReceipt> = {\n score: (receipt) => receipt.grading.score,\n dimensions: (receipt) => receipt.grading.dimensions,\n costUsd: (receipt) =>\n (receipt.usage.costUsdNanos + receipt.grading.usage.costUsdNanos) / 1_000_000_000,\n costProvenance: (receipt) =>\n receipt.usage.costProvenance === 'observed' &&\n receipt.grading.usage.costProvenance === 'observed'\n ? 'observed'\n : 'estimated',\n latencyMs: (receipt) => receipt.timing.durationMs + receipt.grading.timing.durationMs,\n completed: (receipt) => receipt.outcome.status === 'succeeded',\n passed: (receipt) => receipt.grading.passed,\n}\n","/**\n * # `intake/run-record-dir` — load a directory or file of `RunRecord`s.\n *\n * The on-disk counterpart to the in-memory intake adapters: point it at a\n * single `.json` (array) / `.jsonl` (one record per line) file or at a\n * directory of such files, and it returns the substrate-canonical\n * `RunRecord[]` ready for `analyzeRuns({ runs })`.\n *\n * Validation is at the boundary: each parsed object goes through\n * `parseRunRecordSafe`. By default an invalid record fails loud with its\n * file + index; pass `onInvalid: 'collect'` to keep the valid records and\n * receive the rejects as structured diagnostics instead.\n */\n\nimport { readdir, readFile, stat } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { parseRunRecordSafe, type RunRecord } from '../../run-record'\n\n/** A record that failed boundary validation, with enough context to fix it. */\nexport interface RunRecordRejection {\n /** Absolute or caller-relative path to the file the record came from. */\n file: string\n /** Zero-based position within the file (array index or JSONL line number). */\n index: number\n /** The validator's message. */\n reason: string\n}\n\nexport interface FromRunRecordDirOptions {\n /**\n * How to treat a record that fails `parseRunRecordSafe`:\n * - `'throw'` (default) — fail loud on the first invalid record.\n * - `'collect'` — drop it, keep the rest, and return it under `rejected`.\n */\n onInvalid?: 'throw' | 'collect'\n /**\n * When the input is a directory, only files matching this predicate are\n * read. Default: any file ending in `.json` or `.jsonl`. The `analysis.json`\n * artifact `evalReportingSuite` writes is always skipped so a re-run never\n * ingests its own output.\n */\n include?: (fileName: string) => boolean\n /**\n * Recurse into subdirectories when the input is a directory. Default false —\n * a flat run directory is the common case and recursion can silently pull in\n * unrelated corpora.\n */\n recursive?: boolean\n}\n\nexport interface FromRunRecordDirResult {\n /** Records that passed boundary validation, in file-then-index order. */\n runs: RunRecord[]\n /** Records that failed validation. Empty unless `onInvalid: 'collect'`. */\n rejected: RunRecordRejection[]\n /** The files that were read, in the order they were processed. */\n files: string[]\n}\n\nconst ANALYSIS_ARTIFACT = 'analysis.json'\n\nfunction defaultInclude(fileName: string): boolean {\n if (fileName === ANALYSIS_ARTIFACT) return false\n return fileName.endsWith('.json') || fileName.endsWith('.jsonl')\n}\n\n/**\n * Resolve a file or directory path into validated `RunRecord[]`.\n *\n * A `.json` file must parse to a top-level array; a `.jsonl` file is one\n * record per non-empty line. Directories are read shallowly by default\n * (set `recursive` to descend); the `analysis.json` output artifact is\n * always excluded.\n */\nexport async function fromRunRecordDir(\n path: string,\n options: FromRunRecordDirOptions = {},\n): Promise<FromRunRecordDirResult> {\n const onInvalid = options.onInvalid ?? 'throw'\n const include = options.include ?? defaultInclude\n\n const stats = await stat(path)\n const filePaths = stats.isDirectory()\n ? await collectFiles(path, include, options.recursive ?? false)\n : [path]\n\n const runs: RunRecord[] = []\n const rejected: RunRecordRejection[] = []\n\n for (const file of filePaths) {\n const raw = await parseRecordFile(file)\n for (const { index, value } of raw) {\n const parsed = parseRunRecordSafe(value)\n if (parsed.ok) {\n runs.push(parsed.value)\n continue\n }\n const rejection: RunRecordRejection = { file, index, reason: parsed.error.message }\n if (onInvalid === 'throw') {\n throw new Error(\n `fromRunRecordDir: invalid RunRecord in '${file}' at index ${index}: ${parsed.error.message}`,\n )\n }\n rejected.push(rejection)\n }\n }\n\n return { runs, rejected, files: filePaths }\n}\n\n/** Read a single `.json` / `.jsonl` file into `{ index, value }` pairs. A\n * malformed JSONL line throws with its line number rather than being skipped —\n * silent line-dropping is how corpora quietly shrink. */\nasync function parseRecordFile(file: string): Promise<Array<{ index: number; value: unknown }>> {\n const text = await readFile(file, 'utf8')\n const trimmed = text.trim()\n if (trimmed.length === 0) return []\n\n if (trimmed.startsWith('[')) {\n const parsed = JSON.parse(trimmed) as unknown\n if (!Array.isArray(parsed)) {\n throw new Error(`fromRunRecordDir: file '${file}' did not parse to an array`)\n }\n return parsed.map((value, index) => ({ index, value }))\n }\n\n const out: Array<{ index: number; value: unknown }> = []\n const lines = trimmed.split('\\n')\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!.trim()\n if (line.length === 0) continue\n try {\n out.push({ index: i, value: JSON.parse(line) as unknown })\n } catch (err) {\n throw new Error(\n `fromRunRecordDir: file '${file}' line ${i + 1} is not valid JSON: ${\n err instanceof Error ? err.message : String(err)\n }`,\n )\n }\n }\n return out\n}\n\n/** Sorted file list under a directory, filtered by `include`. Sorted so the\n * resulting `RunRecord` order — and any downstream fingerprint — is stable\n * across filesystems. */\nasync function collectFiles(\n dir: string,\n include: (fileName: string) => boolean,\n recursive: boolean,\n): Promise<string[]> {\n const entries = await readdir(dir, { withFileTypes: true })\n const files: string[] = []\n const subdirs: string[] = []\n for (const entry of entries) {\n if (entry.isDirectory()) {\n if (recursive) subdirs.push(join(dir, entry.name))\n continue\n }\n if (include(entry.name)) files.push(join(dir, entry.name))\n }\n files.sort()\n subdirs.sort()\n for (const sub of subdirs) {\n files.push(...(await collectFiles(sub, include, recursive)))\n }\n return files\n}\n","/**\n * # `evalReportingSuite` — one call from runs (or a run dir) to `analysis.json`.\n *\n * A thin wrapper over the analysis primitive (`analyzeRuns`) and the on-disk\n * intake adapter (`fromRunRecordDir`). It does NOT reimplement any statistics,\n * distributions, or clustering — it resolves the input into validated\n * `RunRecord[]`, calls `analyzeRuns` with the options you'd pass it directly,\n * wraps the result in a small provenance envelope, and (optionally) writes a\n * single `analysis.json` artifact.\n *\n * ```ts\n * // From a directory of run files, write ./runs/analysis.json:\n * const suite = await evalReportingSuite('./runs', { write: true })\n * // From records already in memory, no write:\n * const suite = await evalReportingSuite(records, { analyze: { decisionThreshold: 0.03 } })\n * suite.report // the InsightReport — distributions, paired lift, findings rollup\n * ```\n */\n\nimport { mkdir, writeFile } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\nimport type { RunRecord } from '../run-record'\nimport { type AnalyzeRunsOptions, analyzeRuns } from './analyze-runs'\nimport type { InsightReport } from './insight-report'\nimport {\n type FromRunRecordDirOptions,\n type FromRunRecordDirResult,\n fromRunRecordDir,\n} from './intake/run-record-dir'\n\n/** Either records in hand or a path to a `.json` / `.jsonl` file or a\n * directory of them. */\nexport type EvalReportingSuiteInput = RunRecord[] | string\n\nexport interface EvalReportingSuiteOptions {\n /** Forwarded verbatim to `analyzeRuns` (everything except `runs`, which the\n * suite supplies from the resolved input). Use this for split selection,\n * baseline/candidate ids, canaries, prior-period runs, the analyst registry,\n * etc. */\n analyze?: Omit<AnalyzeRunsOptions, 'runs'>\n /** Loader options used only when the input is a path. */\n load?: FromRunRecordDirOptions\n /**\n * Write the suite result as a single `analysis.json`.\n * - `true` — write to `<dir>/analysis.json` when the input is a directory,\n * or alongside the input file; throws if the input is in-memory records\n * (no directory to anchor to — pass an explicit path instead).\n * - a string — write to exactly this path (a directory path gets\n * `analysis.json` appended; any other path is used verbatim).\n * - omitted / false — do not write.\n */\n write?: boolean | string\n}\n\n/** The suite artifact — the `analyzeRuns` report plus provenance. This is the\n * exact shape serialized to `analysis.json`. */\nexport interface EvalReportingSuiteResult {\n /** The analysis itself — distributions, paired stats/lift, failure rollup,\n * recommendations. Produced by `analyzeRuns`. */\n report: InsightReport\n /** How the suite was run, so a reader can verify provenance. */\n provenance: {\n /** ISO timestamp the suite ran. */\n generatedAt: string\n /** Number of records analyzed (mirrors `report.n`). */\n runCount: number\n /** The source path when the input was a directory/file; null for\n * in-memory records. */\n sourcePath: string | null\n /** Files read when loading from disk; empty for in-memory input. */\n files: string[]\n /** Records dropped at the validation boundary. Always empty unless\n * `load.onInvalid` was set to `'collect'`. */\n rejected: FromRunRecordDirResult['rejected']\n }\n /** The path `analysis.json` was written to, or null when `write` was unset. */\n writtenTo: string | null\n}\n\nconst ANALYSIS_ARTIFACT = 'analysis.json'\n\n/**\n * Resolve runs (or a run dir/file), run `analyzeRuns`, and optionally persist a\n * single `analysis.json`. The only analysis logic lives in `analyzeRuns`; this\n * function is composition + I/O.\n */\nexport async function evalReportingSuite(\n input: EvalReportingSuiteInput,\n options: EvalReportingSuiteOptions = {},\n): Promise<EvalReportingSuiteResult> {\n const fromPath = typeof input === 'string'\n\n let runs: RunRecord[]\n let files: string[] = []\n let rejected: FromRunRecordDirResult['rejected'] = []\n if (fromPath) {\n const loaded = await fromRunRecordDir(input, options.load)\n runs = loaded.runs\n files = loaded.files\n rejected = loaded.rejected\n } else {\n runs = input\n }\n\n if (runs.length === 0) {\n throw new Error(\n fromPath\n ? `evalReportingSuite: no RunRecords found at '${input}'`\n : 'evalReportingSuite: no RunRecords to analyze',\n )\n }\n\n const report = await analyzeRuns({ ...options.analyze, runs })\n\n const result: EvalReportingSuiteResult = {\n report,\n provenance: {\n generatedAt: new Date().toISOString(),\n runCount: runs.length,\n sourcePath: fromPath ? input : null,\n files,\n rejected,\n },\n writtenTo: null,\n }\n\n const target = resolveWriteTarget(options.write, fromPath ? input : null)\n if (target) {\n await mkdir(dirname(target), { recursive: true })\n await writeFile(target, `${JSON.stringify(result, null, 2)}\\n`, 'utf8')\n result.writtenTo = target\n }\n\n return result\n}\n\n/** Resolve where (if anywhere) to write `analysis.json`. Returns null when\n * writing is disabled. Throws on `write: true` with in-memory input — there is\n * no directory to anchor the artifact to, and silently inventing `cwd` would\n * scatter files. */\nfunction resolveWriteTarget(\n write: EvalReportingSuiteOptions['write'],\n sourcePath: string | null,\n): string | null {\n if (!write) return null\n\n if (typeof write === 'string') {\n const looksLikeDir =\n write.endsWith('/') || (!write.endsWith('.json') && !write.endsWith('.jsonl'))\n return looksLikeDir ? join(write, ANALYSIS_ARTIFACT) : write\n }\n\n // write === true\n if (sourcePath === null) {\n throw new Error(\n 'evalReportingSuite: write:true needs a source path to anchor analysis.json — pass an explicit output path when analyzing in-memory records',\n )\n }\n const isFile = sourcePath.endsWith('.json') || sourcePath.endsWith('.jsonl')\n return isFile ? join(dirname(sourcePath), ANALYSIS_ARTIFACT) : join(sourcePath, ANALYSIS_ARTIFACT)\n}\n","/**\n * # `@tangle-network/agent-eval/contract` — eval-run diff primitive.\n *\n * The substrate side of the v-N-versus-v-N+1 dashboard view. Given two\n * `EvalRunEvent`s (or two `EvalRunGenerationSnapshot`s from one run), this\n * returns a normalised diff: per-cell composite + per-judge/per-dimension\n * deltas, surface-hash change, aggregate cost + duration shifts.\n *\n * Consumed by:\n * - The hosted-tier dashboard (intelligence-web) — renders v3 vs v4\n * comparisons of cells × judges × dimensions.\n * - CI reporting — emits a \"shipped: composite +0.07, cost +$1.20\" line\n * in PR review for autonomous-improvement runs.\n * - Any downstream consumer that needs \"what actually changed\" without\n * reimplementing the matching + arithmetic.\n *\n * Cells are matched on the natural composite key `(scenarioId, rep)`.\n * Unmatched cells surface as `removed` / `added` so callers can tell\n * \"this cell got worse\" from \"this cell wasn't run.\"\n */\n\nimport type { GateDecision } from '../campaign/types'\nimport type { EvalRunCellScore, EvalRunEvent, EvalRunGenerationSnapshot } from '../hosted/types'\n\n// ── Types ────────────────────────────────────────────────────────────\n\n/** Per-dimension delta. `before` / `after` are null when the judge did not\n * emit a value for that side. `delta` is `after - before`; null when\n * either side is null. */\nexport interface EvalDimensionDelta {\n before: number | null\n after: number | null\n delta: number | null\n}\n\n/** Per-cell delta, keyed on `(scenarioId, rep)`. */\nexport interface EvalCellScoreDelta {\n scenarioId: string\n rep: number\n compositeBefore: number | null\n compositeAfter: number | null\n compositeDelta: number | null\n /** Per-judge → per-dimension deltas. Outer key = judge name from\n * `EvalRunCellScore.dimensions`; inner key = dimension name. */\n dimensions: Record<string, Record<string, EvalDimensionDelta>>\n}\n\n/** Diff between two generation snapshots — the unit the dashboard renders\n * for a single \"v3 vs v4\" comparison. */\nexport interface EvalGenerationDiff {\n beforeIndex: number\n afterIndex: number\n beforeSurfaceHash: string\n afterSurfaceHash: string\n surfaceChanged: boolean\n /** Cells present in both snapshots, matched on `(scenarioId, rep)`. */\n matched: EvalCellScoreDelta[]\n /** Cells present in `before` but missing from `after`. */\n removed: EvalRunCellScore[]\n /** Cells present in `after` but missing from `before`. */\n added: EvalRunCellScore[]\n /** Aggregate composite mean, null when that snapshot was unscored. */\n compositeBefore: number | null\n compositeAfter: number | null\n compositeDelta: number | null\n costUsdBefore: number\n costUsdAfter: number\n costUsdDelta: number\n durationMsBefore: number\n durationMsAfter: number\n durationMsDelta: number\n}\n\n/** Diff between two full eval-runs. Includes both baseline-vs-baseline and\n * winner-vs-winner generation diffs when both sides expose them, plus\n * run-level metadata. */\nexport interface EvalRunDiff {\n beforeRunId: string\n afterRunId: string\n beforeTimestamp: string\n afterTimestamp: string\n beforeGateDecision: GateDecision | null\n afterGateDecision: GateDecision | null\n beforeHoldoutLift: number | null\n afterHoldoutLift: number | null\n holdoutLiftDelta: number | null\n beforeTotalCostUsd: number\n afterTotalCostUsd: number\n totalCostUsdDelta: number\n beforeTotalDurationMs: number\n afterTotalDurationMs: number\n totalDurationMsDelta: number\n /** Baseline-vs-baseline diff. Null when either run has no baseline. */\n baselineDiff: EvalGenerationDiff | null\n /** Highest-index-generation comparison. Null when either run has no\n * recorded generations (e.g. baseline-only or errored before any\n * generation completed). */\n winnersDiff: EvalGenerationDiff | null\n}\n\n// ── Implementation ───────────────────────────────────────────────────\n\nfunction keyForCell(cell: EvalRunCellScore): string {\n // JSON-tuple key — `scenarioId` may legitimately contain `::` or any other\n // delimiter, so we use JSON.stringify on a 2-tuple to get an unambiguous,\n // collision-free composite key.\n return JSON.stringify([cell.scenarioId, cell.rep])\n}\n\n/** Build the per-dimension delta map for a matched cell. Each judge name +\n * dimension name encountered on EITHER side appears in the result. */\nfunction diffDimensions(\n before: EvalRunCellScore['dimensions'],\n after: EvalRunCellScore['dimensions'],\n): EvalCellScoreDelta['dimensions'] {\n const out: EvalCellScoreDelta['dimensions'] = {}\n const judges = new Set<string>([...Object.keys(before), ...Object.keys(after)])\n for (const judge of judges) {\n const beforeDims = before[judge] ?? {}\n const afterDims = after[judge] ?? {}\n const dims = new Set<string>([...Object.keys(beforeDims), ...Object.keys(afterDims)])\n const judgeOut: Record<string, EvalDimensionDelta> = {}\n for (const dim of dims) {\n // Coerce non-finite values (NaN, ±Infinity) to null so the diff never\n // surfaces NaN/Infinity to the dashboard. A NaN score is a substrate\n // bug from upstream; the diff treats it as \"no value\" rather than\n // propagating the corruption.\n const rawBefore = beforeDims[dim]\n const rawAfter = afterDims[dim]\n const b = typeof rawBefore === 'number' && Number.isFinite(rawBefore) ? rawBefore : null\n const a = typeof rawAfter === 'number' && Number.isFinite(rawAfter) ? rawAfter : null\n judgeOut[dim] = {\n before: b,\n after: a,\n delta: b !== null && a !== null ? a - b : null,\n }\n }\n out[judge] = judgeOut\n }\n return out\n}\n\n/**\n * Diff two generation snapshots. Cells are matched on `(scenarioId, rep)`;\n * unmatched cells surface in `added` / `removed`. Aggregate fields are\n * recomputed from the snapshot's stored fields, not re-derived from cells —\n * this keeps the diff consistent with whatever aggregation the substrate\n * actually reported.\n */\nexport function diffGenerations(\n before: EvalRunGenerationSnapshot,\n after: EvalRunGenerationSnapshot,\n): EvalGenerationDiff {\n const beforeMap = new Map(before.cells.map((c) => [keyForCell(c), c]))\n const afterMap = new Map(after.cells.map((c) => [keyForCell(c), c]))\n\n const matched: EvalCellScoreDelta[] = []\n const removed: EvalRunCellScore[] = []\n const added: EvalRunCellScore[] = []\n\n for (const [key, beforeCell] of beforeMap) {\n const afterCell = afterMap.get(key)\n if (!afterCell) {\n removed.push(beforeCell)\n continue\n }\n matched.push({\n scenarioId: beforeCell.scenarioId,\n rep: beforeCell.rep,\n compositeBefore: beforeCell.compositeMean,\n compositeAfter: afterCell.compositeMean,\n compositeDelta:\n beforeCell.compositeMean === null || afterCell.compositeMean === null\n ? null\n : afterCell.compositeMean - beforeCell.compositeMean,\n dimensions: diffDimensions(beforeCell.dimensions, afterCell.dimensions),\n })\n }\n for (const [key, afterCell] of afterMap) {\n if (!beforeMap.has(key)) added.push(afterCell)\n }\n\n return {\n beforeIndex: before.index,\n afterIndex: after.index,\n beforeSurfaceHash: before.surfaceHash,\n afterSurfaceHash: after.surfaceHash,\n surfaceChanged: before.surfaceHash !== after.surfaceHash,\n matched,\n removed,\n added,\n compositeBefore: before.compositeMean,\n compositeAfter: after.compositeMean,\n compositeDelta:\n before.compositeMean === null || after.compositeMean === null\n ? null\n : after.compositeMean - before.compositeMean,\n costUsdBefore: before.costUsd,\n costUsdAfter: after.costUsd,\n costUsdDelta: after.costUsd - before.costUsd,\n durationMsBefore: before.durationMs,\n durationMsAfter: after.durationMs,\n durationMsDelta: after.durationMs - before.durationMs,\n }\n}\n\n/** Highest-index generation, or null if the run recorded none. */\nfunction winnerOf(run: EvalRunEvent): EvalRunGenerationSnapshot | null {\n if (run.generations.length === 0) return null\n let winner = run.generations[0] as EvalRunGenerationSnapshot\n for (const gen of run.generations) {\n if (gen.index > winner.index) winner = gen\n }\n return winner\n}\n\n/**\n * Diff two full eval-runs. Produces baseline-vs-baseline and\n * winner-vs-winner generation diffs when both sides expose them, plus\n * run-level cost / lift / gate-decision deltas.\n */\nexport function diffRuns(before: EvalRunEvent, after: EvalRunEvent): EvalRunDiff {\n const beforeWinner = winnerOf(before)\n const afterWinner = winnerOf(after)\n const baselineDiff =\n before.baseline && after.baseline ? diffGenerations(before.baseline, after.baseline) : null\n const winnersDiff =\n beforeWinner && afterWinner ? diffGenerations(beforeWinner, afterWinner) : null\n\n const beforeLift = before.holdoutLift ?? null\n const afterLift = after.holdoutLift ?? null\n\n return {\n beforeRunId: before.runId,\n afterRunId: after.runId,\n beforeTimestamp: before.timestamp,\n afterTimestamp: after.timestamp,\n beforeGateDecision: before.gateDecision ?? null,\n afterGateDecision: after.gateDecision ?? null,\n beforeHoldoutLift: beforeLift,\n afterHoldoutLift: afterLift,\n holdoutLiftDelta: beforeLift !== null && afterLift !== null ? afterLift - beforeLift : null,\n beforeTotalCostUsd: before.totalCostUsd,\n afterTotalCostUsd: after.totalCostUsd,\n totalCostUsdDelta: after.totalCostUsd - before.totalCostUsd,\n beforeTotalDurationMs: before.totalDurationMs,\n afterTotalDurationMs: after.totalDurationMs,\n totalDurationMsDelta: after.totalDurationMs - before.totalDurationMs,\n baselineDiff,\n winnersDiff,\n }\n}\n\n/**\n * Within-run baseline → winning-generation diff. The natural \"what did the\n * improvement loop produce\" view for a single run. Returns null when the\n * run never reached a generation past baseline (errored early, or the gate\n * shipped the baseline as-is).\n */\nexport function diffRunBaselineToWinner(run: EvalRunEvent): EvalGenerationDiff | null {\n if (!run.baseline) return null\n const winner = winnerOf(run)\n if (!winner || winner.index === run.baseline.index) return null\n return diffGenerations(run.baseline, winner)\n}\n","/**\n * `fromAgentTrace` — provenance correlation from Cursor's Agent Trace spec\n * (https://github.com/cursor/agent-trace, RFC v0.1.0).\n *\n * Agent Trace is NOT a run/quality trace — it carries no outcome, score, or\n * cost. It records *code authorship*: for a VCS revision, which AI model /\n * conversation authored which file ranges. It explicitly disclaims quality\n * assessment — which is exactly what `analyzeRuns` adds.\n *\n * The two layers join on a key the substrate already has: a `RunRecord`\n * carries `commitSha`, and an Agent Trace record is keyed by\n * `vcs.revision`. So this adapter does not produce `RunRecord`s — it builds a\n * provenance index by commit and partitions existing runs by their authoring\n * model. Feed each cohort to `analyzeRuns` (or pass one as `baselineRuns`) to\n * answer the question no run-only trace can: *which authoring agent's code\n * fails / regresses / costs more.*\n *\n * Granularity is commit-level (the SHA join). Per-file/per-line correlation\n * would require runs to record which files they exercised — out of scope.\n */\n\nimport type { RunRecord } from '../../run-record'\n\n// ── Agent Trace record schema (the subset we read) ──────────────────────────\n\nexport type AgentTraceContributorType = 'human' | 'ai' | 'mixed' | 'unknown'\n\nexport interface AgentTraceContributor {\n type: AgentTraceContributorType\n /** models.dev id, e.g. `anthropic/claude-opus-4-5-20251101`. */\n model_id?: string\n}\n\nexport interface AgentTraceRange {\n start_line: number\n end_line: number\n content_hash?: string\n /** Per-range contributor override (agent handoffs). Wins over the\n * conversation-level contributor for these lines. */\n contributor?: AgentTraceContributor\n}\n\nexport interface AgentTraceConversation {\n url?: string\n contributor?: AgentTraceContributor\n ranges: AgentTraceRange[]\n}\n\nexport interface AgentTraceFile {\n path: string\n conversations: AgentTraceConversation[]\n}\n\nexport interface AgentTraceRecord {\n version: string\n id: string\n timestamp: string\n vcs?: { type: string; revision: string }\n tool?: { name?: string; version?: string }\n files: AgentTraceFile[]\n}\n\n// ── Provenance index ─────────────────────────────────────────────────────────\n\n/** Authorship provenance for one VCS revision, aggregated across the record's\n * files/conversations/ranges. */\nexport interface AuthoringProvenance {\n commitSha: string\n /** Unique AI model ids that authored code in this commit (type ai|mixed). */\n aiModels: string[]\n /** Tools that produced the records (e.g. `cursor`). */\n tools: string[]\n conversationCount: number\n fileCount: number\n /** Total attributed lines (sum of range spans). */\n lineCount: number\n /** True if any range was authored (in whole or part) by a human. */\n humanInvolved: boolean\n}\n\nexport type AgentTraceIndex = Map<string, AuthoringProvenance>\n\nfunction rangeLines(r: AgentTraceRange): number {\n return Math.max(0, r.end_line - r.start_line + 1)\n}\n\n/**\n * Build a commit → provenance index from Agent Trace records. Multiple records\n * for the same revision are merged. Records without `vcs.revision` are skipped\n * (the SHA is the join key — without it there is nothing to correlate against).\n */\nexport function parseAgentTrace(records: AgentTraceRecord[]): AgentTraceIndex {\n interface Acc {\n models: Set<string>\n tools: Set<string>\n files: Set<string>\n conversationCount: number\n lineCount: number\n humanInvolved: boolean\n }\n const acc = new Map<string, Acc>()\n\n for (const record of records) {\n const sha = record.vcs?.revision\n if (!sha) continue // the SHA is the join key — nothing to correlate without it\n\n let a = acc.get(sha)\n if (!a) {\n a = {\n models: new Set(),\n tools: new Set(),\n files: new Set(),\n conversationCount: 0,\n lineCount: 0,\n humanInvolved: false,\n }\n acc.set(sha, a)\n }\n\n if (record.tool?.name) a.tools.add(record.tool.name)\n\n for (const file of record.files ?? []) {\n a.files.add(file.path)\n for (const conv of file.conversations ?? []) {\n a.conversationCount += 1\n for (const range of conv.ranges ?? []) {\n // Per-range contributor wins, else the conversation contributor.\n const contributor = range.contributor ?? conv.contributor\n a.lineCount += rangeLines(range)\n if (!contributor) continue\n if (contributor.type === 'human' || contributor.type === 'mixed') {\n a.humanInvolved = true\n }\n if ((contributor.type === 'ai' || contributor.type === 'mixed') && contributor.model_id) {\n a.models.add(contributor.model_id)\n }\n }\n }\n }\n }\n\n const index: AgentTraceIndex = new Map()\n for (const [sha, a] of acc) {\n index.set(sha, {\n commitSha: sha,\n aiModels: [...a.models].sort(),\n tools: [...a.tools].sort(),\n conversationCount: a.conversationCount,\n fileCount: a.files.size,\n lineCount: a.lineCount,\n humanInvolved: a.humanInvolved,\n })\n }\n return index\n}\n\n// ── Run ↔ provenance join ──────────────────────────────────────────────────\n\nexport interface PartitionByAuthoringModelResult {\n /** Runs grouped by each AI model that authored code in the run's commit. A\n * run whose commit had multiple authoring models appears under EACH — the\n * cohorts overlap by construction at commit granularity. */\n byModel: Map<string, RunRecord[]>\n /** Runs whose `commitSha` had no Agent Trace provenance (no record, or no\n * AI authorship). Kept separate — never silently folded into a cohort. */\n unattributed: RunRecord[]\n}\n\n/**\n * Partition runs by the AI model(s) that authored the code at each run's\n * `commitSha`. Feed `byModel.get(modelId)` to `analyzeRuns`, or compare two\n * model cohorts via `analyzeRuns({ runs: a, baselineRuns: b })` for a lift CI\n * on \"model A's code vs model B's code\".\n */\nexport function partitionRunsByAuthoringModel(\n runs: RunRecord[],\n index: AgentTraceIndex,\n): PartitionByAuthoringModelResult {\n const byModel = new Map<string, RunRecord[]>()\n const unattributed: RunRecord[] = []\n\n for (const run of runs) {\n const provenance = index.get(run.commitSha)\n if (!provenance || provenance.aiModels.length === 0) {\n unattributed.push(run)\n continue\n }\n for (const model of provenance.aiModels) {\n const cohort = byModel.get(model) ?? []\n cohort.push(run)\n byModel.set(model, cohort)\n }\n }\n\n return { byModel, unattributed }\n}\n","export type CodeAgentSessionSource = 'codex' | 'claude-code' | 'opencode' | 'kimi-code' | 'pi'\n\nexport type CodeAgentSessionTerminalStatus = 'completed' | 'failed' | 'unknown'\n\nexport type CodeAgentSessionActionKind = 'tool' | 'patch' | 'terminal' | 'graph-completion'\n\nexport type CodeAgentSessionActionSurface =\n | 'tool'\n | 'mcp'\n | 'subagent'\n | 'skill'\n | 'hook'\n | 'web'\n | 'code'\n\nexport type CodeAgentSessionActionStatus = 'started' | 'completed' | 'failed' | 'unknown'\n\nexport interface CodeAgentSessionExecutionReceipt {\n exitCode: number\n startedAtMs?: number\n completedAtMs?: number\n}\n\nexport interface CodeAgentSessionAction {\n id: string\n stepIndex: number\n kind: CodeAgentSessionActionKind\n surface: CodeAgentSessionActionSurface\n name: string\n status: CodeAgentSessionActionStatus\n timestampMs?: number\n costUsd?: number\n metadata: Record<string, unknown>\n}\n\nexport interface CodeAgentSessionObservation {\n source: CodeAgentSessionSource\n sessionId: string\n finalText: string | null\n terminal: {\n status: CodeAgentSessionTerminalStatus\n explicit: boolean\n }\n actions: CodeAgentSessionAction[]\n}\n\nexport interface ObserveCodeAgentSessionOptions {\n source: CodeAgentSessionSource\n entries: unknown[]\n sourcePath?: string\n execution?: CodeAgentSessionExecutionReceipt\n}\n\ninterface SessionProjection {\n finalText: string | null\n terminal: CodeAgentSessionTerminalStatus\n explicitTerminal: boolean\n actions: CodeAgentSessionAction[]\n}\n\n/**\n * Project one provider session into the exact user-visible answer and a\n * provider-neutral action stream. Raw prompts, tool inputs, and tool outputs\n * stay out of this projection; callers retain the source JSONL as evidence.\n */\nexport function observeCodeAgentSession(\n options: ObserveCodeAgentSessionOptions,\n): CodeAgentSessionObservation {\n const entries = options.entries.filter(isRecord)\n const projection = projectionFor(options.source, entries)\n const terminal = terminalWithExecution(projection, options.execution)\n return {\n source: options.source,\n sessionId:\n sessionIdFromEntries(options.source, entries) ??\n fallbackSessionId(options.source, options.sourcePath),\n finalText: projection.finalText,\n terminal,\n actions: projection.actions,\n }\n}\n\nfunction projectionFor(\n source: CodeAgentSessionSource,\n entries: Record<string, unknown>[],\n): SessionProjection {\n switch (source) {\n case 'codex':\n return codexProjection(entries)\n case 'claude-code':\n return claudeProjection(entries)\n case 'opencode':\n return openCodeProjection(entries)\n case 'kimi-code':\n return kimiProjection(entries)\n case 'pi':\n return piProjection(entries)\n }\n}\n\nfunction codexProjection(entries: Record<string, unknown>[]): SessionProjection {\n const actions: CodeAgentSessionAction[] = []\n const calls = new Map<string, CodeAgentSessionAction>()\n let finalText: string | null = null\n let terminal: CodeAgentSessionTerminalStatus = 'unknown'\n let explicitTerminal = false\n\n for (const entry of entries) {\n const entryType = stringField(entry, 'type')\n const payload = record(entry.payload) ?? {}\n const payloadType = stringField(payload, 'type')\n const timestampMs = timestamp(entry.timestamp)\n const item = record(entry.item)\n\n if (entryType === 'item.started' && item) {\n const itemType = stringField(item, 'type')\n if (isCodexActionItem(itemType)) {\n const id = stringField(item, 'id') ?? `item-${actions.length}`\n const action = actionFor({\n id,\n stepIndex: actions.length,\n kind: itemType === 'file_change' ? 'patch' : 'tool',\n surface: codexItemSurface(itemType, item),\n name: codexItemName(itemType, item),\n status: 'started',\n timestampMs,\n metadata: compactMetadata({ sourceEventType: entryType, itemType }),\n })\n calls.set(id, action)\n actions.push(action)\n }\n }\n\n if (entryType === 'item.completed' && item) {\n const itemType = stringField(item, 'type')\n if (itemType === 'agent_message' || itemType === 'message') {\n finalText = nonEmpty(stringField(item, 'text')) ?? finalText\n }\n if (isCodexActionItem(itemType)) {\n const id = stringField(item, 'id') ?? `item-${actions.length}`\n const status = codexItemStatus(itemType, item)\n const existing = calls.get(id)\n if (existing) {\n existing.status = status\n } else {\n const action = actionFor({\n id,\n stepIndex: actions.length,\n kind: itemType === 'file_change' ? 'patch' : 'tool',\n surface: codexItemSurface(itemType, item),\n name: codexItemName(itemType, item),\n status,\n timestampMs,\n metadata: compactMetadata({ sourceEventType: entryType, itemType }),\n })\n calls.set(id, action)\n actions.push(action)\n }\n }\n }\n\n if (entryType === 'response_item') {\n if (payloadType === 'message' || payloadType === 'agent_message') {\n finalText = textFromMessagePayload(payload) ?? finalText\n }\n if (payloadType === 'function_call' || payloadType === 'custom_tool_call') {\n const id =\n stringField(payload, 'call_id') ?? stringField(payload, 'id') ?? `call-${actions.length}`\n const name = stringField(payload, 'name') ?? payloadType\n const action = actionFor({\n id,\n stepIndex: actions.length,\n kind: 'tool',\n surface: surfaceForTool(name),\n name,\n status: 'started',\n timestampMs,\n metadata: compactMetadata({ sourceEventType: entryType, payloadType }),\n })\n calls.set(id, action)\n actions.push(action)\n }\n if (payloadType === 'function_call_output' || payloadType === 'custom_tool_call_output') {\n const id = stringField(payload, 'call_id') ?? stringField(payload, 'id')\n const existing = id ? calls.get(id) : undefined\n if (existing) existing.status = looksLikeError(payload.output) ? 'failed' : 'completed'\n }\n }\n\n if (entryType === 'event_msg') {\n if (payloadType === 'agent_message') {\n finalText =\n nonEmpty(stringField(payload, 'message')) ??\n nonEmpty(stringField(payload, 'text')) ??\n finalText\n }\n if (payloadType === 'patch_apply_end') {\n const patchStatus =\n typeof payload.success === 'boolean'\n ? payload.success\n ? 'completed'\n : 'failed'\n : 'unknown'\n actions.push(\n actionFor({\n id: stringField(payload, 'call_id') ?? `patch-${actions.length}`,\n stepIndex: actions.length,\n kind: 'patch',\n surface: 'code',\n name: 'patch',\n status: patchStatus,\n timestampMs,\n metadata: compactMetadata({ sourceEventType: entryType, payloadType }),\n }),\n )\n }\n if (payloadType === 'sub_agent_activity') {\n const name = stringField(payload, 'kind') ?? 'subagent'\n actions.push(\n actionFor({\n id: stringField(payload, 'event_id') ?? `subagent-${actions.length}`,\n stepIndex: actions.length,\n kind: 'tool',\n surface: 'subagent',\n name,\n status: statusFrom(payload),\n timestampMs,\n metadata: compactMetadata({ sourceEventType: entryType, payloadType }),\n }),\n )\n }\n if (payloadType === 'task_complete' || payloadType === 'turn_aborted') {\n const completed = payloadType === 'task_complete'\n terminal = completed ? 'completed' : 'failed'\n explicitTerminal = true\n actions.push(terminalAction(actions.length, payloadType, completed, timestampMs))\n }\n }\n\n if (entryType === 'turn.completed' || entryType === 'exec_done') {\n const completed = entry.success !== false\n terminal = completed ? 'completed' : 'failed'\n explicitTerminal = true\n finalText = nonEmpty(stringField(entry, 'message')) ?? finalText\n actions.push(terminalAction(actions.length, entryType, completed, timestampMs))\n }\n if (entryType === 'turn.failed' || entryType === 'error') {\n terminal = 'failed'\n explicitTerminal = true\n actions.push(terminalAction(actions.length, entryType, false, timestampMs))\n }\n }\n\n return { finalText, terminal, explicitTerminal, actions }\n}\n\nfunction claudeProjection(entries: Record<string, unknown>[]): SessionProjection {\n const actions: CodeAgentSessionAction[] = []\n const calls = new Map<string, CodeAgentSessionAction>()\n let finalText: string | null = null\n let resultText: string | null = null\n let terminal: CodeAgentSessionTerminalStatus = 'unknown'\n let explicitTerminal = false\n\n for (const entry of entries) {\n const entryType = stringField(entry, 'type')\n const timestampMs = timestamp(entry.timestamp)\n const message = record(entry.message)\n const content = Array.isArray(message?.content) ? message.content : []\n\n if (entryType === 'assistant') {\n const text = textBlocks(content)\n if (text !== null) finalText = text\n for (const value of content) {\n const part = record(value)\n if (!part) continue\n const partType = stringField(part, 'type')\n if (partType === 'tool_use') {\n const id = stringField(part, 'id') ?? `tool-${actions.length}`\n const name = stringField(part, 'name') ?? 'tool'\n const action = actionFor({\n id,\n stepIndex: actions.length,\n kind: 'tool',\n surface: surfaceForTool(name),\n name,\n status: 'started',\n timestampMs,\n metadata: compactMetadata({ sourceEventType: entryType, partType }),\n })\n calls.set(id, action)\n actions.push(action)\n }\n }\n completeClaudeTools(content, calls)\n const stopReason = stringField(message ?? {}, 'stop_reason')\n if (stopReason === 'end_turn') {\n terminal = 'completed'\n explicitTerminal = true\n actions.push(terminalAction(actions.length, stopReason, true, timestampMs))\n }\n }\n\n if (entryType === 'user') {\n completeClaudeTools(content, calls)\n }\n if (entryType === 'tool_use') {\n const id = stringField(entry, 'id') ?? `tool-${actions.length}`\n const name = stringField(entry, 'name') ?? 'tool'\n const action = actionFor({\n id,\n stepIndex: actions.length,\n kind: 'tool',\n surface: surfaceForTool(name),\n name,\n status: 'started',\n timestampMs,\n metadata: { sourceEventType: entryType },\n })\n calls.set(id, action)\n actions.push(action)\n }\n if (entryType === 'tool_result') {\n const id = stringField(entry, 'tool_use_id')\n const action = id ? calls.get(id) : undefined\n if (action) action.status = entry.is_error === true ? 'failed' : 'completed'\n }\n\n if (entryType === 'system') {\n const subtype = stringField(entry, 'subtype')\n const hookName = stringField(entry, 'hook_name') ?? stringField(entry, 'hookName')\n if (subtype?.toLowerCase().includes('hook') || hookName) {\n actions.push(\n actionFor({\n id: stringField(entry, 'uuid') ?? `hook-${actions.length}`,\n stepIndex: actions.length,\n kind: 'tool',\n surface: 'hook',\n name: hookName ?? subtype ?? 'hook',\n status: statusFrom(entry),\n timestampMs,\n metadata: compactMetadata({ sourceEventType: entryType, subtype }),\n }),\n )\n }\n }\n\n if (entryType === 'pr-link') {\n actions.push(terminalAction(actions.length, entryType, true, timestampMs))\n }\n\n if (entryType === 'result') {\n resultText = nonEmpty(stringField(entry, 'result')) ?? resultText\n const subtype = stringField(entry, 'subtype')\n const completed = entry.is_error !== true && !subtype?.toLowerCase().includes('error')\n terminal = completed ? 'completed' : 'failed'\n explicitTerminal = true\n actions.push(terminalAction(actions.length, subtype ?? entryType, completed, timestampMs))\n }\n if (entryType === 'error') {\n terminal = 'failed'\n explicitTerminal = true\n actions.push(terminalAction(actions.length, entryType, false, timestampMs))\n }\n }\n\n return {\n finalText: resultText ?? finalText,\n terminal,\n explicitTerminal,\n actions,\n }\n}\n\nfunction openCodeProjection(entries: Record<string, unknown>[]): SessionProjection {\n const actions: CodeAgentSessionAction[] = []\n const assistantMessageIds = new Set(\n entries\n .filter((entry) => stringField(entry, 'role') === 'assistant')\n .map((entry) => stringField(entry, 'id'))\n .filter((id): id is string => id !== undefined),\n )\n let finalText: string | null = null\n let terminal: CodeAgentSessionTerminalStatus = 'unknown'\n let explicitTerminal = false\n\n for (const entry of entries) {\n const entryType = stringField(entry, 'type')\n const part = record(entry.part) ?? entry\n const partType = stringField(part, 'type')\n const timestampMs = timestamp(entry.timestamp) ?? timestamp(record(entry.time)?.created)\n\n if (entryType === 'text' && record(entry.part)) {\n finalText = nonEmpty(stringField(part, 'text')) ?? finalText\n } else if (\n partType === 'text' &&\n (assistantMessageIds.size === 0 ||\n assistantMessageIds.has(stringField(part, 'messageID') ?? ''))\n ) {\n finalText = nonEmpty(stringField(part, 'text')) ?? finalText\n }\n\n if (entryType === 'tool_use' || partType === 'tool') {\n const state = record(part.state) ?? {}\n const name = stringField(part, 'tool') ?? 'tool'\n actions.push(\n actionFor({\n id: stringField(part, 'callID') ?? stringField(part, 'id') ?? `tool-${actions.length}`,\n stepIndex: actions.length,\n kind: 'tool',\n surface: surfaceForTool(name),\n name,\n status: statusFrom(state),\n timestampMs,\n metadata: compactMetadata({ sourceEventType: entryType, partType }),\n }),\n )\n }\n if (partType === 'patch') {\n actions.push(\n actionFor({\n id: stringField(part, 'id') ?? `patch-${actions.length}`,\n stepIndex: actions.length,\n kind: 'patch',\n surface: 'code',\n name: 'patch',\n status: 'completed',\n timestampMs,\n metadata: compactMetadata({ sourceEventType: entryType, partType }),\n }),\n )\n }\n\n if (stringField(entry, 'role') === 'assistant') {\n const finish = stringField(entry, 'finish')\n if (finish === 'stop' || finish === 'error') {\n const completed = finish === 'stop'\n terminal = completed ? 'completed' : 'failed'\n explicitTerminal = true\n actions.push(terminalAction(actions.length, finish, completed, timestampMs))\n }\n }\n if (entryType === 'error') {\n terminal = 'failed'\n explicitTerminal = true\n actions.push(terminalAction(actions.length, entryType, false, timestampMs))\n }\n }\n\n return { finalText, terminal, explicitTerminal, actions }\n}\n\nfunction kimiProjection(entries: Record<string, unknown>[]): SessionProjection {\n const actions: CodeAgentSessionAction[] = []\n const calls = new Map<string, CodeAgentSessionAction>()\n let finalText: string | null = null\n let terminal: CodeAgentSessionTerminalStatus = 'unknown'\n let explicitTerminal = false\n\n for (const entry of entries) {\n const timestampMs = timestamp(entry.timestamp)\n const message = record(entry.message)\n const messageType = stringField(message ?? {}, 'type')\n const payload = record(message?.payload) ?? {}\n if (messageType === 'ContentPart' && stringField(payload, 'type') === 'text') {\n finalText =\n nonEmpty(stringField(payload, 'text')) ??\n nonEmpty(stringField(payload, 'content')) ??\n finalText\n }\n if (messageType === 'ToolCall') {\n const fn = record(payload.function) ?? {}\n const id = stringField(payload, 'id') ?? `tool-${actions.length}`\n const name = stringField(fn, 'name') ?? 'tool'\n const action = actionFor({\n id,\n stepIndex: actions.length,\n kind: 'tool',\n surface: surfaceForTool(name),\n name,\n status: 'started',\n timestampMs,\n metadata: { sourceEventType: messageType },\n })\n calls.set(id, action)\n actions.push(action)\n }\n if (messageType === 'ToolResult') {\n const id = stringField(payload, 'tool_call_id')\n const action = id ? calls.get(id) : undefined\n if (action)\n action.status = record(payload.return_value)?.is_error === true ? 'failed' : 'completed'\n }\n if (messageType === 'TurnEnd' || messageType === 'StepInterrupted') {\n const completed = messageType === 'TurnEnd'\n terminal = completed ? 'completed' : 'failed'\n explicitTerminal = true\n actions.push(terminalAction(actions.length, messageType, completed, timestampMs))\n }\n }\n\n return { finalText, terminal, explicitTerminal, actions }\n}\n\nfunction piProjection(entries: Record<string, unknown>[]): SessionProjection {\n const actions: CodeAgentSessionAction[] = []\n let terminal: CodeAgentSessionTerminalStatus = 'unknown'\n let explicitTerminal = false\n for (const entry of entries) {\n const nodes = Array.isArray(entry.nodes) ? entry.nodes : []\n for (const value of nodes) {\n const node = record(value)\n const ir = record(node?.ir) ?? node\n const kind = stringField(ir ?? {}, 'kind')\n if (kind === 'ToolInvocation') {\n actions.push(\n actionFor({\n id:\n stringField(ir ?? {}, 'id') ??\n stringField(node ?? {}, 'id') ??\n `tool-${actions.length}`,\n stepIndex: actions.length,\n kind: 'tool',\n surface: 'tool',\n name: stringField(ir ?? {}, 'name') ?? 'graph-tool',\n status: 'started',\n timestampMs: timestamp(ir?.createdAt),\n metadata: { sourceEventType: 'graph-node', graphKind: kind },\n }),\n )\n }\n if (kind === 'ToolResult') {\n const prior = [...actions].reverse().find((action) => action.kind === 'tool')\n if (prior) prior.status = 'completed'\n }\n if (kind === 'CompletionDecision') {\n terminal = 'completed'\n explicitTerminal = true\n actions.push(\n actionFor({\n id:\n stringField(ir ?? {}, 'id') ??\n stringField(node ?? {}, 'id') ??\n `completion-${actions.length}`,\n stepIndex: actions.length,\n kind: 'graph-completion',\n surface: 'tool',\n name: 'complete',\n status: 'completed',\n timestampMs: timestamp(ir?.createdAt),\n metadata: { sourceEventType: 'graph-node', graphKind: kind },\n }),\n )\n }\n }\n }\n return { finalText: null, terminal, explicitTerminal, actions }\n}\n\nfunction completeClaudeTools(content: unknown[], calls: Map<string, CodeAgentSessionAction>): void {\n for (const value of content) {\n const part = record(value)\n if (!part || stringField(part, 'type') !== 'tool_result') continue\n const id = stringField(part, 'tool_use_id')\n const action = id ? calls.get(id) : undefined\n if (action) action.status = part.is_error === true ? 'failed' : 'completed'\n }\n}\n\nfunction isCodexActionItem(itemType: string | undefined): boolean {\n return (\n itemType === 'command_execution' ||\n itemType === 'mcp_tool_call' ||\n itemType === 'collab_tool_call' ||\n itemType === 'web_search' ||\n itemType === 'file_change'\n )\n}\n\nfunction codexItemSurface(\n itemType: string | undefined,\n item: Record<string, unknown>,\n): CodeAgentSessionActionSurface {\n if (itemType === 'mcp_tool_call') return 'mcp'\n if (itemType === 'collab_tool_call') return 'subagent'\n if (itemType === 'web_search') return 'web'\n if (itemType === 'file_change') return 'code'\n return surfaceForTool(stringField(item, 'name') ?? itemType ?? 'tool')\n}\n\nfunction codexItemName(itemType: string | undefined, item: Record<string, unknown>): string {\n if (itemType === 'mcp_tool_call') {\n const server = stringField(item, 'server')\n const tool = stringField(item, 'tool')\n return [server, tool].filter(Boolean).join('/') || 'mcp'\n }\n if (itemType === 'collab_tool_call') return stringField(item, 'tool') ?? 'subagent'\n if (itemType === 'web_search') return 'web_search'\n if (itemType === 'file_change') return 'file_change'\n return stringField(item, 'name') ?? itemType ?? 'tool'\n}\n\nfunction codexItemStatus(\n itemType: string | undefined,\n item: Record<string, unknown>,\n): CodeAgentSessionActionStatus {\n const status = statusFrom(item)\n if (status === 'failed') return status\n if (itemType === 'command_execution') {\n const exitCode = numberField(item, 'exit_code')\n if (exitCode !== undefined) return exitCode === 0 ? 'completed' : 'failed'\n }\n if (itemType === 'mcp_tool_call' && record(item.error)) return 'failed'\n return status === 'unknown' || status === 'started' ? 'completed' : status\n}\n\nfunction textFromMessagePayload(payload: Record<string, unknown>): string | null {\n const direct = nonEmpty(stringField(payload, 'text'))\n if (direct) return direct\n const content = payload.content\n if (typeof content === 'string') return nonEmpty(content)\n if (Array.isArray(content)) return textBlocks(content)\n return null\n}\n\nfunction textBlocks(values: unknown[]): string | null {\n const text = values\n .map((value) => record(value))\n .filter((value): value is Record<string, unknown> => value !== null)\n .filter((value) => stringField(value, 'type') === 'text')\n .map((value) => stringField(value, 'text'))\n .filter((value): value is string => value !== undefined)\n .join('\\n')\n return nonEmpty(text)\n}\n\nfunction terminalWithExecution(\n projection: SessionProjection,\n execution: CodeAgentSessionExecutionReceipt | undefined,\n): CodeAgentSessionObservation['terminal'] {\n if (!execution) {\n return { status: projection.terminal, explicit: projection.explicitTerminal }\n }\n assertExecutionReceipt(execution)\n return {\n status: execution.exitCode !== 0 || projection.terminal === 'failed' ? 'failed' : 'completed',\n explicit: true,\n }\n}\n\nfunction assertExecutionReceipt(receipt: CodeAgentSessionExecutionReceipt): void {\n if (!Number.isSafeInteger(receipt.exitCode)) {\n throw new Error('code-agent execution exitCode must be a safe integer')\n }\n for (const [name, value] of [\n ['startedAtMs', receipt.startedAtMs],\n ['completedAtMs', receipt.completedAtMs],\n ] as const) {\n if (value !== undefined && (!Number.isFinite(value) || value < 0)) {\n throw new Error(`code-agent execution ${name} must be a non-negative finite number`)\n }\n }\n if (\n receipt.startedAtMs !== undefined &&\n receipt.completedAtMs !== undefined &&\n receipt.completedAtMs < receipt.startedAtMs\n ) {\n throw new Error('code-agent execution completedAtMs precedes startedAtMs')\n }\n}\n\nfunction terminalAction(\n stepIndex: number,\n name: string,\n completed: boolean,\n timestampMs: number | undefined,\n): CodeAgentSessionAction {\n return actionFor({\n id: `terminal-${stepIndex}`,\n stepIndex,\n kind: 'terminal',\n surface: 'tool',\n name,\n status: completed ? 'completed' : 'failed',\n timestampMs,\n metadata: { sourceEventType: name },\n })\n}\n\nfunction actionFor(input: CodeAgentSessionAction): CodeAgentSessionAction {\n return input\n}\n\nfunction surfaceForTool(name: string): CodeAgentSessionActionSurface {\n const normalized = name.toLowerCase()\n if (normalized.startsWith('mcp__') || normalized.includes('mcp_tool')) return 'mcp'\n if (\n normalized === 'task' ||\n normalized === 'agent' ||\n normalized.includes('subagent') ||\n normalized.includes('spawn_agent') ||\n normalized.includes('collab') ||\n normalized.startsWith('multi_agent')\n ) {\n return 'subagent'\n }\n if (normalized === 'skill' || normalized.includes('skill')) return 'skill'\n if (normalized.includes('hook')) return 'hook'\n if (\n normalized.includes('web_search') ||\n normalized.includes('webfetch') ||\n normalized === 'web'\n ) {\n return 'web'\n }\n if (\n normalized === 'edit' ||\n normalized === 'write' ||\n normalized.includes('patch') ||\n normalized.includes('file_change')\n ) {\n return 'code'\n }\n return 'tool'\n}\n\nfunction statusFrom(value: Record<string, unknown>): CodeAgentSessionActionStatus {\n const status = (stringField(value, 'status') ?? '').toLowerCase()\n if (status === 'completed' || status === 'success' || status === 'succeeded') return 'completed'\n if (status === 'error' || status === 'failed' || status === 'declined') return 'failed'\n if (status === 'running' || status === 'started' || status === 'in_progress') return 'started'\n return 'unknown'\n}\n\nfunction compactMetadata(input: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(Object.entries(input).filter((entry) => entry[1] !== undefined))\n}\n\nfunction sessionIdFromEntries(\n source: CodeAgentSessionSource,\n entries: Record<string, unknown>[],\n): string | undefined {\n for (const entry of entries) {\n if (source === 'codex') {\n const threadId = stringField(entry, 'thread_id')\n if (threadId) return threadId\n const payload = record(entry.payload)\n const id = payload ? stringField(payload, 'id') : undefined\n if (id) return id\n }\n const message = record(entry.message)\n const payload = record(message?.payload)\n const sessionId =\n stringField(entry, 'sessionID') ??\n stringField(entry, 'sessionId') ??\n stringField(entry, 'session_id') ??\n stringField(payload ?? {}, 'session_id')\n if (sessionId) return sessionId\n }\n return undefined\n}\n\nfunction fallbackSessionId(source: CodeAgentSessionSource, sourcePath: string | undefined): string {\n return `${source}:${sourcePath ?? 'unknown-session'}`\n}\n\nfunction looksLikeError(value: unknown): boolean {\n if (isRecord(value)) {\n if (value.success === false || value.is_error === true) return true\n const exitCode = numberField(value, 'exit_code')\n if (exitCode !== undefined && exitCode !== 0) return true\n }\n const text = typeof value === 'string' ? value : JSON.stringify(value ?? '')\n return /\\b(?:error|failed|failure)\\b|exit(?:_| )code[\"\\s:]+[1-9]/i.test(text)\n}\n\nfunction nonEmpty(value: string | undefined): string | null {\n return value !== undefined && value.length > 0 ? value : null\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction record(value: unknown): Record<string, unknown> | null {\n return isRecord(value) ? value : null\n}\n\nfunction stringField(value: Record<string, unknown>, key: string): string | undefined {\n const field = value[key]\n return typeof field === 'string' && field.length > 0 ? field : undefined\n}\n\nfunction numberField(value: Record<string, unknown>, key: string): number | undefined {\n const field = value[key]\n return typeof field === 'number' && Number.isFinite(field) ? field : undefined\n}\n\nfunction timestamp(value: unknown): number | undefined {\n if (typeof value === 'number' && Number.isFinite(value)) {\n return value > 1_000_000_000_000 ? value : value * 1_000\n }\n if (typeof value === 'string' && value.length > 0) {\n const parsed = Date.parse(value)\n return Number.isFinite(parsed) ? parsed : undefined\n }\n return undefined\n}\n","import { createHash } from 'node:crypto'\nimport { estimateCost, isModelPriced } from '../../metrics'\nimport type {\n RunCostProvenance,\n RunRecord,\n RunSplitTag,\n RunTerminalOutcome,\n RunTokenUsage,\n} from '../../run-record'\nimport { extractUsage } from '../../trace/extract-usage'\nimport {\n type CodeAgentSessionExecutionReceipt,\n type CodeAgentSessionObservation,\n type CodeAgentSessionSource,\n observeCodeAgentSession,\n} from './code-agent-observation'\n\nexport type {\n CodeAgentSessionAction,\n CodeAgentSessionActionKind,\n CodeAgentSessionActionStatus,\n CodeAgentSessionActionSurface,\n CodeAgentSessionExecutionReceipt,\n CodeAgentSessionObservation,\n CodeAgentSessionSource,\n CodeAgentSessionTerminalStatus,\n ObserveCodeAgentSessionOptions,\n} from './code-agent-observation'\nexport { observeCodeAgentSession } from './code-agent-observation'\n\nexport interface ParsedCodeAgentJsonl {\n entries: unknown[]\n malformedLines: number\n}\n\nexport interface CodeAgentSessionMetrics {\n entries: number\n userMessages: number\n assistantMessages: number\n reasoningItems: number\n toolCalls: number\n toolOutputs: number\n toolErrors: number\n unclassifiedErrors: number\n patchAttempts: number\n patchSuccesses: number\n patchFailures: number\n turnsStarted: number\n turnsCompleted: number\n turnsAborted: number\n contextCompactions: number\n mcpCalls: number\n subagentCalls: number\n skillCalls: number\n hookCalls: number\n webCalls: number\n codeActions: number\n prLinks: number\n fileSnapshots: number\n graphNodes: number\n graphEdges: number\n actionCandidates: number\n verificationReports: number\n completionDecisions: number\n reliabilityRows: number\n reliabilityLift: number\n inputTokens: number\n outputTokens: number\n reasoningTokens: number\n cachedTokens: number\n cacheWriteTokens: number\n observedCostUsd: number\n observedCostCaptured?: boolean\n wallMs: number\n processScore: number\n}\n\nexport interface CodeAgentSessionDiagnostic {\n source: CodeAgentSessionSource\n sessionId: string\n sourcePath?: string\n entries: number\n malformedLines: number\n hasExplicitTerminalSignal: boolean\n hasFinalOutput: boolean\n hasQualityLabel: boolean\n hasTokenUsage: boolean\n hasCost: boolean\n costKind?: RunCostProvenance['kind']\n warnings: string[]\n}\n\nexport interface CodeAgentSessionIntakeResult {\n runs: RunRecord[]\n diagnostics: CodeAgentSessionDiagnostic[]\n metrics: CodeAgentSessionMetrics[]\n observations: CodeAgentSessionObservation[]\n}\n\nexport interface CodeAgentSessionIntakeOptions {\n entries: unknown[]\n malformedLines?: number\n sourcePath?: string\n experimentId?: string\n candidateId?: string\n seed?: number\n splitTag?: RunSplitTag\n scenarioId?: string\n model?: string\n promptHash?: string\n configHash?: string\n commitSha?: string\n score?: number\n /** Explicit cost receipt. When omitted, source-reported cost wins, then a\n * token-priced estimate, then uncaptured. */\n costProvenance?: RunCostProvenance\n /** Exact executor-owned process result. This is required when a provider's\n * JSON stream has no terminal event, as with `opencode run --format json`. */\n execution?: CodeAgentSessionExecutionReceipt\n}\n\nexport function parseCodeAgentJsonl(jsonl: string): ParsedCodeAgentJsonl {\n const entries: unknown[] = []\n let malformedLines = 0\n for (const line of jsonl.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed) continue\n try {\n entries.push(JSON.parse(trimmed))\n } catch {\n malformedLines += 1\n }\n }\n return { entries, malformedLines }\n}\n\nexport function fromCodexSession(\n options: CodeAgentSessionIntakeOptions,\n): CodeAgentSessionIntakeResult {\n return fromCodeAgentSession('codex', options)\n}\n\nexport function fromClaudeCodeSession(\n options: CodeAgentSessionIntakeOptions,\n): CodeAgentSessionIntakeResult {\n return fromCodeAgentSession('claude-code', options)\n}\n\nexport function fromOpenCodeSession(\n options: CodeAgentSessionIntakeOptions,\n): CodeAgentSessionIntakeResult {\n return fromCodeAgentSession('opencode', options)\n}\n\nexport function fromKimiCodeSession(\n options: CodeAgentSessionIntakeOptions,\n): CodeAgentSessionIntakeResult {\n return fromCodeAgentSession('kimi-code', options)\n}\n\nexport function fromPiSession(\n options: CodeAgentSessionIntakeOptions,\n): CodeAgentSessionIntakeResult {\n return fromCodeAgentSession('pi', options)\n}\n\nexport const fromPigraphSession = fromPiSession\n\nfunction fromCodeAgentSession(\n source: CodeAgentSessionSource,\n options: CodeAgentSessionIntakeOptions,\n): CodeAgentSessionIntakeResult {\n const entries = options.entries.filter(isRecord)\n if (entries.length === 0) {\n return {\n runs: [],\n diagnostics: [\n {\n source,\n sessionId: fallbackSessionId(source, options.sourcePath),\n sourcePath: options.sourcePath,\n entries: 0,\n malformedLines: options.malformedLines ?? 0,\n hasExplicitTerminalSignal: false,\n hasFinalOutput: false,\n hasQualityLabel: false,\n hasTokenUsage: false,\n hasCost: false,\n costKind: 'uncaptured',\n warnings: ['no parseable session entries'],\n },\n ],\n metrics: [],\n observations: [],\n }\n }\n\n const metrics = metricsFor(source, entries)\n const sessionId =\n sessionIdFromEntries(source, entries) ?? fallbackSessionId(source, options.sourcePath)\n const observation = observeCodeAgentSession({\n source,\n entries,\n sourcePath: options.sourcePath,\n execution: options.execution,\n })\n applyObservedSurfaceMetrics(metrics, observation)\n const model = withSnapshot(options.model ?? modelFromEntries(source, entries) ?? source)\n const tokenUsage: RunTokenUsage = {\n input: metrics.inputTokens,\n output: metrics.outputTokens,\n ...(metrics.reasoningTokens > 0 ? { reasoning: metrics.reasoningTokens } : {}),\n ...(metrics.cachedTokens > 0 ? { cached: metrics.cachedTokens } : {}),\n ...(metrics.cacheWriteTokens > 0 ? { cacheWrite: metrics.cacheWriteTokens } : {}),\n }\n const { costUsd, costProvenance } = resolveSessionCost(options.costProvenance, metrics, model)\n const qualityScore = finiteScore(options.score)\n const invalidQualityScore = options.score !== undefined && qualityScore === undefined\n const promptHash =\n options.promptHash ?? hashString(`prompt:${source}:${firstUserText(entries) ?? ''}`)\n const configHash =\n options.configHash ??\n hashJson({\n source,\n model,\n sourcePath: options.sourcePath,\n cwd: cwdFromEntries(entries),\n entryCount: entries.length,\n })\n const explicitTerminal = observation.terminal.explicit\n const warnings = diagnosticsFor(metrics, {\n model,\n explicitTerminal,\n malformedLines: options.malformedLines ?? 0,\n hasQualityLabel: qualityScore !== undefined,\n invalidQualityScore,\n costKind: costProvenance.kind,\n })\n\n const terminalOutcome = terminalOutcomeFromSession(observation.terminal)\n const processExitCode = options.execution?.exitCode\n const splitTag = options.splitTag ?? 'holdout'\n const run: RunRecord = {\n runId: `${source}:${sessionId}`,\n experimentId: options.experimentId ?? `${source}-local-sessions`,\n candidateId: options.candidateId ?? model,\n seed: options.seed ?? stableSeed(sessionId),\n model,\n promptHash,\n configHash,\n commitSha: options.commitSha ?? 'local-session',\n wallMs: metrics.wallMs,\n costUsd,\n costProvenance,\n tokenUsage,\n terminalOutcome,\n ...(terminalOutcome === 'failed'\n ? {\n terminalFailureReason:\n processExitCode !== undefined && processExitCode !== 0\n ? `process exited with code ${processExitCode}`\n : metrics.turnsAborted > 0\n ? 'turn aborted'\n : 'session reported terminal failure',\n }\n : {}),\n outcome: {\n ...(qualityScore === undefined\n ? {}\n : splitTag === 'holdout'\n ? { holdoutScore: qualityScore }\n : { searchScore: qualityScore }),\n raw: {\n entries: metrics.entries,\n user_messages: metrics.userMessages,\n assistant_messages: metrics.assistantMessages,\n reasoning_items: metrics.reasoningItems,\n tool_calls: metrics.toolCalls,\n tool_outputs: metrics.toolOutputs,\n tool_errors: metrics.toolErrors,\n execution_error_count: metrics.toolErrors,\n process_error_count: terminalOutcome === 'failed' ? 1 : 0,\n unclassified_error_count: metrics.unclassifiedErrors,\n ...(processExitCode !== undefined ? { process_exit_code: processExitCode } : {}),\n patch_attempts: metrics.patchAttempts,\n patch_successes: metrics.patchSuccesses,\n patch_failures: metrics.patchFailures,\n turns_started: metrics.turnsStarted,\n turns_completed: metrics.turnsCompleted,\n turns_aborted: metrics.turnsAborted,\n context_compactions: metrics.contextCompactions,\n mcp_calls: metrics.mcpCalls,\n subagent_calls: metrics.subagentCalls,\n skill_calls: metrics.skillCalls,\n hook_calls: metrics.hookCalls,\n web_calls: metrics.webCalls,\n code_actions: metrics.codeActions,\n pr_links: metrics.prLinks,\n file_snapshots: metrics.fileSnapshots,\n graph_nodes: metrics.graphNodes,\n graph_edges: metrics.graphEdges,\n action_candidates: metrics.actionCandidates,\n verification_reports: metrics.verificationReports,\n completion_decisions: metrics.completionDecisions,\n reliability_rows: metrics.reliabilityRows,\n reliability_lift: metrics.reliabilityLift,\n input_tokens: metrics.inputTokens,\n output_tokens: metrics.outputTokens,\n reasoning_tokens: metrics.reasoningTokens,\n cached_tokens: metrics.cachedTokens,\n cache_write_tokens: metrics.cacheWriteTokens,\n observed_cost_usd: metrics.observedCostUsd,\n observed_cost_captured: metrics.observedCostCaptured ? 1 : 0,\n estimated_cost_usd: costProvenance.kind === 'estimated' ? costProvenance.usd : 0,\n process_score: metrics.processScore,\n explicit_terminal_signal: explicitTerminal ? 1 : 0,\n quality_label_present: qualityScore !== undefined ? 1 : 0,\n cost_observed: costProvenance.kind === 'observed' ? 1 : 0,\n cost_estimated: costProvenance.kind === 'estimated' ? 1 : 0,\n cost_uncaptured: costProvenance.kind === 'uncaptured' ? 1 : 0,\n cost_unknown: costProvenance.kind === 'uncaptured' ? 1 : 0,\n },\n },\n splitTag,\n scenarioId: options.scenarioId ?? sessionId,\n }\n\n return {\n runs: [run],\n diagnostics: [\n {\n source,\n sessionId,\n sourcePath: options.sourcePath,\n entries: entries.length,\n malformedLines: options.malformedLines ?? 0,\n hasExplicitTerminalSignal: explicitTerminal,\n hasFinalOutput: observation.finalText !== null,\n hasQualityLabel: qualityScore !== undefined,\n hasTokenUsage:\n metrics.inputTokens > 0 ||\n metrics.outputTokens > 0 ||\n metrics.reasoningTokens > 0 ||\n metrics.cachedTokens > 0 ||\n metrics.cacheWriteTokens > 0,\n hasCost: costProvenance.kind !== 'uncaptured',\n costKind: costProvenance.kind,\n warnings,\n },\n ],\n metrics: [metrics],\n observations: [{ ...observation, sessionId }],\n }\n}\n\nfunction terminalOutcomeFromSession(\n terminal: CodeAgentSessionObservation['terminal'],\n): RunTerminalOutcome {\n if (!terminal.explicit) return 'unknown'\n if (terminal.status === 'completed') return 'succeeded'\n if (terminal.status === 'failed') return 'failed'\n return 'unknown'\n}\n\nfunction metricsFor(\n source: CodeAgentSessionSource,\n entries: Record<string, unknown>[],\n): CodeAgentSessionMetrics {\n switch (source) {\n case 'codex':\n return codexMetrics(entries)\n case 'claude-code':\n return claudeCodeMetrics(entries)\n case 'opencode':\n return openCodeMetrics(entries)\n case 'kimi-code':\n return kimiCodeMetrics(entries)\n case 'pi':\n return piMetrics(entries)\n }\n}\n\nfunction codexMetrics(entries: Record<string, unknown>[]): CodeAgentSessionMetrics {\n const metrics = emptyMetrics(entries.length)\n const startedToolIds = new Set<string>()\n let startedAt: number | undefined\n let completedAt: number | undefined\n\n for (const entry of entries) {\n const payload = record(entry.payload) ?? {}\n const entryType = stringField(entry, 'type')\n const payloadType = stringField(payload, 'type')\n const timestamp = timestampMs(entry.timestamp)\n if (timestamp !== undefined) {\n startedAt = startedAt === undefined ? timestamp : Math.min(startedAt, timestamp)\n completedAt = completedAt === undefined ? timestamp : Math.max(completedAt, timestamp)\n }\n\n if (entryType === 'turn.started') metrics.turnsStarted += 1\n if (entryType === 'turn.completed') {\n metrics.turnsCompleted += 1\n addCodexExecUsage(metrics, record(entry.usage))\n }\n if (entryType === 'turn.failed') metrics.turnsAborted += 1\n if (entryType === 'error') metrics.unclassifiedErrors += 1\n\n const item = record(entry.item)\n if (item && (entryType === 'item.started' || entryType === 'item.completed')) {\n addCodexExecItem(metrics, startedToolIds, entryType, item)\n }\n\n if (entryType === 'response_item') {\n if (payloadType === 'function_call' || payloadType === 'custom_tool_call')\n metrics.toolCalls += 1\n if (payloadType === 'function_call_output' || payloadType === 'custom_tool_call_output')\n metrics.toolOutputs += 1\n if (payloadType === 'reasoning') metrics.reasoningItems += 1\n if (payloadType === 'message' && stringField(payload, 'role') === 'assistant')\n metrics.assistantMessages += 1\n }\n\n if (entryType === 'event_msg') {\n if (payloadType === 'user_message') metrics.userMessages += 1\n if (payloadType === 'agent_message') metrics.assistantMessages += 1\n if (payloadType === 'task_started') {\n metrics.turnsStarted += 1\n const started = timestampMs(payload.started_at)\n if (started !== undefined) {\n startedAt = startedAt === undefined ? started : Math.min(startedAt, started)\n }\n }\n if (payloadType === 'task_complete') {\n metrics.turnsCompleted += 1\n const completed = timestampMs(payload.completed_at)\n if (completed !== undefined) {\n completedAt = completedAt === undefined ? completed : Math.max(completedAt, completed)\n }\n const duration = numberField(payload, 'duration_ms')\n if (duration !== undefined) metrics.wallMs = Math.max(metrics.wallMs, duration)\n }\n if (payloadType === 'turn_aborted') {\n metrics.turnsAborted += 1\n const completed = timestampMs(payload.completed_at)\n if (completed !== undefined) {\n completedAt = completedAt === undefined ? completed : Math.max(completedAt, completed)\n }\n }\n if (payloadType === 'context_compacted') metrics.contextCompactions += 1\n if (payloadType === 'patch_apply_end') {\n metrics.patchAttempts += 1\n if (payload.success === true) metrics.patchSuccesses += 1\n else {\n metrics.patchFailures += 1\n metrics.toolErrors += 1\n }\n }\n if (payloadType === 'token_count')\n setCodexCumulativeUsage(metrics, record(record(payload.info)?.total_token_usage))\n const result = record(payload.result)\n if (result && 'Err' in result) metrics.unclassifiedErrors += 1\n }\n }\n\n if (metrics.wallMs === 0 && startedAt !== undefined && completedAt !== undefined) {\n metrics.wallMs = Math.max(0, completedAt - startedAt)\n }\n metrics.processScore = codexProcessScore(metrics)\n return metrics\n}\n\nfunction addCodexExecItem(\n metrics: CodeAgentSessionMetrics,\n startedToolIds: Set<string>,\n eventType: 'item.started' | 'item.completed',\n item: Record<string, unknown>,\n): void {\n const itemType = stringField(item, 'type')\n const itemId = stringField(item, 'id')\n const isTool =\n itemType === 'command_execution' ||\n itemType === 'mcp_tool_call' ||\n itemType === 'collab_tool_call' ||\n itemType === 'web_search'\n\n if (eventType === 'item.started' && isTool) {\n metrics.toolCalls += 1\n if (itemId) startedToolIds.add(itemId)\n }\n if (eventType === 'item.completed' && isTool) {\n if (!itemId || !startedToolIds.has(itemId)) metrics.toolCalls += 1\n metrics.toolOutputs += 1\n }\n if (eventType !== 'item.completed') return\n\n if (itemType === 'agent_message' || itemType === 'message') metrics.assistantMessages += 1\n if (itemType === 'reasoning') metrics.reasoningItems += 1\n if (itemType === 'file_change') {\n metrics.patchAttempts += 1\n const status = stringField(item, 'status')\n if (status === 'completed') metrics.patchSuccesses += 1\n if (status === 'failed') {\n metrics.patchFailures += 1\n metrics.toolErrors += 1\n }\n }\n if (itemType === 'error') metrics.unclassifiedErrors += 1\n else if (codexExecToolFailed(itemType, item)) metrics.toolErrors += 1\n}\n\nfunction codexExecToolFailed(itemType: string | undefined, item: Record<string, unknown>): boolean {\n const status = stringField(item, 'status')\n if (itemType === 'command_execution') {\n const exitCode = numberField(item, 'exit_code')\n return (\n status === 'failed' || status === 'declined' || (exitCode !== undefined && exitCode !== 0)\n )\n }\n if (itemType === 'mcp_tool_call') return status === 'failed' || record(item.error) !== null\n return itemType === 'collab_tool_call' && status === 'failed'\n}\n\nfunction addCodexExecUsage(\n metrics: CodeAgentSessionMetrics,\n usage: Record<string, unknown> | null,\n): void {\n const parsed = readUsage(usage)\n metrics.inputTokens += parsed.input\n metrics.outputTokens += parsed.output\n metrics.reasoningTokens += parsed.reasoning\n metrics.cachedTokens += parsed.cached\n metrics.cacheWriteTokens += parsed.cacheWrite\n}\n\nfunction setCodexCumulativeUsage(\n metrics: CodeAgentSessionMetrics,\n usage: Record<string, unknown> | null,\n): void {\n const parsed = readUsage(usage)\n metrics.inputTokens = Math.max(metrics.inputTokens, parsed.input)\n metrics.outputTokens = Math.max(metrics.outputTokens, parsed.output)\n metrics.reasoningTokens = Math.max(metrics.reasoningTokens, parsed.reasoning)\n metrics.cachedTokens = Math.max(metrics.cachedTokens, parsed.cached)\n metrics.cacheWriteTokens = Math.max(metrics.cacheWriteTokens, parsed.cacheWrite)\n}\n\nfunction claudeCodeMetrics(entries: Record<string, unknown>[]): CodeAgentSessionMetrics {\n const metrics = emptyMetrics(entries.length)\n let startedAt: number | undefined\n let completedAt: number | undefined\n\n for (const entry of entries) {\n const type = stringField(entry, 'type')\n const timestamp = timestampMs(entry.timestamp)\n if (timestamp !== undefined) {\n startedAt = startedAt === undefined ? timestamp : Math.min(startedAt, timestamp)\n completedAt = completedAt === undefined ? timestamp : Math.max(completedAt, timestamp)\n }\n\n if (type === 'user') metrics.userMessages += 1\n if (type === 'assistant') metrics.assistantMessages += 1\n if (type === 'pr-link') metrics.prLinks += 1\n if (type === 'file-history-snapshot') metrics.fileSnapshots += 1\n\n const message = record(entry.message)\n if (message) addUsage(metrics, record(message.usage))\n const content = Array.isArray(message?.content) ? message.content : []\n for (const item of content) {\n const part = record(item)\n if (!part) continue\n const partType = stringField(part, 'type')\n if (partType === 'thinking') metrics.reasoningItems += 1\n if (partType === 'tool_use') metrics.toolCalls += 1\n if (partType === 'tool_result') {\n metrics.toolOutputs += 1\n if (part.is_error === true) metrics.toolErrors += 1\n }\n }\n }\n\n if (startedAt !== undefined && completedAt !== undefined)\n metrics.wallMs = Math.max(0, completedAt - startedAt)\n metrics.processScore = claudeProcessScore(metrics)\n return metrics\n}\n\nfunction openCodeMetrics(entries: Record<string, unknown>[]): CodeAgentSessionMetrics {\n const metrics = emptyMetrics(entries.length)\n const messageUsage = emptyTokenTotals()\n const partUsage = emptyTokenTotals()\n let messageCost = 0\n let partCost = 0\n let messageCostCaptured = false\n let partCostCaptured = false\n let startedAt: number | undefined\n let completedAt: number | undefined\n\n for (const entry of entries) {\n const time = record(entry.time)\n const created = timestampMs(time?.created)\n const completed = timestampMs(time?.completed)\n if (created !== undefined)\n startedAt = startedAt === undefined ? created : Math.min(startedAt, created)\n if (completed !== undefined)\n completedAt = completedAt === undefined ? completed : Math.max(completedAt, completed)\n\n const role = stringField(entry, 'role')\n if (role === 'user') metrics.userMessages += 1\n if (role === 'assistant') {\n metrics.assistantMessages += 1\n const finish = stringField(entry, 'finish')\n if (finish === 'stop') metrics.turnsCompleted += 1\n if (finish === 'error') metrics.turnsAborted += 1\n }\n\n const type = stringField(entry, 'type')\n if (type === 'reasoning') metrics.reasoningItems += 1\n if (type === 'tool') {\n metrics.toolCalls += 1\n const status = stringField(record(entry.state) ?? {}, 'status')\n if (status === 'completed') metrics.toolOutputs += 1\n if (status === 'error') {\n metrics.toolOutputs += 1\n metrics.toolErrors += 1\n }\n }\n if (type === 'patch') {\n metrics.patchAttempts += 1\n metrics.patchSuccesses += 1\n }\n\n const cost = numberField(entry, 'cost')\n if (record(entry.tokens) && role) {\n addUsageTo(messageUsage, record(entry.tokens))\n if (cost !== undefined) {\n messageCost += cost\n messageCostCaptured = true\n }\n } else if (record(entry.tokens)) {\n addUsageTo(partUsage, record(entry.tokens))\n if (cost !== undefined) {\n partCost += cost\n partCostCaptured = true\n }\n }\n }\n\n const usage = hasTokenTotals(messageUsage) ? messageUsage : partUsage\n metrics.inputTokens = usage.input\n metrics.outputTokens = usage.output\n metrics.reasoningTokens = usage.reasoning\n metrics.cachedTokens = usage.cached\n metrics.cacheWriteTokens = usage.cacheWrite\n metrics.observedCostUsd = messageCostCaptured ? messageCost : partCost\n metrics.observedCostCaptured = messageCostCaptured || partCostCaptured\n if (metrics.wallMs === 0 && startedAt !== undefined && completedAt !== undefined)\n metrics.wallMs = Math.max(0, completedAt - startedAt)\n metrics.processScore = terminalProcessScore(metrics)\n return metrics\n}\n\nfunction kimiCodeMetrics(entries: Record<string, unknown>[]): CodeAgentSessionMetrics {\n const metrics = emptyMetrics(entries.length)\n let startedAt: number | undefined\n let completedAt: number | undefined\n\n for (const entry of entries) {\n const timestamp = timestampMs(entry.timestamp)\n if (timestamp !== undefined) {\n startedAt = startedAt === undefined ? timestamp : Math.min(startedAt, timestamp)\n completedAt = completedAt === undefined ? timestamp : Math.max(completedAt, timestamp)\n }\n\n const role = stringField(entry, 'role')\n if (role === 'user') metrics.userMessages += 1\n if (role === 'assistant') metrics.assistantMessages += 1\n if (role === '_usage') addUsage(metrics, entry)\n\n const message = record(entry.message)\n const messageType = message ? stringField(message, 'type') : undefined\n const payload = record(message?.payload) ?? {}\n if (messageType === 'TurnBegin') {\n metrics.userMessages += 1\n metrics.turnsStarted += 1\n }\n if (messageType === 'TurnEnd') metrics.turnsCompleted += 1\n if (messageType === 'StepInterrupted') metrics.turnsAborted += 1\n if (messageType === 'StepBegin') metrics.reasoningItems += 1\n if (messageType === 'ContentPart') {\n const payloadType = stringField(payload, 'type')\n if (payloadType === 'think') metrics.reasoningItems += 1\n if (payloadType === 'text') metrics.assistantMessages += 1\n }\n if (messageType === 'ToolCall') metrics.toolCalls += 1\n if (messageType === 'ToolResult') {\n metrics.toolOutputs += 1\n if (record(payload.return_value)?.is_error === true) metrics.toolErrors += 1\n }\n if (messageType === 'StatusUpdate') addUsage(metrics, record(payload.token_usage))\n if (messageType === 'Notification') {\n const notification = record(payload.payload)\n const exitCode = numberField(notification ?? {}, 'exit_code')\n if (notification?.timed_out === true || (exitCode !== undefined && exitCode !== 0)) {\n metrics.toolErrors += 1\n }\n }\n }\n\n if (startedAt !== undefined && completedAt !== undefined)\n metrics.wallMs = Math.max(0, completedAt - startedAt)\n metrics.processScore = terminalProcessScore(metrics)\n return metrics\n}\n\nfunction piMetrics(entries: Record<string, unknown>[]): CodeAgentSessionMetrics {\n const metrics = emptyMetrics(entries.length)\n let bestReliabilityScore: number | undefined\n\n for (const entry of entries) {\n const nodes = Array.isArray(entry.nodes) ? entry.nodes : []\n const edges = Array.isArray(entry.edges) ? entry.edges : []\n metrics.graphNodes += nodes.length\n metrics.graphEdges += edges.length\n\n for (const node of nodes) {\n const obj = record(node)\n const ir = record(obj?.ir) ?? obj\n const kind = stringField(ir ?? {}, 'kind')\n if (kind === 'ActionCandidate') metrics.actionCandidates += 1\n if (kind === 'ToolInvocation') metrics.toolCalls += 1\n if (kind === 'ToolResult') metrics.toolOutputs += 1\n if (kind === 'VerificationReport') metrics.verificationReports += 1\n if (kind === 'CompletionDecision') {\n metrics.completionDecisions += 1\n metrics.turnsCompleted += 1\n }\n }\n\n const averageReliability = numberField(entry, 'averageNodeReliability')\n if (averageReliability !== undefined)\n bestReliabilityScore = maxOptional(bestReliabilityScore, averageReliability)\n const pessimisticPath = numberField(entry, 'pessimisticPathEstimate')\n if (pessimisticPath !== undefined)\n bestReliabilityScore = maxOptional(bestReliabilityScore, pessimisticPath)\n\n const rows = Array.isArray(entry.rows) ? entry.rows : []\n metrics.reliabilityRows += rows.length\n for (const row of rows) {\n const obj = record(row)\n if (!obj) continue\n const lift = numberField(obj, 'lift')\n if (lift !== undefined) metrics.reliabilityLift = Math.max(metrics.reliabilityLift, lift)\n const validated = numberField(obj, 'validatedSuccessEstimate')\n if (validated !== undefined)\n bestReliabilityScore = maxOptional(bestReliabilityScore, validated)\n }\n }\n\n metrics.processScore =\n bestReliabilityScore !== undefined\n ? clamp01(bestReliabilityScore)\n : metrics.completionDecisions > 0\n ? 1\n : 0\n return metrics\n}\n\nfunction emptyMetrics(entries: number): CodeAgentSessionMetrics {\n return {\n entries,\n userMessages: 0,\n assistantMessages: 0,\n reasoningItems: 0,\n toolCalls: 0,\n toolOutputs: 0,\n toolErrors: 0,\n unclassifiedErrors: 0,\n patchAttempts: 0,\n patchSuccesses: 0,\n patchFailures: 0,\n turnsStarted: 0,\n turnsCompleted: 0,\n turnsAborted: 0,\n contextCompactions: 0,\n mcpCalls: 0,\n subagentCalls: 0,\n skillCalls: 0,\n hookCalls: 0,\n webCalls: 0,\n codeActions: 0,\n prLinks: 0,\n fileSnapshots: 0,\n graphNodes: 0,\n graphEdges: 0,\n actionCandidates: 0,\n verificationReports: 0,\n completionDecisions: 0,\n reliabilityRows: 0,\n reliabilityLift: 0,\n inputTokens: 0,\n outputTokens: 0,\n reasoningTokens: 0,\n cachedTokens: 0,\n cacheWriteTokens: 0,\n observedCostUsd: 0,\n observedCostCaptured: false,\n wallMs: 0,\n processScore: 0,\n }\n}\n\nfunction codexProcessScore(metrics: CodeAgentSessionMetrics): number {\n const terminalTurns = metrics.turnsCompleted + metrics.turnsAborted\n const base =\n terminalTurns > 0\n ? metrics.turnsCompleted / terminalTurns\n : metrics.assistantMessages > 0\n ? 0.5\n : 0\n return penalizeErrors(base, metrics)\n}\n\nfunction claudeProcessScore(metrics: CodeAgentSessionMetrics): number {\n const base = metrics.prLinks > 0 ? 1 : metrics.assistantMessages > 0 ? 0.75 : 0\n return penalizeErrors(base, metrics)\n}\n\nfunction terminalProcessScore(metrics: CodeAgentSessionMetrics): number {\n const terminalTurns = metrics.turnsCompleted + metrics.turnsAborted\n const base =\n terminalTurns > 0\n ? metrics.turnsCompleted / terminalTurns\n : metrics.assistantMessages > 0\n ? 0.75\n : metrics.toolCalls > 0\n ? 0.5\n : 0\n return penalizeErrors(base, metrics)\n}\n\nfunction penalizeErrors(base: number, metrics: CodeAgentSessionMetrics): number {\n const operations = Math.max(1, metrics.toolCalls + metrics.patchAttempts)\n const errorRate = Math.min(1, (metrics.toolErrors + metrics.patchFailures) / operations)\n return clamp01(base * (1 - 0.5 * errorRate))\n}\n\ntype TokenTotals = Required<RunTokenUsage>\n\nfunction emptyTokenTotals(): TokenTotals {\n return { input: 0, output: 0, reasoning: 0, cached: 0, cacheWrite: 0 }\n}\n\nfunction hasTokenTotals(usage: TokenTotals): boolean {\n return (\n usage.input > 0 ||\n usage.output > 0 ||\n usage.reasoning > 0 ||\n usage.cached > 0 ||\n usage.cacheWrite > 0\n )\n}\n\nfunction addUsage(\n metrics: CodeAgentSessionMetrics,\n usage: Record<string, unknown> | null | undefined,\n): void {\n const parsed = readUsage(usage)\n metrics.inputTokens += parsed.input\n metrics.outputTokens += parsed.output\n metrics.reasoningTokens += parsed.reasoning\n metrics.cachedTokens += parsed.cached\n metrics.cacheWriteTokens += parsed.cacheWrite\n}\n\nfunction addUsageTo(totals: TokenTotals, usage: Record<string, unknown> | null | undefined): void {\n const parsed = readUsage(usage)\n totals.input += parsed.input\n totals.output += parsed.output\n totals.reasoning += parsed.reasoning\n totals.cached += parsed.cached\n totals.cacheWrite += parsed.cacheWrite\n}\n\nfunction readUsage(usage: Record<string, unknown> | null | undefined): TokenTotals {\n const parsed = extractUsage(usage)\n return {\n input: parsed?.input ?? 0,\n output: parsed?.output ?? 0,\n reasoning: parsed?.reasoning ?? 0,\n cached: parsed?.cached ?? 0,\n cacheWrite: parsed?.cacheWrite ?? 0,\n }\n}\n\nfunction resolveSessionCost(\n explicit: RunCostProvenance | undefined,\n metrics: CodeAgentSessionMetrics,\n model: string,\n): { costUsd: number | null; costProvenance: RunCostProvenance } {\n if (explicit) {\n if (explicit.kind === 'uncaptured') {\n if (explicit.usd !== null) throw new Error('uncaptured cost must have usd: null')\n return { costUsd: null, costProvenance: explicit }\n }\n if (!Number.isFinite(explicit.usd) || explicit.usd < 0) {\n throw new Error(`${explicit.kind} cost must be a finite, non-negative USD amount`)\n }\n return { costUsd: explicit.usd, costProvenance: explicit }\n }\n\n if (metrics.observedCostCaptured) {\n const costProvenance = { kind: 'observed', usd: metrics.observedCostUsd } as const\n return { costUsd: metrics.observedCostUsd, costProvenance }\n }\n\n const hasUsage = metrics.inputTokens > 0 || metrics.outputTokens > 0\n if (hasUsage && isModelPriced(model)) {\n const costUsd = estimateCost(metrics.inputTokens, metrics.outputTokens, model)\n return { costUsd, costProvenance: { kind: 'estimated', usd: costUsd } }\n }\n\n return { costUsd: null, costProvenance: { kind: 'uncaptured', usd: null } }\n}\n\nfunction diagnosticsFor(\n metrics: CodeAgentSessionMetrics,\n options: {\n model: string\n explicitTerminal: boolean\n malformedLines: number\n hasQualityLabel: boolean\n invalidQualityScore: boolean\n costKind: RunCostProvenance['kind']\n },\n): string[] {\n const warnings: string[] = []\n if (options.invalidQualityScore) warnings.push('non-finite task quality score omitted')\n else if (!options.hasQualityLabel) warnings.push('task quality score not supplied')\n if (!options.explicitTerminal) warnings.push('no explicit terminal success/failure signal')\n if (\n metrics.inputTokens === 0 &&\n metrics.outputTokens === 0 &&\n metrics.reasoningTokens === 0 &&\n metrics.cachedTokens === 0 &&\n metrics.cacheWriteTokens === 0\n ) {\n warnings.push('missing token usage')\n }\n if (options.costKind === 'estimated')\n warnings.push('USD cost estimated from token usage and model pricing')\n if (options.costKind === 'uncaptured') warnings.push('USD cost uncaptured')\n if (options.costKind === 'uncaptured' && !isModelPriced(options.model))\n warnings.push('model pricing unknown')\n if (options.malformedLines > 0)\n warnings.push(`${options.malformedLines} malformed JSONL lines skipped`)\n return warnings\n}\n\nfunction applyObservedSurfaceMetrics(\n metrics: CodeAgentSessionMetrics,\n observation: CodeAgentSessionObservation,\n): void {\n const actions = observation.actions.filter(\n (action) => action.kind === 'tool' || action.kind === 'patch',\n )\n metrics.mcpCalls = actions.filter((action) => action.surface === 'mcp').length\n metrics.subagentCalls = actions.filter((action) => action.surface === 'subagent').length\n metrics.skillCalls = actions.filter((action) => action.surface === 'skill').length\n metrics.hookCalls = actions.filter((action) => action.surface === 'hook').length\n metrics.webCalls = actions.filter((action) => action.surface === 'web').length\n metrics.codeActions = actions.filter((action) => action.surface === 'code').length\n}\n\nfunction sessionIdFromEntries(\n source: CodeAgentSessionSource,\n entries: Record<string, unknown>[],\n): string | undefined {\n for (const entry of entries) {\n if (source === 'codex') {\n const threadId = stringField(entry, 'thread_id')\n if (threadId) return threadId\n const payload = record(entry.payload)\n const id = payload ? stringField(payload, 'id') : undefined\n if (id) return id\n }\n const message = record(entry.message)\n const payload = record(message?.payload)\n const sessionId =\n stringField(entry, 'sessionID') ??\n stringField(entry, 'sessionId') ??\n stringField(entry, 'session_id') ??\n stringField(payload ?? {}, 'session_id')\n if (sessionId) return sessionId\n }\n return undefined\n}\n\nfunction modelFromEntries(\n source: CodeAgentSessionSource,\n entries: Record<string, unknown>[],\n): string | undefined {\n let providerModel: string | undefined\n for (const entry of entries) {\n if (source === 'codex') {\n const payload = record(entry.payload)\n const model = payload ? stringField(payload, 'model') : undefined\n if (model) return model\n providerModel =\n providerModel ?? (payload ? stringField(payload, 'model_provider') : undefined)\n }\n const openCodeModel = stringField(entry, 'modelID')\n if (openCodeModel) {\n const provider = stringField(entry, 'providerID')\n return provider ? `${provider}/${openCodeModel}` : openCodeModel\n }\n const modelObject = record(entry.model)\n const nestedModel = stringField(modelObject ?? {}, 'modelID')\n if (nestedModel) {\n const provider = stringField(modelObject ?? {}, 'providerID')\n return provider ? `${provider}/${nestedModel}` : nestedModel\n }\n const message = record(entry.message)\n const model = message ? stringField(message, 'model') : undefined\n if (model) return model\n }\n return providerModel\n}\n\nfunction cwdFromEntries(entries: Record<string, unknown>[]): string | undefined {\n for (const entry of entries) {\n const path = record(entry.path)\n const cwd =\n stringField(entry, 'cwd') ??\n stringField(path ?? {}, 'cwd') ??\n stringField(path ?? {}, 'root') ??\n (record(entry.payload) ? stringField(record(entry.payload)!, 'cwd') : undefined)\n if (cwd) return cwd\n }\n return undefined\n}\n\nfunction firstUserText(entries: Record<string, unknown>[]): string | undefined {\n for (const entry of entries) {\n const payload = record(entry.payload)\n const payloadType = payload ? stringField(payload, 'type') : undefined\n if (payloadType === 'user_message') return stringField(payload!, 'message')\n\n if (stringField(entry, 'role') === 'user') {\n const content = entry.content\n if (typeof content === 'string') return content\n }\n\n const wirePayload = record(record(entry.message)?.payload)\n const userInput = wirePayload ? stringField(wirePayload, 'user_input') : undefined\n if (userInput) return userInput\n\n const message = record(entry.message)\n if (message && stringField(message, 'role') === 'user') {\n const content = message.content\n if (typeof content === 'string') return content\n if (Array.isArray(content)) {\n const text = content\n .map((part) => {\n const obj = record(part)\n return obj ? stringField(obj, 'text') : undefined\n })\n .filter((part): part is string => part !== undefined)\n .join('\\n')\n if (text) return text\n }\n }\n }\n return undefined\n}\n\nfunction fallbackSessionId(source: CodeAgentSessionSource, sourcePath: string | undefined): string {\n return hashString(`${source}:${sourcePath ?? 'unknown-session'}`).slice(\n 'sha256:'.length,\n 'sha256:'.length + 20,\n )\n}\n\nfunction withSnapshot(model: string): string {\n const trimmed = model.trim() || 'unknown'\n if (trimmed.includes('@') || /-\\d{8}$/.test(trimmed) || /-\\d{4}-\\d{2}-\\d{2}$/.test(trimmed)) {\n return trimmed\n }\n return `${trimmed}@observed-local`\n}\n\nfunction hashJson(value: unknown): string {\n return hashString(JSON.stringify(value))\n}\n\nfunction hashString(value: string): string {\n return `sha256:${createHash('sha256').update(value).digest('hex')}`\n}\n\nfunction stableSeed(value: string): number {\n return createHash('sha256').update(value).digest().readUInt32BE(0)\n}\n\nfunction maxOptional(current: number | undefined, next: number): number {\n return current === undefined ? next : Math.max(current, next)\n}\n\nfunction clamp01(value: number): number {\n if (!Number.isFinite(value)) return 0\n return Math.max(0, Math.min(1, value))\n}\n\nfunction finiteScore(value: number | undefined): number | undefined {\n return value !== undefined && Number.isFinite(value) ? clamp01(value) : undefined\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction record(value: unknown): Record<string, unknown> | null {\n return isRecord(value) ? value : null\n}\n\nfunction stringField(obj: Record<string, unknown>, key: string): string | undefined {\n const value = obj[key]\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\nfunction numberField(obj: Record<string, unknown>, key: string): number | undefined {\n const value = obj[key]\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined\n}\n\nfunction timestampMs(value: unknown): number | undefined {\n if (typeof value === 'number' && Number.isFinite(value)) {\n return value > 1_000_000_000_000 ? value : value * 1000\n }\n if (typeof value === 'string' && value.length > 0) {\n const parsed = Date.parse(value)\n return Number.isFinite(parsed) ? parsed : undefined\n }\n return undefined\n}\n","/**\n * # `intake/feedback-table` — multi-rater approve/reject corpus → `RunRecord[]`.\n *\n * The generic shape behind Obsidian's `#approved` / `#rejected` tags, a\n * Google Sheet, a Postgres `feedback` table, or any CSV with ratings.\n *\n * Caller supplies one row per (run, rater) tuple plus per-run metadata; the\n * adapter rolls them up into the substrate-canonical `RunRecord` shape so\n * `analyzeRuns({ runs, raterScores })` can produce inter-rater agreement,\n * disagreement triage, and downstream recommendations.\n *\n * The rater mean is written to the score field matching the run split\n * (normalised to 0..1 when a scale is supplied); `outcome.raw` carries\n * per-rater scores keyed by rater id for downstream attribution.\n */\n\nimport type { JudgeScoresRecord, RunOutcome, RunRecord, RunSplitTag } from '../../run-record'\n\nexport interface FeedbackTableRow {\n /** Stable id for this run — the unit a rater scored. Drives pairing\n * across analysis primitives. */\n runId: string\n /** Identifier of the rater that produced this rating. */\n rater: string\n /** The rating itself. Accepts boolean (approve/reject), 0..1 scalar,\n * or any numeric scale — see `scale`. */\n rating: number | boolean\n /** Optional metadata carried through to `RunRecord.outcome.raw` and the\n * custom-shape metadata bag. */\n metadata?: Record<string, unknown>\n}\n\nexport interface FeedbackTableMeta {\n runId: string\n /** When omitted, defaults to `'feedback-corpus'`. Used to group related\n * runs in `analyzeRuns()` lift analysis. */\n experimentId?: string\n /** When omitted, defaults to `runId` — each run is its own candidate. */\n candidateId?: string\n /** Observed cost in USD, when available. */\n costUsd?: number\n /** Stable scenario identity. Defaults to `runId`. */\n scenarioId?: string\n /** Wall-clock ms, when available. Defaults to 0. */\n wallMs?: number\n /** Model identifier including snapshot. Default `unknown@unknown`. */\n model?: string\n /** Optional sha256 of the prompt; default `'sha256:unknown'`. */\n promptHash?: string\n /** Default `'sha256:unknown'`. */\n configHash?: string\n /** Default `'unknown'`. */\n commitSha?: string\n /** Default `'holdout'` — feedback corpora are by nature the holdout\n * signal a closed-loop improvement aims at. */\n splitTag?: RunSplitTag\n /** Free-form metadata available to consumers via the cast-out path on\n * the resulting RunRecord. */\n extras?: Record<string, unknown>\n}\n\nexport interface FromFeedbackTableOptions {\n /** Per-(run, rater) ratings. */\n ratings: FeedbackTableRow[]\n /** Per-run metadata. When a runId appears in `ratings` but not here, the\n * adapter synthesises minimal metadata with defaults documented above. */\n meta?: FeedbackTableMeta[]\n /** Rating scale. Provide `{ min, max }` for non-0..1 numeric scales.\n * Booleans are normalised: true → 1, false → 0. Default: assumes\n * ratings are already 0..1. */\n scale?: { min: number; max: number }\n /** When true, the rater scores are emitted into `raterScores` (a sibling\n * array `analyzeRuns()` accepts) in addition to the aggregate run score.\n * Default `true` preserves rater-level signal for inter-rater analysis. */\n emitRaterScores?: boolean\n}\n\nexport interface FromFeedbackTableResult {\n runs: RunRecord[]\n /** Rater-level scores ready to pass into `analyzeRuns({ raterScores })`\n * for inter-rater agreement + disagreement triage. */\n raterScores: Array<{ runId: string; rater: string; score: number }>\n}\n\nexport function fromFeedbackTable(opts: FromFeedbackTableOptions): FromFeedbackTableResult {\n const { ratings, meta = [], scale, emitRaterScores = true } = opts\n const metaByRun = new Map(meta.map((m) => [m.runId, m]))\n\n // Normalise per-rating to a 0..1 score.\n const normalise = (rating: number | boolean): number => {\n if (typeof rating === 'boolean') return rating ? 1 : 0\n if (!Number.isFinite(rating)) return Number.NaN\n if (!scale) return rating\n const { min, max } = scale\n if (max === min) return rating\n return (rating - min) / (max - min)\n }\n\n // Group ratings by runId.\n const byRun = new Map<string, FeedbackTableRow[]>()\n for (const row of ratings) {\n const list = byRun.get(row.runId) ?? []\n list.push(row)\n byRun.set(row.runId, list)\n }\n\n const runs: RunRecord[] = []\n const raterScores: FromFeedbackTableResult['raterScores'] = []\n\n for (const [runId, rowsForRun] of byRun) {\n const normalised = rowsForRun\n .map((r) => ({ rater: r.rater, score: normalise(r.rating) }))\n .filter((r) => Number.isFinite(r.score))\n if (normalised.length === 0) continue\n\n const meanScore = normalised.reduce((s, r) => s + r.score, 0) / normalised.length\n\n const runMeta = metaByRun.get(runId) ?? ({ runId } as FeedbackTableMeta)\n\n const judgeScores: JudgeScoresRecord = {\n perJudge: Object.fromEntries(normalised.map((r) => [r.rater, { rating: r.score }])),\n perDimMean: { rating: meanScore },\n composite: meanScore,\n }\n\n const splitTag = runMeta.splitTag ?? 'holdout'\n const outcome: RunOutcome = {\n ...(splitTag === 'holdout' ? { holdoutScore: meanScore } : { searchScore: meanScore }),\n raw: Object.fromEntries(normalised.map((r) => [`rater:${r.rater}`, r.score])),\n judgeScores,\n }\n\n const costUsd = runMeta.costUsd ?? null\n runs.push({\n runId,\n experimentId: runMeta.experimentId ?? 'feedback-corpus',\n candidateId: runMeta.candidateId ?? runId,\n seed: 0,\n model: runMeta.model ?? 'unknown@unknown',\n promptHash: runMeta.promptHash ?? 'sha256:unknown',\n configHash: runMeta.configHash ?? 'sha256:unknown',\n commitSha: runMeta.commitSha ?? 'unknown',\n wallMs: runMeta.wallMs ?? 0,\n costUsd,\n costProvenance:\n costUsd === null ? { kind: 'uncaptured', usd: null } : { kind: 'observed', usd: costUsd },\n tokenUsage: { input: 0, output: 0 },\n terminalOutcome: 'unknown',\n outcome,\n splitTag,\n scenarioId: runMeta.scenarioId ?? runId,\n })\n\n if (emitRaterScores) {\n for (const r of normalised) raterScores.push({ runId, rater: r.rater, score: r.score })\n }\n }\n\n return { runs, raterScores }\n}\n","/**\n * # `intake/otel-spans` — OTel `TraceSpanEvent[]` → `RunRecord[]`.\n *\n * Turns an existing observability stream into the substrate-canonical\n * `RunRecord` shape so consumers with logs but no eval discipline can\n * call `analyzeRuns()` against their production traffic immediately.\n *\n * Pivot rule: spans are grouped by `tangle.runId` (the same attribute the\n * hosted-tier wire format uses) or, when absent, by `traceId`. One group\n * becomes one `RunRecord`. The root span (no `parentSpanId`) supplies:\n *\n * - `runId` (the group key)\n * - `wallMs` from `endTimeUnixNano - startTimeUnixNano`\n * - `model` from `gen_ai.request.model` / `llm.model` / `tangle.model`\n * - task failure class and detail from explicit `tangle.task.*` attributes\n * - cost from `cost.usd` / `gen_ai.usage.cost_usd` / `tangle.cost.usd`\n * - token usage from model-call input, output, cache-read, and cache-write\n * attributes without double-counting aggregate parent spans\n * - task quality from an explicit `scoreForRun` callback or a designated\n * evaluation attribute on a root / `EVALUATOR` span; `outcome.raw`\n * collects every numeric attribute without promoting it to task quality.\n *\n * Errored tool, model, and child-agent spans contribute to execution-error\n * counts. Root process, guardrail, evaluator, propagated parent, and unknown\n * errors retain separate counters. Only one failed root can set\n * `RunRecord.terminalOutcome` and `RunRecord.terminalFailureReason`; a child\n * error cannot become a task failure.\n */\n\nimport { ValidationError } from '../../errors'\nimport type { TraceSpanEvent } from '../../hosted/types'\nimport type {\n JudgeScoresRecord,\n RunOutcome,\n RunRecord,\n RunSplitTag,\n RunTerminalOutcome,\n} from '../../run-record'\nimport { summarizeTraceErrors, type TraceErrorRole } from '../../trace/error-classification'\nimport {\n recordAggregateMeasurements,\n summarizeExecutionMeasurements,\n} from '../../trace/execution-measurements'\nimport {\n classifyOtlpSpanRole,\n isOtlpModelCall,\n LLM_MODEL_ATTR_KEYS,\n SPAN_KIND_ATTR_KEYS,\n} from '../../trace/otlp-attributes'\nimport { readTaskFailureLabels } from '../../trace/task-failure-attributes'\n\nconst TASK_SCORE_ATTR_KEYS = [\n 'gen_ai.evaluation.score.value',\n 'tangle.task.score',\n 'eval.score',\n 'tangle.score',\n] as const\nconst MODEL_KEYS = ['tangle.model', ...LLM_MODEL_ATTR_KEYS, 'model']\nconst PROMPT_HASH_KEYS = ['tangle.prompt_hash', 'prompt.hash']\nconst CONFIG_HASH_KEYS = ['tangle.config_hash', 'config.hash']\n\nexport interface FromOtelSpansOptions {\n spans: TraceSpanEvent[]\n /** Default split tag for synthesized records. Defaults to `'holdout'`. */\n defaultSplit?: RunSplitTag\n /** Default `experimentId` when not present on any span. */\n experimentId?: string\n /**\n * Explicit task-quality score for a logical run. The callback receives\n * spans in deterministic time/id order. Its value must agree with any\n * designated score attributes present on root or `EVALUATOR` spans.\n */\n scoreForRun?: (runId: string, spans: readonly TraceSpanEvent[]) => number | undefined\n}\n\nexport function fromOtelSpans(opts: FromOtelSpansOptions): RunRecord[] {\n const { spans, defaultSplit = 'holdout', experimentId = 'otel-corpus' } = opts\n const grouped = groupSpans(spans)\n\n const runs: RunRecord[] = []\n for (const [groupKey, groupSpans] of grouped) {\n const root = findRoot(groupSpans)\n if (!root) continue\n const measurements = summarizeExecutionMeasurements(\n groupSpans.map((span) => ({\n id: span.spanId,\n ...(span.parentSpanId ? { parentId: span.parentSpanId } : {}),\n attributes: span.attributes,\n modelCall: isExplicitModelCall(span),\n aggregate: isExplicitAggregate(span),\n })),\n )\n const callSpanIds = new Set(measurements.callSpanIds)\n const callSpans = groupSpans.filter((span) => callSpanIds.has(span.spanId))\n const wallMs = unixNanoDurationMs(root.startTimeUnixNano, root.endTimeUnixNano)\n const model =\n readAttrString(callSpans, MODEL_KEYS) ??\n readAttrString(groupSpans, MODEL_KEYS) ??\n 'unknown@unknown'\n const capturedCost =\n (measurements.cost.complete ? measurements.cost.value : undefined) ??\n measurements.aggregate?.costUsd\n const costUsd = capturedCost ?? null\n const scenarioId = readConsistentScenarioId(groupKey, groupSpans) ?? groupKey\n const promptHash = readAttrString(groupSpans, PROMPT_HASH_KEYS) ?? 'sha256:unknown'\n const configHash = readAttrString(groupSpans, CONFIG_HASH_KEYS) ?? 'sha256:unknown'\n const score = resolveTaskScore(groupKey, groupSpans, opts.scoreForRun)\n const taskFailure = readTaskFailureLabels(\n groupSpans.filter((span) => !span.parentSpanId && isTerminalRootCandidate(span)),\n `fromOtelSpans: run '${groupKey}'`,\n )\n\n const rawNumeric = collectNumericAttrs(groupSpans)\n const errorSummary = summarizeTraceErrors(\n groupSpans.map((span) => ({\n id: spanIdentity(span),\n ...(span.parentSpanId ? { parentId: parentIdentity(span) } : {}),\n role: errorRoleForSpan(span),\n error: span.status?.code === 'ERROR',\n processRoot: !span.parentSpanId && isTerminalRootCandidate(span),\n })),\n )\n rawNumeric.error_span_count = errorSummary.total\n rawNumeric.execution_error_count = errorSummary.execution\n rawNumeric.process_error_count = errorSummary.process\n rawNumeric.guardrail_error_count = errorSummary.guardrail\n rawNumeric.judge_error_count = errorSummary.evaluation\n rawNumeric.propagated_error_count = errorSummary.propagated\n rawNumeric.unclassified_error_count = errorSummary.unclassified\n rawNumeric.llm_span_count = measurements.modelCallCount\n if (measurements.cost.value !== undefined && !measurements.cost.complete) {\n rawNumeric.partial_observed_cost_usd = measurements.cost.value\n }\n recordAggregateMeasurements(rawNumeric, measurements.aggregate)\n\n const judgeScores: JudgeScoresRecord | undefined =\n score !== undefined\n ? {\n perJudge: { 'otel-derived': { score } },\n perDimMean: { score },\n composite: score,\n }\n : undefined\n\n const terminalOutcome = terminalOutcomeFromRoots(groupSpans)\n const failedRoot =\n terminalOutcome === 'failed'\n ? groupSpans.find(\n (span) =>\n !span.parentSpanId && isTerminalRootCandidate(span) && span.status?.code === 'ERROR',\n )\n : undefined\n const outcome: RunOutcome = {\n raw: rawNumeric,\n ...(judgeScores ? { judgeScores } : {}),\n }\n if (score !== undefined) {\n if (defaultSplit === 'holdout') outcome.holdoutScore = score\n else outcome.searchScore = score\n }\n\n runs.push({\n runId: groupKey,\n experimentId,\n candidateId: (root.attributes['tangle.candidateId'] as string | undefined) ?? 'otel-default',\n seed: 0,\n model,\n promptHash,\n configHash,\n commitSha: (root.attributes['tangle.commit_sha'] as string | undefined) ?? 'unknown',\n wallMs,\n costUsd,\n costProvenance:\n capturedCost === undefined\n ? { kind: 'uncaptured', usd: null }\n : { kind: 'observed', usd: capturedCost },\n tokenUsage: measurements.tokenUsage,\n terminalOutcome,\n ...(failedRoot\n ? { terminalFailureReason: failedRoot.status?.message ?? failedRoot.name }\n : {}),\n outcome,\n ...taskFailure,\n splitTag: defaultSplit,\n scenarioId,\n })\n }\n return runs\n}\n\nfunction terminalOutcomeFromRoots(spans: TraceSpanEvent[]): RunTerminalOutcome {\n const roots = spans.filter((span) => !span.parentSpanId && isTerminalRootCandidate(span))\n if (roots.length !== 1) return 'unknown'\n if (roots[0]!.status?.code === 'OK') return 'succeeded'\n if (roots[0]!.status?.code === 'ERROR') return 'failed'\n return 'unknown'\n}\n\nfunction isTerminalRootCandidate(span: TraceSpanEvent): boolean {\n const role = errorRoleForSpan(span)\n if (role === 'LLM' || role === 'TOOL' || role === 'GUARDRAIL' || role === 'EVALUATOR') {\n return false\n }\n return true\n}\n\nfunction readSpanKind(span: TraceSpanEvent): string | undefined {\n return readAttrString([span], [...SPAN_KIND_ATTR_KEYS, 'span.kind'])?.toUpperCase()\n}\n\nfunction errorRoleForSpan(span: TraceSpanEvent): TraceErrorRole {\n return classifyOtlpSpanRole({\n kind: readSpanKind(span),\n name: span.name,\n attributes: span.attributes,\n })\n}\n\nfunction spanIdentity(span: TraceSpanEvent): string {\n return `${span.traceId}:${span.spanId}`\n}\n\nfunction parentIdentity(span: TraceSpanEvent): string {\n return `${span.traceId}:${span.parentSpanId}`\n}\n\nfunction isExplicitModelCall(span: TraceSpanEvent): boolean {\n return isOtlpModelCall({\n kind: readSpanKind(span),\n name: span.name,\n attributes: span.attributes,\n })\n}\n\nfunction isExplicitAggregate(span: TraceSpanEvent): boolean {\n const kind = readSpanKind(span)\n return kind !== undefined && kind !== 'LLM'\n}\n\n// ── Internal helpers ────────────────────────────────────────────────\n\nfunction groupSpans(spans: TraceSpanEvent[]): Map<string, TraceSpanEvent[]> {\n const m = new Map<string, TraceSpanEvent[]>()\n for (const span of spans) {\n const key = (span['tangle.runId'] as string | undefined) ?? span.traceId\n const list = m.get(key) ?? []\n list.push(span)\n m.set(key, list)\n }\n return m\n}\n\nfunction findRoot(group: TraceSpanEvent[]): TraceSpanEvent | undefined {\n const structuralRoots = group.filter((span) => !span.parentSpanId)\n const terminalRoots = structuralRoots.filter(isTerminalRootCandidate)\n const pool =\n terminalRoots.length > 0 ? terminalRoots : structuralRoots.length > 0 ? structuralRoots : group\n return orderSpans(pool)[0]\n}\n\nfunction readAttrString(spans: TraceSpanEvent[], keys: string[]): string | undefined {\n for (const span of spans) {\n for (const key of keys) {\n const v = span.attributes[key]\n if (typeof v === 'string' && v.length > 0) return v\n }\n }\n return undefined\n}\n\nfunction readConsistentScenarioId(\n runId: string,\n spans: readonly TraceSpanEvent[],\n): string | undefined {\n const values = new Set<string>()\n for (const span of spans) {\n const topLevel = span['tangle.scenarioId']\n if (typeof topLevel === 'string' && topLevel.length > 0) values.add(topLevel)\n const attribute = span.attributes['tangle.scenarioId']\n if (typeof attribute === 'string' && attribute.length > 0) values.add(attribute)\n }\n if (values.size > 1) {\n throw new ValidationError(\n `fromOtelSpans: conflicting scenario ids for run '${runId}': ${[...values].sort().join(', ')}`,\n )\n }\n return values.values().next().value\n}\n\ninterface TaskScoreSource {\n label: string\n value: number\n}\n\nfunction resolveTaskScore(\n runId: string,\n spans: TraceSpanEvent[],\n scoreForRun: FromOtelSpansOptions['scoreForRun'],\n): number | undefined {\n const orderedSpans = orderSpans(spans)\n const sources: TaskScoreSource[] = []\n\n if (scoreForRun) {\n const supplied: unknown = scoreForRun(runId, orderedSpans)\n if (supplied !== undefined) {\n if (typeof supplied !== 'number' || !Number.isFinite(supplied)) {\n throw new ValidationError(\n `fromOtelSpans: scoreForRun returned a non-finite number for run '${runId}'`,\n )\n }\n sources.push({ label: 'scoreForRun', value: supplied })\n }\n }\n\n for (const span of orderedSpans) {\n const role = errorRoleForSpan(span)\n if (span.parentSpanId && role !== 'EVALUATOR') continue\n if (role === 'EVALUATOR' && span.status?.code === 'ERROR') continue\n for (const key of TASK_SCORE_ATTR_KEYS) {\n if (!Object.hasOwn(span.attributes, key)) continue\n sources.push({\n label: `span '${span.spanId}' attribute '${key}'`,\n value: parseTaskScoreAttribute(runId, span.spanId, key, span.attributes[key]),\n })\n }\n }\n\n if (sources.length === 0) return undefined\n sources.sort((left, right) => left.label.localeCompare(right.label))\n const score = sources[0]!.value\n if (sources.some((source) => source.value !== score)) {\n const details = sources.map((source) => `${source.label}=${source.value}`).join(', ')\n throw new ValidationError(\n `fromOtelSpans: conflicting task-quality scores for run '${runId}': ${details}`,\n )\n }\n return score\n}\n\nfunction parseTaskScoreAttribute(\n runId: string,\n spanId: string,\n key: string,\n value: unknown,\n): number {\n const source = `span '${spanId}' attribute '${key}'`\n if (typeof value === 'string') {\n if (value.trim().length === 0) {\n throw new ValidationError(\n `fromOtelSpans: ${source} is blank for run '${runId}'; task quality must be finite`,\n )\n }\n const parsed = Number(value)\n if (Number.isFinite(parsed)) return parsed\n } else if (typeof value === 'number' && Number.isFinite(value)) {\n return value\n }\n throw new ValidationError(\n `fromOtelSpans: ${source} is not a finite task-quality score for run '${runId}'`,\n )\n}\n\nfunction orderSpans(spans: readonly TraceSpanEvent[]): TraceSpanEvent[] {\n return [...spans].sort(\n (left, right) =>\n compareUnixNano(left.startTimeUnixNano, right.startTimeUnixNano) ||\n left.spanId.localeCompare(right.spanId),\n )\n}\n\nfunction parseUnixNano(value: string): bigint {\n try {\n return BigInt(value)\n } catch {\n throw new ValidationError(`fromOtelSpans: invalid Unix nanosecond timestamp '${value}'`)\n }\n}\n\nfunction compareUnixNano(left: string, right: string): number {\n const leftValue = parseUnixNano(left)\n const rightValue = parseUnixNano(right)\n return leftValue < rightValue ? -1 : leftValue > rightValue ? 1 : 0\n}\n\nfunction unixNanoDurationMs(start: string, end: string): number {\n const delta = parseUnixNano(end) - parseUnixNano(start)\n if (delta <= 0n) return 0\n const wholeMs = delta / 1_000_000n\n const fractionalMs = delta % 1_000_000n\n const value = Number(wholeMs) + Number(fractionalMs) / 1_000_000\n if (!Number.isSafeInteger(Number(wholeMs))) {\n throw new ValidationError('fromOtelSpans: span duration exceeds the safe millisecond range')\n }\n return value\n}\n\nfunction collectNumericAttrs(spans: TraceSpanEvent[]): Record<string, number> {\n const raw: Record<string, number> = {}\n for (const span of spans) {\n for (const [k, v] of Object.entries(span.attributes)) {\n if (typeof v === 'number' && Number.isFinite(v)) raw[k] = v\n }\n }\n return raw\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAoXA,IAAa,sBAAb,cAAyC,MAAM;CAC7C;CACA;CAEA,YAAY,OAAgB,QAA0B;EACpD,MAAM,WAAW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CAAC,GAAG,IAAI,KAAK;CAG9D,OAAO;AACT"}
1
+ {"version":3,"file":"index.js","names":["hashString","ANALYSIS_ARTIFACT","isRecord","sessionIdFromEntries","fallbackSessionId","stringField","record","numberField"],"sources":["../../src/contract/self-improve.ts","../../src/contract/define-agent-eval.ts","../../src/contract/fixed-spend.ts","../../src/contract/concurrent-map.ts","../../src/contract/paid-paired-measurement.ts","../../src/contract/measured-comparison.ts","../../src/contract/profile-measured-comparison.ts","../../src/contract/intake/run-record-dir.ts","../../src/contract/eval-reporting-suite.ts","../../src/contract/diff.ts","../../src/contract/intake/agent-trace.ts","../../src/contract/intake/code-agent-observation.ts","../../src/contract/intake/code-agent-session.ts","../../src/contract/intake/feedback-table.ts","../../src/contract/intake/otel-spans.ts"],"sourcesContent":["/**\n * Run one complete improvement job.\n *\n * A caller-owned `proposer` can generate candidates across local generations.\n * An external `method`, such as official GEPA or SkillOpt, owns its complete\n * search and returns one candidate. Both paths remeasure the selected candidate\n * against cases that candidate generation never receives.\n */\n\nimport type { ProposalFinding } from '../analyst/types'\nimport { defaultProductionGate } from '../campaign/gates/default-production-gate'\nimport { type PowerPreflight, powerPreflight } from '../campaign/gates/power-preflight'\nimport {\n assertOptimizationResult,\n type OptimizationMethod,\n type OptimizationMethodProvenance,\n type OptimizationMethodResult,\n} from '../campaign/presets/compare-optimization-methods'\nimport {\n type RunImprovementLoopResult,\n runImprovementLoop,\n} from '../campaign/presets/run-improvement-loop'\nimport type {\n PremeasuredOptimizationBaseline,\n RunOptimizationOptions,\n} from '../campaign/presets/run-optimization'\nimport {\n emitLoopProvenance,\n type LoopProvenanceRecord,\n loopProvenanceArgsFromResult,\n} from '../campaign/provenance'\nimport { resolveRunDir } from '../campaign/run-dir'\nimport {\n campaignCellExecutionEvidence,\n campaignCellJudgeDimensions,\n campaignCellTaskScore,\n campaignCellToRunRecord,\n} from '../campaign/run-record'\nimport {\n type CampaignStorage,\n createRunCostLedger,\n fsCampaignStorage,\n inMemoryCampaignStorage,\n} from '../campaign/storage'\nimport { surfaceContentHash, surfaceHash } from '../campaign/surface-identity'\nimport type {\n CampaignCellResult,\n DispatchContext,\n Gate,\n JudgeConfig,\n LabeledScenarioStore,\n MutableSurface,\n Scenario,\n SurfaceProposer,\n} from '../campaign/types'\nimport type { CostLedgerHandle, CostLedgerSummary, CostReceipt } from '../cost-ledger'\nimport { ValidationError } from '../errors'\nimport { createHostedClient, type HostedTenant } from '../hosted/client'\nimport type { EvalRunCellScore, EvalRunEvent, EvalRunGenerationSnapshot } from '../hosted/types'\nimport { modelHasSnapshot, type RunRecord, type RunSplitTag } from '../run-record'\nimport { analyzeRuns } from './analyze-runs'\nimport type { InsightReport } from './insight-report'\n\nexport interface SelfImproveBudget {\n /** Hard spend cap across the full run. Each paid call reserves its enforced\n * maximum before dispatch, so completed spend cannot cross this amount. */\n dollars?: number\n /** Proposer generations. Default: 3. External methods own their rounds and\n * require this value to be omitted or set to 1. Set 0 only for a\n * proposer-free baseline run. */\n generations?: number\n /** Candidates the proposer emits per generation. Default 2. */\n populationSize?: number\n /** Max concurrent cells across the loop. Default 2. */\n maxConcurrency?: number\n /** Candidate campaigns scored in parallel. Default 1. Total concurrent\n * cells are bounded by `candidateConcurrency * maxConcurrency`. */\n candidateConcurrency?: number\n /** Fraction of `scenarios` held out from training, used for the gate.\n * Default 0.25. Ignored when `holdoutScenarios` is set explicitly. */\n holdoutFraction?: number\n /** Fraction of the non-final cases reserved for method selection.\n * Default 0.25. Used only with `method` and ignored when\n * `selectionScenarios` is supplied explicitly. */\n selectionFraction?: number\n /** Explicit held-out scenarios; overrides `holdoutFraction`. */\n holdoutScenarios?: Scenario[]\n /** Holdout policy. Default `'measured'`: split, re-score baseline vs winner\n * on the held-out set, gate on that comparison. `'deferred'`: run the\n * improvement-set campaigns + search promotion, dispatch ZERO holdout cells,\n * force the gate to `'hold'`, return `lift: undefined`, and record\n * `holdout: 'deferred'` in the provenance record — for callers that measure\n * the held-out comparison in a separate later run instead of faking a\n * static holdout scenario and recording a meaningless lift. Unless\n * `holdoutScenarios` reserves an explicit set, ALL scenarios train. */\n holdout?: 'measured' | 'deferred'\n /** Per-scenario replicates per cell — raises bootstrap-CI tightness. Default 1. */\n reps?: number\n /** DEPTH dial forwarded to the proposer's `propose()` as\n * `ctx.maxImprovementShots` — max iterations an agentic candidate generator\n * may take per candidate (verify-in-session retries). Unset ⇒ the\n * proposer's own default. */\n maxImprovementShots?: number\n}\n\nexport type SelfImproveProgressEvent =\n | { kind: 'baseline.started'; scenarios: number }\n | { kind: 'baseline.completed'; compositeMean: number; durationMs: number }\n | { kind: 'generation.started'; index: number; populationSize: number }\n | { kind: 'generation.completed'; index: number; bestComposite: number; durationMs: number }\n // `lift` is absent when `budget.holdout === 'deferred'` — no held-out\n // measurement ran, and the search-split delta must not masquerade as one.\n | { kind: 'gate.decided'; decision: string; lift?: number }\n | { kind: 'power.estimated'; n: number; sd: number; mde: number; underpowered: boolean }\n\nexport interface SelfImproveOptions<TScenario extends Scenario, TArtifact> {\n /**\n * Your agent — a function that takes the current `MutableSurface`\n * (typically a system prompt the loop is optimizing) plus the\n * scenario + cell ctx, and returns the artifact your judge scores.\n *\n * Same shape as `RunOptimizationOptions.dispatchWithSurface`. Wrap a\n * plain `Dispatch` if you don't have a surface seam:\n *\n * agent: (_surface, scenario, ctx) => yourPlainDispatch(scenario, ctx)\n *\n * That mode evaluates without mutating any surface — useful as a\n * baseline-only run (set `budget.generations = 0`).\n */\n agent: (surface: MutableSurface, scenario: TScenario, ctx: DispatchContext) => Promise<TArtifact>\n\n /**\n * Snapshot-bearing model identity for agents that do not report a paid-call\n * receipt through `ctx.cost.runPaidCall()`.\n *\n * Omit this when every cell reports its concrete model in a receipt.\n */\n model?: string\n\n /** Scenarios to evaluate against. Train/holdout split is computed from\n * these unless `budget.holdoutScenarios` is set explicitly. */\n scenarios: TScenario[]\n\n /** Judge that scores artifacts. Bring your own; use `langchainJudge`\n * from `/adapters/langchain` for a Runnable-shaped one. */\n judge: JudgeConfig<TArtifact, TScenario>\n\n /** Starting surface — system prompt, JSON config, anything `MutableSurface`\n * accepts. The proposer mutates this each generation. */\n baselineSurface: MutableSurface\n\n /** Budget + loop shape. All fields optional. */\n budget?: SelfImproveBudget\n\n /**\n * Complete prior measurement of `baselineSurface` over the TRAIN split.\n * Forwarded to the loop body, which validates its surface hash, scenario\n * split, seed (42), reps, and coverage, then skips the baseline search\n * campaign entirely — no baseline dispatch, no resumability lookup. The\n * train split is `scenarios` minus the holdout split, so premeasure with\n * exactly that scenario set (explicit `budget.holdoutScenarios`, or\n * `budget.holdout: 'deferred'` with no reserved set, makes the train split\n * deterministic). Prior spend stays in the imported campaign aggregates and\n * is not re-added to this run's cost ledger.\n */\n premeasuredBaseline?: PremeasuredOptimizationBaseline<TArtifact, TScenario>\n\n /**\n * Candidate generator for this local generation loop.\n * Required when `budget.generations` is greater than zero.\n */\n proposer?: SurfaceProposer<ProposalFinding>\n\n /**\n * Complete optimization method, such as official GEPA or SkillOpt.\n * The method receives disjoint train and selection cases and never receives\n * the final comparison cases. Mutually exclusive with `proposer`.\n */\n method?: OptimizationMethod<TScenario, TArtifact>\n\n /** Explicit method-selection cases. They must also appear in `scenarios`\n * and must not overlap the final comparison cases. */\n selectionScenarios?: TScenario[]\n\n /** Custom gate. Default is `defaultProductionGate` with\n * `deltaThreshold: 0.05` on the held-out split. */\n gate?: Gate<TArtifact, TScenario>\n\n /** Placebo control. When supplied AND the winner differs from baseline, the\n * loop scores a THIRD held-out arm: the winner surface with its content\n * footprint-matched-blanked by this fn (typically via `neutralizeText`). Its\n * scores reach the gate as `ctx.neutralizedJudgeScores`, letting a\n * `neutralizationGate` reject a win whose lift survives blanking the content\n * (decorative — driven by footprint, not content). Costs one extra held-out\n * campaign; omit to skip. Compose `neutralizationGate` into `gate` to act on it. */\n neutralize?: (winnerSurface: MutableSurface, baselineSurface: MutableSurface) => MutableSurface\n\n /** Storage backend. A filesystem run directory uses `fsCampaignStorage()`;\n * a `mem://` directory uses in-memory storage. External methods default to\n * a filesystem directory because their official state must survive. */\n storage?: CampaignStorage\n\n /** Run directory. Proposer mode defaults to\n * `mem://selfImprove-<timestamp>`. External method mode defaults to\n * `.agent-eval/runs/self-improve-<timestamp>`. */\n runDir?: string\n\n /** Fires once the durable provenance record + OTel spans are emitted.\n * Receives the structured record for inline assertions / custom routing. */\n onProvenance?: (record: LoopProvenanceRecord) => void\n\n /** Distributed execution seam — same as `RunCampaignOptions.cellPlacement`.\n * Returns an opaque placement key the substrate forwards to your agent\n * as `ctx.placement`. Combined with `httpDispatch` from\n * `/adapters/http`, fans cells across regions. */\n cellPlacement?: (input: {\n scenario: TScenario\n rep: number\n generation?: number\n }) => string | undefined\n\n /** Per-cell agent dispatch deadline, applied to baseline, candidate, and\n * held-out campaigns. Default 600_000 ms. Set 0 to disable. */\n dispatchTimeoutMs?: number\n\n /** Streaming hook — fires on baseline + each generation + gate decision.\n * Consumer routes events wherever (UI, dashboard, logs). */\n onProgress?: (event: SelfImproveProgressEvent) => void\n\n /** Auto-promotion behavior on a ship decision. Default `'none'` — we\n * return the winner; you ship it however you ship. `'pr'` opens a\n * GitHub PR via `openAutoPr`; requires `ghOwner` + `ghRepo`. */\n autoOnPromote?: 'pr' | 'none'\n ghOwner?: string\n ghRepo?: string\n\n /**\n * Opt-in: ship eval-run events to a hosted orchestrator (ours, your\n * self-hosted one, or any compatible implementation of the\n * `docs/hosted-ingest-spec.md` wire format). When set, the substrate\n * POSTs the final `EvalRunEvent` to `${endpoint}/v1/ingest/eval-runs`\n * after the loop completes. Failures are logged but do not fail the\n * loop — local result is always returned.\n *\n * For our orchestrator: `{ endpoint: 'https://orchestrator.tangle.tools/v1', apiKey, tenantId }`.\n *\n * For your self-hosted: any URL serving the wire format. See\n * `examples/hosted-ingest-server/` for the reference receiver.\n */\n hostedTenant?: HostedTenant\n\n /** Free-form labels attached to the hosted event (env, branch, model id,\n * etc.). Ignored when `hostedTenant` is unset. */\n hostedLabels?: Record<string, string>\n\n /** Capture every search artifact and judge score to this store.\n * The store is output only and is never exposed to candidate generation.\n * Pass `'off'` to disable. Default: off. */\n labeledStore?: LabeledScenarioStore | 'off'\n\n /** Capture-source tag for `labeledStore`. Default `'eval-run'`. */\n captureSource?: 'production-trace' | 'eval-run' | 'manual' | 'red-team' | 'synthetic'\n\n /**\n * Per-cell backend-integrity expectation — the fail-loud guard. A cell that\n * produced an artifact but reported `costUsd === 0` AND zero tokens is a\n * stub. Modes: `'assert'` throws on the first such cell, `'warn'` logs it,\n * `'off'` skips the check (offline/replay). Default `'assert'` — `selfImprove`\n * is the real-run path, so a stub fails loud rather than scoring a clean 0.\n */\n expectUsage?: 'assert' | 'warn' | 'off'\n\n /**\n * Per-generation findings producer. Runs once on the baseline campaign (as\n * `generation: -1`) before generation 0 proposes — so single-generation runs\n * propose with trace context — and again after each generation is scored;\n * whatever it returns REPLACES the proposer's `findings` for the next\n * `propose()`. Plug a trace-analyst registry / HALO here. When absent,\n * findings stay `opts.findings`.\n */\n analyzeGeneration?: RunOptimizationOptions<TScenario, TArtifact>['analyzeGeneration']\n\n /** Static findings forwarded to the proposer's `propose()` as `ctx.findings`\n * (a findings-grounded proposer consumes them). Default: none. */\n findings?: ProposalFinding[]\n\n /** Override how the WINNER is selected among coverage-complete candidates.\n * Defaults to the scalar mean composite (historical behavior). A binary-with-\n * replicates consumer whose ship-gate counts an instance resolved only when\n * every replicate resolved passes a fail-closed lexicographic key here so that\n * winner-selection and the ship-gate rank on the identical metric and cannot\n * invert. See `RunOptimizationOptions.selectionRankKey`. */\n selectionRankKey?: RunOptimizationOptions<TScenario, TArtifact>['selectionRankKey']\n}\n\nexport interface SelfImproveResult<TScenario extends Scenario, TArtifact> {\n /** Composite mean across all scenarios, baseline run. When\n * `budget.holdout === 'deferred'` this is measured on the improvement\n * (search) split — no holdout campaign ran. */\n baseline: {\n compositeMean: number\n perScenario: Record<string, number>\n }\n /** Composite mean on the held-out set, winner run. When\n * `budget.holdout === 'deferred'` this is the winner's improvement-set\n * (search) measurement — no holdout campaign ran. */\n winner: {\n compositeMean: number\n perScenario: Record<string, number>\n surface: MutableSurface\n /** Proposer label for the promoted change. Absent ⇒ winner == baseline or\n * a bare-surface mutator. */\n label?: string\n /** Proposer rationale — the \"because Z\" that motivated the promoted change.\n * Threaded from the proposer's `ProposedCandidate` through the loop.\n * Absent ⇒ winner == baseline. */\n rationale?: string\n }\n /** `winner.compositeMean - baselineOnHoldout.compositeMean`. Positive\n * means the gate observed improvement. Absent iff\n * `budget.holdout === 'deferred'` — no held-out measurement ran, so there\n * is no lift to report (never a fabricated 0). */\n lift?: number\n /** The explicit baseline→winner unified diff. Always present (empty string\n * when winner == baseline). */\n diff: string\n /** Durable, queryable provenance record: candidate→cell→gate→promote chain +\n * rationale + diff + backend provenance. The artifact the hosted ingest\n * path stores; the +lift RECOMPUTES from `record.heldOutLift`. */\n provenance: LoopProvenanceRecord\n /** `defaultProductionGate.decide()` result. */\n gateDecision: 'ship' | 'hold' | 'need_more_work' | 'model_ceiling' | 'arch_ceiling'\n /** Number of generations actually explored (may be less than the\n * budget if the proposer gave up early). */\n generationsExplored: number\n /** Wall-clock total. */\n durationMs: number\n /** Total newly observed cost across the full run. */\n totalCostUsd: number\n /** Canonical run-wide spend summary. */\n cost: CostLedgerSummary\n /** Run-wide receipts across proposal, search, holdout, judging, analysis,\n * and promotion work, with phase and actor attribution. */\n receipts: CostReceipt[]\n /** Exact external method and source identity, when `method` was used. */\n optimization?: {\n name: string\n cost: OptimizationMethodResult['cost']\n durationMs?: number\n provenance?: OptimizationMethodProvenance\n }\n /**\n * Rigor packet: distributional summary, paired-bootstrap lift CI,\n * judge stats, contamination check, recommendations. Wired through\n * `analyzeRuns()` on the baseline + winner cells of the campaign.\n * Hosted-tier dashboards render this as the v3-vs-v4 decision view.\n */\n insight: InsightReport\n /** Minimum-detectable-lift analysis from the baseline holdout cells: could this\n * budget have shipped ANY plausible effect? Absent when the baseline produced\n * fewer than 3 scored holdout cells. See `powerPreflight` for the standalone\n * pre-run version (run `gate: 'none'` first, budget the real search after). */\n power?: PowerPreflight\n /**\n * Raw substrate result for advanced inspection — full per-generation\n * candidates, full campaign artifacts, all judge scores. Useful for\n * debugging or reporting beyond the summary.\n */\n raw: RunImprovementLoopResult<TArtifact, TScenario>\n}\n\n/** Failed self-improvement run with an immutable receipt snapshot. */\nexport class SelfImproveRunError extends Error {\n readonly cost: CostLedgerSummary\n readonly receipts: CostReceipt[]\n\n constructor(cause: unknown, ledger: CostLedgerHandle) {\n const original = cause instanceof Error ? cause : new Error(String(cause))\n super(original.message, { cause: original })\n this.name = 'SelfImproveRunError'\n this.cost = ledger.summary()\n this.receipts = ledger.list()\n }\n}\n\nfunction assertSelfImproveSearchMode<TScenario extends Scenario, TArtifact>(\n opts: SelfImproveOptions<TScenario, TArtifact>,\n): void {\n if (opts.method && opts.proposer) {\n throw new Error('selfImprove: method and proposer are mutually exclusive')\n }\n if (!opts.method) {\n if (opts.selectionScenarios !== undefined) {\n throw new Error('selfImprove: selectionScenarios requires method')\n }\n return\n }\n if (\n typeof opts.method.name !== 'string' ||\n !opts.method.name.trim() ||\n opts.method.name.trim() !== opts.method.name ||\n typeof opts.method.optimize !== 'function'\n ) {\n throw new Error('selfImprove: method must have a trimmed name and optimize(input)')\n }\n const budget = opts.budget\n if (budget?.generations !== undefined && budget.generations !== 1) {\n throw new Error('selfImprove: method owns its rounds; budget.generations must be 1 when set')\n }\n if (budget?.populationSize !== undefined && budget.populationSize !== 1) {\n throw new Error(\n 'selfImprove: method owns its candidates; budget.populationSize must be 1 when set',\n )\n }\n if (\n budget?.candidateConcurrency !== undefined ||\n budget?.maxImprovementShots !== undefined ||\n opts.analyzeGeneration !== undefined ||\n opts.findings !== undefined\n ) {\n throw new Error(\n 'selfImprove: candidateConcurrency, maxImprovementShots, analyzeGeneration, and findings apply only to proposer mode',\n )\n }\n}\n\nfunction splitMethodPartitions<TScenario extends Scenario>(\n searchScenarios: TScenario[],\n explicitSelection: TScenario[] | undefined,\n fraction: number,\n): { train: TScenario[]; selection: TScenario[] } {\n if (!Number.isFinite(fraction) || fraction <= 0 || fraction >= 1) {\n throw new Error('selfImprove: budget.selectionFraction must be in (0, 1)')\n }\n const byId = new Map<string, TScenario>()\n for (const scenario of searchScenarios) {\n if (byId.has(scenario.id)) {\n throw new Error(`selfImprove: duplicate scenario id '${scenario.id}'`)\n }\n byId.set(scenario.id, scenario)\n }\n if (explicitSelection) {\n if (explicitSelection.length === 0) {\n throw new Error('selfImprove: selectionScenarios must not be empty')\n }\n const selectionIds = new Set<string>()\n for (const scenario of explicitSelection) {\n if (!byId.has(scenario.id)) {\n throw new Error(\n `selfImprove: selection scenario '${scenario.id}' is absent from the non-final cases`,\n )\n }\n if (selectionIds.has(scenario.id)) {\n throw new Error(`selfImprove: duplicate selection scenario id '${scenario.id}'`)\n }\n selectionIds.add(scenario.id)\n }\n const train = searchScenarios.filter((scenario) => !selectionIds.has(scenario.id))\n if (train.length === 0) {\n throw new Error('selfImprove: method train split is empty')\n }\n return {\n train,\n selection: explicitSelection.map((scenario) => byId.get(scenario.id)!),\n }\n }\n if (searchScenarios.length < 2) {\n throw new Error('selfImprove: method requires at least two non-final scenarios')\n }\n const sorted = [...searchScenarios].sort(\n (a, b) => stableScenarioHash(a.id) - stableScenarioHash(b.id),\n )\n const count = Math.max(1, Math.min(sorted.length - 1, Math.round(sorted.length * fraction)))\n return {\n selection: sorted.slice(0, count),\n train: sorted.slice(count),\n }\n}\n\nfunction safeRunComponent(value: string): string {\n return value.replace(/[^a-zA-Z0-9._-]/g, '_')\n}\n\nfunction stableScenarioHash(value: string): number {\n let hash = 2166136261 >>> 0\n for (let index = 0; index < value.length; index++) {\n hash ^= value.charCodeAt(index)\n hash = Math.imul(hash, 16777619) >>> 0\n }\n return hash\n}\n\n/**\n * Deterministic train/holdout split by a stable hash of `scenario.id`,\n * so the same scenario set always splits the same way across runs.\n */\nfunction splitTrainHoldout<TScenario extends Scenario>(\n scenarios: TScenario[],\n fraction: number,\n): { train: TScenario[]; holdout: TScenario[] } {\n const sorted = [...scenarios].sort((a, b) => stableScenarioHash(a.id) - stableScenarioHash(b.id))\n const nHoldout = Math.max(1, Math.min(sorted.length - 1, Math.round(sorted.length * fraction)))\n return {\n holdout: sorted.slice(0, nHoldout),\n train: sorted.slice(nHoldout),\n }\n}\n\nfunction meanComposite(byScenario: Record<string, { meanComposite: number }>): {\n compositeMean: number\n perScenario: Record<string, number>\n} {\n const perScenario: Record<string, number> = {}\n const values: number[] = []\n for (const [id, agg] of Object.entries(byScenario)) {\n perScenario[id] = agg.meanComposite\n values.push(agg.meanComposite)\n }\n return {\n compositeMean: values.length === 0 ? 0 : values.reduce((s, v) => s + v, 0) / values.length,\n perScenario,\n }\n}\n\n/**\n * Latest search campaign measured for the winner surface; the baseline search\n * campaign when the winner IS the baseline. Used by the deferred-holdout\n * summary, where no holdout campaign exists to summarize.\n */\nfunction winnerSearchCampaign<TScenario extends Scenario, TArtifact>(\n result: RunImprovementLoopResult<TArtifact, TScenario>,\n): RunImprovementLoopResult<TArtifact, TScenario>['baselineCampaign'] {\n for (let i = result.generations.length - 1; i >= 0; i--) {\n const measured = result.generations[i]?.surfaces.find(\n (s) => s.surfaceHash === result.winnerSurfaceHash,\n )\n if (measured) return measured.campaign\n }\n return result.baselineCampaign\n}\n\n/**\n * One-shot self-improvement loop. See module docstring for defaults +\n * extension points.\n *\n * @example Minimum:\n *\n * const result = await selfImprove({\n * agent: (surface, scenario, ctx) => myAgent(surface, scenario, ctx.signal),\n * scenarios,\n * judge,\n * baselineSurface: DEFAULT_PROMPT,\n * proposer,\n * })\n * console.log(`lift: ${result.lift.toFixed(3)} (${result.gateDecision})`)\n *\n * @example Distributed (workers in three regions):\n *\n * await selfImprove({\n * agent: httpDispatch({ resolveUrl: ({ placement }) => REGION_URLS[placement!] }),\n * scenarios,\n * judge,\n * baselineSurface: DEFAULT_PROMPT,\n * cellPlacement: ({ scenario }) => scenario.region,\n * budget: { maxConcurrency: 12 },\n * })\n */\nexport async function selfImprove<TScenario extends Scenario, TArtifact>(\n opts: SelfImproveOptions<TScenario, TArtifact>,\n): Promise<SelfImproveResult<TScenario, TArtifact>> {\n const startedAt = Date.now()\n const requestedRunDir =\n opts.runDir ??\n (opts.method ? `.agent-eval/runs/self-improve-${startedAt}` : `mem://selfImprove-${startedAt}`)\n const runDir = resolveRunDir(requestedRunDir)\n const storage =\n opts.storage ?? (runDir.startsWith('mem://') ? inMemoryCampaignStorage() : fsCampaignStorage())\n const costLedger = createRunCostLedger({\n storage,\n runDir,\n costCeilingUsd: opts.budget?.dollars,\n })\n try {\n return await runSelfImprove(opts, costLedger, startedAt, runDir, storage)\n } catch (error) {\n throw new SelfImproveRunError(error, costLedger)\n }\n}\n\nasync function runSelfImprove<TScenario extends Scenario, TArtifact>(\n opts: SelfImproveOptions<TScenario, TArtifact>,\n costLedger: CostLedgerHandle,\n startedAt: number,\n runDir: string,\n storage: CampaignStorage,\n): Promise<SelfImproveResult<TScenario, TArtifact>> {\n const budget = opts.budget ?? {}\n assertSelfImproveSearchMode(opts)\n const generations = opts.method ? 1 : (budget.generations ?? 3)\n const populationSize = opts.method ? 1 : (budget.populationSize ?? 2)\n const maxConcurrency = budget.maxConcurrency ?? 2\n const holdoutFraction = budget.holdoutFraction ?? 0.25\n const holdoutMode = budget.holdout ?? 'measured'\n const holdoutDeferred = holdoutMode === 'deferred'\n const expectUsage = opts.expectUsage ?? 'assert'\n\n // Deferred holdout without an explicitly reserved set trains on EVERYTHING:\n // there is no held-out measurement in this run, so carving out a fraction\n // would waste scenarios. An explicit `holdoutScenarios` set stays reserved\n // (excluded from training) even when deferred, for the later measured run.\n const explicitHoldout = budget.holdoutScenarios\n const { train, holdout } = explicitHoldout\n ? {\n train: opts.scenarios.filter((s) => !explicitHoldout.some((h) => h.id === s.id)),\n holdout: explicitHoldout as TScenario[],\n }\n : holdoutDeferred\n ? { train: opts.scenarios, holdout: [] as TScenario[] }\n : splitTrainHoldout(opts.scenarios, holdoutFraction)\n\n if (train.length === 0) {\n throw new Error(\n 'selfImprove: train split is empty. Reduce holdoutFraction or pass more scenarios.',\n )\n }\n if (holdout.length === 0 && !holdoutDeferred) {\n throw new Error('selfImprove: holdout split is empty. Pass more scenarios.')\n }\n\n if (generations > 0 && !opts.proposer && !opts.method) {\n throw new Error(\n 'selfImprove: method or proposer is required when budget.generations is greater than zero',\n )\n }\n let optimizationResult: OptimizationMethodResult | undefined\n const methodPartitions = opts.method\n ? splitMethodPartitions(train, opts.selectionScenarios, budget.selectionFraction ?? 0.25)\n : undefined\n const proposer: SurfaceProposer<ProposalFinding> = opts.method\n ? {\n kind: `method:${opts.method.name}`,\n propose: async (context) => {\n if (context.generation > 0) return []\n const result = await opts.method!.optimize(\n Object.freeze({\n baselineSurface: structuredClone(context.currentSurface),\n trainScenarios: Object.freeze(\n methodPartitions!.train.map((scenario) => structuredClone(scenario)),\n ),\n selectionScenarios: Object.freeze(\n methodPartitions!.selection.map((scenario) => structuredClone(scenario)),\n ),\n dispatchWithSurface: opts.agent,\n judges: Object.freeze([opts.judge]),\n runDir: `${runDir}/optimization/${safeRunComponent(opts.method!.name)}`,\n seed: 42,\n runOptions: Object.freeze({\n storage,\n maxConcurrency,\n reps: budget.reps,\n dispatchTimeoutMs: opts.dispatchTimeoutMs,\n expectUsage,\n costCeiling: budget.dollars,\n }),\n costLedger,\n }),\n )\n assertOptimizationResult(opts.method!.name, result)\n optimizationResult = structuredClone(result)\n return [\n {\n surface: structuredClone(result.winnerSurface),\n label: opts.method!.name,\n rationale: `${opts.method!.name} selected this surface without final cases.`,\n },\n ]\n },\n }\n : (opts.proposer ?? {\n kind: 'baseline-only',\n propose: async () => [],\n })\n\n const gate: Gate<TArtifact, TScenario> =\n opts.gate ??\n defaultProductionGate<TArtifact, TScenario>({\n holdoutScenarios: holdout,\n deltaThreshold: 0.05,\n })\n\n if (opts.onProgress) {\n opts.onProgress({ kind: 'baseline.started', scenarios: opts.scenarios.length })\n }\n\n const result = await runImprovementLoop<TScenario, TArtifact>({\n scenarios: train,\n baselineSurface: opts.baselineSurface,\n premeasuredBaseline: opts.premeasuredBaseline,\n dispatchWithSurface: opts.agent,\n proposer,\n judges: [opts.judge],\n populationSize,\n maxGenerations: generations,\n candidateConcurrency: budget.candidateConcurrency,\n reps: budget.reps,\n maxImprovementShots: budget.maxImprovementShots,\n holdoutScenarios: holdout,\n holdout: holdoutMode,\n gate,\n neutralize: opts.neutralize,\n autoOnPromote: opts.autoOnPromote ?? 'none',\n ghOwner: opts.ghOwner,\n ghRepo: opts.ghRepo,\n storage,\n runDir,\n maxConcurrency,\n cellPlacement: opts.cellPlacement,\n dispatchTimeoutMs: opts.dispatchTimeoutMs,\n costLedger,\n expectUsage,\n labeledStore: opts.labeledStore,\n captureSource: opts.captureSource,\n analyzeGeneration: opts.analyzeGeneration,\n findings: opts.findings,\n selectionRankKey: opts.selectionRankKey,\n })\n\n // Deferred holdout ran zero holdout cells, so the summary stats come from\n // the improvement-set (search) campaigns — labeled as such on the result\n // type — and `lift` is omitted rather than fabricated from empty campaigns.\n const reportSplit: RunSplitTag = holdoutDeferred ? 'search' : 'holdout'\n const reportBaselineCampaign = holdoutDeferred\n ? result.baselineCampaign\n : result.baselineOnHoldout\n const reportWinnerCampaign = holdoutDeferred\n ? winnerSearchCampaign(result)\n : result.winnerOnHoldout\n const baseline = meanComposite(reportBaselineCampaign.aggregates.byScenario)\n const winnerStats = meanComposite(reportWinnerCampaign.aggregates.byScenario)\n\n // Power analysis from the baseline holdout cells — the number that says whether\n // this budget could ship ANY effect. Attached to every result; loud when the\n // search was structurally unable to promote (that spend should not repeat).\n let power: PowerPreflight | undefined\n const baselineHoldoutComposites = result.baselineOnHoldout.cells\n .filter((cell) => !cell.error)\n .map((cell) => {\n const scores = Object.values(cell.judgeScores)\n return scores.length === 0\n ? Number.NaN\n : scores.reduce((sum, s) => sum + s.composite, 0) / scores.length\n })\n .filter((v) => Number.isFinite(v))\n if (baselineHoldoutComposites.length >= 3) {\n // selfImprove's holdout is scored by the SAME judge as the gate — the\n // shared-channel case by construction (S1c): flag it so the MDE reads as a\n // lower bound and nobody buys reps expecting them to fix judge bias.\n power = powerPreflight({\n baselineComposites: baselineHoldoutComposites,\n sharedScorerChannel: true,\n })\n if (opts.onProgress) {\n opts.onProgress({\n kind: 'power.estimated',\n n: power.n,\n sd: power.sd,\n mde: power.mde,\n underpowered: power.underpowered,\n })\n }\n if (power.underpowered && generations > 0) {\n console.warn(`[selfImprove] ${power.recommendation}`)\n }\n }\n\n if (opts.onProgress) {\n opts.onProgress({\n kind: 'baseline.completed',\n compositeMean: baseline.compositeMean,\n durationMs: Date.now() - startedAt,\n })\n opts.onProgress({\n kind: 'gate.decided',\n decision: result.gateResult.decision,\n // Deferred holdout has no held-out measurement: in that mode the summary\n // stats are search-split numbers, and emitting their delta as `lift`\n // would misreport a train-split delta as a held-out one. Omit instead.\n ...(holdoutDeferred ? {} : { lift: winnerStats.compositeMean - baseline.compositeMean }),\n })\n }\n\n const cost = result.cost\n const totalCost = cost.totalCostUsd\n\n // Rigor packet: feed baseline + winner cells through analyzeRuns().\n // The two candidates (`baseline` / `winner`) give the lift section a\n // clean paired comparison; per-judge / per-dimension / cost-quality\n // sections populate from the cells' judgeScores.\n const insight = await analyzeRuns({\n runs: [\n ...cellsToRunRecords(\n reportBaselineCampaign.cells,\n 'baseline',\n runDir,\n opts.baselineSurface,\n reportSplit,\n opts.model,\n ),\n ...cellsToRunRecords(\n reportWinnerCampaign.cells,\n 'winner',\n runDir,\n result.winnerSurface,\n reportSplit,\n opts.model,\n ),\n ],\n baselineCandidateId: 'baseline',\n candidateCandidateId: 'winner',\n })\n\n // ── Durable provenance: candidate→cell→gate→promote chain + rationale +\n // diff + backend provenance. Always emitted; the +lift recomputes from it.\n const durationMs = Date.now() - startedAt\n const { record: provenance } = await emitLoopProvenance<TArtifact, TScenario>({\n ...loopProvenanceArgsFromResult({\n runId: `${runDir}#${startedAt}`,\n runDir,\n timestamp: new Date(startedAt).toISOString(),\n baselineSurface: opts.baselineSurface,\n result,\n costReceipts: costLedger.list(),\n totalCostUsd: totalCost,\n totalDurationMs: durationMs,\n }),\n ...(optimizationResult\n ? {\n optimizationMethod: {\n name: opts.method!.name,\n cost: structuredClone(optimizationResult.cost),\n ...(optimizationResult.durationMs === undefined\n ? {}\n : { durationMs: optimizationResult.durationMs }),\n ...(optimizationResult.provenance === undefined\n ? {}\n : { provenance: structuredClone(optimizationResult.provenance) }),\n },\n }\n : {}),\n storage,\n hostedClient: opts.hostedTenant ? createHostedClient(opts.hostedTenant) : undefined,\n })\n if (opts.onProvenance) opts.onProvenance(provenance)\n\n const summary: SelfImproveResult<TScenario, TArtifact> = {\n baseline,\n winner: {\n ...winnerStats,\n surface: result.winnerSurface,\n ...(result.winnerLabel ? { label: result.winnerLabel } : {}),\n ...(result.winnerRationale ? { rationale: result.winnerRationale } : {}),\n },\n ...(holdoutDeferred ? {} : { lift: winnerStats.compositeMean - baseline.compositeMean }),\n diff: result.promotedDiff,\n provenance,\n gateDecision: result.gateResult.decision,\n generationsExplored: result.generations.length,\n durationMs,\n totalCostUsd: totalCost,\n cost,\n receipts: costLedger.list(),\n ...(optimizationResult\n ? {\n optimization: {\n name: opts.method!.name,\n cost: structuredClone(optimizationResult.cost),\n ...(optimizationResult.durationMs === undefined\n ? {}\n : { durationMs: optimizationResult.durationMs }),\n ...(optimizationResult.provenance === undefined\n ? {}\n : { provenance: structuredClone(optimizationResult.provenance) }),\n },\n }\n : {}),\n insight,\n ...(power ? { power } : {}),\n raw: result,\n }\n\n // Opt-in hosted ingest. Failures are logged but never fail the loop: the\n // local result is always returned.\n if (opts.hostedTenant) {\n try {\n await shipEvalRunToHosted(opts.hostedTenant, opts, summary, result, runDir)\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n // eslint-disable-next-line no-console -- intentional: hosted-ingest is best-effort\n console.warn(`[agent-eval] hosted ingest failed (continuing): ${msg}`)\n }\n }\n\n return summary\n}\n\nasync function shipEvalRunToHosted<TScenario extends Scenario, TArtifact>(\n tenant: HostedTenant,\n opts: SelfImproveOptions<TScenario, TArtifact>,\n summary: SelfImproveResult<TScenario, TArtifact>,\n raw: RunImprovementLoopResult<TArtifact, TScenario>,\n runDir: string,\n): Promise<void> {\n const client = createHostedClient(tenant)\n\n function snapshotFromCampaign(\n index: number,\n surface: MutableSurface,\n campaign: RunImprovementLoopResult<TArtifact, TScenario>['baselineCampaign'],\n durationMs: number,\n ): EvalRunGenerationSnapshot {\n const cells: EvalRunCellScore[] = campaign.cells.map((cell) => {\n const execution = campaignCellExecutionEvidence(cell)\n return {\n scenarioId: cell.scenarioId,\n rep: cell.rep,\n compositeMean: campaignCellTaskScore(cell) ?? null,\n dimensions: campaignCellJudgeDimensions(cell),\n terminalOutcome: execution.terminalOutcome,\n executionErrorCount: execution.executionErrorCount ?? null,\n errorMessage: cell.error ?? undefined,\n }\n })\n const scoredCells = cells.flatMap((cell) =>\n cell.compositeMean === null ? [] : [cell.compositeMean],\n )\n const compositeMean =\n scoredCells.length === 0\n ? null\n : scoredCells.reduce((sum, score) => sum + score, 0) / scoredCells.length\n return {\n index,\n surfaceHash: surfaceHash(surface),\n surface,\n cells,\n compositeMean,\n costUsd: campaign.aggregates.cost.totalCostUsd,\n durationMs,\n }\n }\n\n const generations: EvalRunGenerationSnapshot[] = []\n // Baseline as generation 0.\n generations.push(snapshotFromCampaign(0, opts.baselineSurface, raw.baselineCampaign, 0))\n // Improvement generations as 1..N. Substrate stores per-surface campaigns\n // per generation — we summarize the WINNING surface per generation here.\n for (const gen of raw.generations) {\n const winner = gen.surfaces.reduce(\n (best, s) =>\n s.campaign.aggregates.cellsExecuted > 0 &&\n (best === undefined || averageComposite(s.campaign) > averageComposite(best.campaign))\n ? s\n : best,\n gen.surfaces[0],\n )\n if (!winner) continue\n generations.push(\n snapshotFromCampaign(gen.record.generationIndex + 1, winner.surface, winner.campaign, 0),\n )\n }\n\n const event: EvalRunEvent = {\n runId: `${runDir}#${Date.now()}`,\n runDir,\n timestamp: new Date().toISOString(),\n status: 'finished',\n labels: opts.hostedLabels ?? {},\n baseline: generations[0],\n generations,\n gateDecision: summary.gateDecision,\n holdoutLift: summary.lift,\n totalCostUsd: summary.totalCostUsd,\n totalDurationMs: summary.durationMs,\n insightReport: summary.insight,\n }\n\n await client.ingestEvalRun(event)\n}\n\nfunction averageComposite(\n campaign: RunImprovementLoopResult<unknown, Scenario>['baselineCampaign'],\n): number {\n const aggs = Object.values(campaign.aggregates.byScenario)\n return aggs.length === 0 ? 0 : aggs.reduce((s, a) => s + a.meanComposite, 0) / aggs.length\n}\n\nfunction hashString(s: string): string {\n let h = 2166136261 >>> 0\n for (let i = 0; i < s.length; i++) {\n h ^= s.charCodeAt(i)\n h = Math.imul(h, 16777619) >>> 0\n }\n return h.toString(16).padStart(8, '0')\n}\n\n/**\n * Adapt campaign cells into the `RunRecord` shape `analyzeRuns()` consumes.\n * Each cell becomes one run; `candidateId` is the caller-supplied label so\n * baseline + winner pair cleanly on `(experimentId, scenarioId, seed)`.\n *\n * `promptHash` is the REAL sha256 content hash of the surface this cell ran\n * (baseline vs winner are byte-distinguishable + byte-identical-verifiable);\n * `configHash` is the sha256 of the candidate label so the two candidates'\n * config rows differ. Both were previously the literal `'sha256:cell'`, which\n * made baseline and winner indistinguishable in every downstream record.\n */\nfunction cellsToRunRecords<TArtifact>(\n cells: ReadonlyArray<CampaignCellResult<TArtifact>>,\n candidateId: 'baseline' | 'winner',\n runId: string,\n surface: MutableSurface,\n splitTag: RunSplitTag,\n fallbackModel?: string,\n): RunRecord[] {\n const promptHash = surfaceContentHash(surface)\n const configHash = surfaceContentHash(candidateId)\n return cells.map((cell) => {\n const receiptModels = cell.resolvedModels ?? (cell.resolvedModel ? [cell.resolvedModel] : [])\n if (receiptModels.length > 1) {\n throw new ValidationError(\n `selfImprove cell ${cell.cellId} used multiple agent models: ${receiptModels.join(', ')}`,\n )\n }\n const model = receiptModels[0] ?? fallbackModel\n if (!model) {\n throw new ValidationError(\n `selfImprove.model is required when cell ${cell.cellId} has no paid-call model receipt`,\n )\n }\n if (!modelHasSnapshot(model)) {\n throw new ValidationError(\n `selfImprove model \"${model}\" lacks a snapshot version for cell ${cell.cellId}`,\n )\n }\n return campaignCellToRunRecord(cell, {\n runId: `${runId}::${candidateId}::${cell.cellId}`,\n experimentId: runId,\n candidateId,\n // scenarioId is explicit; seed keeps repeated runs distinct.\n seed:\n cell.rep * 1_000_000 +\n hashString(cell.scenarioId)\n .slice(0, 6)\n .split('')\n .reduce((a, c) => (a * 31 + c.charCodeAt(0)) >>> 0, 0),\n model,\n promptHash,\n configHash,\n commitSha: 'cell',\n splitTag,\n })\n })\n}\n","import type { RunEvalOptions } from '../campaign/presets/run-eval'\nimport { runEval } from '../campaign/presets/run-eval'\nimport { inMemoryCampaignStorage } from '../campaign/storage'\nimport type {\n CampaignResult,\n DispatchContext,\n JudgeConfig,\n MutableSurface,\n Scenario,\n} from '../campaign/types'\nimport type { HostedTenant } from '../hosted/client'\nimport {\n type SelfImproveBudget,\n type SelfImproveOptions,\n type SelfImproveResult,\n selfImprove,\n} from './self-improve'\n\nexport type AgentEvalAgent<TScenario extends Scenario, TArtifact> = (\n surface: MutableSurface,\n scenario: TScenario,\n ctx: DispatchContext,\n) => Promise<TArtifact>\n\nexport type DefineAgentEvalOptions<TScenario extends Scenario, TArtifact> = SelfImproveOptions<\n TScenario,\n TArtifact\n>\n\nexport interface AgentEvalEvaluateOptions<TScenario extends Scenario, TArtifact>\n extends Omit<\n RunEvalOptions<TScenario, TArtifact>,\n 'dispatch' | 'judges' | 'runDir' | 'scenarios'\n > {\n /** Scenario set to evaluate. Defaults to the scenarios passed to `defineAgentEval`. */\n scenarios?: TScenario[]\n /** Surface to evaluate. Defaults to the baseline surface passed to `defineAgentEval`. */\n surface?: MutableSurface\n /** Agent to evaluate. Defaults to the agent passed to `defineAgentEval`. */\n agent?: AgentEvalAgent<TScenario, TArtifact>\n /** Single judge override. Ignored when `judges` is set. */\n judge?: JudgeConfig<TArtifact, TScenario>\n /** Full judge list override. Defaults to the single judge passed to `defineAgentEval`. */\n judges?: JudgeConfig<TArtifact, TScenario>[]\n /** Logical or filesystem run directory. Defaults to an in-memory run. */\n runDir?: string\n}\n\nexport type AgentEvalImproveOptions<TScenario extends Scenario, TArtifact> = Omit<\n Partial<SelfImproveOptions<TScenario, TArtifact>>,\n 'budget' | 'hostedTenant'\n> & {\n budget?: Partial<SelfImproveBudget>\n hostedTenant?: Partial<HostedTenant>\n}\n\nexport interface DefinedAgentEval<TScenario extends Scenario, TArtifact> {\n /** The default scenarios used by `evaluate()` and `improve()`. */\n readonly scenarios: readonly TScenario[]\n /** The default baseline surface used by `evaluate()` and `improve()`. */\n readonly baselineSurface: MutableSurface\n /**\n * Run one scored evaluation. Use this for a baseline score or to score one\n * candidate surface without running an improvement loop.\n */\n evaluate(\n opts?: AgentEvalEvaluateOptions<TScenario, TArtifact>,\n ): Promise<CampaignResult<TArtifact, TScenario>>\n /**\n * Run the closed improvement loop. Per-call overrides replace the definition\n * except for nested config objects (`budget`, `hostedTenant`), which\n * are merged field-by-field so callers can override one knob without\n * repeating secrets or budget defaults.\n */\n improve(\n opts?: AgentEvalImproveOptions<TScenario, TArtifact>,\n ): Promise<SelfImproveResult<TScenario, TArtifact>>\n}\n\n/**\n * Define an agent eval once, then either score a surface with `evaluate()` or\n * run the closed loop with `improve()`.\n *\n * This is a DX wrapper only: it delegates to `runEval()` and `selfImprove()` and\n * returns their native result shapes.\n */\nexport function defineAgentEval<TScenario extends Scenario, TArtifact>(\n defaults: DefineAgentEvalOptions<TScenario, TArtifact>,\n): DefinedAgentEval<TScenario, TArtifact> {\n const defaultEvaluateOptions = evaluateDefaults(defaults)\n\n return {\n scenarios: defaults.scenarios,\n baselineSurface: defaults.baselineSurface,\n\n async evaluate(opts = {}) {\n const { agent, judge, judges, runDir, scenarios, surface, ...campaignOpts } = opts\n const selectedAgent = agent ?? defaults.agent\n const selectedSurface = surface ?? defaults.baselineSurface\n const selectedRunDir = runDir ?? defaults.runDir ?? `mem://defineAgentEval-${Date.now()}`\n const selectedStorage =\n campaignOpts.storage ??\n defaultEvaluateOptions.storage ??\n (selectedRunDir.startsWith('mem://') ? inMemoryCampaignStorage() : undefined)\n const evalOptions: RunEvalOptions<TScenario, TArtifact> = {\n ...defaultEvaluateOptions,\n ...campaignOpts,\n ...(selectedStorage ? { storage: selectedStorage } : {}),\n runDir: selectedRunDir,\n scenarios: scenarios ?? defaults.scenarios,\n dispatch: (scenario, ctx) => selectedAgent(selectedSurface, scenario, ctx),\n judges: evaluateJudges(judges, judge ?? defaults.judge),\n }\n if (evalOptions.reps !== undefined)\n evalOptions.reps = requirePositiveInteger(evalOptions.reps, 'reps')\n return runEval<TScenario, TArtifact>(evalOptions)\n },\n\n async improve(opts = {}) {\n const {\n budget: budgetOverride,\n hostedTenant: hostedTenantOverride,\n ...topLevelOverrides\n } = opts\n const merged = mergeDefined(defaults, topLevelOverrides)\n const budget = mergeBudget(defaults.budget, budgetOverride)\n const hostedTenant = mergeHostedTenant(defaults.hostedTenant, hostedTenantOverride)\n return selfImprove<TScenario, TArtifact>({\n ...merged,\n ...(budget ? { budget } : {}),\n ...(hostedTenant ? { hostedTenant } : {}),\n })\n },\n }\n}\n\ntype SharedEvaluateDefaults<TScenario extends Scenario, TArtifact> = Omit<\n RunEvalOptions<TScenario, TArtifact>,\n 'dispatch' | 'judges' | 'runDir' | 'scenarios'\n>\n\nfunction evaluateDefaults<TScenario extends Scenario, TArtifact>(\n defaults: DefineAgentEvalOptions<TScenario, TArtifact>,\n): SharedEvaluateDefaults<TScenario, TArtifact> {\n const out: SharedEvaluateDefaults<TScenario, TArtifact> = {}\n if (defaults.storage) out.storage = defaults.storage\n if (defaults.labeledStore) out.labeledStore = defaults.labeledStore\n if (defaults.captureSource) out.captureSource = defaults.captureSource\n if (defaults.cellPlacement) out.cellPlacement = defaults.cellPlacement\n if (defaults.expectUsage) out.expectUsage = defaults.expectUsage\n if (defaults.budget?.dollars !== undefined) out.costCeiling = defaults.budget.dollars\n if (defaults.budget?.maxConcurrency !== undefined)\n out.maxConcurrency = defaults.budget.maxConcurrency\n if (defaults.budget?.reps !== undefined)\n out.reps = requirePositiveInteger(defaults.budget.reps, 'budget.reps')\n return out\n}\n\nfunction mergeBudget(\n defaults: SelfImproveBudget | undefined,\n overrides: Partial<SelfImproveBudget> | undefined,\n): SelfImproveBudget | undefined {\n const merged = mergeOptionalObject(defaults, overrides)\n if (merged?.reps !== undefined) merged.reps = requirePositiveInteger(merged.reps, 'budget.reps')\n return merged\n}\n\nfunction mergeHostedTenant(\n defaults: HostedTenant | undefined,\n overrides: Partial<HostedTenant> | undefined,\n): HostedTenant | undefined {\n const merged = mergeOptionalObject(defaults, overrides)\n if (!merged) return undefined\n if (!merged.endpoint?.trim() || !merged.apiKey?.trim() || !merged.tenantId?.trim()) {\n throw new Error(\n 'defineAgentEval.improve: hostedTenant requires endpoint, apiKey, and tenantId after merging defaults and overrides',\n )\n }\n return merged\n}\n\nfunction mergeDefined<T extends object>(defaults: T, overrides: Partial<T> | undefined): T {\n if (!overrides) return defaults\n const merged = { ...defaults } as Record<string, unknown>\n for (const [key, value] of Object.entries(overrides)) {\n if (value !== undefined) merged[key] = value\n }\n return merged as T\n}\n\nfunction mergeOptionalObject<T extends object>(\n defaults: T | undefined,\n overrides: Partial<T> | undefined,\n): T | undefined {\n if (!defaults && !overrides) return undefined\n return mergeDefined(defaults ?? ({} as T), overrides)\n}\n\nfunction evaluateJudges<TArtifact, TScenario extends Scenario>(\n judges: JudgeConfig<TArtifact, TScenario>[] | undefined,\n defaultJudge: JudgeConfig<TArtifact, TScenario>,\n): JudgeConfig<TArtifact, TScenario>[] {\n if (judges !== undefined) {\n if (judges.length === 0) {\n throw new Error('defineAgentEval.evaluate: judges must not be empty')\n }\n return judges\n }\n return [defaultJudge]\n}\n\nfunction requirePositiveInteger(value: number, field: string): number {\n if (!Number.isInteger(value) || value < 1) {\n throw new Error(`defineAgentEval: ${field} must be a positive integer`)\n }\n return value\n}\n","import type { AgentCandidateFixedSpend } from '@tangle-network/agent-interface'\n\nexport function addFixedSpend(\n left: AgentCandidateFixedSpend,\n right: AgentCandidateFixedSpend,\n): AgentCandidateFixedSpend {\n return {\n inputTokens: left.inputTokens + right.inputTokens,\n outputTokens: left.outputTokens + right.outputTokens,\n cachedInputTokens: left.cachedInputTokens + right.cachedInputTokens,\n reasoningTokens: left.reasoningTokens + right.reasoningTokens,\n modelCalls: left.modelCalls + right.modelCalls,\n costUsdNanos: left.costUsdNanos + right.costUsdNanos,\n costProvenance:\n left.costProvenance === 'observed' && right.costProvenance === 'observed'\n ? 'observed'\n : 'estimated',\n }\n}\n","import { mapConcurrentRange } from '../concurrency'\n\nexport interface MapPairedConcurrentOptions<T> {\n count: number\n maxConcurrency: number\n label: string\n signal?: AbortSignal\n map(index: number, arm: 'baseline' | 'candidate', signal: AbortSignal): Promise<T>\n}\n\n/** Map both arms while bounding the actual executions, not the number of pairs. */\nexport async function mapPairedConcurrent<T>(\n options: MapPairedConcurrentOptions<T>,\n): Promise<Array<{ baseline: T; candidate: T }>> {\n if (!Number.isSafeInteger(options.count) || options.count < 0) {\n throw new Error(`${options.label} pair count must be a non-negative integer`)\n }\n if (options.count > Math.floor(Number.MAX_SAFE_INTEGER / 2)) {\n throw new Error(`${options.label} pair count is too large to schedule both arms`)\n }\n const executions = await mapConcurrentRange({\n count: options.count * 2,\n maxConcurrency: options.maxConcurrency,\n label: options.label,\n ...(options.signal ? { signal: options.signal } : {}),\n map(flatIndex, signal) {\n const index = Math.floor(flatIndex / 2)\n const arm = flatIndex % 2 === 0 ? 'baseline' : 'candidate'\n return options.map(index, arm, signal)\n },\n })\n\n return Array.from({ length: options.count }, (_, index) => ({\n baseline: executions[index * 2]!,\n candidate: executions[index * 2 + 1]!,\n }))\n}\n","import {\n type CostChannel,\n CostLedger,\n type CostLedgerHandle,\n type CostProvenance,\n type CostReceiptInput,\n} from '../cost-ledger'\nimport { mapPairedConcurrent } from './concurrent-map'\n\nexport interface PaidPairedMeasurementResult<T> {\n measurements: Array<{ baseline: T; candidate: T }>\n wallDurationMs: number\n cost: Exclude<CostProvenance, { kind: 'uncaptured' }>\n}\n\nexport interface RunPaidPairedMeasurementOptions<T> {\n count: number\n maxConcurrency: number\n label: string\n budgetUsd?: number\n costLedger?: CostLedgerHandle\n maximumCostUsd: number\n call: {\n callId: string\n channel: CostChannel\n phase: string\n actor: string\n model: string\n tags?: Record<string, string>\n }\n signal?: AbortSignal\n execute(index: number, arm: 'baseline' | 'candidate', signal: AbortSignal): Promise<T>\n receipt(measurements: Array<{ baseline: T; candidate: T }>): CostReceiptInput\n}\n\n/**\n * Reserve the complete signed suite before its first cell starts.\n *\n * The host executor receives each task's signed cap through `execute`; this\n * batch reservation prevents a complete comparison from turning into a partial\n * one after earlier analysis or search has used the remaining budget.\n */\nexport async function runPaidPairedMeasurement<T>(\n options: RunPaidPairedMeasurementOptions<T>,\n): Promise<PaidPairedMeasurementResult<T>> {\n assertNonNegativeFinite(options.maximumCostUsd, 'maximumCostUsd')\n const costLedger = resolveCostLedger(options)\n const startedAt = performance.now()\n const paid = await costLedger.runPaidCall({\n callId: options.call.callId,\n channel: options.call.channel,\n phase: options.call.phase,\n actor: options.call.actor,\n model: options.call.model,\n maximumCharge: { externallyEnforcedMaximumUsd: options.maximumCostUsd },\n ...(options.call.tags ? { tags: options.call.tags } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n execute: async (signal) =>\n await mapPairedConcurrent({\n count: options.count,\n maxConcurrency: options.maxConcurrency,\n label: options.label,\n signal,\n map: options.execute,\n }),\n receipt: options.receipt,\n })\n const wallDurationMs = performance.now() - startedAt\n if (!paid.succeeded) throw paid.error\n if (paid.receipt.costUnknown) {\n throw new Error(`${options.label} did not capture the complete measurement cost`)\n }\n return {\n measurements: paid.value,\n wallDurationMs,\n cost:\n paid.receipt.actualCostUsd === undefined\n ? { kind: 'estimated', usd: paid.receipt.costUsd }\n : { kind: 'observed', usd: paid.receipt.costUsd },\n }\n}\n\nfunction resolveCostLedger(options: RunPaidPairedMeasurementOptions<unknown>): CostLedgerHandle {\n if (options.budgetUsd === undefined) return options.costLedger ?? new CostLedger()\n assertNonNegativeFinite(options.budgetUsd, 'budgetUsd')\n if (!options.costLedger) {\n throw new Error(`${options.label} with a policy budget requires one shared CostLedger`)\n }\n if (options.costLedger.costCeilingUsd !== options.budgetUsd) {\n throw new Error(`${options.label} CostLedger ceiling must equal the frozen policy budget`)\n }\n return options.costLedger\n}\n\nfunction assertNonNegativeFinite(value: number, label: string): void {\n if (!Number.isFinite(value) || value < 0) {\n throw new Error(`${label} must be a non-negative finite number`)\n }\n}\n","import {\n type AgentCandidateBenchmarkCellRef,\n type AgentCandidateBenchmarkSuiteInputs,\n type AgentCandidateBenchmarkTask,\n type AgentCandidateBenchmarkTaskMaterial,\n type AgentCandidateBundle,\n type AgentCandidateEvaluationPolicy,\n type AgentCandidateExperiment,\n type AgentCandidateExperimentMaterial,\n type AgentCandidateExperimentMeasurement,\n type AgentCandidateFixedSpend,\n type AgentImprovementCost,\n type AgentImprovementMeasuredComparison,\n agentCandidateBenchmarkSuiteSchema,\n agentCandidateBenchmarkTaskSchema,\n agentCandidateBundleSchema,\n agentCandidateEvaluationPolicySchema,\n agentCandidateExperimentSchema,\n agentImprovementMeasuredComparisonSchema,\n type CandidateExecutionEvidence,\n candidateExecutionEvidenceSchema,\n canonicalCandidateDigest,\n numbersApproximatelyEqual,\n omitTopLevelDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { heldoutSignificance } from '../campaign/gates/statistical-heldout'\nimport type { CostLedgerHandle, CostReceiptInput } from '../cost-ledger'\nimport { decidePairedPromotion } from '../paired-promotion-decision'\nimport { pairedBootstrap } from '../statistics'\nimport { addFixedSpend } from './fixed-spend'\nimport { runPaidPairedMeasurement } from './paid-paired-measurement'\n\nexport interface SealCandidateBenchmarkSuiteOptions {\n tasks: [AgentCandidateBenchmarkTask, ...AgentCandidateBenchmarkTask[]]\n reps: number\n seeds: [number, ...number[]]\n}\n\nexport interface CandidateExperimentExecutionInput {\n experiment: AgentCandidateExperiment\n arm: 'baseline' | 'candidate'\n bundle: AgentCandidateBundle\n task: AgentCandidateBenchmarkTask\n benchmarkCell: AgentCandidateBenchmarkCellRef\n seed: number\n signal?: AbortSignal\n}\n\nexport interface RunCandidateExperimentOptions {\n experiment: AgentCandidateExperiment\n execute(input: CandidateExperimentExecutionInput): Promise<CandidateExecutionEvidence>\n /** Maximum number of simultaneous execute calls across both arms. */\n maxConcurrency?: number\n /** Shared run budget that also accounts for analysis and candidate search. */\n costLedger?: CostLedgerHandle\n signal?: AbortSignal\n}\n\nexport interface CandidateExperimentRun {\n measurements: AgentCandidateExperimentMeasurement[]\n measurement: {\n wallDurationMs: number\n cost: AgentImprovementCost\n }\n}\n\nexport interface CompareCandidateExperimentOptions {\n experiment: AgentCandidateExperiment\n measurements: AgentCandidateExperimentMeasurement[]\n preparation: {\n wallDurationMs: number\n cost: AgentImprovementCost\n }\n measurement: CandidateExperimentRun['measurement']\n runId: string\n candidate?: AgentImprovementMeasuredComparison['candidate']\n generationsExplored?: number\n metadata?: AgentImprovementMeasuredComparison['metadata']\n}\n\n/** One exact baseline/candidate observation of the same held-out cell. */\nexport interface PairedMeasurement<TRun> {\n cellId: string\n baseline: TRun\n candidate: TRun\n}\n\n/** Maps a product-owned run receipt into the measurements required for a fair paired decision. */\nexport interface PairedMeasurementAdapter<TRun> {\n score(run: TRun): number\n dimensions(run: TRun): readonly { name: string; score: number }[]\n costUsd(run: TRun): number\n costProvenance(run: TRun): AgentImprovementCost['provenance']\n latencyMs(run: TRun): number\n completed(run: TRun): boolean\n passed(run: TRun): boolean\n}\n\nexport interface EvaluatePairedMeasurementsOptions<TRun> {\n measurements: readonly PairedMeasurement<TRun>[]\n policy: AgentCandidateEvaluationPolicy\n adapter: PairedMeasurementAdapter<TRun>\n /** Whether both arms use the same scorer family as the promotion decision. */\n sharedScorerChannel: boolean\n /** Analysis and candidate-search spend that belongs to the same frozen budget. */\n preparationCost?: AgentImprovementCost\n /** Settled aggregate receipt for this exact paired suite, when an executor provides one. */\n measurementCost?: AgentImprovementCost\n}\n\n/** Statistical and operational result derived from complete paired receipts. */\nexport type PairedMeasurementEvaluation = Pick<\n AgentImprovementMeasuredComparison,\n 'overall' | 'objectives' | 'decision' | 'power'\n> & {\n measurementCost: AgentImprovementCost\n totalCost: AgentImprovementCost\n measurementWorkDurationMs: number\n}\n\n/** Content-address one task before any measured execution can see it. */\nexport function sealCandidateBenchmarkTask(\n material: AgentCandidateBenchmarkTaskMaterial,\n): AgentCandidateBenchmarkTask {\n return agentCandidateBenchmarkTaskSchema.parse({\n ...material,\n digest: canonicalCandidateDigest(material),\n })\n}\n\n/** Freeze task order, repetitions, and every seed before either arm runs. */\nexport function sealCandidateBenchmarkSuite(\n options: SealCandidateBenchmarkSuiteOptions,\n): AgentCandidateBenchmarkSuiteInputs {\n for (const task of options.tasks) verifyCandidateBenchmarkTask(task)\n const material = {\n kind: 'agent-candidate-benchmark-suite' as const,\n digestAlgorithm: 'rfc8785-sha256' as const,\n taskDigests: options.tasks.map((task) => task.digest) as [Sha256Digest, ...Sha256Digest[]],\n reps: options.reps,\n seeds: options.seeds,\n }\n const suite = agentCandidateBenchmarkSuiteSchema.parse({\n ...material,\n digest: canonicalCandidateDigest(material),\n })\n return { suite, tasks: options.tasks }\n}\n\n/** Freeze both complete agent states and their exact held-out work. */\nexport function sealCandidateExperiment(\n material: AgentCandidateExperimentMaterial,\n): AgentCandidateExperiment {\n const parsed = agentCandidateExperimentSchema.parse({\n ...material,\n digest: canonicalCandidateDigest(material),\n })\n return verifyCandidateExperiment(parsed)\n}\n\nexport function verifyCandidateExperiment(input: unknown): AgentCandidateExperiment {\n const experiment = agentCandidateExperimentSchema.parse(input)\n verifySelfAddressed(experiment, 'candidate experiment')\n verifyBundle(experiment.baseline, 'baseline bundle')\n verifyBundle(experiment.candidate, 'candidate bundle')\n if (experiment.baseline.digest === experiment.candidate.digest) {\n throw new Error('candidate experiment baseline and candidate bundles are identical')\n }\n verifyCandidateBenchmarkSuiteInputs(experiment.benchmark)\n return experiment\n}\n\n/** Execute each signed cell for both arms. The callback is Runtime's one executor. */\nexport async function runCandidateExperiment(\n options: RunCandidateExperimentOptions,\n): Promise<CandidateExperimentRun> {\n const experiment = verifyCandidateExperiment(options.experiment)\n const { suite, tasks } = experiment.benchmark\n const run = await runPaidPairedMeasurement({\n count: suite.taskDigests.length * suite.reps,\n maxConcurrency: options.maxConcurrency ?? 2,\n label: 'candidate experiment',\n budgetUsd: experiment.policy.budgetUsd,\n ...(options.costLedger ? { costLedger: options.costLedger } : {}),\n maximumCostUsd: candidateMeasurementMaximumCostUsd(experiment),\n call: {\n callId: `candidate-measurement:${experiment.digest}`,\n channel: 'measurement',\n phase: 'heldout',\n actor: experiment.digest,\n model: candidateMeasurementModel(experiment),\n tags: { experimentDigest: experiment.digest },\n },\n ...(options.signal ? { signal: options.signal } : {}),\n async execute(index, arm, signal) {\n const taskIndex = Math.floor(index / suite.reps)\n const repetition = index % suite.reps\n const task = tasks[taskIndex]\n const seed = suite.seeds[index]\n if (!task || seed === undefined) {\n throw new Error(`candidate experiment cell ${index} has no signed task or seed`)\n }\n const benchmarkCell = {\n suiteDigest: suite.digest,\n taskIndex,\n repetition,\n }\n return verifyExecutionEvidence(\n await options.execute({\n experiment,\n arm,\n bundle: experiment[arm],\n task,\n benchmarkCell,\n seed,\n signal,\n }),\n )\n },\n receipt(measurements) {\n return candidateMeasurementCostReceipt(measurements, candidateMeasurementModel(experiment))\n },\n })\n return {\n measurements: run.measurements.map((measurement, index) =>\n verifyMeasurement(experiment, measurement, index),\n ),\n measurement: {\n wallDurationMs: run.wallDurationMs,\n cost: { usd: run.cost.usd, provenance: run.cost.kind },\n },\n }\n}\n\n/**\n * Calculate the shared paired decision from any complete receipt shape.\n *\n * Callers still own sealing their tasks, verifying each receipt against its\n * expected arm and state, and proving every expected cell exists. This function\n * only validates the projected measurements and derives their shared decision.\n */\nexport function evaluatePairedMeasurements<TRun>(\n options: EvaluatePairedMeasurementsOptions<TRun>,\n): PairedMeasurementEvaluation {\n if (options.measurements.length === 0) {\n throw new Error('paired measurement evaluation requires at least one paired cell')\n }\n const preparationCost = options.preparationCost ?? { usd: 0, provenance: 'observed' as const }\n if (!Number.isFinite(preparationCost.usd) || preparationCost.usd < 0) {\n throw new Error('paired measurement evaluation preparation cost must be a non-negative number')\n }\n if (typeof options.sharedScorerChannel !== 'boolean') {\n throw new Error('paired measurement evaluation sharedScorerChannel must be a boolean')\n }\n const policy = agentCandidateEvaluationPolicySchema.parse(options.policy)\n const measurements = options.measurements.map((measurement, index) =>\n projectPairedMeasurement(measurement, index, options.adapter),\n )\n const cellIds = measurements.map((measurement) => measurement.cellId)\n if (new Set(cellIds).size !== cellIds.length) {\n throw new Error('paired measurement evaluation cell ids must be unique')\n }\n const dimensions = sharedProjectedDimensions(measurements)\n const baselineScores = measurements.map((measurement) => measurement.baseline.score)\n const candidateScores = measurements.map((measurement) => measurement.candidate.score)\n const {\n confidenceLevel: confidence,\n resamples,\n bootstrapSeed,\n deltaThreshold,\n minProductiveRuns,\n budgetUsd,\n criticalDimensions,\n regressionTolerance,\n } = policy\n const significance = heldoutSignificance(\n { before: baselineScores, after: candidateScores, cellIds },\n {\n confidence,\n resamples,\n seed: bootstrapSeed,\n statistic: 'mean',\n deltaThreshold,\n minProductiveRuns,\n },\n )\n const overall = measuredEstimate(baselineScores, candidateScores, {\n confidence,\n resamples,\n seed: bootstrapSeed,\n })\n const objectives: AgentImprovementMeasuredComparison['objectives'] = [\n {\n kind: 'objective',\n name: 'benchmark-score',\n direction: 'higher-is-better',\n unit: 'score',\n availability: 'measured',\n ...overall,\n },\n ...dimensions.map((name, index) => ({\n kind: 'dimension' as const,\n objective: 'benchmark-score',\n name,\n direction: 'higher-is-better' as const,\n unit: 'score' as const,\n availability: 'measured' as const,\n ...measuredEstimate(\n measurements.map((measurement) => dimensionScore(measurement.baseline, name)),\n measurements.map((measurement) => dimensionScore(measurement.candidate, name)),\n {\n confidence,\n resamples,\n seed: bootstrapSeed + index + 1,\n },\n ),\n })),\n ]\n const cost = measuredEstimate(\n measurements.map((measurement) => measurement.baseline.costUsd),\n measurements.map((measurement) => measurement.candidate.costUsd),\n {\n confidence,\n resamples,\n seed: bootstrapSeed + dimensions.length + 1,\n },\n )\n const latency = measuredEstimate(\n measurements.map((measurement) => measurement.baseline.latencyMs),\n measurements.map((measurement) => measurement.candidate.latencyMs),\n {\n confidence,\n resamples,\n seed: bootstrapSeed + dimensions.length + 2,\n },\n )\n objectives.push(\n {\n kind: 'cost',\n name: 'cost',\n direction: 'lower-is-better',\n unit: 'usd',\n availability: 'measured',\n ...cost,\n },\n {\n kind: 'latency',\n name: 'latency',\n direction: 'lower-is-better',\n unit: 'milliseconds',\n availability: 'measured',\n ...latency,\n },\n )\n\n const power = observedPairedPrecision({\n baselineScores,\n candidateScores,\n delta: overall.delta,\n lowerBound: overall.confidenceInterval.lower,\n deltaThreshold,\n minProductiveRuns: significance.minimumRequired,\n confidence,\n sharedScorerChannel: options.sharedScorerChannel,\n })\n const powerSufficient = power.sufficient\n const guardedDimensions = new Set(criticalDimensions)\n const missingCriticalDimensions = criticalDimensions.filter(\n (dimension) => !dimensions.includes(dimension),\n )\n // The dimension floor fires on EITHER burden of proof, because the interval\n // arm alone fails OPEN on exactly the shape a safety dimension lands in.\n // `regressionTolerance` is positive, so an interval pinned at [0, 0] — which\n // is what a pass/fail dimension gives whenever its pairs are concordant, and\n // what a percentile bootstrap of the mean gives whenever every delta is\n // identical — never satisfies `lower < -tolerance`, and a real regression is\n // reported as no regression. `decidePairedPromotion` on the reversed arms\n // adds the proven-drop path: a two-point dimension is judged on Tango's score\n // interval, which is valid at the nonzero margin the tolerance creates.\n const regressionProven = new Set(\n dimensions.filter((name) => {\n if (!guardedDimensions.has(name)) return false\n const baselineDim = measurements.map((m) => dimensionScore(m.baseline, name))\n const candidateDim = measurements.map((m) => dimensionScore(m.candidate, name))\n return decidePairedPromotion(candidateDim, baselineDim, {\n confidence,\n resamples,\n statistic: 'mean',\n seed: bootstrapSeed,\n threshold: regressionTolerance,\n minPairs: minProductiveRuns,\n }).promote\n }),\n )\n const regressions = objectives.filter(\n (objective) =>\n objective.kind === 'dimension' &&\n guardedDimensions.has(objective.name) &&\n objective.availability === 'measured' &&\n (objective.confidenceInterval.lower < -regressionTolerance ||\n regressionProven.has(objective.name)),\n )\n const measurementCostUsd = measurements.reduce(\n (sum, measurement) => sum + measurement.baseline.costUsd + measurement.candidate.costUsd,\n 0,\n )\n const measurementWorkDurationMs = measurements.reduce(\n (sum, measurement) => sum + measurement.baseline.latencyMs + measurement.candidate.latencyMs,\n 0,\n )\n const completedRuns = measurements.flatMap((measurement) => [\n measurement.baseline,\n measurement.candidate,\n ])\n const incompleteRuns = completedRuns.filter((run) => !run.completed)\n // FAILED is not REGRESSED, and the gate must ship on the second one.\n //\n // The blocking bar used to be `!candidate.passed` on any cell, i.e. the\n // candidate had to pass EVERY benchmark task. On a benchmark hard enough to\n // be worth running, nothing passes everything, so the bar was unreachable.\n //\n // The demonstration is the synthetic case `repairedNotRegressed(8)` in this\n // file's tests: baseline mean 0.3339, candidate mean 0.8685, paired delta\n // +0.5346 — held with \"candidate failed 2 benchmark tasks\", where both were\n // tasks the BASELINE failed too. An improvement reported as a defect.\n //\n // Stated precisely because an earlier draft of this comment was not: that case\n // is CONSTRUCTED, not observed. No live run of this gate is on disk, and no\n // arm of the work that found this defect ever called a model. The argument for\n // the change is the unreachable bar itself, which is visible in the predicate;\n // it does not rest on a measured candidate, and none should be claimed here.\n //\n // The consequence still holds and is the reason this matters: an improvement\n // null measured through the OLD gate cannot be read as evidence that\n // improvement does not work, because the gate could reject winners.\n //\n // The honest bar is improvement WITHOUT regression. The improvement half is\n // already carried by `paired-significance` (the lift must clear the threshold\n // with statistical evidence) and the quality half by `critical-dimensions`.\n // What was missing here is the per-task regression: a cell the baseline\n // PASSED and the candidate now fails. The baseline arm is already projected\n // through the same `adapter.passed`, so the comparison needs no new evidence —\n // it was available and simply not read.\n //\n // The three-way split is retained (not just the regression count) so a future\n // reader can tell a gate artifact from a real null: `repaired` is the work the\n // candidate did, `shared` is the work neither arm can do, and only `regressed`\n // blocks.\n const regressedTasks = measurements.filter(\n (measurement) => !measurement.candidate.passed && measurement.baseline.passed,\n )\n const sharedTaskFailures = measurements.filter(\n (measurement) => !measurement.candidate.passed && !measurement.baseline.passed,\n )\n const repairedTasks = measurements.filter(\n (measurement) => measurement.candidate.passed && !measurement.baseline.passed,\n )\n const derivedMeasurementCost: AgentImprovementCost = {\n usd: measurementCostUsd,\n provenance: measurements.every(\n (measurement) =>\n measurement.baseline.costProvenance === 'observed' &&\n measurement.candidate.costProvenance === 'observed',\n )\n ? 'observed'\n : 'estimated',\n }\n const measurementCost = options.measurementCost ?? derivedMeasurementCost\n assertKnownCost(measurementCost, 'paired measurement cost')\n if (\n options.measurementCost !== undefined &&\n (measurementCost.provenance !== derivedMeasurementCost.provenance ||\n !numbersApproximatelyEqual(measurementCost.usd, derivedMeasurementCost.usd))\n ) {\n throw new Error('paired measurement cost does not match its signed receipts')\n }\n const totalCost: AgentImprovementCost = {\n usd: preparationCost.usd + measurementCost.usd,\n provenance:\n preparationCost.provenance === 'observed' && measurementCost.provenance === 'observed'\n ? 'observed'\n : 'estimated',\n }\n const budgetPassed =\n budgetUsd === undefined ||\n totalCost.usd < budgetUsd ||\n numbersApproximatelyEqual(totalCost.usd, budgetUsd)\n const checks = [\n { name: 'paired-significance', passed: significance.significant },\n { name: 'paired-precision', passed: powerSufficient },\n { name: 'all-runs-completed', passed: incompleteRuns.length === 0 },\n // Renamed from `candidate-task-pass` with the semantics. A consumer keyed on\n // the old name now sees a MISSING check rather than a silently different\n // one, which is the failure mode worth having.\n { name: 'no-task-regression', passed: regressedTasks.length === 0 },\n {\n name: 'critical-dimensions',\n passed: regressions.length === 0 && missingCriticalDimensions.length === 0,\n },\n { name: 'budget', passed: budgetPassed },\n ]\n const shipped = checks.every((check) => check.passed)\n const hardFailure =\n incompleteRuns.length > 0 ||\n regressedTasks.length > 0 ||\n regressions.length > 0 ||\n missingCriticalDimensions.length > 0 ||\n !budgetPassed\n const reasons = [\n ...(significance.significant ? [] : [significanceReason(significance, deltaThreshold)]),\n ...(powerSufficient || significance.fewRuns ? [] : [power.reason]),\n ...(regressions.length === 0\n ? []\n : [`critical dimensions regressed: ${regressions.map((entry) => entry.name).join(', ')}`]),\n ...(missingCriticalDimensions.length === 0\n ? []\n : [`critical dimensions missing: ${missingCriticalDimensions.join(', ')}`]),\n ...(incompleteRuns.length === 0\n ? []\n : [`${incompleteRuns.length} benchmark executions did not exit successfully`]),\n ...(regressedTasks.length === 0\n ? []\n : [\n `candidate regressed ${regressedTasks.length} benchmark ` +\n `${regressedTasks.length === 1 ? 'task' : 'tasks'} the baseline passed: ` +\n regressedTasks.map((measurement) => measurement.cellId).join(', '),\n ]),\n ...(budgetPassed ? [] : [`total cost ${totalCost.usd} exceeded budget ${budgetUsd}`]),\n // Non-blocking accounting, emitted on any outcome that did NOT ship and has\n // tasks both arms failed — so a `hold` (whatever caused it) and also a\n // `need_more_work`. It lets an operator reading a refusal tell \"the\n // candidate is bad\" from \"the benchmark has tasks neither arm solves\". The\n // `shipped` term is what keeps it off a ship, where it could be misread as a\n // blocking reason.\n ...(shipped || sharedTaskFailures.length === 0\n ? []\n : [\n `benchmark tasks: ${repairedTasks.length} repaired, ${regressedTasks.length} regressed, ` +\n `${sharedTaskFailures.length} still failing that the baseline also failed`,\n ]),\n ]\n\n return {\n overall: {\n name: 'composite',\n direction: 'higher-is-better',\n unit: 'score',\n ...overall,\n },\n objectives,\n decision: {\n outcome: shipped\n ? 'ship'\n : hardFailure\n ? 'hold'\n : // A degenerate paired sample is a MEASUREMENT that cannot decide, not\n // a candidate that lost. `hold` sends the operator to build a better\n // candidate; `need_more_work` sends them to the held-out set, which is\n // the only thing that can actually resolve a zero-variance sample.\n significance.fewRuns || !powerSufficient || significance.decision.indeterminate\n ? 'need_more_work'\n : 'hold',\n reasons: reasons.length > 0 ? reasons : ['all measured checks passed'],\n contributingChecks: checks,\n },\n power: {\n sufficient: powerSufficient,\n n: baselineScores.length,\n minimumDetectableDelta: power.minimumDetectableDelta,\n confidenceLevel: confidence,\n scaleAssumed: power.scaleAssumed,\n sharedScorerChannel: options.sharedScorerChannel,\n reason: power.reason,\n },\n measurementCost,\n totalCost,\n measurementWorkDurationMs,\n }\n}\n\n/**\n * Say why the paired significance check refused, reading the interval that\n * ACTUALLY decided.\n *\n * The old string always printed `significance.bootstrap.low`, which is a\n * DIAGNOSTIC bootstrap that on several paths never enters the decision at all.\n * That produced self-contradicting holds — observed live: \"paired interval lower\n * bound 0.6666666666666669 did not clear 0\", where 0.667 plainly clears 0. Three\n * paths where the old string was simply reporting the wrong number:\n *\n * - ZERO-VARIANCE sample. Every paired delta identical ⇒ the resample\n * distribution is a point mass and the interval collapses to [g, g]. The\n * refusal is correct and load-bearing, and the reason has to say so.\n * Under the bounded asymmetric null this repo documents (2 % of pairs drop\n * by 1.0, the rest gain 0.0204, true mean paired delta exactly 0), a\n * constant-positive sample is exactly a sample in which no pair drew the\n * drop, so its frequency is closed-form 0.98^n — 88.6 % at n = 6 and 66.8 %\n * at n = 20. That reconciles with the false-promotion rates measured on the\n * composable gate for the same null, 88.50 % at n = 6 and 65.65 % at n = 20\n * (see {@link decidePairedPromotion} in `src/paired-promotion-decision.ts`);\n * no number here is independently measured, and none needs to be. A\n * constant positive delta is therefore NOT the strongest evidence — it is\n * the signature of a held-out set too small or too uniform to have sampled\n * the tail, and promoting on it would false-promote a true-zero candidate\n * most of the time. No distribution-free bound rescues it either: a\n * Hoeffding 95 % lower bound on a constant +0.667 with scores in [0, 1] is\n * −0.33 at n = 6 and −0.11 at n = 10, first clearing 0 at n = 20. The\n * estimator genuinely cannot express this sample, so the gate says that and\n * routes to `need_more_work` — vary or extend the held-out cells.\n * - TWO-POINT outcome, where the score interval decided and the bootstrap was\n * never consulted.\n * - McNEMAR VETO, where no interval failed at all.\n */\nfunction significanceReason(\n significance: ReturnType<typeof heldoutSignificance>,\n deltaThreshold: number,\n): string {\n if (significance.fewRuns) {\n return `only ${significance.n} paired runs; ${significance.minimumRequired} required`\n }\n const { decision } = significance\n if (decision.indeterminate) {\n return (\n `paired ${decision.statistic} interval is degenerate at [${decision.low}, ${decision.high}] ` +\n `(${decision.indeterminateCause}); a zero-width interval carries no information about its ` +\n `own error, so no threshold can be cleared on it — vary or extend the held-out cells`\n )\n }\n if (decision.exactTestVetoes && decision.mcnemar !== null) {\n return (\n `McNemar's exact test refuses at threshold ${deltaThreshold}: ` +\n `b=${decision.mcnemar.b}, c=${decision.mcnemar.c}, p=${decision.mcnemar.pValue}`\n )\n }\n return (\n `paired ${decision.statistic} interval lower bound ${decision.low} ` +\n `did not clear ${deltaThreshold}.${decision.methodDetail}`\n )\n}\n\n/** Build the only publishable comparison: paired statistics over Runtime receipts. */\nexport function measuredComparisonFromCandidateExperiment(\n options: CompareCandidateExperimentOptions,\n): AgentImprovementMeasuredComparison {\n const experiment = verifyCandidateExperiment(options.experiment)\n const measurements = options.measurements.map((measurement, index) =>\n verifyMeasurement(experiment, measurement, index),\n )\n const expectedN = experiment.benchmark.suite.taskDigests.length * experiment.benchmark.suite.reps\n if (measurements.length !== expectedN) {\n throw new Error(\n `candidate experiment is incomplete (${measurements.length}/${expectedN} paired cells)`,\n )\n }\n verifyStableProfileMaterialization(measurements)\n if (!options.runId.trim()) throw new Error('candidate experiment runId is required')\n assertPhaseAccounting(options.preparation, 'candidate preparation')\n assertPhaseAccounting(options.measurement, 'candidate measurement')\n const evaluation = evaluatePairedMeasurements({\n measurements: measurements.map((measurement, index) => ({\n cellId: cellIds(experiment)[index]!,\n ...measurement,\n })),\n policy: experiment.policy,\n adapter: candidateExecutionEvidenceAdapter,\n sharedScorerChannel: true,\n preparationCost: options.preparation.cost,\n measurementCost: options.measurement.cost,\n })\n const diff = deriveCandidateBundleDiff(experiment)\n const provisional = agentImprovementMeasuredComparisonSchema.parse({\n kind: 'agent-improvement-measured-comparison',\n experiment,\n measurements,\n overall: evaluation.overall,\n objectives: evaluation.objectives,\n ...(options.candidate ? { candidate: options.candidate } : {}),\n decision: evaluation.decision,\n power: evaluation.power,\n provenance: {\n kind: 'agent-eval-loop',\n schema: 'agent-candidate-experiment',\n runId: options.runId,\n recordDigest: canonicalCandidateDigest({}),\n baselineContentHash: experiment.baseline.digest,\n candidateContentHash: experiment.candidate.digest,\n },\n diff,\n evaluation: {\n generationsExplored: options.generationsExplored ?? 0,\n preparation: options.preparation,\n measurement: {\n wallDurationMs: options.measurement.wallDurationMs,\n workDurationMs: evaluation.measurementWorkDurationMs,\n cost: evaluation.measurementCost,\n },\n total: {\n wallDurationMs: options.preparation.wallDurationMs + options.measurement.wallDurationMs,\n cost: evaluation.totalCost,\n },\n },\n ...(options.metadata ? { metadata: options.metadata } : {}),\n })\n const { recordDigest: _recordDigest, ...provenance } = provisional.provenance\n return agentImprovementMeasuredComparisonSchema.parse({\n ...provisional,\n provenance: {\n ...provenance,\n recordDigest: canonicalCandidateDigest({ ...provisional, provenance }),\n },\n })\n}\n\n/** Recompute every statistic and decision from the signed experiment receipts. */\nexport function verifyCandidateExperimentComparison(\n input: unknown,\n): AgentImprovementMeasuredComparison {\n const comparison = agentImprovementMeasuredComparisonSchema.parse(input)\n const recomputed = measuredComparisonFromCandidateExperiment({\n experiment: comparison.experiment,\n measurements: comparison.measurements,\n runId: comparison.provenance.runId,\n ...(comparison.candidate ? { candidate: comparison.candidate } : {}),\n generationsExplored: comparison.evaluation.generationsExplored,\n preparation: comparison.evaluation.preparation,\n measurement: {\n wallDurationMs: comparison.evaluation.measurement.wallDurationMs,\n cost: comparison.evaluation.measurement.cost,\n },\n ...(comparison.metadata ? { metadata: comparison.metadata } : {}),\n })\n if (canonicalCandidateDigest(recomputed) !== canonicalCandidateDigest(comparison)) {\n throw new Error('candidate experiment comparison does not match its Runtime receipts')\n }\n return comparison\n}\n\nfunction candidateMeasurementMaximumCostUsd(experiment: AgentCandidateExperiment): number {\n const maximum = experiment.benchmark.tasks.reduce(\n (sum, task) => sum + task.limits.maxCostUsd * experiment.benchmark.suite.reps * 2,\n 0,\n )\n if (!Number.isFinite(maximum) || maximum < 0) {\n throw new Error('candidate measurement maximum cost is invalid')\n }\n return maximum\n}\n\nfunction candidateMeasurementModel(experiment: AgentCandidateExperiment): string {\n const models = [...new Set(experiment.benchmark.tasks.map((task) => task.model.model))]\n return models.length === 1 ? models[0]! : 'multiple-models'\n}\n\nfunction candidateMeasurementCostReceipt(\n measurements: Array<{\n baseline: CandidateExecutionEvidence\n candidate: CandidateExecutionEvidence\n }>,\n model: string,\n): CostReceiptInput {\n const usage = measurements.reduce<AgentCandidateFixedSpend>(\n (sum, measurement) =>\n addFixedSpend(\n addFixedSpend(sum, combinedUsage(measurement.baseline)),\n combinedUsage(measurement.candidate),\n ),\n {\n inputTokens: 0,\n outputTokens: 0,\n cachedInputTokens: 0,\n reasoningTokens: 0,\n modelCalls: 0,\n costUsdNanos: 0,\n costProvenance: 'observed',\n },\n )\n const costUsd = usage.costUsdNanos / 1_000_000_000\n return {\n model,\n inputTokens: usage.inputTokens,\n outputTokens: usage.outputTokens,\n cachedTokens: usage.cachedInputTokens,\n reasoningTokens: usage.reasoningTokens,\n ...(usage.costProvenance === 'observed'\n ? { actualCostUsd: costUsd }\n : { estimatedCostUsd: costUsd }),\n }\n}\n\nfunction assertPhaseAccounting(\n accounting: CompareCandidateExperimentOptions['preparation'],\n label: string,\n): void {\n if (!Number.isFinite(accounting.wallDurationMs) || accounting.wallDurationMs < 0) {\n throw new Error(`${label} wall duration must be a non-negative number`)\n }\n assertKnownCost(accounting.cost, `${label} cost`)\n}\n\nfunction assertKnownCost(cost: AgentImprovementCost, label: string): void {\n if (!Number.isFinite(cost.usd) || cost.usd < 0) {\n throw new Error(`${label} must be a non-negative number`)\n }\n if (cost.provenance !== 'observed' && cost.provenance !== 'estimated') {\n throw new Error(`${label} provenance must be observed or estimated`)\n }\n}\n\nfunction deriveCandidateBundleDiff(experiment: AgentCandidateExperiment): string {\n const surfaces = ['profile', 'code', 'execution', 'knowledge', 'memory'] as const\n const changed = surfaces.flatMap((surface) => {\n const baseline = experiment.baseline[surface] ?? null\n const candidate = experiment.candidate[surface] ?? null\n const baselineDigest = canonicalCandidateDigest(baseline)\n const candidateDigest = canonicalCandidateDigest(candidate)\n if (baselineDigest === candidateDigest) return []\n return [\n [\n `--- baseline/${surface} (${baselineDigest})`,\n `+++ candidate/${surface} (${candidateDigest})`,\n JSON.stringify({ baseline, candidate }, null, 2),\n ].join('\\n'),\n ]\n })\n if (changed.length === 0) {\n throw new Error('candidate experiment has no changed candidate surface')\n }\n return changed.join('\\n\\n')\n}\n\nexport function verifyCandidateBenchmarkTask(input: unknown): AgentCandidateBenchmarkTask {\n const task = agentCandidateBenchmarkTaskSchema.parse(input)\n verifySelfAddressed(task, 'candidate benchmark task')\n return task\n}\n\nexport function verifyCandidateBenchmarkSuiteInputs(\n input: unknown,\n): AgentCandidateBenchmarkSuiteInputs {\n if (input === null || typeof input !== 'object' || Array.isArray(input)) {\n throw new Error('candidate benchmark suite inputs must be an object')\n }\n const candidate = input as AgentCandidateBenchmarkSuiteInputs\n const suite = verifyCandidateBenchmarkSuite(candidate.suite)\n if (!Array.isArray(candidate.tasks) || candidate.tasks.length !== suite.taskDigests.length) {\n throw new Error('candidate benchmark suite task count does not match its signed digests')\n }\n candidate.tasks.forEach((task, index) => {\n const verified = verifyCandidateBenchmarkTask(task)\n if (verified.digest !== suite.taskDigests[index]) {\n throw new Error(`candidate benchmark task ${index} does not match the signed suite`)\n }\n })\n return { suite, tasks: candidate.tasks }\n}\n\nexport function verifyCandidateBenchmarkSuite(input: unknown) {\n const suite = agentCandidateBenchmarkSuiteSchema.parse(input)\n verifySelfAddressed(suite, 'candidate benchmark suite')\n return suite\n}\n\nfunction verifyBundle(input: unknown, label: string): AgentCandidateBundle {\n const bundle = agentCandidateBundleSchema.parse(input)\n verifySelfAddressed(bundle, label)\n return bundle\n}\n\nfunction verifyMeasurement(\n experiment: AgentCandidateExperiment,\n input: AgentCandidateExperimentMeasurement,\n index: number,\n): AgentCandidateExperimentMeasurement {\n const suite = experiment.benchmark.suite\n const taskIndex = Math.floor(index / suite.reps)\n const repetition = index % suite.reps\n const task = experiment.benchmark.tasks[taskIndex]\n const seed = suite.seeds[index]\n if (!task || seed === undefined) {\n throw new Error(`candidate experiment measurement ${index} is outside the signed suite`)\n }\n const baseline = verifyExecutionEvidence(input.baseline)\n const candidate = verifyExecutionEvidence(input.candidate)\n for (const [arm, evidence] of [\n ['baseline', baseline],\n ['candidate', candidate],\n ] as const) {\n const bundle = experiment[arm]\n const materialization = evidence.materializationReceipt\n const plan = materialization.executionPlan.material\n const runCell = plan.runCell\n verifySelfAddressed(runCell, 'candidate run cell')\n if (\n runCell.experimentDigest !== experiment.digest ||\n runCell.arm !== arm ||\n runCell.bundleDigest !== bundle.digest ||\n runCell.suiteDigest !== suite.digest ||\n runCell.taskDigest !== task.digest ||\n runCell.taskIndex !== taskIndex ||\n runCell.repetition !== repetition ||\n runCell.seed !== seed ||\n runCell.attempt > task.attempt.maxAttempts ||\n materialization.bundleDigest !== bundle.digest ||\n materialization.benchmark.suite.digest !== suite.digest ||\n materialization.benchmark.task.digest !== task.digest ||\n materialization.codeKind !== bundle.code.kind ||\n materialization.profileActivation.profilePlan.material.sourceProfileDigest !==\n canonicalCandidateDigest(bundle.profile) ||\n evidence.receipt.runCellDigest !== runCell.digest ||\n JSON.stringify(materialization.resolvedModel) !== JSON.stringify(task.model)\n ) {\n throw new Error(`candidate experiment measurement ${index} substituted its ${arm} arm`)\n }\n verifyTaskOutcome(task, evidence, index, arm)\n }\n const baselinePlan = baseline.materializationReceipt.executionPlan.material\n const candidatePlan = candidate.materializationReceipt.executionPlan.material\n if (\n baselinePlan.executionId === candidatePlan.executionId ||\n baselinePlan.runCell.digest === candidatePlan.runCell.digest ||\n baseline.materializationReceipt.digest === candidate.materializationReceipt.digest ||\n baseline.receipt.digest === candidate.receipt.digest ||\n baseline.digest === candidate.digest\n ) {\n throw new Error(`candidate experiment measurement ${index} reused one execution across arms`)\n }\n return { baseline, candidate }\n}\n\nfunction verifyExecutionEvidence(input: unknown): CandidateExecutionEvidence {\n const evidence = candidateExecutionEvidenceSchema.parse(input)\n verifySelfAddressed(evidence, 'candidate execution evidence')\n verifySelfAddressed(evidence.materializationReceipt, 'candidate materialization receipt')\n verifySelfAddressed(\n evidence.materializationReceipt.profileActivation,\n 'candidate profile activation',\n )\n verifyMaterialAddressed(\n evidence.materializationReceipt.profileActivation.profilePlan,\n 'candidate profile plan',\n )\n verifyMaterialAddressed(evidence.materializationReceipt.executionPlan, 'candidate execution plan')\n verifySelfAddressed(evidence.receipt, 'candidate run receipt')\n verifyMaterialAddressed(evidence.receipt.modelSettlement, 'candidate model settlement')\n verifyMaterialAddressed(evidence.receipt.taskOutcome, 'candidate task outcome')\n verifyMaterialAddressed(evidence.receipt.benchmarkResult, 'candidate benchmark result')\n return evidence\n}\n\nfunction verifySelfAddressed<T extends { digest: Sha256Digest }>(document: T, label: string): void {\n if (canonicalCandidateDigest(omitTopLevelDigest(document)) !== document.digest) {\n throw new Error(`${label} digest is invalid`)\n }\n}\n\nfunction verifyTaskOutcome(\n task: AgentCandidateBenchmarkTask,\n evidence: CandidateExecutionEvidence,\n index: number,\n arm: 'baseline' | 'candidate',\n): void {\n const outcome = evidence.receipt.taskOutcome.material.outcome\n const result = evidence.receipt.benchmarkResult.material\n const prefix = `candidate experiment measurement ${index} ${arm}`\n if (result.evidence.sha256 === task.grader.artifact.sha256) {\n throw new Error(`${prefix} reused grader bytes as grading evidence`)\n }\n const usage = combinedUsage(evidence)\n const usageChecks: Array<[number, number, string]> = [\n [usage.modelCalls, task.limits.maxModelCalls, 'model calls'],\n [usage.inputTokens, task.limits.maxInputTokens, 'input tokens'],\n [usage.outputTokens, task.limits.maxOutputTokens, 'output tokens'],\n [usage.costUsdNanos, Math.round(task.limits.maxCostUsd * 1_000_000_000), 'cost'],\n ]\n for (const [actual, maximum, label] of usageChecks) {\n if (actual > maximum) {\n throw new Error(`${prefix} ${label} ${actual} exceeds the signed limit ${maximum}`)\n }\n }\n if (outcome.kind !== task.outcome.kind) {\n throw new Error(`${prefix} returned an outcome outside the signed task contract`)\n }\n if (task.outcome.kind === 'output') {\n if (\n outcome.kind !== 'output' ||\n outcome.spec.mediaType !== task.outcome.mediaType ||\n outcome.spec.maxBytes !== task.outcome.maxBytes\n ) {\n throw new Error(`${prefix} changed the signed output contract`)\n }\n return\n }\n const repository = task.repository\n if (\n outcome.kind !== 'workspace' ||\n repository === undefined ||\n outcome.baseRepository.identity !== repository.identity ||\n outcome.baseRepository.rootIdentity !== repository.rootIdentity ||\n outcome.baseRepository.commit !== repository.baseCommit ||\n outcome.baseRepository.tree !== repository.baseTree\n ) {\n throw new Error(`${prefix} did not start from the signed repository state`)\n }\n}\n\nfunction verifyStableProfileMaterialization(\n measurements: AgentCandidateExperimentMeasurement[],\n): void {\n for (const arm of ['baseline', 'candidate'] as const) {\n const expected = measurements[0]?.[arm].materializationReceipt.profileActivation\n if (!expected) throw new Error('candidate experiment contains no profile materialization')\n const expectedDigest = canonicalCandidateDigest({\n profilePlanDigest: expected.profilePlan.digest,\n files: expected.files,\n })\n for (const [index, measurement] of measurements.entries()) {\n const activation = measurement[arm].materializationReceipt.profileActivation\n if (\n canonicalCandidateDigest({\n profilePlanDigest: activation.profilePlan.digest,\n files: activation.files,\n }) !== expectedDigest\n ) {\n throw new Error(\n `candidate experiment measurement ${index} ${arm} materialized a different profile`,\n )\n }\n }\n }\n}\n\nfunction completedSuccessfully(evidence: CandidateExecutionEvidence): boolean {\n const termination = evidence.receipt.termination\n return termination.kind === 'exit' && termination.exitCode === 0\n}\n\nfunction verifyMaterialAddressed(\n evidence: { digest: Sha256Digest; material: unknown },\n label: string,\n): void {\n if (canonicalCandidateDigest(evidence.material) !== evidence.digest) {\n throw new Error(`${label} digest is invalid`)\n }\n}\n\ninterface ProjectedRun {\n score: number\n dimensions: Map<string, number>\n costUsd: number\n costProvenance: AgentImprovementCost['provenance']\n latencyMs: number\n completed: boolean\n passed: boolean\n}\n\ninterface ProjectedPairedMeasurement {\n cellId: string\n baseline: ProjectedRun\n candidate: ProjectedRun\n}\n\nfunction projectPairedMeasurement<TRun>(\n measurement: PairedMeasurement<TRun>,\n index: number,\n adapter: PairedMeasurementAdapter<TRun>,\n): ProjectedPairedMeasurement {\n if (typeof measurement.cellId !== 'string' || !measurement.cellId.trim()) {\n throw new Error(`paired measurement ${index} requires a cell id`)\n }\n return {\n cellId: measurement.cellId,\n baseline: projectRun(measurement.baseline, adapter, `paired measurement ${index} baseline`),\n candidate: projectRun(measurement.candidate, adapter, `paired measurement ${index} candidate`),\n }\n}\n\nfunction projectRun<TRun>(\n run: TRun,\n adapter: PairedMeasurementAdapter<TRun>,\n label: string,\n): ProjectedRun {\n const suppliedDimensions = adapter.dimensions(run)\n if (!Array.isArray(suppliedDimensions)) {\n throw new Error(`${label} dimensions must be an array`)\n }\n const dimensions = new Map<string, number>()\n for (const dimension of suppliedDimensions) {\n if (typeof dimension.name !== 'string' || !dimension.name.trim()) {\n throw new Error(`${label} contains an unnamed dimension`)\n }\n if (dimensions.has(dimension.name)) {\n throw new Error(`${label} repeats dimension '${dimension.name}'`)\n }\n dimensions.set(dimension.name, finiteMeasurement(dimension.score, `${label} ${dimension.name}`))\n }\n const completed = adapter.completed(run)\n const passed = adapter.passed(run)\n if (typeof completed !== 'boolean' || typeof passed !== 'boolean') {\n throw new Error(`${label} completion and pass values must be booleans`)\n }\n const costProvenance = adapter.costProvenance(run)\n if (costProvenance !== 'observed' && costProvenance !== 'estimated') {\n throw new Error(`${label} cost provenance must be observed or estimated`)\n }\n return {\n score: finiteMeasurement(adapter.score(run), `${label} score`),\n dimensions,\n costUsd: nonNegativeMeasurement(adapter.costUsd(run), `${label} cost`),\n costProvenance,\n latencyMs: nonNegativeMeasurement(adapter.latencyMs(run), `${label} latency`),\n completed,\n passed,\n }\n}\n\nfunction sharedProjectedDimensions(measurements: readonly ProjectedPairedMeasurement[]): string[] {\n const expected = [...measurements[0]!.baseline.dimensions.keys()]\n for (const [index, measurement] of measurements.entries()) {\n for (const [arm, run] of [\n ['baseline', measurement.baseline],\n ['candidate', measurement.candidate],\n ] as const) {\n const actual = [...run.dimensions.keys()]\n if (JSON.stringify(actual) !== JSON.stringify(expected)) {\n throw new Error(`paired measurement ${index} ${arm} dimensions do not match the suite`)\n }\n }\n }\n return expected\n}\n\nfunction dimensionScore(run: ProjectedRun, name: string): number {\n const value = run.dimensions.get(name)\n if (value === undefined) throw new Error(`paired measurement is missing dimension '${name}'`)\n return value\n}\n\nfunction measuredEstimate(\n baseline: number[],\n candidate: number[],\n options: { confidence: number; resamples: number; seed: number },\n): Pick<\n AgentImprovementMeasuredComparison['overall'],\n 'baseline' | 'candidate' | 'delta' | 'confidenceInterval' | 'n'\n> {\n const bootstrap = pairedBootstrap(baseline, candidate, {\n confidence: options.confidence,\n resamples: options.resamples,\n statistic: 'mean',\n seed: options.seed,\n })\n const baselineMean = mean(baseline)\n const candidateMean = mean(candidate)\n const delta = candidateMean - baselineMean\n return {\n baseline: baselineMean,\n candidate: candidateMean,\n delta,\n confidenceInterval: {\n level: bootstrap.confidence,\n lower: Math.min(bootstrap.low, delta),\n upper: Math.max(bootstrap.high, delta),\n method: 'paired-bootstrap',\n statistic: 'mean',\n resamples: bootstrap.resamples,\n },\n n: bootstrap.n,\n }\n}\n\nfunction observedPairedPrecision(options: {\n baselineScores: number[]\n candidateScores: number[]\n delta: number\n lowerBound: number\n deltaThreshold: number\n minProductiveRuns: number\n confidence: number\n sharedScorerChannel: boolean\n}): { sufficient: boolean; minimumDetectableDelta: number; scaleAssumed: boolean; reason: string } {\n const n = options.baselineScores.length\n const lowerMargin = Math.max(0, options.delta - options.lowerBound)\n const minimumDetectableDelta = options.deltaThreshold + lowerMargin\n const allScores = [...options.baselineScores, ...options.candidateScores]\n const scaleAssumed = allScores.every((score) => score >= -0.001 && score <= 1.001)\n const headroom = Math.max(0, 1 - mean(options.baselineScores))\n const enoughRuns = n >= options.minProductiveRuns\n const attainable = !scaleAssumed || minimumDetectableDelta <= headroom\n const sufficient = enoughRuns && attainable\n const scorerNote = options.sharedScorerChannel\n ? ' The same scorer evaluated both arms, so scorer bias is not measured.'\n : ''\n\n if (!enoughRuns) {\n return {\n sufficient,\n minimumDetectableDelta,\n scaleAssumed,\n reason: `only ${n} paired runs; ${options.minProductiveRuns} required.${scorerNote}`,\n }\n }\n if (!attainable) {\n return {\n sufficient,\n minimumDetectableDelta,\n scaleAssumed,\n reason:\n `observed paired uncertainty gives a minimum detectable delta of ` +\n `${minimumDetectableDelta.toFixed(3)}, above the remaining score headroom ` +\n `${headroom.toFixed(3)}.${scorerNote}`,\n }\n }\n return {\n sufficient,\n minimumDetectableDelta,\n scaleAssumed,\n reason:\n `observed paired uncertainty gives a minimum detectable delta of ` +\n `${minimumDetectableDelta.toFixed(3)} at ${options.confidence.toFixed(2)} confidence ` +\n `from ${n} runs.${scorerNote}`,\n }\n}\n\nfunction finiteMeasurement(value: number, label: string): number {\n if (!Number.isFinite(value)) throw new Error(`${label} must be finite`)\n return value\n}\n\nfunction nonNegativeMeasurement(value: number, label: string): number {\n if (!Number.isFinite(value) || value < 0) throw new Error(`${label} must be non-negative`)\n return value\n}\n\nconst candidateExecutionEvidenceAdapter: PairedMeasurementAdapter<CandidateExecutionEvidence> = {\n score: (evidence) => evidence.receipt.benchmarkResult.material.score,\n dimensions: (evidence) => evidence.receipt.benchmarkResult.material.dimensions,\n costUsd: costFromEvidence,\n costProvenance: (evidence) => combinedUsage(evidence).costProvenance,\n latencyMs: latencyFromEvidence,\n completed: completedSuccessfully,\n passed: (evidence) => evidence.receipt.benchmarkResult.material.passed,\n}\n\nfunction costFromEvidence(evidence: CandidateExecutionEvidence): number {\n return combinedUsage(evidence).costUsdNanos / 1_000_000_000\n}\n\nfunction latencyFromEvidence(evidence: CandidateExecutionEvidence): number {\n return (\n evidence.receipt.timing.durationMs +\n evidence.receipt.benchmarkResult.material.grading.timing.durationMs\n )\n}\n\nfunction combinedUsage(evidence: CandidateExecutionEvidence): AgentCandidateFixedSpend {\n const candidate = evidence.receipt.modelSettlement.material.usage\n const grader = evidence.receipt.benchmarkResult.material.grading.usage\n return addFixedSpend(candidate, grader)\n}\n\nfunction cellIds(experiment: AgentCandidateExperiment): string[] {\n const { suite, tasks } = experiment.benchmark\n return suite.seeds.map((_, index) => {\n const taskIndex = Math.floor(index / suite.reps)\n const repetition = index % suite.reps\n return `${tasks[taskIndex]?.scenario.id ?? taskIndex}:${repetition}`\n })\n}\n\nfunction mean(values: number[]): number {\n if (values.length === 0) throw new Error('candidate experiment requires measured values')\n return values.reduce((sum, value) => sum + value, 0) / values.length\n}\n","import {\n type AgentCandidateFixedSpend,\n type AgentImprovementCost,\n type AgentProfileImprovementExperiment,\n type AgentProfileImprovementExperimentMaterial,\n type AgentProfileImprovementMeasuredComparison,\n type AgentProfileImprovementMeasurement,\n type AgentProfileImprovementRunCell,\n type AgentProfileImprovementRunReceipt,\n type AgentProfileImprovementSuiteInputs,\n type AgentProfileImprovementTask,\n type AgentProfileImprovementTaskMaterial,\n agentProfileImprovementExperimentSchema,\n agentProfileImprovementMeasuredComparisonSchema,\n agentProfileImprovementRunCellSchema,\n agentProfileImprovementRunReceiptSchema,\n agentProfileImprovementSuiteInputsSchema,\n agentProfileImprovementSuiteSchema,\n agentProfileImprovementTaskSchema,\n canonicalCandidateDigest,\n canonicalCandidateJson,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport type { CostLedgerHandle, CostReceiptInput } from '../cost-ledger'\nimport { addFixedSpend } from './fixed-spend'\nimport { evaluatePairedMeasurements, type PairedMeasurementAdapter } from './measured-comparison'\nimport { runPaidPairedMeasurement } from './paid-paired-measurement'\n\nexport interface SealAgentProfileImprovementSuiteOptions {\n splitDigest: Sha256Digest\n tasks: [AgentProfileImprovementTask, ...AgentProfileImprovementTask[]]\n reps: number\n seeds: [number, ...number[]]\n}\n\nexport interface AgentProfileImprovementExperimentExecutionInput {\n experiment: AgentProfileImprovementExperiment\n arm: 'baseline' | 'candidate'\n stateDigest: Sha256Digest\n task: AgentProfileImprovementTask\n runCell: AgentProfileImprovementRunCell\n seed: number\n signal?: AbortSignal\n}\n\nexport interface RunAgentProfileImprovementExperimentOptions {\n experiment: AgentProfileImprovementExperiment\n execute(\n input: AgentProfileImprovementExperimentExecutionInput,\n ): Promise<AgentProfileImprovementRunReceipt>\n /** Maximum number of simultaneous execute calls across both arms. */\n maxConcurrency?: number\n /** Shared run budget that also accounts for analysis and candidate search. */\n costLedger?: CostLedgerHandle\n signal?: AbortSignal\n}\n\nexport interface AgentProfileImprovementExperimentRun {\n measurements: AgentProfileImprovementMeasurement[]\n measurement: {\n wallDurationMs: number\n cost: AgentImprovementCost\n }\n}\n\nexport interface CompareAgentProfileImprovementExperimentOptions {\n experiment: AgentProfileImprovementExperiment\n measurements: AgentProfileImprovementMeasurement[]\n preparation: {\n wallDurationMs: number\n cost: AgentImprovementCost\n }\n measurement: AgentProfileImprovementExperimentRun['measurement']\n runId: string\n candidate?: AgentProfileImprovementMeasuredComparison['candidate']\n generationsExplored?: number\n metadata?: AgentProfileImprovementMeasuredComparison['metadata']\n}\n\n/** Content-address one held-out profile task before either state can execute it. */\nexport function sealAgentProfileImprovementTask(\n material: AgentProfileImprovementTaskMaterial,\n): AgentProfileImprovementTask {\n return agentProfileImprovementTaskSchema.parse({\n ...material,\n digest: canonicalCandidateDigest(material),\n })\n}\n\n/** Freeze profile task order, repetitions, seeds, and the held-out split. */\nexport function sealAgentProfileImprovementSuite(\n options: SealAgentProfileImprovementSuiteOptions,\n): AgentProfileImprovementSuiteInputs {\n for (const task of options.tasks) verifyAgentProfileImprovementTask(task)\n const material = {\n kind: 'agent-profile-improvement-suite' as const,\n digestAlgorithm: 'rfc8785-sha256' as const,\n splitDigest: options.splitDigest,\n taskDigests: options.tasks.map((task) => task.digest) as [Sha256Digest, ...Sha256Digest[]],\n reps: options.reps,\n seeds: options.seeds,\n }\n const suite = agentProfileImprovementSuiteSchema.parse({\n ...material,\n digest: canonicalCandidateDigest(material),\n })\n return agentProfileImprovementSuiteInputsSchema.parse({\n suite,\n tasks: options.tasks,\n })\n}\n\n/** Freeze the two host-owned profile states and their exact held-out work. */\nexport function sealAgentProfileImprovementExperiment(\n material: AgentProfileImprovementExperimentMaterial,\n): AgentProfileImprovementExperiment {\n return verifyAgentProfileImprovementExperiment({\n ...material,\n digest: canonicalCandidateDigest(material),\n })\n}\n\nexport function verifyAgentProfileImprovementTask(input: unknown): AgentProfileImprovementTask {\n return agentProfileImprovementTaskSchema.parse(input)\n}\n\nexport function verifyAgentProfileImprovementSuiteInputs(\n input: unknown,\n): AgentProfileImprovementSuiteInputs {\n return agentProfileImprovementSuiteInputsSchema.parse(input)\n}\n\nexport function verifyAgentProfileImprovementExperiment(\n input: unknown,\n): AgentProfileImprovementExperiment {\n return agentProfileImprovementExperimentSchema.parse(input)\n}\n\n/**\n * Execute each signed profile cell through the host's one exact-state executor.\n * Eval owns only the cell schedule and receipt checks; the host resolves each\n * state digest and captures its own run, billing, trace, and grader evidence.\n */\nexport async function runAgentProfileImprovementExperiment(\n options: RunAgentProfileImprovementExperimentOptions,\n): Promise<AgentProfileImprovementExperimentRun> {\n const experiment = verifyAgentProfileImprovementExperiment(options.experiment)\n const expectedCount =\n experiment.benchmark.suite.taskDigests.length * experiment.benchmark.suite.reps\n const run = await runPaidPairedMeasurement({\n count: expectedCount,\n maxConcurrency: options.maxConcurrency ?? 2,\n label: 'profile improvement experiment',\n budgetUsd: experiment.policy.budgetUsd,\n ...(options.costLedger ? { costLedger: options.costLedger } : {}),\n maximumCostUsd: profileMeasurementMaximumCostUsd(experiment),\n call: {\n callId: `profile-improvement-measurement:${experiment.digest}`,\n channel: 'measurement',\n phase: 'heldout',\n actor: experiment.executionRef.identity,\n model: profileMeasurementModel(experiment),\n tags: { experimentDigest: experiment.digest, executorDigest: experiment.executionRef.digest },\n },\n ...(options.signal ? { signal: options.signal } : {}),\n async execute(index, arm, signal) {\n const expected = profileExecutionInput(experiment, arm, index, signal)\n const receipt = agentProfileImprovementRunReceiptSchema.parse(await options.execute(expected))\n verifyProfileReceiptContract(receipt, expected, index)\n return receipt\n },\n receipt(measurements) {\n return profileMeasurementCostReceipt(measurements, profileMeasurementModel(experiment))\n },\n })\n return {\n measurements: run.measurements.map((measurement, index) =>\n verifyProfileMeasurement(experiment, measurement, index),\n ),\n measurement: {\n wallDurationMs: run.wallDurationMs,\n cost: { usd: run.cost.usd, provenance: run.cost.kind },\n },\n }\n}\n\n/** Build the only publishable profile comparison from complete host receipts. */\nexport function measuredComparisonFromAgentProfileImprovementExperiment(\n options: CompareAgentProfileImprovementExperimentOptions,\n): AgentProfileImprovementMeasuredComparison {\n const experiment = verifyAgentProfileImprovementExperiment(options.experiment)\n const measurements = options.measurements.map((measurement, index) =>\n verifyProfileMeasurement(experiment, measurement, index),\n )\n const expectedCount =\n experiment.benchmark.suite.taskDigests.length * experiment.benchmark.suite.reps\n if (measurements.length !== expectedCount) {\n throw new Error(\n `profile improvement experiment is incomplete (${measurements.length}/${expectedCount} paired cells)`,\n )\n }\n if (!options.runId.trim()) {\n throw new Error('profile improvement experiment runId is required')\n }\n\n const evaluation = evaluatePairedMeasurements({\n measurements: measurements.map((measurement, index) => ({\n cellId: profileCellId(experiment, index),\n ...measurement,\n })),\n policy: experiment.policy,\n adapter: profileReceiptAdapter,\n sharedScorerChannel: true,\n preparationCost: options.preparation.cost,\n measurementCost: options.measurement.cost,\n })\n const provisional = agentProfileImprovementMeasuredComparisonSchema.parse({\n kind: 'agent-profile-improvement-measured-comparison',\n experiment,\n measurements,\n overall: evaluation.overall,\n objectives: evaluation.objectives,\n ...(options.candidate ? { candidate: options.candidate } : {}),\n decision: evaluation.decision,\n power: evaluation.power,\n provenance: {\n kind: 'agent-eval-loop',\n schema: 'agent-profile-improvement-experiment',\n runId: options.runId,\n recordDigest: canonicalCandidateDigest({}),\n baselineContentHash: experiment.baseline.stateDigest,\n candidateContentHash: experiment.candidate.stateDigest,\n },\n diff: canonicalCandidateJson(experiment.change),\n evaluation: {\n generationsExplored: options.generationsExplored ?? 0,\n preparation: options.preparation,\n measurement: {\n wallDurationMs: options.measurement.wallDurationMs,\n workDurationMs: evaluation.measurementWorkDurationMs,\n cost: evaluation.measurementCost,\n },\n total: {\n wallDurationMs: options.preparation.wallDurationMs + options.measurement.wallDurationMs,\n cost: evaluation.totalCost,\n },\n },\n ...(options.metadata ? { metadata: options.metadata } : {}),\n })\n const { recordDigest: _recordDigest, ...provenance } = provisional.provenance\n return agentProfileImprovementMeasuredComparisonSchema.parse({\n ...provisional,\n provenance: {\n ...provenance,\n recordDigest: canonicalCandidateDigest({ ...provisional, provenance }),\n },\n })\n}\n\n/** Recompute a profile comparison from the exact sealed experiment and receipts. */\nexport function verifyAgentProfileImprovementExperimentComparison(\n input: unknown,\n): AgentProfileImprovementMeasuredComparison {\n const comparison = agentProfileImprovementMeasuredComparisonSchema.parse(input)\n const recomputed = measuredComparisonFromAgentProfileImprovementExperiment({\n experiment: comparison.experiment,\n measurements: comparison.measurements,\n runId: comparison.provenance.runId,\n ...(comparison.candidate ? { candidate: comparison.candidate } : {}),\n generationsExplored: comparison.evaluation.generationsExplored,\n preparation: comparison.evaluation.preparation,\n measurement: {\n wallDurationMs: comparison.evaluation.measurement.wallDurationMs,\n cost: comparison.evaluation.measurement.cost,\n },\n ...(comparison.metadata ? { metadata: comparison.metadata } : {}),\n })\n if (canonicalCandidateDigest(recomputed) !== canonicalCandidateDigest(comparison)) {\n throw new Error('profile improvement comparison does not match its Runtime receipts')\n }\n return comparison\n}\n\nfunction profileMeasurementMaximumCostUsd(experiment: AgentProfileImprovementExperiment): number {\n const pairs = experiment.benchmark.suite.reps\n const maximum = experiment.benchmark.tasks.reduce(\n (sum, task) => sum + task.limits.maxCostUsd * pairs * 2,\n 0,\n )\n if (!Number.isFinite(maximum) || maximum < 0) {\n throw new Error('profile improvement measurement maximum cost is invalid')\n }\n return maximum\n}\n\nfunction profileMeasurementModel(experiment: AgentProfileImprovementExperiment): string {\n const models = [...new Set(experiment.benchmark.tasks.map((task) => task.model.model))]\n return models.length === 1 ? models[0]! : 'multiple-models'\n}\n\nfunction profileMeasurementCostReceipt(\n measurements: Array<{\n baseline: AgentProfileImprovementRunReceipt\n candidate: AgentProfileImprovementRunReceipt\n }>,\n model: string,\n): CostReceiptInput {\n const usage = measurements.reduce<AgentCandidateFixedSpend>(\n (sum, measurement) =>\n addFixedSpend(\n addFixedSpend(sum, combinedProfileUsage(measurement.baseline)),\n combinedProfileUsage(measurement.candidate),\n ),\n {\n inputTokens: 0,\n outputTokens: 0,\n cachedInputTokens: 0,\n reasoningTokens: 0,\n modelCalls: 0,\n costUsdNanos: 0,\n costProvenance: 'observed',\n },\n )\n const costUsd = usage.costUsdNanos / 1_000_000_000\n return {\n model,\n inputTokens: usage.inputTokens,\n outputTokens: usage.outputTokens,\n cachedTokens: usage.cachedInputTokens,\n reasoningTokens: usage.reasoningTokens,\n ...(usage.costProvenance === 'observed'\n ? { actualCostUsd: costUsd }\n : { estimatedCostUsd: costUsd }),\n }\n}\n\nfunction combinedProfileUsage(\n receipt: AgentProfileImprovementRunReceipt,\n): AgentCandidateFixedSpend {\n return addFixedSpend(receipt.usage, receipt.grading.usage)\n}\n\nfunction profileExecutionInput(\n experiment: AgentProfileImprovementExperiment,\n arm: 'baseline' | 'candidate',\n index: number,\n signal: AbortSignal | undefined,\n): AgentProfileImprovementExperimentExecutionInput {\n const { task, taskIndex, repetition, seed } = profileCell(experiment, index)\n const stateDigest = experiment[arm].stateDigest\n const runCellMaterial = {\n kind: 'agent-profile-improvement-run-cell' as const,\n experimentDigest: experiment.digest,\n arm,\n stateDigest,\n suiteDigest: experiment.benchmark.suite.digest,\n taskDigest: task.digest,\n taskIndex,\n repetition,\n seed,\n attempt: 1,\n }\n const runCell = agentProfileImprovementRunCellSchema.parse({\n ...runCellMaterial,\n digest: canonicalCandidateDigest(runCellMaterial),\n })\n return {\n experiment,\n arm,\n stateDigest,\n task,\n runCell,\n seed,\n ...(signal ? { signal } : {}),\n }\n}\n\nfunction verifyProfileMeasurement(\n experiment: AgentProfileImprovementExperiment,\n input: unknown,\n index: number,\n): AgentProfileImprovementMeasurement {\n if (input === null || typeof input !== 'object' || Array.isArray(input)) {\n throw new Error(`profile improvement measurement ${index} must be an object`)\n }\n const material = input as { baseline?: unknown; candidate?: unknown }\n const expectedBaseline = profileExecutionInput(experiment, 'baseline', index, undefined)\n const expectedCandidate = profileExecutionInput(experiment, 'candidate', index, undefined)\n const baseline = agentProfileImprovementRunReceiptSchema.parse(material.baseline)\n const candidate = agentProfileImprovementRunReceiptSchema.parse(material.candidate)\n if (\n baseline.runCell.digest !== expectedBaseline.runCell.digest ||\n candidate.runCell.digest !== expectedCandidate.runCell.digest\n ) {\n throw new Error(`profile improvement measurement ${index} substituted a measured arm`)\n }\n verifyProfileReceiptContract(baseline, expectedBaseline, index)\n verifyProfileReceiptContract(candidate, expectedCandidate, index)\n if (baseline.executionId === candidate.executionId || baseline.digest === candidate.digest) {\n throw new Error(`profile improvement measurement ${index} reused one execution across arms`)\n }\n return { baseline, candidate }\n}\n\nfunction verifyProfileReceiptContract(\n receipt: AgentProfileImprovementRunReceipt,\n expected: AgentProfileImprovementExperimentExecutionInput,\n index: number,\n): void {\n const task = expected.task\n if (\n canonicalCandidateDigest(receipt.resolvedModel) !== canonicalCandidateDigest(task.model) ||\n canonicalCandidateDigest(receipt.limits) !== canonicalCandidateDigest(task.limits) ||\n canonicalCandidateDigest(receipt.grading.grader) !== canonicalCandidateDigest(task.grader)\n ) {\n throw new Error(\n `profile improvement measurement ${index} substituted its ${expected.arm} task contract`,\n )\n }\n if (\n canonicalCandidateDigest(receipt.executionRef) !==\n canonicalCandidateDigest(expected.experiment.executionRef)\n ) {\n throw new Error(\n `profile improvement measurement ${index} substituted its ${expected.arm} executor`,\n )\n }\n}\n\nfunction profileCell(\n experiment: AgentProfileImprovementExperiment,\n index: number,\n): {\n task: AgentProfileImprovementTask\n taskIndex: number\n repetition: number\n seed: number\n} {\n const { suite, tasks } = experiment.benchmark\n const taskIndex = Math.floor(index / suite.reps)\n const repetition = index % suite.reps\n const task = tasks[taskIndex]\n const seed = suite.seeds[index]\n if (!task || seed === undefined) {\n throw new Error(`profile improvement experiment cell ${index} is outside the signed suite`)\n }\n return { task, taskIndex, repetition, seed }\n}\n\nfunction profileCellId(experiment: AgentProfileImprovementExperiment, index: number): string {\n return `${experiment.benchmark.suite.digest}:${index}`\n}\n\nconst profileReceiptAdapter: PairedMeasurementAdapter<AgentProfileImprovementRunReceipt> = {\n score: (receipt) => receipt.grading.score,\n dimensions: (receipt) => receipt.grading.dimensions,\n costUsd: (receipt) =>\n (receipt.usage.costUsdNanos + receipt.grading.usage.costUsdNanos) / 1_000_000_000,\n costProvenance: (receipt) =>\n receipt.usage.costProvenance === 'observed' &&\n receipt.grading.usage.costProvenance === 'observed'\n ? 'observed'\n : 'estimated',\n latencyMs: (receipt) => receipt.timing.durationMs + receipt.grading.timing.durationMs,\n completed: (receipt) => receipt.outcome.status === 'succeeded',\n passed: (receipt) => receipt.grading.passed,\n}\n","/**\n * # `intake/run-record-dir` — load a directory or file of `RunRecord`s.\n *\n * The on-disk counterpart to the in-memory intake adapters: point it at a\n * single `.json` (array) / `.jsonl` (one record per line) file or at a\n * directory of such files, and it returns the substrate-canonical\n * `RunRecord[]` ready for `analyzeRuns({ runs })`.\n *\n * Validation is at the boundary: each parsed object goes through\n * `parseRunRecordSafe`. By default an invalid record fails loud with its\n * file + index; pass `onInvalid: 'collect'` to keep the valid records and\n * receive the rejects as structured diagnostics instead.\n */\n\nimport { readdir, readFile, stat } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { parseRunRecordSafe, type RunRecord } from '../../run-record'\n\n/** A record that failed boundary validation, with enough context to fix it. */\nexport interface RunRecordRejection {\n /** Absolute or caller-relative path to the file the record came from. */\n file: string\n /** Zero-based position within the file (array index or JSONL line number). */\n index: number\n /** The validator's message. */\n reason: string\n}\n\nexport interface FromRunRecordDirOptions {\n /**\n * How to treat a record that fails `parseRunRecordSafe`:\n * - `'throw'` (default) — fail loud on the first invalid record.\n * - `'collect'` — drop it, keep the rest, and return it under `rejected`.\n */\n onInvalid?: 'throw' | 'collect'\n /**\n * When the input is a directory, only files matching this predicate are\n * read. Default: any file ending in `.json` or `.jsonl`. The `analysis.json`\n * artifact `evalReportingSuite` writes is always skipped so a re-run never\n * ingests its own output.\n */\n include?: (fileName: string) => boolean\n /**\n * Recurse into subdirectories when the input is a directory. Default false —\n * a flat run directory is the common case and recursion can silently pull in\n * unrelated corpora.\n */\n recursive?: boolean\n}\n\nexport interface FromRunRecordDirResult {\n /** Records that passed boundary validation, in file-then-index order. */\n runs: RunRecord[]\n /** Records that failed validation. Empty unless `onInvalid: 'collect'`. */\n rejected: RunRecordRejection[]\n /** The files that were read, in the order they were processed. */\n files: string[]\n}\n\nconst ANALYSIS_ARTIFACT = 'analysis.json'\n\nfunction defaultInclude(fileName: string): boolean {\n if (fileName === ANALYSIS_ARTIFACT) return false\n return fileName.endsWith('.json') || fileName.endsWith('.jsonl')\n}\n\n/**\n * Resolve a file or directory path into validated `RunRecord[]`.\n *\n * A `.json` file must parse to a top-level array; a `.jsonl` file is one\n * record per non-empty line. Directories are read shallowly by default\n * (set `recursive` to descend); the `analysis.json` output artifact is\n * always excluded.\n */\nexport async function fromRunRecordDir(\n path: string,\n options: FromRunRecordDirOptions = {},\n): Promise<FromRunRecordDirResult> {\n const onInvalid = options.onInvalid ?? 'throw'\n const include = options.include ?? defaultInclude\n\n const stats = await stat(path)\n const filePaths = stats.isDirectory()\n ? await collectFiles(path, include, options.recursive ?? false)\n : [path]\n\n const runs: RunRecord[] = []\n const rejected: RunRecordRejection[] = []\n\n for (const file of filePaths) {\n const raw = await parseRecordFile(file)\n for (const { index, value } of raw) {\n const parsed = parseRunRecordSafe(value)\n if (parsed.ok) {\n runs.push(parsed.value)\n continue\n }\n const rejection: RunRecordRejection = { file, index, reason: parsed.error.message }\n if (onInvalid === 'throw') {\n throw new Error(\n `fromRunRecordDir: invalid RunRecord in '${file}' at index ${index}: ${parsed.error.message}`,\n )\n }\n rejected.push(rejection)\n }\n }\n\n return { runs, rejected, files: filePaths }\n}\n\n/** Read a single `.json` / `.jsonl` file into `{ index, value }` pairs. A\n * malformed JSONL line throws with its line number rather than being skipped —\n * silent line-dropping is how corpora quietly shrink. */\nasync function parseRecordFile(file: string): Promise<Array<{ index: number; value: unknown }>> {\n const text = await readFile(file, 'utf8')\n const trimmed = text.trim()\n if (trimmed.length === 0) return []\n\n if (trimmed.startsWith('[')) {\n const parsed = JSON.parse(trimmed) as unknown\n if (!Array.isArray(parsed)) {\n throw new Error(`fromRunRecordDir: file '${file}' did not parse to an array`)\n }\n return parsed.map((value, index) => ({ index, value }))\n }\n\n const out: Array<{ index: number; value: unknown }> = []\n const lines = trimmed.split('\\n')\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!.trim()\n if (line.length === 0) continue\n try {\n out.push({ index: i, value: JSON.parse(line) as unknown })\n } catch (err) {\n throw new Error(\n `fromRunRecordDir: file '${file}' line ${i + 1} is not valid JSON: ${\n err instanceof Error ? err.message : String(err)\n }`,\n )\n }\n }\n return out\n}\n\n/** Sorted file list under a directory, filtered by `include`. Sorted so the\n * resulting `RunRecord` order — and any downstream fingerprint — is stable\n * across filesystems. */\nasync function collectFiles(\n dir: string,\n include: (fileName: string) => boolean,\n recursive: boolean,\n): Promise<string[]> {\n const entries = await readdir(dir, { withFileTypes: true })\n const files: string[] = []\n const subdirs: string[] = []\n for (const entry of entries) {\n if (entry.isDirectory()) {\n if (recursive) subdirs.push(join(dir, entry.name))\n continue\n }\n if (include(entry.name)) files.push(join(dir, entry.name))\n }\n files.sort()\n subdirs.sort()\n for (const sub of subdirs) {\n files.push(...(await collectFiles(sub, include, recursive)))\n }\n return files\n}\n","/**\n * # `evalReportingSuite` — one call from runs (or a run dir) to `analysis.json`.\n *\n * A thin wrapper over the analysis primitive (`analyzeRuns`) and the on-disk\n * intake adapter (`fromRunRecordDir`). It does NOT reimplement any statistics,\n * distributions, or clustering — it resolves the input into validated\n * `RunRecord[]`, calls `analyzeRuns` with the options you'd pass it directly,\n * wraps the result in a small provenance envelope, and (optionally) writes a\n * single `analysis.json` artifact.\n *\n * ```ts\n * // From a directory of run files, write ./runs/analysis.json:\n * const suite = await evalReportingSuite('./runs', { write: true })\n * // From records already in memory, no write:\n * const suite = await evalReportingSuite(records, { analyze: { decisionThreshold: 0.03 } })\n * suite.report // the InsightReport — distributions, paired lift, findings rollup\n * ```\n */\n\nimport { mkdir, writeFile } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\nimport type { RunRecord } from '../run-record'\nimport { type AnalyzeRunsOptions, analyzeRuns } from './analyze-runs'\nimport type { InsightReport } from './insight-report'\nimport {\n type FromRunRecordDirOptions,\n type FromRunRecordDirResult,\n fromRunRecordDir,\n} from './intake/run-record-dir'\n\n/** Either records in hand or a path to a `.json` / `.jsonl` file or a\n * directory of them. */\nexport type EvalReportingSuiteInput = RunRecord[] | string\n\nexport interface EvalReportingSuiteOptions {\n /** Forwarded verbatim to `analyzeRuns` (everything except `runs`, which the\n * suite supplies from the resolved input). Use this for split selection,\n * baseline/candidate ids, canaries, prior-period runs, the analyst registry,\n * etc. */\n analyze?: Omit<AnalyzeRunsOptions, 'runs'>\n /** Loader options used only when the input is a path. */\n load?: FromRunRecordDirOptions\n /**\n * Write the suite result as a single `analysis.json`.\n * - `true` — write to `<dir>/analysis.json` when the input is a directory,\n * or alongside the input file; throws if the input is in-memory records\n * (no directory to anchor to — pass an explicit path instead).\n * - a string — write to exactly this path (a directory path gets\n * `analysis.json` appended; any other path is used verbatim).\n * - omitted / false — do not write.\n */\n write?: boolean | string\n}\n\n/** The suite artifact — the `analyzeRuns` report plus provenance. This is the\n * exact shape serialized to `analysis.json`. */\nexport interface EvalReportingSuiteResult {\n /** The analysis itself — distributions, paired stats/lift, failure rollup,\n * recommendations. Produced by `analyzeRuns`. */\n report: InsightReport\n /** How the suite was run, so a reader can verify provenance. */\n provenance: {\n /** ISO timestamp the suite ran. */\n generatedAt: string\n /** Number of records analyzed (mirrors `report.n`). */\n runCount: number\n /** The source path when the input was a directory/file; null for\n * in-memory records. */\n sourcePath: string | null\n /** Files read when loading from disk; empty for in-memory input. */\n files: string[]\n /** Records dropped at the validation boundary. Always empty unless\n * `load.onInvalid` was set to `'collect'`. */\n rejected: FromRunRecordDirResult['rejected']\n }\n /** The path `analysis.json` was written to, or null when `write` was unset. */\n writtenTo: string | null\n}\n\nconst ANALYSIS_ARTIFACT = 'analysis.json'\n\n/**\n * Resolve runs (or a run dir/file), run `analyzeRuns`, and optionally persist a\n * single `analysis.json`. The only analysis logic lives in `analyzeRuns`; this\n * function is composition + I/O.\n */\nexport async function evalReportingSuite(\n input: EvalReportingSuiteInput,\n options: EvalReportingSuiteOptions = {},\n): Promise<EvalReportingSuiteResult> {\n const fromPath = typeof input === 'string'\n\n let runs: RunRecord[]\n let files: string[] = []\n let rejected: FromRunRecordDirResult['rejected'] = []\n if (fromPath) {\n const loaded = await fromRunRecordDir(input, options.load)\n runs = loaded.runs\n files = loaded.files\n rejected = loaded.rejected\n } else {\n runs = input\n }\n\n if (runs.length === 0) {\n throw new Error(\n fromPath\n ? `evalReportingSuite: no RunRecords found at '${input}'`\n : 'evalReportingSuite: no RunRecords to analyze',\n )\n }\n\n const report = await analyzeRuns({ ...options.analyze, runs })\n\n const result: EvalReportingSuiteResult = {\n report,\n provenance: {\n generatedAt: new Date().toISOString(),\n runCount: runs.length,\n sourcePath: fromPath ? input : null,\n files,\n rejected,\n },\n writtenTo: null,\n }\n\n const target = resolveWriteTarget(options.write, fromPath ? input : null)\n if (target) {\n await mkdir(dirname(target), { recursive: true })\n await writeFile(target, `${JSON.stringify(result, null, 2)}\\n`, 'utf8')\n result.writtenTo = target\n }\n\n return result\n}\n\n/** Resolve where (if anywhere) to write `analysis.json`. Returns null when\n * writing is disabled. Throws on `write: true` with in-memory input — there is\n * no directory to anchor the artifact to, and silently inventing `cwd` would\n * scatter files. */\nfunction resolveWriteTarget(\n write: EvalReportingSuiteOptions['write'],\n sourcePath: string | null,\n): string | null {\n if (!write) return null\n\n if (typeof write === 'string') {\n const looksLikeDir =\n write.endsWith('/') || (!write.endsWith('.json') && !write.endsWith('.jsonl'))\n return looksLikeDir ? join(write, ANALYSIS_ARTIFACT) : write\n }\n\n // write === true\n if (sourcePath === null) {\n throw new Error(\n 'evalReportingSuite: write:true needs a source path to anchor analysis.json — pass an explicit output path when analyzing in-memory records',\n )\n }\n const isFile = sourcePath.endsWith('.json') || sourcePath.endsWith('.jsonl')\n return isFile ? join(dirname(sourcePath), ANALYSIS_ARTIFACT) : join(sourcePath, ANALYSIS_ARTIFACT)\n}\n","/**\n * # `@tangle-network/agent-eval/contract` — eval-run diff primitive.\n *\n * The substrate side of the v-N-versus-v-N+1 dashboard view. Given two\n * `EvalRunEvent`s (or two `EvalRunGenerationSnapshot`s from one run), this\n * returns a normalised diff: per-cell composite + per-judge/per-dimension\n * deltas, surface-hash change, aggregate cost + duration shifts.\n *\n * Consumed by:\n * - The hosted-tier dashboard (intelligence-web) — renders v3 vs v4\n * comparisons of cells × judges × dimensions.\n * - CI reporting — emits a \"shipped: composite +0.07, cost +$1.20\" line\n * in PR review for autonomous-improvement runs.\n * - Any downstream consumer that needs \"what actually changed\" without\n * reimplementing the matching + arithmetic.\n *\n * Cells are matched on the natural composite key `(scenarioId, rep)`.\n * Unmatched cells surface as `removed` / `added` so callers can tell\n * \"this cell got worse\" from \"this cell wasn't run.\"\n */\n\nimport type { GateDecision } from '../campaign/types'\nimport type { EvalRunCellScore, EvalRunEvent, EvalRunGenerationSnapshot } from '../hosted/types'\n\n// ── Types ────────────────────────────────────────────────────────────\n\n/** Per-dimension delta. `before` / `after` are null when the judge did not\n * emit a value for that side. `delta` is `after - before`; null when\n * either side is null. */\nexport interface EvalDimensionDelta {\n before: number | null\n after: number | null\n delta: number | null\n}\n\n/** Per-cell delta, keyed on `(scenarioId, rep)`. */\nexport interface EvalCellScoreDelta {\n scenarioId: string\n rep: number\n compositeBefore: number | null\n compositeAfter: number | null\n compositeDelta: number | null\n /** Per-judge → per-dimension deltas. Outer key = judge name from\n * `EvalRunCellScore.dimensions`; inner key = dimension name. */\n dimensions: Record<string, Record<string, EvalDimensionDelta>>\n}\n\n/** Diff between two generation snapshots — the unit the dashboard renders\n * for a single \"v3 vs v4\" comparison. */\nexport interface EvalGenerationDiff {\n beforeIndex: number\n afterIndex: number\n beforeSurfaceHash: string\n afterSurfaceHash: string\n surfaceChanged: boolean\n /** Cells present in both snapshots, matched on `(scenarioId, rep)`. */\n matched: EvalCellScoreDelta[]\n /** Cells present in `before` but missing from `after`. */\n removed: EvalRunCellScore[]\n /** Cells present in `after` but missing from `before`. */\n added: EvalRunCellScore[]\n /** Aggregate composite mean, null when that snapshot was unscored. */\n compositeBefore: number | null\n compositeAfter: number | null\n compositeDelta: number | null\n costUsdBefore: number\n costUsdAfter: number\n costUsdDelta: number\n durationMsBefore: number\n durationMsAfter: number\n durationMsDelta: number\n}\n\n/** Diff between two full eval-runs. Includes both baseline-vs-baseline and\n * winner-vs-winner generation diffs when both sides expose them, plus\n * run-level metadata. */\nexport interface EvalRunDiff {\n beforeRunId: string\n afterRunId: string\n beforeTimestamp: string\n afterTimestamp: string\n beforeGateDecision: GateDecision | null\n afterGateDecision: GateDecision | null\n beforeHoldoutLift: number | null\n afterHoldoutLift: number | null\n holdoutLiftDelta: number | null\n beforeTotalCostUsd: number\n afterTotalCostUsd: number\n totalCostUsdDelta: number\n beforeTotalDurationMs: number\n afterTotalDurationMs: number\n totalDurationMsDelta: number\n /** Baseline-vs-baseline diff. Null when either run has no baseline. */\n baselineDiff: EvalGenerationDiff | null\n /** Highest-index-generation comparison. Null when either run has no\n * recorded generations (e.g. baseline-only or errored before any\n * generation completed). */\n winnersDiff: EvalGenerationDiff | null\n}\n\n// ── Implementation ───────────────────────────────────────────────────\n\nfunction keyForCell(cell: EvalRunCellScore): string {\n // JSON-tuple key — `scenarioId` may legitimately contain `::` or any other\n // delimiter, so we use JSON.stringify on a 2-tuple to get an unambiguous,\n // collision-free composite key.\n return JSON.stringify([cell.scenarioId, cell.rep])\n}\n\n/** Build the per-dimension delta map for a matched cell. Each judge name +\n * dimension name encountered on EITHER side appears in the result. */\nfunction diffDimensions(\n before: EvalRunCellScore['dimensions'],\n after: EvalRunCellScore['dimensions'],\n): EvalCellScoreDelta['dimensions'] {\n const out: EvalCellScoreDelta['dimensions'] = {}\n const judges = new Set<string>([...Object.keys(before), ...Object.keys(after)])\n for (const judge of judges) {\n const beforeDims = before[judge] ?? {}\n const afterDims = after[judge] ?? {}\n const dims = new Set<string>([...Object.keys(beforeDims), ...Object.keys(afterDims)])\n const judgeOut: Record<string, EvalDimensionDelta> = {}\n for (const dim of dims) {\n // Coerce non-finite values (NaN, ±Infinity) to null so the diff never\n // surfaces NaN/Infinity to the dashboard. A NaN score is a substrate\n // bug from upstream; the diff treats it as \"no value\" rather than\n // propagating the corruption.\n const rawBefore = beforeDims[dim]\n const rawAfter = afterDims[dim]\n const b = typeof rawBefore === 'number' && Number.isFinite(rawBefore) ? rawBefore : null\n const a = typeof rawAfter === 'number' && Number.isFinite(rawAfter) ? rawAfter : null\n judgeOut[dim] = {\n before: b,\n after: a,\n delta: b !== null && a !== null ? a - b : null,\n }\n }\n out[judge] = judgeOut\n }\n return out\n}\n\n/**\n * Diff two generation snapshots. Cells are matched on `(scenarioId, rep)`;\n * unmatched cells surface in `added` / `removed`. Aggregate fields are\n * recomputed from the snapshot's stored fields, not re-derived from cells —\n * this keeps the diff consistent with whatever aggregation the substrate\n * actually reported.\n */\nexport function diffGenerations(\n before: EvalRunGenerationSnapshot,\n after: EvalRunGenerationSnapshot,\n): EvalGenerationDiff {\n const beforeMap = new Map(before.cells.map((c) => [keyForCell(c), c]))\n const afterMap = new Map(after.cells.map((c) => [keyForCell(c), c]))\n\n const matched: EvalCellScoreDelta[] = []\n const removed: EvalRunCellScore[] = []\n const added: EvalRunCellScore[] = []\n\n for (const [key, beforeCell] of beforeMap) {\n const afterCell = afterMap.get(key)\n if (!afterCell) {\n removed.push(beforeCell)\n continue\n }\n matched.push({\n scenarioId: beforeCell.scenarioId,\n rep: beforeCell.rep,\n compositeBefore: beforeCell.compositeMean,\n compositeAfter: afterCell.compositeMean,\n compositeDelta:\n beforeCell.compositeMean === null || afterCell.compositeMean === null\n ? null\n : afterCell.compositeMean - beforeCell.compositeMean,\n dimensions: diffDimensions(beforeCell.dimensions, afterCell.dimensions),\n })\n }\n for (const [key, afterCell] of afterMap) {\n if (!beforeMap.has(key)) added.push(afterCell)\n }\n\n return {\n beforeIndex: before.index,\n afterIndex: after.index,\n beforeSurfaceHash: before.surfaceHash,\n afterSurfaceHash: after.surfaceHash,\n surfaceChanged: before.surfaceHash !== after.surfaceHash,\n matched,\n removed,\n added,\n compositeBefore: before.compositeMean,\n compositeAfter: after.compositeMean,\n compositeDelta:\n before.compositeMean === null || after.compositeMean === null\n ? null\n : after.compositeMean - before.compositeMean,\n costUsdBefore: before.costUsd,\n costUsdAfter: after.costUsd,\n costUsdDelta: after.costUsd - before.costUsd,\n durationMsBefore: before.durationMs,\n durationMsAfter: after.durationMs,\n durationMsDelta: after.durationMs - before.durationMs,\n }\n}\n\n/** Highest-index generation, or null if the run recorded none. */\nfunction winnerOf(run: EvalRunEvent): EvalRunGenerationSnapshot | null {\n if (run.generations.length === 0) return null\n let winner = run.generations[0] as EvalRunGenerationSnapshot\n for (const gen of run.generations) {\n if (gen.index > winner.index) winner = gen\n }\n return winner\n}\n\n/**\n * Diff two full eval-runs. Produces baseline-vs-baseline and\n * winner-vs-winner generation diffs when both sides expose them, plus\n * run-level cost / lift / gate-decision deltas.\n */\nexport function diffRuns(before: EvalRunEvent, after: EvalRunEvent): EvalRunDiff {\n const beforeWinner = winnerOf(before)\n const afterWinner = winnerOf(after)\n const baselineDiff =\n before.baseline && after.baseline ? diffGenerations(before.baseline, after.baseline) : null\n const winnersDiff =\n beforeWinner && afterWinner ? diffGenerations(beforeWinner, afterWinner) : null\n\n const beforeLift = before.holdoutLift ?? null\n const afterLift = after.holdoutLift ?? null\n\n return {\n beforeRunId: before.runId,\n afterRunId: after.runId,\n beforeTimestamp: before.timestamp,\n afterTimestamp: after.timestamp,\n beforeGateDecision: before.gateDecision ?? null,\n afterGateDecision: after.gateDecision ?? null,\n beforeHoldoutLift: beforeLift,\n afterHoldoutLift: afterLift,\n holdoutLiftDelta: beforeLift !== null && afterLift !== null ? afterLift - beforeLift : null,\n beforeTotalCostUsd: before.totalCostUsd,\n afterTotalCostUsd: after.totalCostUsd,\n totalCostUsdDelta: after.totalCostUsd - before.totalCostUsd,\n beforeTotalDurationMs: before.totalDurationMs,\n afterTotalDurationMs: after.totalDurationMs,\n totalDurationMsDelta: after.totalDurationMs - before.totalDurationMs,\n baselineDiff,\n winnersDiff,\n }\n}\n\n/**\n * Within-run baseline → winning-generation diff. The natural \"what did the\n * improvement loop produce\" view for a single run. Returns null when the\n * run never reached a generation past baseline (errored early, or the gate\n * shipped the baseline as-is).\n */\nexport function diffRunBaselineToWinner(run: EvalRunEvent): EvalGenerationDiff | null {\n if (!run.baseline) return null\n const winner = winnerOf(run)\n if (!winner || winner.index === run.baseline.index) return null\n return diffGenerations(run.baseline, winner)\n}\n","/**\n * `fromAgentTrace` — provenance correlation from Cursor's Agent Trace spec\n * (https://github.com/cursor/agent-trace, RFC v0.1.0).\n *\n * Agent Trace is NOT a run/quality trace — it carries no outcome, score, or\n * cost. It records *code authorship*: for a VCS revision, which AI model /\n * conversation authored which file ranges. It explicitly disclaims quality\n * assessment — which is exactly what `analyzeRuns` adds.\n *\n * The two layers join on a key the substrate already has: a `RunRecord`\n * carries `commitSha`, and an Agent Trace record is keyed by\n * `vcs.revision`. So this adapter does not produce `RunRecord`s — it builds a\n * provenance index by commit and partitions existing runs by their authoring\n * model. Feed each cohort to `analyzeRuns` (or pass one as `baselineRuns`) to\n * answer the question no run-only trace can: *which authoring agent's code\n * fails / regresses / costs more.*\n *\n * Granularity is commit-level (the SHA join). Per-file/per-line correlation\n * would require runs to record which files they exercised — out of scope.\n */\n\nimport type { RunRecord } from '../../run-record'\n\n// ── Agent Trace record schema (the subset we read) ──────────────────────────\n\nexport type AgentTraceContributorType = 'human' | 'ai' | 'mixed' | 'unknown'\n\nexport interface AgentTraceContributor {\n type: AgentTraceContributorType\n /** models.dev id, e.g. `anthropic/claude-opus-4-5-20251101`. */\n model_id?: string\n}\n\nexport interface AgentTraceRange {\n start_line: number\n end_line: number\n content_hash?: string\n /** Per-range contributor override (agent handoffs). Wins over the\n * conversation-level contributor for these lines. */\n contributor?: AgentTraceContributor\n}\n\nexport interface AgentTraceConversation {\n url?: string\n contributor?: AgentTraceContributor\n ranges: AgentTraceRange[]\n}\n\nexport interface AgentTraceFile {\n path: string\n conversations: AgentTraceConversation[]\n}\n\nexport interface AgentTraceRecord {\n version: string\n id: string\n timestamp: string\n vcs?: { type: string; revision: string }\n tool?: { name?: string; version?: string }\n files: AgentTraceFile[]\n}\n\n// ── Provenance index ─────────────────────────────────────────────────────────\n\n/** Authorship provenance for one VCS revision, aggregated across the record's\n * files/conversations/ranges. */\nexport interface AuthoringProvenance {\n commitSha: string\n /** Unique AI model ids that authored code in this commit (type ai|mixed). */\n aiModels: string[]\n /** Tools that produced the records (e.g. `cursor`). */\n tools: string[]\n conversationCount: number\n fileCount: number\n /** Total attributed lines (sum of range spans). */\n lineCount: number\n /** True if any range was authored (in whole or part) by a human. */\n humanInvolved: boolean\n}\n\nexport type AgentTraceIndex = Map<string, AuthoringProvenance>\n\nfunction rangeLines(r: AgentTraceRange): number {\n return Math.max(0, r.end_line - r.start_line + 1)\n}\n\n/**\n * Build a commit → provenance index from Agent Trace records. Multiple records\n * for the same revision are merged. Records without `vcs.revision` are skipped\n * (the SHA is the join key — without it there is nothing to correlate against).\n */\nexport function parseAgentTrace(records: AgentTraceRecord[]): AgentTraceIndex {\n interface Acc {\n models: Set<string>\n tools: Set<string>\n files: Set<string>\n conversationCount: number\n lineCount: number\n humanInvolved: boolean\n }\n const acc = new Map<string, Acc>()\n\n for (const record of records) {\n const sha = record.vcs?.revision\n if (!sha) continue // the SHA is the join key — nothing to correlate without it\n\n let a = acc.get(sha)\n if (!a) {\n a = {\n models: new Set(),\n tools: new Set(),\n files: new Set(),\n conversationCount: 0,\n lineCount: 0,\n humanInvolved: false,\n }\n acc.set(sha, a)\n }\n\n if (record.tool?.name) a.tools.add(record.tool.name)\n\n for (const file of record.files ?? []) {\n a.files.add(file.path)\n for (const conv of file.conversations ?? []) {\n a.conversationCount += 1\n for (const range of conv.ranges ?? []) {\n // Per-range contributor wins, else the conversation contributor.\n const contributor = range.contributor ?? conv.contributor\n a.lineCount += rangeLines(range)\n if (!contributor) continue\n if (contributor.type === 'human' || contributor.type === 'mixed') {\n a.humanInvolved = true\n }\n if ((contributor.type === 'ai' || contributor.type === 'mixed') && contributor.model_id) {\n a.models.add(contributor.model_id)\n }\n }\n }\n }\n }\n\n const index: AgentTraceIndex = new Map()\n for (const [sha, a] of acc) {\n index.set(sha, {\n commitSha: sha,\n aiModels: [...a.models].sort(),\n tools: [...a.tools].sort(),\n conversationCount: a.conversationCount,\n fileCount: a.files.size,\n lineCount: a.lineCount,\n humanInvolved: a.humanInvolved,\n })\n }\n return index\n}\n\n// ── Run ↔ provenance join ──────────────────────────────────────────────────\n\nexport interface PartitionByAuthoringModelResult {\n /** Runs grouped by each AI model that authored code in the run's commit. A\n * run whose commit had multiple authoring models appears under EACH — the\n * cohorts overlap by construction at commit granularity. */\n byModel: Map<string, RunRecord[]>\n /** Runs whose `commitSha` had no Agent Trace provenance (no record, or no\n * AI authorship). Kept separate — never silently folded into a cohort. */\n unattributed: RunRecord[]\n}\n\n/**\n * Partition runs by the AI model(s) that authored the code at each run's\n * `commitSha`. Feed `byModel.get(modelId)` to `analyzeRuns`, or compare two\n * model cohorts via `analyzeRuns({ runs: a, baselineRuns: b })` for a lift CI\n * on \"model A's code vs model B's code\".\n */\nexport function partitionRunsByAuthoringModel(\n runs: RunRecord[],\n index: AgentTraceIndex,\n): PartitionByAuthoringModelResult {\n const byModel = new Map<string, RunRecord[]>()\n const unattributed: RunRecord[] = []\n\n for (const run of runs) {\n const provenance = index.get(run.commitSha)\n if (!provenance || provenance.aiModels.length === 0) {\n unattributed.push(run)\n continue\n }\n for (const model of provenance.aiModels) {\n const cohort = byModel.get(model) ?? []\n cohort.push(run)\n byModel.set(model, cohort)\n }\n }\n\n return { byModel, unattributed }\n}\n","export type CodeAgentSessionSource = 'codex' | 'claude-code' | 'opencode' | 'kimi-code' | 'pi'\n\nexport type CodeAgentSessionTerminalStatus = 'completed' | 'failed' | 'unknown'\n\nexport type CodeAgentSessionActionKind = 'tool' | 'patch' | 'terminal' | 'graph-completion'\n\nexport type CodeAgentSessionActionSurface =\n | 'tool'\n | 'mcp'\n | 'subagent'\n | 'skill'\n | 'hook'\n | 'web'\n | 'code'\n\nexport type CodeAgentSessionActionStatus = 'started' | 'completed' | 'failed' | 'unknown'\n\nexport interface CodeAgentSessionExecutionReceipt {\n exitCode: number\n startedAtMs?: number\n completedAtMs?: number\n}\n\nexport interface CodeAgentSessionAction {\n id: string\n stepIndex: number\n kind: CodeAgentSessionActionKind\n surface: CodeAgentSessionActionSurface\n name: string\n status: CodeAgentSessionActionStatus\n timestampMs?: number\n costUsd?: number\n metadata: Record<string, unknown>\n}\n\nexport interface CodeAgentSessionObservation {\n source: CodeAgentSessionSource\n sessionId: string\n finalText: string | null\n terminal: {\n status: CodeAgentSessionTerminalStatus\n explicit: boolean\n }\n actions: CodeAgentSessionAction[]\n}\n\nexport interface ObserveCodeAgentSessionOptions {\n source: CodeAgentSessionSource\n entries: unknown[]\n sourcePath?: string\n execution?: CodeAgentSessionExecutionReceipt\n}\n\ninterface SessionProjection {\n finalText: string | null\n terminal: CodeAgentSessionTerminalStatus\n explicitTerminal: boolean\n actions: CodeAgentSessionAction[]\n}\n\n/**\n * Project one provider session into the exact user-visible answer and a\n * provider-neutral action stream. Raw prompts, tool inputs, and tool outputs\n * stay out of this projection; callers retain the source JSONL as evidence.\n */\nexport function observeCodeAgentSession(\n options: ObserveCodeAgentSessionOptions,\n): CodeAgentSessionObservation {\n const entries = options.entries.filter(isRecord)\n const projection = projectionFor(options.source, entries)\n const terminal = terminalWithExecution(projection, options.execution)\n return {\n source: options.source,\n sessionId:\n sessionIdFromEntries(options.source, entries) ??\n fallbackSessionId(options.source, options.sourcePath),\n finalText: projection.finalText,\n terminal,\n actions: projection.actions,\n }\n}\n\nfunction projectionFor(\n source: CodeAgentSessionSource,\n entries: Record<string, unknown>[],\n): SessionProjection {\n switch (source) {\n case 'codex':\n return codexProjection(entries)\n case 'claude-code':\n return claudeProjection(entries)\n case 'opencode':\n return openCodeProjection(entries)\n case 'kimi-code':\n return kimiProjection(entries)\n case 'pi':\n return piProjection(entries)\n }\n}\n\nfunction codexProjection(entries: Record<string, unknown>[]): SessionProjection {\n const actions: CodeAgentSessionAction[] = []\n const calls = new Map<string, CodeAgentSessionAction>()\n let finalText: string | null = null\n let terminal: CodeAgentSessionTerminalStatus = 'unknown'\n let explicitTerminal = false\n\n for (const entry of entries) {\n const entryType = stringField(entry, 'type')\n const payload = record(entry.payload) ?? {}\n const payloadType = stringField(payload, 'type')\n const timestampMs = timestamp(entry.timestamp)\n const item = record(entry.item)\n\n if (entryType === 'item.started' && item) {\n const itemType = stringField(item, 'type')\n if (isCodexActionItem(itemType)) {\n const id = stringField(item, 'id') ?? `item-${actions.length}`\n const action = actionFor({\n id,\n stepIndex: actions.length,\n kind: itemType === 'file_change' ? 'patch' : 'tool',\n surface: codexItemSurface(itemType, item),\n name: codexItemName(itemType, item),\n status: 'started',\n timestampMs,\n metadata: compactMetadata({ sourceEventType: entryType, itemType }),\n })\n calls.set(id, action)\n actions.push(action)\n }\n }\n\n if (entryType === 'item.completed' && item) {\n const itemType = stringField(item, 'type')\n if (itemType === 'agent_message' || itemType === 'message') {\n finalText = nonEmpty(stringField(item, 'text')) ?? finalText\n }\n if (isCodexActionItem(itemType)) {\n const id = stringField(item, 'id') ?? `item-${actions.length}`\n const status = codexItemStatus(itemType, item)\n const existing = calls.get(id)\n if (existing) {\n existing.status = status\n } else {\n const action = actionFor({\n id,\n stepIndex: actions.length,\n kind: itemType === 'file_change' ? 'patch' : 'tool',\n surface: codexItemSurface(itemType, item),\n name: codexItemName(itemType, item),\n status,\n timestampMs,\n metadata: compactMetadata({ sourceEventType: entryType, itemType }),\n })\n calls.set(id, action)\n actions.push(action)\n }\n }\n }\n\n if (entryType === 'response_item') {\n if (payloadType === 'message' || payloadType === 'agent_message') {\n finalText = textFromMessagePayload(payload) ?? finalText\n }\n if (payloadType === 'function_call' || payloadType === 'custom_tool_call') {\n const id =\n stringField(payload, 'call_id') ?? stringField(payload, 'id') ?? `call-${actions.length}`\n const name = stringField(payload, 'name') ?? payloadType\n const action = actionFor({\n id,\n stepIndex: actions.length,\n kind: 'tool',\n surface: surfaceForTool(name),\n name,\n status: 'started',\n timestampMs,\n metadata: compactMetadata({ sourceEventType: entryType, payloadType }),\n })\n calls.set(id, action)\n actions.push(action)\n }\n if (payloadType === 'function_call_output' || payloadType === 'custom_tool_call_output') {\n const id = stringField(payload, 'call_id') ?? stringField(payload, 'id')\n const existing = id ? calls.get(id) : undefined\n if (existing) existing.status = looksLikeError(payload.output) ? 'failed' : 'completed'\n }\n }\n\n if (entryType === 'event_msg') {\n if (payloadType === 'agent_message') {\n finalText =\n nonEmpty(stringField(payload, 'message')) ??\n nonEmpty(stringField(payload, 'text')) ??\n finalText\n }\n if (payloadType === 'patch_apply_end') {\n const patchStatus =\n typeof payload.success === 'boolean'\n ? payload.success\n ? 'completed'\n : 'failed'\n : 'unknown'\n actions.push(\n actionFor({\n id: stringField(payload, 'call_id') ?? `patch-${actions.length}`,\n stepIndex: actions.length,\n kind: 'patch',\n surface: 'code',\n name: 'patch',\n status: patchStatus,\n timestampMs,\n metadata: compactMetadata({ sourceEventType: entryType, payloadType }),\n }),\n )\n }\n if (payloadType === 'sub_agent_activity') {\n const name = stringField(payload, 'kind') ?? 'subagent'\n actions.push(\n actionFor({\n id: stringField(payload, 'event_id') ?? `subagent-${actions.length}`,\n stepIndex: actions.length,\n kind: 'tool',\n surface: 'subagent',\n name,\n status: statusFrom(payload),\n timestampMs,\n metadata: compactMetadata({ sourceEventType: entryType, payloadType }),\n }),\n )\n }\n if (payloadType === 'task_complete' || payloadType === 'turn_aborted') {\n const completed = payloadType === 'task_complete'\n terminal = completed ? 'completed' : 'failed'\n explicitTerminal = true\n actions.push(terminalAction(actions.length, payloadType, completed, timestampMs))\n }\n }\n\n if (entryType === 'turn.completed' || entryType === 'exec_done') {\n const completed = entry.success !== false\n terminal = completed ? 'completed' : 'failed'\n explicitTerminal = true\n finalText = nonEmpty(stringField(entry, 'message')) ?? finalText\n actions.push(terminalAction(actions.length, entryType, completed, timestampMs))\n }\n if (entryType === 'turn.failed' || entryType === 'error') {\n terminal = 'failed'\n explicitTerminal = true\n actions.push(terminalAction(actions.length, entryType, false, timestampMs))\n }\n }\n\n return { finalText, terminal, explicitTerminal, actions }\n}\n\nfunction claudeProjection(entries: Record<string, unknown>[]): SessionProjection {\n const actions: CodeAgentSessionAction[] = []\n const calls = new Map<string, CodeAgentSessionAction>()\n let finalText: string | null = null\n let resultText: string | null = null\n let terminal: CodeAgentSessionTerminalStatus = 'unknown'\n let explicitTerminal = false\n\n for (const entry of entries) {\n const entryType = stringField(entry, 'type')\n const timestampMs = timestamp(entry.timestamp)\n const message = record(entry.message)\n const content = Array.isArray(message?.content) ? message.content : []\n\n if (entryType === 'assistant') {\n const text = textBlocks(content)\n if (text !== null) finalText = text\n for (const value of content) {\n const part = record(value)\n if (!part) continue\n const partType = stringField(part, 'type')\n if (partType === 'tool_use') {\n const id = stringField(part, 'id') ?? `tool-${actions.length}`\n const name = stringField(part, 'name') ?? 'tool'\n const action = actionFor({\n id,\n stepIndex: actions.length,\n kind: 'tool',\n surface: surfaceForTool(name),\n name,\n status: 'started',\n timestampMs,\n metadata: compactMetadata({ sourceEventType: entryType, partType }),\n })\n calls.set(id, action)\n actions.push(action)\n }\n }\n completeClaudeTools(content, calls)\n const stopReason = stringField(message ?? {}, 'stop_reason')\n if (stopReason === 'end_turn') {\n terminal = 'completed'\n explicitTerminal = true\n actions.push(terminalAction(actions.length, stopReason, true, timestampMs))\n }\n }\n\n if (entryType === 'user') {\n completeClaudeTools(content, calls)\n }\n if (entryType === 'tool_use') {\n const id = stringField(entry, 'id') ?? `tool-${actions.length}`\n const name = stringField(entry, 'name') ?? 'tool'\n const action = actionFor({\n id,\n stepIndex: actions.length,\n kind: 'tool',\n surface: surfaceForTool(name),\n name,\n status: 'started',\n timestampMs,\n metadata: { sourceEventType: entryType },\n })\n calls.set(id, action)\n actions.push(action)\n }\n if (entryType === 'tool_result') {\n const id = stringField(entry, 'tool_use_id')\n const action = id ? calls.get(id) : undefined\n if (action) action.status = entry.is_error === true ? 'failed' : 'completed'\n }\n\n if (entryType === 'system') {\n const subtype = stringField(entry, 'subtype')\n const hookName = stringField(entry, 'hook_name') ?? stringField(entry, 'hookName')\n if (subtype?.toLowerCase().includes('hook') || hookName) {\n actions.push(\n actionFor({\n id: stringField(entry, 'uuid') ?? `hook-${actions.length}`,\n stepIndex: actions.length,\n kind: 'tool',\n surface: 'hook',\n name: hookName ?? subtype ?? 'hook',\n status: statusFrom(entry),\n timestampMs,\n metadata: compactMetadata({ sourceEventType: entryType, subtype }),\n }),\n )\n }\n }\n\n if (entryType === 'pr-link') {\n actions.push(terminalAction(actions.length, entryType, true, timestampMs))\n }\n\n if (entryType === 'result') {\n resultText = nonEmpty(stringField(entry, 'result')) ?? resultText\n const subtype = stringField(entry, 'subtype')\n const completed = entry.is_error !== true && !subtype?.toLowerCase().includes('error')\n terminal = completed ? 'completed' : 'failed'\n explicitTerminal = true\n actions.push(terminalAction(actions.length, subtype ?? entryType, completed, timestampMs))\n }\n if (entryType === 'error') {\n terminal = 'failed'\n explicitTerminal = true\n actions.push(terminalAction(actions.length, entryType, false, timestampMs))\n }\n }\n\n return {\n finalText: resultText ?? finalText,\n terminal,\n explicitTerminal,\n actions,\n }\n}\n\nfunction openCodeProjection(entries: Record<string, unknown>[]): SessionProjection {\n const actions: CodeAgentSessionAction[] = []\n const assistantMessageIds = new Set(\n entries\n .filter((entry) => stringField(entry, 'role') === 'assistant')\n .map((entry) => stringField(entry, 'id'))\n .filter((id): id is string => id !== undefined),\n )\n let finalText: string | null = null\n let terminal: CodeAgentSessionTerminalStatus = 'unknown'\n let explicitTerminal = false\n\n for (const entry of entries) {\n const entryType = stringField(entry, 'type')\n const part = record(entry.part) ?? entry\n const partType = stringField(part, 'type')\n const timestampMs = timestamp(entry.timestamp) ?? timestamp(record(entry.time)?.created)\n\n if (entryType === 'text' && record(entry.part)) {\n finalText = nonEmpty(stringField(part, 'text')) ?? finalText\n } else if (\n partType === 'text' &&\n (assistantMessageIds.size === 0 ||\n assistantMessageIds.has(stringField(part, 'messageID') ?? ''))\n ) {\n finalText = nonEmpty(stringField(part, 'text')) ?? finalText\n }\n\n if (entryType === 'tool_use' || partType === 'tool') {\n const state = record(part.state) ?? {}\n const name = stringField(part, 'tool') ?? 'tool'\n actions.push(\n actionFor({\n id: stringField(part, 'callID') ?? stringField(part, 'id') ?? `tool-${actions.length}`,\n stepIndex: actions.length,\n kind: 'tool',\n surface: surfaceForTool(name),\n name,\n status: statusFrom(state),\n timestampMs,\n metadata: compactMetadata({ sourceEventType: entryType, partType }),\n }),\n )\n }\n if (partType === 'patch') {\n actions.push(\n actionFor({\n id: stringField(part, 'id') ?? `patch-${actions.length}`,\n stepIndex: actions.length,\n kind: 'patch',\n surface: 'code',\n name: 'patch',\n status: 'completed',\n timestampMs,\n metadata: compactMetadata({ sourceEventType: entryType, partType }),\n }),\n )\n }\n\n if (stringField(entry, 'role') === 'assistant') {\n const finish = stringField(entry, 'finish')\n if (finish === 'stop' || finish === 'error') {\n const completed = finish === 'stop'\n terminal = completed ? 'completed' : 'failed'\n explicitTerminal = true\n actions.push(terminalAction(actions.length, finish, completed, timestampMs))\n }\n }\n if (entryType === 'error') {\n terminal = 'failed'\n explicitTerminal = true\n actions.push(terminalAction(actions.length, entryType, false, timestampMs))\n }\n }\n\n return { finalText, terminal, explicitTerminal, actions }\n}\n\nfunction kimiProjection(entries: Record<string, unknown>[]): SessionProjection {\n const actions: CodeAgentSessionAction[] = []\n const calls = new Map<string, CodeAgentSessionAction>()\n let finalText: string | null = null\n let terminal: CodeAgentSessionTerminalStatus = 'unknown'\n let explicitTerminal = false\n\n for (const entry of entries) {\n const timestampMs = timestamp(entry.timestamp)\n const message = record(entry.message)\n const messageType = stringField(message ?? {}, 'type')\n const payload = record(message?.payload) ?? {}\n if (messageType === 'ContentPart' && stringField(payload, 'type') === 'text') {\n finalText =\n nonEmpty(stringField(payload, 'text')) ??\n nonEmpty(stringField(payload, 'content')) ??\n finalText\n }\n if (messageType === 'ToolCall') {\n const fn = record(payload.function) ?? {}\n const id = stringField(payload, 'id') ?? `tool-${actions.length}`\n const name = stringField(fn, 'name') ?? 'tool'\n const action = actionFor({\n id,\n stepIndex: actions.length,\n kind: 'tool',\n surface: surfaceForTool(name),\n name,\n status: 'started',\n timestampMs,\n metadata: { sourceEventType: messageType },\n })\n calls.set(id, action)\n actions.push(action)\n }\n if (messageType === 'ToolResult') {\n const id = stringField(payload, 'tool_call_id')\n const action = id ? calls.get(id) : undefined\n if (action)\n action.status = record(payload.return_value)?.is_error === true ? 'failed' : 'completed'\n }\n if (messageType === 'TurnEnd' || messageType === 'StepInterrupted') {\n const completed = messageType === 'TurnEnd'\n terminal = completed ? 'completed' : 'failed'\n explicitTerminal = true\n actions.push(terminalAction(actions.length, messageType, completed, timestampMs))\n }\n }\n\n return { finalText, terminal, explicitTerminal, actions }\n}\n\nfunction piProjection(entries: Record<string, unknown>[]): SessionProjection {\n const actions: CodeAgentSessionAction[] = []\n let terminal: CodeAgentSessionTerminalStatus = 'unknown'\n let explicitTerminal = false\n for (const entry of entries) {\n const nodes = Array.isArray(entry.nodes) ? entry.nodes : []\n for (const value of nodes) {\n const node = record(value)\n const ir = record(node?.ir) ?? node\n const kind = stringField(ir ?? {}, 'kind')\n if (kind === 'ToolInvocation') {\n actions.push(\n actionFor({\n id:\n stringField(ir ?? {}, 'id') ??\n stringField(node ?? {}, 'id') ??\n `tool-${actions.length}`,\n stepIndex: actions.length,\n kind: 'tool',\n surface: 'tool',\n name: stringField(ir ?? {}, 'name') ?? 'graph-tool',\n status: 'started',\n timestampMs: timestamp(ir?.createdAt),\n metadata: { sourceEventType: 'graph-node', graphKind: kind },\n }),\n )\n }\n if (kind === 'ToolResult') {\n const prior = [...actions].reverse().find((action) => action.kind === 'tool')\n if (prior) prior.status = 'completed'\n }\n if (kind === 'CompletionDecision') {\n terminal = 'completed'\n explicitTerminal = true\n actions.push(\n actionFor({\n id:\n stringField(ir ?? {}, 'id') ??\n stringField(node ?? {}, 'id') ??\n `completion-${actions.length}`,\n stepIndex: actions.length,\n kind: 'graph-completion',\n surface: 'tool',\n name: 'complete',\n status: 'completed',\n timestampMs: timestamp(ir?.createdAt),\n metadata: { sourceEventType: 'graph-node', graphKind: kind },\n }),\n )\n }\n }\n }\n return { finalText: null, terminal, explicitTerminal, actions }\n}\n\nfunction completeClaudeTools(content: unknown[], calls: Map<string, CodeAgentSessionAction>): void {\n for (const value of content) {\n const part = record(value)\n if (!part || stringField(part, 'type') !== 'tool_result') continue\n const id = stringField(part, 'tool_use_id')\n const action = id ? calls.get(id) : undefined\n if (action) action.status = part.is_error === true ? 'failed' : 'completed'\n }\n}\n\nfunction isCodexActionItem(itemType: string | undefined): boolean {\n return (\n itemType === 'command_execution' ||\n itemType === 'mcp_tool_call' ||\n itemType === 'collab_tool_call' ||\n itemType === 'web_search' ||\n itemType === 'file_change'\n )\n}\n\nfunction codexItemSurface(\n itemType: string | undefined,\n item: Record<string, unknown>,\n): CodeAgentSessionActionSurface {\n if (itemType === 'mcp_tool_call') return 'mcp'\n if (itemType === 'collab_tool_call') return 'subagent'\n if (itemType === 'web_search') return 'web'\n if (itemType === 'file_change') return 'code'\n return surfaceForTool(stringField(item, 'name') ?? itemType ?? 'tool')\n}\n\nfunction codexItemName(itemType: string | undefined, item: Record<string, unknown>): string {\n if (itemType === 'mcp_tool_call') {\n const server = stringField(item, 'server')\n const tool = stringField(item, 'tool')\n return [server, tool].filter(Boolean).join('/') || 'mcp'\n }\n if (itemType === 'collab_tool_call') return stringField(item, 'tool') ?? 'subagent'\n if (itemType === 'web_search') return 'web_search'\n if (itemType === 'file_change') return 'file_change'\n return stringField(item, 'name') ?? itemType ?? 'tool'\n}\n\nfunction codexItemStatus(\n itemType: string | undefined,\n item: Record<string, unknown>,\n): CodeAgentSessionActionStatus {\n const status = statusFrom(item)\n if (status === 'failed') return status\n if (itemType === 'command_execution') {\n const exitCode = numberField(item, 'exit_code')\n if (exitCode !== undefined) return exitCode === 0 ? 'completed' : 'failed'\n }\n if (itemType === 'mcp_tool_call' && record(item.error)) return 'failed'\n return status === 'unknown' || status === 'started' ? 'completed' : status\n}\n\nfunction textFromMessagePayload(payload: Record<string, unknown>): string | null {\n const direct = nonEmpty(stringField(payload, 'text'))\n if (direct) return direct\n const content = payload.content\n if (typeof content === 'string') return nonEmpty(content)\n if (Array.isArray(content)) return textBlocks(content)\n return null\n}\n\nfunction textBlocks(values: unknown[]): string | null {\n const text = values\n .map((value) => record(value))\n .filter((value): value is Record<string, unknown> => value !== null)\n .filter((value) => stringField(value, 'type') === 'text')\n .map((value) => stringField(value, 'text'))\n .filter((value): value is string => value !== undefined)\n .join('\\n')\n return nonEmpty(text)\n}\n\nfunction terminalWithExecution(\n projection: SessionProjection,\n execution: CodeAgentSessionExecutionReceipt | undefined,\n): CodeAgentSessionObservation['terminal'] {\n if (!execution) {\n return { status: projection.terminal, explicit: projection.explicitTerminal }\n }\n assertExecutionReceipt(execution)\n return {\n status: execution.exitCode !== 0 || projection.terminal === 'failed' ? 'failed' : 'completed',\n explicit: true,\n }\n}\n\nfunction assertExecutionReceipt(receipt: CodeAgentSessionExecutionReceipt): void {\n if (!Number.isSafeInteger(receipt.exitCode)) {\n throw new Error('code-agent execution exitCode must be a safe integer')\n }\n for (const [name, value] of [\n ['startedAtMs', receipt.startedAtMs],\n ['completedAtMs', receipt.completedAtMs],\n ] as const) {\n if (value !== undefined && (!Number.isFinite(value) || value < 0)) {\n throw new Error(`code-agent execution ${name} must be a non-negative finite number`)\n }\n }\n if (\n receipt.startedAtMs !== undefined &&\n receipt.completedAtMs !== undefined &&\n receipt.completedAtMs < receipt.startedAtMs\n ) {\n throw new Error('code-agent execution completedAtMs precedes startedAtMs')\n }\n}\n\nfunction terminalAction(\n stepIndex: number,\n name: string,\n completed: boolean,\n timestampMs: number | undefined,\n): CodeAgentSessionAction {\n return actionFor({\n id: `terminal-${stepIndex}`,\n stepIndex,\n kind: 'terminal',\n surface: 'tool',\n name,\n status: completed ? 'completed' : 'failed',\n timestampMs,\n metadata: { sourceEventType: name },\n })\n}\n\nfunction actionFor(input: CodeAgentSessionAction): CodeAgentSessionAction {\n return input\n}\n\nfunction surfaceForTool(name: string): CodeAgentSessionActionSurface {\n const normalized = name.toLowerCase()\n if (normalized.startsWith('mcp__') || normalized.includes('mcp_tool')) return 'mcp'\n if (\n normalized === 'task' ||\n normalized === 'agent' ||\n normalized.includes('subagent') ||\n normalized.includes('spawn_agent') ||\n normalized.includes('collab') ||\n normalized.startsWith('multi_agent')\n ) {\n return 'subagent'\n }\n if (normalized === 'skill' || normalized.includes('skill')) return 'skill'\n if (normalized.includes('hook')) return 'hook'\n if (\n normalized.includes('web_search') ||\n normalized.includes('webfetch') ||\n normalized === 'web'\n ) {\n return 'web'\n }\n if (\n normalized === 'edit' ||\n normalized === 'write' ||\n normalized.includes('patch') ||\n normalized.includes('file_change')\n ) {\n return 'code'\n }\n return 'tool'\n}\n\nfunction statusFrom(value: Record<string, unknown>): CodeAgentSessionActionStatus {\n const status = (stringField(value, 'status') ?? '').toLowerCase()\n if (status === 'completed' || status === 'success' || status === 'succeeded') return 'completed'\n if (status === 'error' || status === 'failed' || status === 'declined') return 'failed'\n if (status === 'running' || status === 'started' || status === 'in_progress') return 'started'\n return 'unknown'\n}\n\nfunction compactMetadata(input: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(Object.entries(input).filter((entry) => entry[1] !== undefined))\n}\n\nfunction sessionIdFromEntries(\n source: CodeAgentSessionSource,\n entries: Record<string, unknown>[],\n): string | undefined {\n for (const entry of entries) {\n if (source === 'codex') {\n const threadId = stringField(entry, 'thread_id')\n if (threadId) return threadId\n const payload = record(entry.payload)\n const id = payload ? stringField(payload, 'id') : undefined\n if (id) return id\n }\n const message = record(entry.message)\n const payload = record(message?.payload)\n const sessionId =\n stringField(entry, 'sessionID') ??\n stringField(entry, 'sessionId') ??\n stringField(entry, 'session_id') ??\n stringField(payload ?? {}, 'session_id')\n if (sessionId) return sessionId\n }\n return undefined\n}\n\nfunction fallbackSessionId(source: CodeAgentSessionSource, sourcePath: string | undefined): string {\n return `${source}:${sourcePath ?? 'unknown-session'}`\n}\n\nfunction looksLikeError(value: unknown): boolean {\n if (isRecord(value)) {\n if (value.success === false || value.is_error === true) return true\n const exitCode = numberField(value, 'exit_code')\n if (exitCode !== undefined && exitCode !== 0) return true\n }\n const text = typeof value === 'string' ? value : JSON.stringify(value ?? '')\n return /\\b(?:error|failed|failure)\\b|exit(?:_| )code[\"\\s:]+[1-9]/i.test(text)\n}\n\nfunction nonEmpty(value: string | undefined): string | null {\n return value !== undefined && value.length > 0 ? value : null\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction record(value: unknown): Record<string, unknown> | null {\n return isRecord(value) ? value : null\n}\n\nfunction stringField(value: Record<string, unknown>, key: string): string | undefined {\n const field = value[key]\n return typeof field === 'string' && field.length > 0 ? field : undefined\n}\n\nfunction numberField(value: Record<string, unknown>, key: string): number | undefined {\n const field = value[key]\n return typeof field === 'number' && Number.isFinite(field) ? field : undefined\n}\n\nfunction timestamp(value: unknown): number | undefined {\n if (typeof value === 'number' && Number.isFinite(value)) {\n return value > 1_000_000_000_000 ? value : value * 1_000\n }\n if (typeof value === 'string' && value.length > 0) {\n const parsed = Date.parse(value)\n return Number.isFinite(parsed) ? parsed : undefined\n }\n return undefined\n}\n","import { createHash } from 'node:crypto'\nimport { estimateCost, isModelPriced } from '../../metrics'\nimport type {\n RunCostProvenance,\n RunRecord,\n RunSplitTag,\n RunTerminalOutcome,\n RunTokenUsage,\n} from '../../run-record'\nimport { extractUsage } from '../../trace/extract-usage'\nimport {\n type CodeAgentSessionExecutionReceipt,\n type CodeAgentSessionObservation,\n type CodeAgentSessionSource,\n observeCodeAgentSession,\n} from './code-agent-observation'\n\nexport type {\n CodeAgentSessionAction,\n CodeAgentSessionActionKind,\n CodeAgentSessionActionStatus,\n CodeAgentSessionActionSurface,\n CodeAgentSessionExecutionReceipt,\n CodeAgentSessionObservation,\n CodeAgentSessionSource,\n CodeAgentSessionTerminalStatus,\n ObserveCodeAgentSessionOptions,\n} from './code-agent-observation'\nexport { observeCodeAgentSession } from './code-agent-observation'\n\nexport interface ParsedCodeAgentJsonl {\n entries: unknown[]\n malformedLines: number\n}\n\nexport interface CodeAgentSessionMetrics {\n entries: number\n userMessages: number\n assistantMessages: number\n reasoningItems: number\n toolCalls: number\n toolOutputs: number\n toolErrors: number\n unclassifiedErrors: number\n patchAttempts: number\n patchSuccesses: number\n patchFailures: number\n turnsStarted: number\n turnsCompleted: number\n turnsAborted: number\n contextCompactions: number\n mcpCalls: number\n subagentCalls: number\n skillCalls: number\n hookCalls: number\n webCalls: number\n codeActions: number\n prLinks: number\n fileSnapshots: number\n graphNodes: number\n graphEdges: number\n actionCandidates: number\n verificationReports: number\n completionDecisions: number\n reliabilityRows: number\n reliabilityLift: number\n inputTokens: number\n outputTokens: number\n reasoningTokens: number\n cachedTokens: number\n cacheWriteTokens: number\n observedCostUsd: number\n observedCostCaptured?: boolean\n wallMs: number\n processScore: number\n}\n\nexport interface CodeAgentSessionDiagnostic {\n source: CodeAgentSessionSource\n sessionId: string\n sourcePath?: string\n entries: number\n malformedLines: number\n hasExplicitTerminalSignal: boolean\n hasFinalOutput: boolean\n hasQualityLabel: boolean\n hasTokenUsage: boolean\n hasCost: boolean\n costKind?: RunCostProvenance['kind']\n warnings: string[]\n}\n\nexport interface CodeAgentSessionIntakeResult {\n runs: RunRecord[]\n diagnostics: CodeAgentSessionDiagnostic[]\n metrics: CodeAgentSessionMetrics[]\n observations: CodeAgentSessionObservation[]\n}\n\nexport interface CodeAgentSessionIntakeOptions {\n entries: unknown[]\n malformedLines?: number\n sourcePath?: string\n experimentId?: string\n candidateId?: string\n seed?: number\n splitTag?: RunSplitTag\n scenarioId?: string\n model?: string\n promptHash?: string\n configHash?: string\n commitSha?: string\n score?: number\n /** Explicit cost receipt. When omitted, source-reported cost wins, then a\n * token-priced estimate, then uncaptured. */\n costProvenance?: RunCostProvenance\n /** Exact executor-owned process result. This is required when a provider's\n * JSON stream has no terminal event, as with `opencode run --format json`. */\n execution?: CodeAgentSessionExecutionReceipt\n}\n\nexport function parseCodeAgentJsonl(jsonl: string): ParsedCodeAgentJsonl {\n const entries: unknown[] = []\n let malformedLines = 0\n for (const line of jsonl.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed) continue\n try {\n entries.push(JSON.parse(trimmed))\n } catch {\n malformedLines += 1\n }\n }\n return { entries, malformedLines }\n}\n\nexport function fromCodexSession(\n options: CodeAgentSessionIntakeOptions,\n): CodeAgentSessionIntakeResult {\n return fromCodeAgentSession('codex', options)\n}\n\nexport function fromClaudeCodeSession(\n options: CodeAgentSessionIntakeOptions,\n): CodeAgentSessionIntakeResult {\n return fromCodeAgentSession('claude-code', options)\n}\n\nexport function fromOpenCodeSession(\n options: CodeAgentSessionIntakeOptions,\n): CodeAgentSessionIntakeResult {\n return fromCodeAgentSession('opencode', options)\n}\n\nexport function fromKimiCodeSession(\n options: CodeAgentSessionIntakeOptions,\n): CodeAgentSessionIntakeResult {\n return fromCodeAgentSession('kimi-code', options)\n}\n\nexport function fromPiSession(\n options: CodeAgentSessionIntakeOptions,\n): CodeAgentSessionIntakeResult {\n return fromCodeAgentSession('pi', options)\n}\n\nexport const fromPigraphSession = fromPiSession\n\nfunction fromCodeAgentSession(\n source: CodeAgentSessionSource,\n options: CodeAgentSessionIntakeOptions,\n): CodeAgentSessionIntakeResult {\n const entries = options.entries.filter(isRecord)\n if (entries.length === 0) {\n return {\n runs: [],\n diagnostics: [\n {\n source,\n sessionId: fallbackSessionId(source, options.sourcePath),\n sourcePath: options.sourcePath,\n entries: 0,\n malformedLines: options.malformedLines ?? 0,\n hasExplicitTerminalSignal: false,\n hasFinalOutput: false,\n hasQualityLabel: false,\n hasTokenUsage: false,\n hasCost: false,\n costKind: 'uncaptured',\n warnings: ['no parseable session entries'],\n },\n ],\n metrics: [],\n observations: [],\n }\n }\n\n const metrics = metricsFor(source, entries)\n const sessionId =\n sessionIdFromEntries(source, entries) ?? fallbackSessionId(source, options.sourcePath)\n const observation = observeCodeAgentSession({\n source,\n entries,\n sourcePath: options.sourcePath,\n execution: options.execution,\n })\n applyObservedSurfaceMetrics(metrics, observation)\n const model = withSnapshot(options.model ?? modelFromEntries(source, entries) ?? source)\n const tokenUsage: RunTokenUsage = {\n input: metrics.inputTokens,\n output: metrics.outputTokens,\n ...(metrics.reasoningTokens > 0 ? { reasoning: metrics.reasoningTokens } : {}),\n ...(metrics.cachedTokens > 0 ? { cached: metrics.cachedTokens } : {}),\n ...(metrics.cacheWriteTokens > 0 ? { cacheWrite: metrics.cacheWriteTokens } : {}),\n }\n const { costUsd, costProvenance } = resolveSessionCost(options.costProvenance, metrics, model)\n const qualityScore = finiteScore(options.score)\n const invalidQualityScore = options.score !== undefined && qualityScore === undefined\n const promptHash =\n options.promptHash ?? hashString(`prompt:${source}:${firstUserText(entries) ?? ''}`)\n const configHash =\n options.configHash ??\n hashJson({\n source,\n model,\n sourcePath: options.sourcePath,\n cwd: cwdFromEntries(entries),\n entryCount: entries.length,\n })\n const explicitTerminal = observation.terminal.explicit\n const warnings = diagnosticsFor(metrics, {\n model,\n explicitTerminal,\n malformedLines: options.malformedLines ?? 0,\n hasQualityLabel: qualityScore !== undefined,\n invalidQualityScore,\n costKind: costProvenance.kind,\n })\n\n const terminalOutcome = terminalOutcomeFromSession(observation.terminal)\n const processExitCode = options.execution?.exitCode\n const splitTag = options.splitTag ?? 'holdout'\n const run: RunRecord = {\n runId: `${source}:${sessionId}`,\n experimentId: options.experimentId ?? `${source}-local-sessions`,\n candidateId: options.candidateId ?? model,\n seed: options.seed ?? stableSeed(sessionId),\n model,\n promptHash,\n configHash,\n commitSha: options.commitSha ?? 'local-session',\n wallMs: metrics.wallMs,\n costUsd,\n costProvenance,\n tokenUsage,\n terminalOutcome,\n ...(terminalOutcome === 'failed'\n ? {\n terminalFailureReason:\n processExitCode !== undefined && processExitCode !== 0\n ? `process exited with code ${processExitCode}`\n : metrics.turnsAborted > 0\n ? 'turn aborted'\n : 'session reported terminal failure',\n }\n : {}),\n outcome: {\n ...(qualityScore === undefined\n ? {}\n : splitTag === 'holdout'\n ? { holdoutScore: qualityScore }\n : { searchScore: qualityScore }),\n raw: {\n entries: metrics.entries,\n user_messages: metrics.userMessages,\n assistant_messages: metrics.assistantMessages,\n reasoning_items: metrics.reasoningItems,\n tool_calls: metrics.toolCalls,\n tool_outputs: metrics.toolOutputs,\n tool_errors: metrics.toolErrors,\n execution_error_count: metrics.toolErrors,\n process_error_count: terminalOutcome === 'failed' ? 1 : 0,\n unclassified_error_count: metrics.unclassifiedErrors,\n ...(processExitCode !== undefined ? { process_exit_code: processExitCode } : {}),\n patch_attempts: metrics.patchAttempts,\n patch_successes: metrics.patchSuccesses,\n patch_failures: metrics.patchFailures,\n turns_started: metrics.turnsStarted,\n turns_completed: metrics.turnsCompleted,\n turns_aborted: metrics.turnsAborted,\n context_compactions: metrics.contextCompactions,\n mcp_calls: metrics.mcpCalls,\n subagent_calls: metrics.subagentCalls,\n skill_calls: metrics.skillCalls,\n hook_calls: metrics.hookCalls,\n web_calls: metrics.webCalls,\n code_actions: metrics.codeActions,\n pr_links: metrics.prLinks,\n file_snapshots: metrics.fileSnapshots,\n graph_nodes: metrics.graphNodes,\n graph_edges: metrics.graphEdges,\n action_candidates: metrics.actionCandidates,\n verification_reports: metrics.verificationReports,\n completion_decisions: metrics.completionDecisions,\n reliability_rows: metrics.reliabilityRows,\n reliability_lift: metrics.reliabilityLift,\n input_tokens: metrics.inputTokens,\n output_tokens: metrics.outputTokens,\n reasoning_tokens: metrics.reasoningTokens,\n cached_tokens: metrics.cachedTokens,\n cache_write_tokens: metrics.cacheWriteTokens,\n observed_cost_usd: metrics.observedCostUsd,\n observed_cost_captured: metrics.observedCostCaptured ? 1 : 0,\n estimated_cost_usd: costProvenance.kind === 'estimated' ? costProvenance.usd : 0,\n process_score: metrics.processScore,\n explicit_terminal_signal: explicitTerminal ? 1 : 0,\n quality_label_present: qualityScore !== undefined ? 1 : 0,\n cost_observed: costProvenance.kind === 'observed' ? 1 : 0,\n cost_estimated: costProvenance.kind === 'estimated' ? 1 : 0,\n cost_uncaptured: costProvenance.kind === 'uncaptured' ? 1 : 0,\n cost_unknown: costProvenance.kind === 'uncaptured' ? 1 : 0,\n },\n },\n splitTag,\n scenarioId: options.scenarioId ?? sessionId,\n }\n\n return {\n runs: [run],\n diagnostics: [\n {\n source,\n sessionId,\n sourcePath: options.sourcePath,\n entries: entries.length,\n malformedLines: options.malformedLines ?? 0,\n hasExplicitTerminalSignal: explicitTerminal,\n hasFinalOutput: observation.finalText !== null,\n hasQualityLabel: qualityScore !== undefined,\n hasTokenUsage:\n metrics.inputTokens > 0 ||\n metrics.outputTokens > 0 ||\n metrics.reasoningTokens > 0 ||\n metrics.cachedTokens > 0 ||\n metrics.cacheWriteTokens > 0,\n hasCost: costProvenance.kind !== 'uncaptured',\n costKind: costProvenance.kind,\n warnings,\n },\n ],\n metrics: [metrics],\n observations: [{ ...observation, sessionId }],\n }\n}\n\nfunction terminalOutcomeFromSession(\n terminal: CodeAgentSessionObservation['terminal'],\n): RunTerminalOutcome {\n if (!terminal.explicit) return 'unknown'\n if (terminal.status === 'completed') return 'succeeded'\n if (terminal.status === 'failed') return 'failed'\n return 'unknown'\n}\n\nfunction metricsFor(\n source: CodeAgentSessionSource,\n entries: Record<string, unknown>[],\n): CodeAgentSessionMetrics {\n switch (source) {\n case 'codex':\n return codexMetrics(entries)\n case 'claude-code':\n return claudeCodeMetrics(entries)\n case 'opencode':\n return openCodeMetrics(entries)\n case 'kimi-code':\n return kimiCodeMetrics(entries)\n case 'pi':\n return piMetrics(entries)\n }\n}\n\nfunction codexMetrics(entries: Record<string, unknown>[]): CodeAgentSessionMetrics {\n const metrics = emptyMetrics(entries.length)\n const startedToolIds = new Set<string>()\n let startedAt: number | undefined\n let completedAt: number | undefined\n\n for (const entry of entries) {\n const payload = record(entry.payload) ?? {}\n const entryType = stringField(entry, 'type')\n const payloadType = stringField(payload, 'type')\n const timestamp = timestampMs(entry.timestamp)\n if (timestamp !== undefined) {\n startedAt = startedAt === undefined ? timestamp : Math.min(startedAt, timestamp)\n completedAt = completedAt === undefined ? timestamp : Math.max(completedAt, timestamp)\n }\n\n if (entryType === 'turn.started') metrics.turnsStarted += 1\n if (entryType === 'turn.completed') {\n metrics.turnsCompleted += 1\n addCodexExecUsage(metrics, record(entry.usage))\n }\n if (entryType === 'turn.failed') metrics.turnsAborted += 1\n if (entryType === 'error') metrics.unclassifiedErrors += 1\n\n const item = record(entry.item)\n if (item && (entryType === 'item.started' || entryType === 'item.completed')) {\n addCodexExecItem(metrics, startedToolIds, entryType, item)\n }\n\n if (entryType === 'response_item') {\n if (payloadType === 'function_call' || payloadType === 'custom_tool_call')\n metrics.toolCalls += 1\n if (payloadType === 'function_call_output' || payloadType === 'custom_tool_call_output')\n metrics.toolOutputs += 1\n if (payloadType === 'reasoning') metrics.reasoningItems += 1\n if (payloadType === 'message' && stringField(payload, 'role') === 'assistant')\n metrics.assistantMessages += 1\n }\n\n if (entryType === 'event_msg') {\n if (payloadType === 'user_message') metrics.userMessages += 1\n if (payloadType === 'agent_message') metrics.assistantMessages += 1\n if (payloadType === 'task_started') {\n metrics.turnsStarted += 1\n const started = timestampMs(payload.started_at)\n if (started !== undefined) {\n startedAt = startedAt === undefined ? started : Math.min(startedAt, started)\n }\n }\n if (payloadType === 'task_complete') {\n metrics.turnsCompleted += 1\n const completed = timestampMs(payload.completed_at)\n if (completed !== undefined) {\n completedAt = completedAt === undefined ? completed : Math.max(completedAt, completed)\n }\n const duration = numberField(payload, 'duration_ms')\n if (duration !== undefined) metrics.wallMs = Math.max(metrics.wallMs, duration)\n }\n if (payloadType === 'turn_aborted') {\n metrics.turnsAborted += 1\n const completed = timestampMs(payload.completed_at)\n if (completed !== undefined) {\n completedAt = completedAt === undefined ? completed : Math.max(completedAt, completed)\n }\n }\n if (payloadType === 'context_compacted') metrics.contextCompactions += 1\n if (payloadType === 'patch_apply_end') {\n metrics.patchAttempts += 1\n if (payload.success === true) metrics.patchSuccesses += 1\n else {\n metrics.patchFailures += 1\n metrics.toolErrors += 1\n }\n }\n if (payloadType === 'token_count')\n setCodexCumulativeUsage(metrics, record(record(payload.info)?.total_token_usage))\n const result = record(payload.result)\n if (result && 'Err' in result) metrics.unclassifiedErrors += 1\n }\n }\n\n if (metrics.wallMs === 0 && startedAt !== undefined && completedAt !== undefined) {\n metrics.wallMs = Math.max(0, completedAt - startedAt)\n }\n metrics.processScore = codexProcessScore(metrics)\n return metrics\n}\n\nfunction addCodexExecItem(\n metrics: CodeAgentSessionMetrics,\n startedToolIds: Set<string>,\n eventType: 'item.started' | 'item.completed',\n item: Record<string, unknown>,\n): void {\n const itemType = stringField(item, 'type')\n const itemId = stringField(item, 'id')\n const isTool =\n itemType === 'command_execution' ||\n itemType === 'mcp_tool_call' ||\n itemType === 'collab_tool_call' ||\n itemType === 'web_search'\n\n if (eventType === 'item.started' && isTool) {\n metrics.toolCalls += 1\n if (itemId) startedToolIds.add(itemId)\n }\n if (eventType === 'item.completed' && isTool) {\n if (!itemId || !startedToolIds.has(itemId)) metrics.toolCalls += 1\n metrics.toolOutputs += 1\n }\n if (eventType !== 'item.completed') return\n\n if (itemType === 'agent_message' || itemType === 'message') metrics.assistantMessages += 1\n if (itemType === 'reasoning') metrics.reasoningItems += 1\n if (itemType === 'file_change') {\n metrics.patchAttempts += 1\n const status = stringField(item, 'status')\n if (status === 'completed') metrics.patchSuccesses += 1\n if (status === 'failed') {\n metrics.patchFailures += 1\n metrics.toolErrors += 1\n }\n }\n if (itemType === 'error') metrics.unclassifiedErrors += 1\n else if (codexExecToolFailed(itemType, item)) metrics.toolErrors += 1\n}\n\nfunction codexExecToolFailed(itemType: string | undefined, item: Record<string, unknown>): boolean {\n const status = stringField(item, 'status')\n if (itemType === 'command_execution') {\n const exitCode = numberField(item, 'exit_code')\n return (\n status === 'failed' || status === 'declined' || (exitCode !== undefined && exitCode !== 0)\n )\n }\n if (itemType === 'mcp_tool_call') return status === 'failed' || record(item.error) !== null\n return itemType === 'collab_tool_call' && status === 'failed'\n}\n\nfunction addCodexExecUsage(\n metrics: CodeAgentSessionMetrics,\n usage: Record<string, unknown> | null,\n): void {\n const parsed = readUsage(usage)\n metrics.inputTokens += parsed.input\n metrics.outputTokens += parsed.output\n metrics.reasoningTokens += parsed.reasoning\n metrics.cachedTokens += parsed.cached\n metrics.cacheWriteTokens += parsed.cacheWrite\n}\n\nfunction setCodexCumulativeUsage(\n metrics: CodeAgentSessionMetrics,\n usage: Record<string, unknown> | null,\n): void {\n const parsed = readUsage(usage)\n metrics.inputTokens = Math.max(metrics.inputTokens, parsed.input)\n metrics.outputTokens = Math.max(metrics.outputTokens, parsed.output)\n metrics.reasoningTokens = Math.max(metrics.reasoningTokens, parsed.reasoning)\n metrics.cachedTokens = Math.max(metrics.cachedTokens, parsed.cached)\n metrics.cacheWriteTokens = Math.max(metrics.cacheWriteTokens, parsed.cacheWrite)\n}\n\nfunction claudeCodeMetrics(entries: Record<string, unknown>[]): CodeAgentSessionMetrics {\n const metrics = emptyMetrics(entries.length)\n let startedAt: number | undefined\n let completedAt: number | undefined\n\n for (const entry of entries) {\n const type = stringField(entry, 'type')\n const timestamp = timestampMs(entry.timestamp)\n if (timestamp !== undefined) {\n startedAt = startedAt === undefined ? timestamp : Math.min(startedAt, timestamp)\n completedAt = completedAt === undefined ? timestamp : Math.max(completedAt, timestamp)\n }\n\n if (type === 'user') metrics.userMessages += 1\n if (type === 'assistant') metrics.assistantMessages += 1\n if (type === 'pr-link') metrics.prLinks += 1\n if (type === 'file-history-snapshot') metrics.fileSnapshots += 1\n\n const message = record(entry.message)\n if (message) addUsage(metrics, record(message.usage))\n const content = Array.isArray(message?.content) ? message.content : []\n for (const item of content) {\n const part = record(item)\n if (!part) continue\n const partType = stringField(part, 'type')\n if (partType === 'thinking') metrics.reasoningItems += 1\n if (partType === 'tool_use') metrics.toolCalls += 1\n if (partType === 'tool_result') {\n metrics.toolOutputs += 1\n if (part.is_error === true) metrics.toolErrors += 1\n }\n }\n }\n\n if (startedAt !== undefined && completedAt !== undefined)\n metrics.wallMs = Math.max(0, completedAt - startedAt)\n metrics.processScore = claudeProcessScore(metrics)\n return metrics\n}\n\nfunction openCodeMetrics(entries: Record<string, unknown>[]): CodeAgentSessionMetrics {\n const metrics = emptyMetrics(entries.length)\n const messageUsage = emptyTokenTotals()\n const partUsage = emptyTokenTotals()\n let messageCost = 0\n let partCost = 0\n let messageCostCaptured = false\n let partCostCaptured = false\n let startedAt: number | undefined\n let completedAt: number | undefined\n\n for (const entry of entries) {\n const time = record(entry.time)\n const created = timestampMs(time?.created)\n const completed = timestampMs(time?.completed)\n if (created !== undefined)\n startedAt = startedAt === undefined ? created : Math.min(startedAt, created)\n if (completed !== undefined)\n completedAt = completedAt === undefined ? completed : Math.max(completedAt, completed)\n\n const role = stringField(entry, 'role')\n if (role === 'user') metrics.userMessages += 1\n if (role === 'assistant') {\n metrics.assistantMessages += 1\n const finish = stringField(entry, 'finish')\n if (finish === 'stop') metrics.turnsCompleted += 1\n if (finish === 'error') metrics.turnsAborted += 1\n }\n\n const type = stringField(entry, 'type')\n if (type === 'reasoning') metrics.reasoningItems += 1\n if (type === 'tool') {\n metrics.toolCalls += 1\n const status = stringField(record(entry.state) ?? {}, 'status')\n if (status === 'completed') metrics.toolOutputs += 1\n if (status === 'error') {\n metrics.toolOutputs += 1\n metrics.toolErrors += 1\n }\n }\n if (type === 'patch') {\n metrics.patchAttempts += 1\n metrics.patchSuccesses += 1\n }\n\n const cost = numberField(entry, 'cost')\n if (record(entry.tokens) && role) {\n addUsageTo(messageUsage, record(entry.tokens))\n if (cost !== undefined) {\n messageCost += cost\n messageCostCaptured = true\n }\n } else if (record(entry.tokens)) {\n addUsageTo(partUsage, record(entry.tokens))\n if (cost !== undefined) {\n partCost += cost\n partCostCaptured = true\n }\n }\n }\n\n const usage = hasTokenTotals(messageUsage) ? messageUsage : partUsage\n metrics.inputTokens = usage.input\n metrics.outputTokens = usage.output\n metrics.reasoningTokens = usage.reasoning\n metrics.cachedTokens = usage.cached\n metrics.cacheWriteTokens = usage.cacheWrite\n metrics.observedCostUsd = messageCostCaptured ? messageCost : partCost\n metrics.observedCostCaptured = messageCostCaptured || partCostCaptured\n if (metrics.wallMs === 0 && startedAt !== undefined && completedAt !== undefined)\n metrics.wallMs = Math.max(0, completedAt - startedAt)\n metrics.processScore = terminalProcessScore(metrics)\n return metrics\n}\n\nfunction kimiCodeMetrics(entries: Record<string, unknown>[]): CodeAgentSessionMetrics {\n const metrics = emptyMetrics(entries.length)\n let startedAt: number | undefined\n let completedAt: number | undefined\n\n for (const entry of entries) {\n const timestamp = timestampMs(entry.timestamp)\n if (timestamp !== undefined) {\n startedAt = startedAt === undefined ? timestamp : Math.min(startedAt, timestamp)\n completedAt = completedAt === undefined ? timestamp : Math.max(completedAt, timestamp)\n }\n\n const role = stringField(entry, 'role')\n if (role === 'user') metrics.userMessages += 1\n if (role === 'assistant') metrics.assistantMessages += 1\n if (role === '_usage') addUsage(metrics, entry)\n\n const message = record(entry.message)\n const messageType = message ? stringField(message, 'type') : undefined\n const payload = record(message?.payload) ?? {}\n if (messageType === 'TurnBegin') {\n metrics.userMessages += 1\n metrics.turnsStarted += 1\n }\n if (messageType === 'TurnEnd') metrics.turnsCompleted += 1\n if (messageType === 'StepInterrupted') metrics.turnsAborted += 1\n if (messageType === 'StepBegin') metrics.reasoningItems += 1\n if (messageType === 'ContentPart') {\n const payloadType = stringField(payload, 'type')\n if (payloadType === 'think') metrics.reasoningItems += 1\n if (payloadType === 'text') metrics.assistantMessages += 1\n }\n if (messageType === 'ToolCall') metrics.toolCalls += 1\n if (messageType === 'ToolResult') {\n metrics.toolOutputs += 1\n if (record(payload.return_value)?.is_error === true) metrics.toolErrors += 1\n }\n if (messageType === 'StatusUpdate') addUsage(metrics, record(payload.token_usage))\n if (messageType === 'Notification') {\n const notification = record(payload.payload)\n const exitCode = numberField(notification ?? {}, 'exit_code')\n if (notification?.timed_out === true || (exitCode !== undefined && exitCode !== 0)) {\n metrics.toolErrors += 1\n }\n }\n }\n\n if (startedAt !== undefined && completedAt !== undefined)\n metrics.wallMs = Math.max(0, completedAt - startedAt)\n metrics.processScore = terminalProcessScore(metrics)\n return metrics\n}\n\nfunction piMetrics(entries: Record<string, unknown>[]): CodeAgentSessionMetrics {\n const metrics = emptyMetrics(entries.length)\n let bestReliabilityScore: number | undefined\n\n for (const entry of entries) {\n const nodes = Array.isArray(entry.nodes) ? entry.nodes : []\n const edges = Array.isArray(entry.edges) ? entry.edges : []\n metrics.graphNodes += nodes.length\n metrics.graphEdges += edges.length\n\n for (const node of nodes) {\n const obj = record(node)\n const ir = record(obj?.ir) ?? obj\n const kind = stringField(ir ?? {}, 'kind')\n if (kind === 'ActionCandidate') metrics.actionCandidates += 1\n if (kind === 'ToolInvocation') metrics.toolCalls += 1\n if (kind === 'ToolResult') metrics.toolOutputs += 1\n if (kind === 'VerificationReport') metrics.verificationReports += 1\n if (kind === 'CompletionDecision') {\n metrics.completionDecisions += 1\n metrics.turnsCompleted += 1\n }\n }\n\n const averageReliability = numberField(entry, 'averageNodeReliability')\n if (averageReliability !== undefined)\n bestReliabilityScore = maxOptional(bestReliabilityScore, averageReliability)\n const pessimisticPath = numberField(entry, 'pessimisticPathEstimate')\n if (pessimisticPath !== undefined)\n bestReliabilityScore = maxOptional(bestReliabilityScore, pessimisticPath)\n\n const rows = Array.isArray(entry.rows) ? entry.rows : []\n metrics.reliabilityRows += rows.length\n for (const row of rows) {\n const obj = record(row)\n if (!obj) continue\n const lift = numberField(obj, 'lift')\n if (lift !== undefined) metrics.reliabilityLift = Math.max(metrics.reliabilityLift, lift)\n const validated = numberField(obj, 'validatedSuccessEstimate')\n if (validated !== undefined)\n bestReliabilityScore = maxOptional(bestReliabilityScore, validated)\n }\n }\n\n metrics.processScore =\n bestReliabilityScore !== undefined\n ? clamp01(bestReliabilityScore)\n : metrics.completionDecisions > 0\n ? 1\n : 0\n return metrics\n}\n\nfunction emptyMetrics(entries: number): CodeAgentSessionMetrics {\n return {\n entries,\n userMessages: 0,\n assistantMessages: 0,\n reasoningItems: 0,\n toolCalls: 0,\n toolOutputs: 0,\n toolErrors: 0,\n unclassifiedErrors: 0,\n patchAttempts: 0,\n patchSuccesses: 0,\n patchFailures: 0,\n turnsStarted: 0,\n turnsCompleted: 0,\n turnsAborted: 0,\n contextCompactions: 0,\n mcpCalls: 0,\n subagentCalls: 0,\n skillCalls: 0,\n hookCalls: 0,\n webCalls: 0,\n codeActions: 0,\n prLinks: 0,\n fileSnapshots: 0,\n graphNodes: 0,\n graphEdges: 0,\n actionCandidates: 0,\n verificationReports: 0,\n completionDecisions: 0,\n reliabilityRows: 0,\n reliabilityLift: 0,\n inputTokens: 0,\n outputTokens: 0,\n reasoningTokens: 0,\n cachedTokens: 0,\n cacheWriteTokens: 0,\n observedCostUsd: 0,\n observedCostCaptured: false,\n wallMs: 0,\n processScore: 0,\n }\n}\n\nfunction codexProcessScore(metrics: CodeAgentSessionMetrics): number {\n const terminalTurns = metrics.turnsCompleted + metrics.turnsAborted\n const base =\n terminalTurns > 0\n ? metrics.turnsCompleted / terminalTurns\n : metrics.assistantMessages > 0\n ? 0.5\n : 0\n return penalizeErrors(base, metrics)\n}\n\nfunction claudeProcessScore(metrics: CodeAgentSessionMetrics): number {\n const base = metrics.prLinks > 0 ? 1 : metrics.assistantMessages > 0 ? 0.75 : 0\n return penalizeErrors(base, metrics)\n}\n\nfunction terminalProcessScore(metrics: CodeAgentSessionMetrics): number {\n const terminalTurns = metrics.turnsCompleted + metrics.turnsAborted\n const base =\n terminalTurns > 0\n ? metrics.turnsCompleted / terminalTurns\n : metrics.assistantMessages > 0\n ? 0.75\n : metrics.toolCalls > 0\n ? 0.5\n : 0\n return penalizeErrors(base, metrics)\n}\n\nfunction penalizeErrors(base: number, metrics: CodeAgentSessionMetrics): number {\n const operations = Math.max(1, metrics.toolCalls + metrics.patchAttempts)\n const errorRate = Math.min(1, (metrics.toolErrors + metrics.patchFailures) / operations)\n return clamp01(base * (1 - 0.5 * errorRate))\n}\n\ntype TokenTotals = Required<Omit<RunTokenUsage, 'tokensKnown'>>\n\nfunction emptyTokenTotals(): TokenTotals {\n return { input: 0, output: 0, reasoning: 0, cached: 0, cacheWrite: 0 }\n}\n\nfunction hasTokenTotals(usage: TokenTotals): boolean {\n return (\n usage.input > 0 ||\n usage.output > 0 ||\n usage.reasoning > 0 ||\n usage.cached > 0 ||\n usage.cacheWrite > 0\n )\n}\n\nfunction addUsage(\n metrics: CodeAgentSessionMetrics,\n usage: Record<string, unknown> | null | undefined,\n): void {\n const parsed = readUsage(usage)\n metrics.inputTokens += parsed.input\n metrics.outputTokens += parsed.output\n metrics.reasoningTokens += parsed.reasoning\n metrics.cachedTokens += parsed.cached\n metrics.cacheWriteTokens += parsed.cacheWrite\n}\n\nfunction addUsageTo(totals: TokenTotals, usage: Record<string, unknown> | null | undefined): void {\n const parsed = readUsage(usage)\n totals.input += parsed.input\n totals.output += parsed.output\n totals.reasoning += parsed.reasoning\n totals.cached += parsed.cached\n totals.cacheWrite += parsed.cacheWrite\n}\n\nfunction readUsage(usage: Record<string, unknown> | null | undefined): TokenTotals {\n const parsed = extractUsage(usage)\n return {\n input: parsed?.input ?? 0,\n output: parsed?.output ?? 0,\n reasoning: parsed?.reasoning ?? 0,\n cached: parsed?.cached ?? 0,\n cacheWrite: parsed?.cacheWrite ?? 0,\n }\n}\n\nfunction resolveSessionCost(\n explicit: RunCostProvenance | undefined,\n metrics: CodeAgentSessionMetrics,\n model: string,\n): { costUsd: number | null; costProvenance: RunCostProvenance } {\n if (explicit) {\n if (explicit.kind === 'uncaptured') {\n if (explicit.usd !== null) throw new Error('uncaptured cost must have usd: null')\n return { costUsd: null, costProvenance: explicit }\n }\n if (!Number.isFinite(explicit.usd) || explicit.usd < 0) {\n throw new Error(`${explicit.kind} cost must be a finite, non-negative USD amount`)\n }\n return { costUsd: explicit.usd, costProvenance: explicit }\n }\n\n if (metrics.observedCostCaptured) {\n const costProvenance = { kind: 'observed', usd: metrics.observedCostUsd } as const\n return { costUsd: metrics.observedCostUsd, costProvenance }\n }\n\n const hasUsage = metrics.inputTokens > 0 || metrics.outputTokens > 0\n if (hasUsage && isModelPriced(model)) {\n const costUsd = estimateCost(metrics.inputTokens, metrics.outputTokens, model)\n return { costUsd, costProvenance: { kind: 'estimated', usd: costUsd } }\n }\n\n return { costUsd: null, costProvenance: { kind: 'uncaptured', usd: null } }\n}\n\nfunction diagnosticsFor(\n metrics: CodeAgentSessionMetrics,\n options: {\n model: string\n explicitTerminal: boolean\n malformedLines: number\n hasQualityLabel: boolean\n invalidQualityScore: boolean\n costKind: RunCostProvenance['kind']\n },\n): string[] {\n const warnings: string[] = []\n if (options.invalidQualityScore) warnings.push('non-finite task quality score omitted')\n else if (!options.hasQualityLabel) warnings.push('task quality score not supplied')\n if (!options.explicitTerminal) warnings.push('no explicit terminal success/failure signal')\n if (\n metrics.inputTokens === 0 &&\n metrics.outputTokens === 0 &&\n metrics.reasoningTokens === 0 &&\n metrics.cachedTokens === 0 &&\n metrics.cacheWriteTokens === 0\n ) {\n warnings.push('missing token usage')\n }\n if (options.costKind === 'estimated')\n warnings.push('USD cost estimated from token usage and model pricing')\n if (options.costKind === 'uncaptured') warnings.push('USD cost uncaptured')\n if (options.costKind === 'uncaptured' && !isModelPriced(options.model))\n warnings.push('model pricing unknown')\n if (options.malformedLines > 0)\n warnings.push(`${options.malformedLines} malformed JSONL lines skipped`)\n return warnings\n}\n\nfunction applyObservedSurfaceMetrics(\n metrics: CodeAgentSessionMetrics,\n observation: CodeAgentSessionObservation,\n): void {\n const actions = observation.actions.filter(\n (action) => action.kind === 'tool' || action.kind === 'patch',\n )\n metrics.mcpCalls = actions.filter((action) => action.surface === 'mcp').length\n metrics.subagentCalls = actions.filter((action) => action.surface === 'subagent').length\n metrics.skillCalls = actions.filter((action) => action.surface === 'skill').length\n metrics.hookCalls = actions.filter((action) => action.surface === 'hook').length\n metrics.webCalls = actions.filter((action) => action.surface === 'web').length\n metrics.codeActions = actions.filter((action) => action.surface === 'code').length\n}\n\nfunction sessionIdFromEntries(\n source: CodeAgentSessionSource,\n entries: Record<string, unknown>[],\n): string | undefined {\n for (const entry of entries) {\n if (source === 'codex') {\n const threadId = stringField(entry, 'thread_id')\n if (threadId) return threadId\n const payload = record(entry.payload)\n const id = payload ? stringField(payload, 'id') : undefined\n if (id) return id\n }\n const message = record(entry.message)\n const payload = record(message?.payload)\n const sessionId =\n stringField(entry, 'sessionID') ??\n stringField(entry, 'sessionId') ??\n stringField(entry, 'session_id') ??\n stringField(payload ?? {}, 'session_id')\n if (sessionId) return sessionId\n }\n return undefined\n}\n\nfunction modelFromEntries(\n source: CodeAgentSessionSource,\n entries: Record<string, unknown>[],\n): string | undefined {\n let providerModel: string | undefined\n for (const entry of entries) {\n if (source === 'codex') {\n const payload = record(entry.payload)\n const model = payload ? stringField(payload, 'model') : undefined\n if (model) return model\n providerModel =\n providerModel ?? (payload ? stringField(payload, 'model_provider') : undefined)\n }\n const openCodeModel = stringField(entry, 'modelID')\n if (openCodeModel) {\n const provider = stringField(entry, 'providerID')\n return provider ? `${provider}/${openCodeModel}` : openCodeModel\n }\n const modelObject = record(entry.model)\n const nestedModel = stringField(modelObject ?? {}, 'modelID')\n if (nestedModel) {\n const provider = stringField(modelObject ?? {}, 'providerID')\n return provider ? `${provider}/${nestedModel}` : nestedModel\n }\n const message = record(entry.message)\n const model = message ? stringField(message, 'model') : undefined\n if (model) return model\n }\n return providerModel\n}\n\nfunction cwdFromEntries(entries: Record<string, unknown>[]): string | undefined {\n for (const entry of entries) {\n const path = record(entry.path)\n const cwd =\n stringField(entry, 'cwd') ??\n stringField(path ?? {}, 'cwd') ??\n stringField(path ?? {}, 'root') ??\n (record(entry.payload) ? stringField(record(entry.payload)!, 'cwd') : undefined)\n if (cwd) return cwd\n }\n return undefined\n}\n\nfunction firstUserText(entries: Record<string, unknown>[]): string | undefined {\n for (const entry of entries) {\n const payload = record(entry.payload)\n const payloadType = payload ? stringField(payload, 'type') : undefined\n if (payloadType === 'user_message') return stringField(payload!, 'message')\n\n if (stringField(entry, 'role') === 'user') {\n const content = entry.content\n if (typeof content === 'string') return content\n }\n\n const wirePayload = record(record(entry.message)?.payload)\n const userInput = wirePayload ? stringField(wirePayload, 'user_input') : undefined\n if (userInput) return userInput\n\n const message = record(entry.message)\n if (message && stringField(message, 'role') === 'user') {\n const content = message.content\n if (typeof content === 'string') return content\n if (Array.isArray(content)) {\n const text = content\n .map((part) => {\n const obj = record(part)\n return obj ? stringField(obj, 'text') : undefined\n })\n .filter((part): part is string => part !== undefined)\n .join('\\n')\n if (text) return text\n }\n }\n }\n return undefined\n}\n\nfunction fallbackSessionId(source: CodeAgentSessionSource, sourcePath: string | undefined): string {\n return hashString(`${source}:${sourcePath ?? 'unknown-session'}`).slice(\n 'sha256:'.length,\n 'sha256:'.length + 20,\n )\n}\n\nfunction withSnapshot(model: string): string {\n const trimmed = model.trim() || 'unknown'\n if (trimmed.includes('@') || /-\\d{8}$/.test(trimmed) || /-\\d{4}-\\d{2}-\\d{2}$/.test(trimmed)) {\n return trimmed\n }\n return `${trimmed}@observed-local`\n}\n\nfunction hashJson(value: unknown): string {\n return hashString(JSON.stringify(value))\n}\n\nfunction hashString(value: string): string {\n return `sha256:${createHash('sha256').update(value).digest('hex')}`\n}\n\nfunction stableSeed(value: string): number {\n return createHash('sha256').update(value).digest().readUInt32BE(0)\n}\n\nfunction maxOptional(current: number | undefined, next: number): number {\n return current === undefined ? next : Math.max(current, next)\n}\n\nfunction clamp01(value: number): number {\n if (!Number.isFinite(value)) return 0\n return Math.max(0, Math.min(1, value))\n}\n\nfunction finiteScore(value: number | undefined): number | undefined {\n return value !== undefined && Number.isFinite(value) ? clamp01(value) : undefined\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction record(value: unknown): Record<string, unknown> | null {\n return isRecord(value) ? value : null\n}\n\nfunction stringField(obj: Record<string, unknown>, key: string): string | undefined {\n const value = obj[key]\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\nfunction numberField(obj: Record<string, unknown>, key: string): number | undefined {\n const value = obj[key]\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined\n}\n\nfunction timestampMs(value: unknown): number | undefined {\n if (typeof value === 'number' && Number.isFinite(value)) {\n return value > 1_000_000_000_000 ? value : value * 1000\n }\n if (typeof value === 'string' && value.length > 0) {\n const parsed = Date.parse(value)\n return Number.isFinite(parsed) ? parsed : undefined\n }\n return undefined\n}\n","/**\n * # `intake/feedback-table` — multi-rater approve/reject corpus → `RunRecord[]`.\n *\n * The generic shape behind Obsidian's `#approved` / `#rejected` tags, a\n * Google Sheet, a Postgres `feedback` table, or any CSV with ratings.\n *\n * Caller supplies one row per (run, rater) tuple plus per-run metadata; the\n * adapter rolls them up into the substrate-canonical `RunRecord` shape so\n * `analyzeRuns({ runs, raterScores })` can produce inter-rater agreement,\n * disagreement triage, and downstream recommendations.\n *\n * The rater mean is written to the score field matching the run split\n * (normalised to 0..1 when a scale is supplied); `outcome.raw` carries\n * per-rater scores keyed by rater id for downstream attribution.\n */\n\nimport type { JudgeScoresRecord, RunOutcome, RunRecord, RunSplitTag } from '../../run-record'\n\nexport interface FeedbackTableRow {\n /** Stable id for this run — the unit a rater scored. Drives pairing\n * across analysis primitives. */\n runId: string\n /** Identifier of the rater that produced this rating. */\n rater: string\n /** The rating itself. Accepts boolean (approve/reject), 0..1 scalar,\n * or any numeric scale — see `scale`. */\n rating: number | boolean\n /** Optional metadata carried through to `RunRecord.outcome.raw` and the\n * custom-shape metadata bag. */\n metadata?: Record<string, unknown>\n}\n\nexport interface FeedbackTableMeta {\n runId: string\n /** When omitted, defaults to `'feedback-corpus'`. Used to group related\n * runs in `analyzeRuns()` lift analysis. */\n experimentId?: string\n /** When omitted, defaults to `runId` — each run is its own candidate. */\n candidateId?: string\n /** Observed cost in USD, when available. */\n costUsd?: number\n /** Stable scenario identity. Defaults to `runId`. */\n scenarioId?: string\n /** Wall-clock ms, when available. Defaults to 0. */\n wallMs?: number\n /** Model identifier including snapshot. Default `unknown@unknown`. */\n model?: string\n /** Optional sha256 of the prompt; default `'sha256:unknown'`. */\n promptHash?: string\n /** Default `'sha256:unknown'`. */\n configHash?: string\n /** Default `'unknown'`. */\n commitSha?: string\n /** Default `'holdout'` — feedback corpora are by nature the holdout\n * signal a closed-loop improvement aims at. */\n splitTag?: RunSplitTag\n /** Free-form metadata available to consumers via the cast-out path on\n * the resulting RunRecord. */\n extras?: Record<string, unknown>\n}\n\nexport interface FromFeedbackTableOptions {\n /** Per-(run, rater) ratings. */\n ratings: FeedbackTableRow[]\n /** Per-run metadata. When a runId appears in `ratings` but not here, the\n * adapter synthesises minimal metadata with defaults documented above. */\n meta?: FeedbackTableMeta[]\n /** Rating scale. Provide `{ min, max }` for non-0..1 numeric scales.\n * Booleans are normalised: true → 1, false → 0. Default: assumes\n * ratings are already 0..1. */\n scale?: { min: number; max: number }\n /** When true, the rater scores are emitted into `raterScores` (a sibling\n * array `analyzeRuns()` accepts) in addition to the aggregate run score.\n * Default `true` preserves rater-level signal for inter-rater analysis. */\n emitRaterScores?: boolean\n}\n\nexport interface FromFeedbackTableResult {\n runs: RunRecord[]\n /** Rater-level scores ready to pass into `analyzeRuns({ raterScores })`\n * for inter-rater agreement + disagreement triage. */\n raterScores: Array<{ runId: string; rater: string; score: number }>\n}\n\nexport function fromFeedbackTable(opts: FromFeedbackTableOptions): FromFeedbackTableResult {\n const { ratings, meta = [], scale, emitRaterScores = true } = opts\n const metaByRun = new Map(meta.map((m) => [m.runId, m]))\n\n // Normalise per-rating to a 0..1 score.\n const normalise = (rating: number | boolean): number => {\n if (typeof rating === 'boolean') return rating ? 1 : 0\n if (!Number.isFinite(rating)) return Number.NaN\n if (!scale) return rating\n const { min, max } = scale\n if (max === min) return rating\n return (rating - min) / (max - min)\n }\n\n // Group ratings by runId.\n const byRun = new Map<string, FeedbackTableRow[]>()\n for (const row of ratings) {\n const list = byRun.get(row.runId) ?? []\n list.push(row)\n byRun.set(row.runId, list)\n }\n\n const runs: RunRecord[] = []\n const raterScores: FromFeedbackTableResult['raterScores'] = []\n\n for (const [runId, rowsForRun] of byRun) {\n const normalised = rowsForRun\n .map((r) => ({ rater: r.rater, score: normalise(r.rating) }))\n .filter((r) => Number.isFinite(r.score))\n if (normalised.length === 0) continue\n\n const meanScore = normalised.reduce((s, r) => s + r.score, 0) / normalised.length\n\n const runMeta = metaByRun.get(runId) ?? ({ runId } as FeedbackTableMeta)\n\n const judgeScores: JudgeScoresRecord = {\n perJudge: Object.fromEntries(normalised.map((r) => [r.rater, { rating: r.score }])),\n perDimMean: { rating: meanScore },\n composite: meanScore,\n }\n\n const splitTag = runMeta.splitTag ?? 'holdout'\n const outcome: RunOutcome = {\n ...(splitTag === 'holdout' ? { holdoutScore: meanScore } : { searchScore: meanScore }),\n raw: Object.fromEntries(normalised.map((r) => [`rater:${r.rater}`, r.score])),\n judgeScores,\n }\n\n const costUsd = runMeta.costUsd ?? null\n runs.push({\n runId,\n experimentId: runMeta.experimentId ?? 'feedback-corpus',\n candidateId: runMeta.candidateId ?? runId,\n seed: 0,\n model: runMeta.model ?? 'unknown@unknown',\n promptHash: runMeta.promptHash ?? 'sha256:unknown',\n configHash: runMeta.configHash ?? 'sha256:unknown',\n commitSha: runMeta.commitSha ?? 'unknown',\n wallMs: runMeta.wallMs ?? 0,\n costUsd,\n costProvenance:\n costUsd === null ? { kind: 'uncaptured', usd: null } : { kind: 'observed', usd: costUsd },\n tokenUsage: { input: 0, output: 0 },\n terminalOutcome: 'unknown',\n outcome,\n splitTag,\n scenarioId: runMeta.scenarioId ?? runId,\n })\n\n if (emitRaterScores) {\n for (const r of normalised) raterScores.push({ runId, rater: r.rater, score: r.score })\n }\n }\n\n return { runs, raterScores }\n}\n","/**\n * # `intake/otel-spans` — OTel `TraceSpanEvent[]` → `RunRecord[]`.\n *\n * Turns an existing observability stream into the substrate-canonical\n * `RunRecord` shape so consumers with logs but no eval discipline can\n * call `analyzeRuns()` against their production traffic immediately.\n *\n * Pivot rule: spans are grouped by `tangle.runId` (the same attribute the\n * hosted-tier wire format uses) or, when absent, by `traceId`. One group\n * becomes one `RunRecord`. The root span (no `parentSpanId`) supplies:\n *\n * - `runId` (the group key)\n * - `wallMs` from `endTimeUnixNano - startTimeUnixNano`\n * - `model` from `gen_ai.request.model` / `llm.model` / `tangle.model`\n * - task failure class and detail from explicit `tangle.task.*` attributes\n * - cost from `cost.usd` / `gen_ai.usage.cost_usd` / `tangle.cost.usd`\n * - token usage from model-call input, output, cache-read, and cache-write\n * attributes without double-counting aggregate parent spans\n * - task quality from an explicit `scoreForRun` callback or a designated\n * evaluation attribute on a root / `EVALUATOR` span; `outcome.raw`\n * collects every numeric attribute without promoting it to task quality.\n *\n * Errored tool, model, and child-agent spans contribute to execution-error\n * counts. Root process, guardrail, evaluator, propagated parent, and unknown\n * errors retain separate counters. Only one failed root can set\n * `RunRecord.terminalOutcome` and `RunRecord.terminalFailureReason`; a child\n * error cannot become a task failure.\n */\n\nimport { ValidationError } from '../../errors'\nimport type { TraceSpanEvent } from '../../hosted/types'\nimport type {\n JudgeScoresRecord,\n RunOutcome,\n RunRecord,\n RunSplitTag,\n RunTerminalOutcome,\n} from '../../run-record'\nimport { summarizeTraceErrors, type TraceErrorRole } from '../../trace/error-classification'\nimport {\n recordAggregateMeasurements,\n summarizeExecutionMeasurements,\n} from '../../trace/execution-measurements'\nimport {\n classifyOtlpSpanRole,\n isOtlpModelCall,\n LLM_MODEL_ATTR_KEYS,\n SPAN_KIND_ATTR_KEYS,\n} from '../../trace/otlp-attributes'\nimport { readTaskFailureLabels } from '../../trace/task-failure-attributes'\n\nconst TASK_SCORE_ATTR_KEYS = [\n 'gen_ai.evaluation.score.value',\n 'tangle.task.score',\n 'eval.score',\n 'tangle.score',\n] as const\nconst MODEL_KEYS = ['tangle.model', ...LLM_MODEL_ATTR_KEYS, 'model']\nconst PROMPT_HASH_KEYS = ['tangle.prompt_hash', 'prompt.hash']\nconst CONFIG_HASH_KEYS = ['tangle.config_hash', 'config.hash']\n\nexport interface FromOtelSpansOptions {\n spans: TraceSpanEvent[]\n /** Default split tag for synthesized records. Defaults to `'holdout'`. */\n defaultSplit?: RunSplitTag\n /** Default `experimentId` when not present on any span. */\n experimentId?: string\n /**\n * Explicit task-quality score for a logical run. The callback receives\n * spans in deterministic time/id order. Its value must agree with any\n * designated score attributes present on root or `EVALUATOR` spans.\n */\n scoreForRun?: (runId: string, spans: readonly TraceSpanEvent[]) => number | undefined\n}\n\nexport function fromOtelSpans(opts: FromOtelSpansOptions): RunRecord[] {\n const { spans, defaultSplit = 'holdout', experimentId = 'otel-corpus' } = opts\n const grouped = groupSpans(spans)\n\n const runs: RunRecord[] = []\n for (const [groupKey, groupSpans] of grouped) {\n const root = findRoot(groupSpans)\n if (!root) continue\n const measurements = summarizeExecutionMeasurements(\n groupSpans.map((span) => ({\n id: span.spanId,\n ...(span.parentSpanId ? { parentId: span.parentSpanId } : {}),\n attributes: span.attributes,\n modelCall: isExplicitModelCall(span),\n aggregate: isExplicitAggregate(span),\n })),\n )\n const callSpanIds = new Set(measurements.callSpanIds)\n const callSpans = groupSpans.filter((span) => callSpanIds.has(span.spanId))\n const wallMs = unixNanoDurationMs(root.startTimeUnixNano, root.endTimeUnixNano)\n const model =\n readAttrString(callSpans, MODEL_KEYS) ??\n readAttrString(groupSpans, MODEL_KEYS) ??\n 'unknown@unknown'\n const capturedCost =\n (measurements.cost.complete ? measurements.cost.value : undefined) ??\n measurements.aggregate?.costUsd\n const costUsd = capturedCost ?? null\n const scenarioId = readConsistentScenarioId(groupKey, groupSpans) ?? groupKey\n const promptHash = readAttrString(groupSpans, PROMPT_HASH_KEYS) ?? 'sha256:unknown'\n const configHash = readAttrString(groupSpans, CONFIG_HASH_KEYS) ?? 'sha256:unknown'\n const score = resolveTaskScore(groupKey, groupSpans, opts.scoreForRun)\n const taskFailure = readTaskFailureLabels(\n groupSpans.filter((span) => !span.parentSpanId && isTerminalRootCandidate(span)),\n `fromOtelSpans: run '${groupKey}'`,\n )\n\n const rawNumeric = collectNumericAttrs(groupSpans)\n const errorSummary = summarizeTraceErrors(\n groupSpans.map((span) => ({\n id: spanIdentity(span),\n ...(span.parentSpanId ? { parentId: parentIdentity(span) } : {}),\n role: errorRoleForSpan(span),\n error: span.status?.code === 'ERROR',\n processRoot: !span.parentSpanId && isTerminalRootCandidate(span),\n })),\n )\n rawNumeric.error_span_count = errorSummary.total\n rawNumeric.execution_error_count = errorSummary.execution\n rawNumeric.process_error_count = errorSummary.process\n rawNumeric.guardrail_error_count = errorSummary.guardrail\n rawNumeric.judge_error_count = errorSummary.evaluation\n rawNumeric.propagated_error_count = errorSummary.propagated\n rawNumeric.unclassified_error_count = errorSummary.unclassified\n rawNumeric.llm_span_count = measurements.modelCallCount\n if (measurements.cost.value !== undefined && !measurements.cost.complete) {\n rawNumeric.partial_observed_cost_usd = measurements.cost.value\n }\n recordAggregateMeasurements(rawNumeric, measurements.aggregate)\n\n const judgeScores: JudgeScoresRecord | undefined =\n score !== undefined\n ? {\n perJudge: { 'otel-derived': { score } },\n perDimMean: { score },\n composite: score,\n }\n : undefined\n\n const terminalOutcome = terminalOutcomeFromRoots(groupSpans)\n const failedRoot =\n terminalOutcome === 'failed'\n ? groupSpans.find(\n (span) =>\n !span.parentSpanId && isTerminalRootCandidate(span) && span.status?.code === 'ERROR',\n )\n : undefined\n const outcome: RunOutcome = {\n raw: rawNumeric,\n ...(judgeScores ? { judgeScores } : {}),\n }\n if (score !== undefined) {\n if (defaultSplit === 'holdout') outcome.holdoutScore = score\n else outcome.searchScore = score\n }\n\n runs.push({\n runId: groupKey,\n experimentId,\n candidateId: (root.attributes['tangle.candidateId'] as string | undefined) ?? 'otel-default',\n seed: 0,\n model,\n promptHash,\n configHash,\n commitSha: (root.attributes['tangle.commit_sha'] as string | undefined) ?? 'unknown',\n wallMs,\n costUsd,\n costProvenance:\n capturedCost === undefined\n ? { kind: 'uncaptured', usd: null }\n : { kind: 'observed', usd: capturedCost },\n tokenUsage: measurements.tokenUsage,\n terminalOutcome,\n ...(failedRoot\n ? { terminalFailureReason: failedRoot.status?.message ?? failedRoot.name }\n : {}),\n outcome,\n ...taskFailure,\n splitTag: defaultSplit,\n scenarioId,\n })\n }\n return runs\n}\n\nfunction terminalOutcomeFromRoots(spans: TraceSpanEvent[]): RunTerminalOutcome {\n const roots = spans.filter((span) => !span.parentSpanId && isTerminalRootCandidate(span))\n if (roots.length !== 1) return 'unknown'\n if (roots[0]!.status?.code === 'OK') return 'succeeded'\n if (roots[0]!.status?.code === 'ERROR') return 'failed'\n return 'unknown'\n}\n\nfunction isTerminalRootCandidate(span: TraceSpanEvent): boolean {\n const role = errorRoleForSpan(span)\n if (role === 'LLM' || role === 'TOOL' || role === 'GUARDRAIL' || role === 'EVALUATOR') {\n return false\n }\n return true\n}\n\nfunction readSpanKind(span: TraceSpanEvent): string | undefined {\n return readAttrString([span], [...SPAN_KIND_ATTR_KEYS, 'span.kind'])?.toUpperCase()\n}\n\nfunction errorRoleForSpan(span: TraceSpanEvent): TraceErrorRole {\n return classifyOtlpSpanRole({\n kind: readSpanKind(span),\n name: span.name,\n attributes: span.attributes,\n })\n}\n\nfunction spanIdentity(span: TraceSpanEvent): string {\n return `${span.traceId}:${span.spanId}`\n}\n\nfunction parentIdentity(span: TraceSpanEvent): string {\n return `${span.traceId}:${span.parentSpanId}`\n}\n\nfunction isExplicitModelCall(span: TraceSpanEvent): boolean {\n return isOtlpModelCall({\n kind: readSpanKind(span),\n name: span.name,\n attributes: span.attributes,\n })\n}\n\nfunction isExplicitAggregate(span: TraceSpanEvent): boolean {\n const kind = readSpanKind(span)\n return kind !== undefined && kind !== 'LLM'\n}\n\n// ── Internal helpers ────────────────────────────────────────────────\n\nfunction groupSpans(spans: TraceSpanEvent[]): Map<string, TraceSpanEvent[]> {\n const m = new Map<string, TraceSpanEvent[]>()\n for (const span of spans) {\n const key = (span['tangle.runId'] as string | undefined) ?? span.traceId\n const list = m.get(key) ?? []\n list.push(span)\n m.set(key, list)\n }\n return m\n}\n\nfunction findRoot(group: TraceSpanEvent[]): TraceSpanEvent | undefined {\n const structuralRoots = group.filter((span) => !span.parentSpanId)\n const terminalRoots = structuralRoots.filter(isTerminalRootCandidate)\n const pool =\n terminalRoots.length > 0 ? terminalRoots : structuralRoots.length > 0 ? structuralRoots : group\n return orderSpans(pool)[0]\n}\n\nfunction readAttrString(spans: TraceSpanEvent[], keys: string[]): string | undefined {\n for (const span of spans) {\n for (const key of keys) {\n const v = span.attributes[key]\n if (typeof v === 'string' && v.length > 0) return v\n }\n }\n return undefined\n}\n\nfunction readConsistentScenarioId(\n runId: string,\n spans: readonly TraceSpanEvent[],\n): string | undefined {\n const values = new Set<string>()\n for (const span of spans) {\n const topLevel = span['tangle.scenarioId']\n if (typeof topLevel === 'string' && topLevel.length > 0) values.add(topLevel)\n const attribute = span.attributes['tangle.scenarioId']\n if (typeof attribute === 'string' && attribute.length > 0) values.add(attribute)\n }\n if (values.size > 1) {\n throw new ValidationError(\n `fromOtelSpans: conflicting scenario ids for run '${runId}': ${[...values].sort().join(', ')}`,\n )\n }\n return values.values().next().value\n}\n\ninterface TaskScoreSource {\n label: string\n value: number\n}\n\nfunction resolveTaskScore(\n runId: string,\n spans: TraceSpanEvent[],\n scoreForRun: FromOtelSpansOptions['scoreForRun'],\n): number | undefined {\n const orderedSpans = orderSpans(spans)\n const sources: TaskScoreSource[] = []\n\n if (scoreForRun) {\n const supplied: unknown = scoreForRun(runId, orderedSpans)\n if (supplied !== undefined) {\n if (typeof supplied !== 'number' || !Number.isFinite(supplied)) {\n throw new ValidationError(\n `fromOtelSpans: scoreForRun returned a non-finite number for run '${runId}'`,\n )\n }\n sources.push({ label: 'scoreForRun', value: supplied })\n }\n }\n\n for (const span of orderedSpans) {\n const role = errorRoleForSpan(span)\n if (span.parentSpanId && role !== 'EVALUATOR') continue\n if (role === 'EVALUATOR' && span.status?.code === 'ERROR') continue\n for (const key of TASK_SCORE_ATTR_KEYS) {\n if (!Object.hasOwn(span.attributes, key)) continue\n sources.push({\n label: `span '${span.spanId}' attribute '${key}'`,\n value: parseTaskScoreAttribute(runId, span.spanId, key, span.attributes[key]),\n })\n }\n }\n\n if (sources.length === 0) return undefined\n sources.sort((left, right) => left.label.localeCompare(right.label))\n const score = sources[0]!.value\n if (sources.some((source) => source.value !== score)) {\n const details = sources.map((source) => `${source.label}=${source.value}`).join(', ')\n throw new ValidationError(\n `fromOtelSpans: conflicting task-quality scores for run '${runId}': ${details}`,\n )\n }\n return score\n}\n\nfunction parseTaskScoreAttribute(\n runId: string,\n spanId: string,\n key: string,\n value: unknown,\n): number {\n const source = `span '${spanId}' attribute '${key}'`\n if (typeof value === 'string') {\n if (value.trim().length === 0) {\n throw new ValidationError(\n `fromOtelSpans: ${source} is blank for run '${runId}'; task quality must be finite`,\n )\n }\n const parsed = Number(value)\n if (Number.isFinite(parsed)) return parsed\n } else if (typeof value === 'number' && Number.isFinite(value)) {\n return value\n }\n throw new ValidationError(\n `fromOtelSpans: ${source} is not a finite task-quality score for run '${runId}'`,\n )\n}\n\nfunction orderSpans(spans: readonly TraceSpanEvent[]): TraceSpanEvent[] {\n return [...spans].sort(\n (left, right) =>\n compareUnixNano(left.startTimeUnixNano, right.startTimeUnixNano) ||\n left.spanId.localeCompare(right.spanId),\n )\n}\n\nfunction parseUnixNano(value: string): bigint {\n try {\n return BigInt(value)\n } catch {\n throw new ValidationError(`fromOtelSpans: invalid Unix nanosecond timestamp '${value}'`)\n }\n}\n\nfunction compareUnixNano(left: string, right: string): number {\n const leftValue = parseUnixNano(left)\n const rightValue = parseUnixNano(right)\n return leftValue < rightValue ? -1 : leftValue > rightValue ? 1 : 0\n}\n\nfunction unixNanoDurationMs(start: string, end: string): number {\n const delta = parseUnixNano(end) - parseUnixNano(start)\n if (delta <= 0n) return 0\n const wholeMs = delta / 1_000_000n\n const fractionalMs = delta % 1_000_000n\n const value = Number(wholeMs) + Number(fractionalMs) / 1_000_000\n if (!Number.isSafeInteger(Number(wholeMs))) {\n throw new ValidationError('fromOtelSpans: span duration exceeds the safe millisecond range')\n }\n return value\n}\n\nfunction collectNumericAttrs(spans: TraceSpanEvent[]): Record<string, number> {\n const raw: Record<string, number> = {}\n for (const span of spans) {\n for (const [k, v] of Object.entries(span.attributes)) {\n if (typeof v === 'number' && Number.isFinite(v)) raw[k] = v\n }\n }\n return raw\n}\n"],"m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