@tangle-network/agent-eval 1.0.35 → 1.0.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/dist/adapters/http.d.ts +2 -2
- package/dist/{agent-profile-BpLyM2kL.d.ts → agent-profile-BKgR30kv.d.ts} +2 -2
- package/dist/{agent-profile-BpLyM2kL.d.ts.map → agent-profile-BKgR30kv.d.ts.map} +1 -1
- package/dist/analyst/index.d.ts +11 -11
- package/dist/analyst/index.js +7 -7
- package/dist/{analyze-runs-DfUDLaCk.d.ts → analyze-runs-Ctuz-dd3.d.ts} +12 -7
- package/dist/analyze-runs-Ctuz-dd3.d.ts.map +1 -0
- package/dist/{analyze-runs-AaVEG5r7.js → analyze-runs-DqHx3Q_g.js} +49 -7
- package/dist/analyze-runs-DqHx3Q_g.js.map +1 -0
- package/dist/app-grade/index.d.ts +3 -3
- package/dist/{benchmark-command-ZN7x3hTW.js → benchmark-command-08LitQTo.js} +11 -6
- package/dist/benchmark-command-08LitQTo.js.map +1 -0
- package/dist/benchmarks/index.d.ts +5 -5
- package/dist/benchmarks/index.js +3 -3
- package/dist/campaign/index.d.ts +8 -7
- package/dist/campaign/index.js +9 -9
- package/dist/{campaign-BOoc6hc3.js → campaign-DJciOYZ6.js} +15 -19
- package/dist/campaign-DJciOYZ6.js.map +1 -0
- package/dist/{campaign-evidence-DGTNdS_7.js → campaign-evidence-BX8OveG5.js} +28 -4
- package/dist/campaign-evidence-BX8OveG5.js.map +1 -0
- package/dist/{chat-client-PJEzoot9.js → chat-client-DmPB31_2.js} +2 -2
- package/dist/{chat-client-PJEzoot9.js.map → chat-client-DmPB31_2.js.map} +1 -1
- package/dist/{chat-json-call-CaNO3k0A.js → chat-json-call-Rfhu7JbJ.js} +2 -2
- package/dist/{chat-json-call-CaNO3k0A.js.map → chat-json-call-Rfhu7JbJ.js.map} +1 -1
- package/dist/cli.js +10 -10
- package/dist/cluster-CSd0LE_M.d.ts.map +1 -1
- package/dist/{completion-verifier-xkC5kuME.js → completion-verifier-C3q1T96h.js} +4 -3
- package/dist/{completion-verifier-xkC5kuME.js.map → completion-verifier-C3q1T96h.js.map} +1 -1
- package/dist/contract/index.d.ts +13 -12
- package/dist/contract/index.js +10 -10
- package/dist/{default-registry-CfZCJdJT.d.ts → default-registry-BzCIR-YP.d.ts} +7 -7
- package/dist/{default-registry-CfZCJdJT.d.ts.map → default-registry-BzCIR-YP.d.ts.map} +1 -1
- package/dist/{default-registry-DQQ7hTXJ.js → default-registry-CpGvgSYQ.js} +2 -2
- package/dist/{default-registry-DQQ7hTXJ.js.map → default-registry-CpGvgSYQ.js.map} +1 -1
- package/dist/{define-agent-eval-QdTTdbyE.d.ts → define-agent-eval-DOB58LaZ.d.ts} +20 -8
- package/dist/define-agent-eval-DOB58LaZ.d.ts.map +1 -0
- package/dist/{define-agent-eval-Cw0HHdMF.js → define-agent-eval-Db2cZJjC.js} +19 -9
- package/dist/define-agent-eval-Db2cZJjC.js.map +1 -0
- package/dist/diagnosis/index.d.ts +3 -3
- package/dist/diagnosis/index.js +1 -1
- package/dist/{dspy-rlm-engine-Bf6cJHt_.js → dspy-rlm-engine-EC-Pkdf-.js} +2 -2
- package/dist/{dspy-rlm-engine-Bf6cJHt_.js.map → dspy-rlm-engine-EC-Pkdf-.js.map} +1 -1
- package/dist/{engine-yaSDTpEa.d.ts → engine-B2w3ARpj.d.ts} +2 -2
- package/dist/{engine-yaSDTpEa.d.ts.map → engine-B2w3ARpj.d.ts.map} +1 -1
- package/dist/{eval-campaign-CHy1PEhT.js → eval-campaign-CWWh-1p1.js} +2 -2
- package/dist/{eval-campaign-CHy1PEhT.js.map → eval-campaign-CWWh-1p1.js.map} +1 -1
- package/dist/{evaluation-imW3I7tD.d.ts → evaluation-DJqWiVkb.d.ts} +4 -4
- package/dist/{evaluation-imW3I7tD.d.ts.map → evaluation-DJqWiVkb.d.ts.map} +1 -1
- package/dist/evaluation.d.ts +1 -1
- package/dist/{exact-types-xrjBO9sb.d.ts → exact-types-B0_jA3V7.d.ts} +2 -2
- package/dist/{exact-types-xrjBO9sb.d.ts.map → exact-types-B0_jA3V7.d.ts.map} +1 -1
- package/dist/{execution-insight-B-My58JW.d.ts → execution-insight-9No6Si55.d.ts} +3 -3
- package/dist/{execution-insight-B-My58JW.d.ts.map → execution-insight-9No6Si55.d.ts.map} +1 -1
- package/dist/experiment/index.d.ts +1 -1
- package/dist/experiment/index.js +1 -1
- package/dist/{exporters-CfKvJlti.js → exporters-C9AwGDDK.js} +4 -4
- package/dist/exporters-C9AwGDDK.js.map +1 -0
- package/dist/{external-optimizer-process-CQBDk8TP.js → external-optimizer-process-DFEPdWJY.js} +2 -2
- package/dist/{external-optimizer-process-CQBDk8TP.js.map → external-optimizer-process-DFEPdWJY.js.map} +1 -1
- package/dist/{external-optimizer-subprocess-BUCI-uFn.js → external-optimizer-subprocess-BspZ0bZb.js} +2 -2
- package/dist/{external-optimizer-subprocess-BUCI-uFn.js.map → external-optimizer-subprocess-BspZ0bZb.js.map} +1 -1
- package/dist/{feedback-trajectory-BbwTH49m.d.ts → feedback-trajectory-FamLu3Wt.d.ts} +3 -3
- package/dist/{feedback-trajectory-BbwTH49m.d.ts.map → feedback-trajectory-FamLu3Wt.d.ts.map} +1 -1
- package/dist/{findings-store-Dt2l5kHQ.js → findings-store-71J302Ls.js} +4 -4
- package/dist/{findings-store-Dt2l5kHQ.js.map → findings-store-71J302Ls.js.map} +1 -1
- package/dist/{hf-dataset-BA0wmOMB.js → hf-dataset-kthWy7xl.js} +2 -2
- package/dist/{hf-dataset-BA0wmOMB.js.map → hf-dataset-kthWy7xl.js.map} +1 -1
- package/dist/hosted/index.js +1 -1
- package/dist/{index-_Gwk9sZl.d.ts → index-BEAzBo4U.d.ts} +4 -4
- package/dist/{index-_Gwk9sZl.d.ts.map → index-BEAzBo4U.d.ts.map} +1 -1
- package/dist/{index-sOdbeWGO.d.ts → index-BOm81bra.d.ts} +9 -9
- package/dist/{index-sOdbeWGO.d.ts.map → index-BOm81bra.d.ts.map} +1 -1
- package/dist/{index-CeTno9aO.d.ts → index-CDEe3TyM.d.ts} +6 -6
- package/dist/{index-CeTno9aO.d.ts.map → index-CDEe3TyM.d.ts.map} +1 -1
- package/dist/{index-CeEW0CHk.d.ts → index-D5_Srjot.d.ts} +19 -19
- package/dist/{index-CeEW0CHk.d.ts.map → index-D5_Srjot.d.ts.map} +1 -1
- package/dist/{index-DshgWP9U.d.ts → index-DX0t5hA_.d.ts} +23 -9
- package/dist/index-DX0t5hA_.d.ts.map +1 -0
- package/dist/{index-Yec_iihg.d.ts → index-DtW7KhyE.d.ts} +2 -2
- package/dist/{index-Yec_iihg.d.ts.map → index-DtW7KhyE.d.ts.map} +1 -1
- package/dist/index.d.ts +24 -24
- package/dist/index.js +19 -18
- package/dist/index.js.map +1 -1
- package/dist/{judge-gate-MP1rHOB4.js → judge-gate-LbmZU-pA.js} +2 -2
- package/dist/{judge-gate-MP1rHOB4.js.map → judge-gate-LbmZU-pA.js.map} +1 -1
- package/dist/{llm-client-Bj-TooRS.js → llm-client-CdHo3SH0.js} +3 -276
- package/dist/llm-client-CdHo3SH0.js.map +1 -0
- package/dist/{llm-judge-DOgWUOml.js → llm-judge-C5pZ7DSS.js} +82 -15
- package/dist/llm-judge-C5pZ7DSS.js.map +1 -0
- package/dist/{matrix-Bk8Iz49C.d.ts → matrix-C5hfz5wA.d.ts} +2 -2
- package/dist/{matrix-Bk8Iz49C.d.ts.map → matrix-C5hfz5wA.d.ts.map} +1 -1
- package/dist/meta-eval/index.d.ts +2 -2
- package/dist/meta-eval/index.js +2 -2
- package/dist/{mint-CVlHND-Q.js → mint-VN-qtJTc.js} +2 -2
- package/dist/{mint-CVlHND-Q.js.map → mint-VN-qtJTc.js.map} +1 -1
- package/dist/model-comparison-BHNL8Qrn.d.ts +25 -0
- package/dist/model-comparison-BHNL8Qrn.d.ts.map +1 -0
- package/dist/model-comparison-BZr_Hu00.js +44 -0
- package/dist/model-comparison-BZr_Hu00.js.map +1 -0
- package/dist/multishot/golden/index.d.ts +1 -1
- package/dist/multishot/index.d.ts +2 -2
- package/dist/multishot/index.js +1 -1
- package/dist/openapi.json +1 -1
- package/dist/{pareto-LXHRfcP7.js → pareto-BNWWbLNl.js} +2 -2
- package/dist/{pareto-LXHRfcP7.js.map → pareto-BNWWbLNl.js.map} +1 -1
- package/dist/{prime-protocol-3aHqoxSH.d.ts → prime-protocol-BR0xy0cF.d.ts} +2 -2
- package/dist/{prime-protocol-3aHqoxSH.d.ts.map → prime-protocol-BR0xy0cF.d.ts.map} +1 -1
- package/dist/{promotion-gate-D-ffRHFQ.d.ts → promotion-gate-XiTqW22r.d.ts} +3 -3
- package/dist/{promotion-gate-D-ffRHFQ.d.ts.map → promotion-gate-XiTqW22r.d.ts.map} +1 -1
- package/dist/{proposal-findings-DHLDbsuH.js → proposal-findings-DFQvA-k5.js} +2 -2
- package/dist/{proposal-findings-DHLDbsuH.js.map → proposal-findings-DFQvA-k5.js.map} +1 -1
- package/dist/{registry-x5n4GeBx.d.ts → registry-D23oO0_f.d.ts} +3 -3
- package/dist/{registry-x5n4GeBx.d.ts.map → registry-D23oO0_f.d.ts.map} +1 -1
- package/dist/{release-confidence-DEMX-Ftk.js → release-confidence-BdidB0mG.js} +2 -2
- package/dist/{release-confidence-DEMX-Ftk.js.map → release-confidence-BdidB0mG.js.map} +1 -1
- package/dist/reporting.d.ts +4 -4
- package/dist/reporting.js +1 -1
- package/dist/{research-report-CUbXuGX-.d.ts → research-report-BGKsOqkF.d.ts} +3 -3
- package/dist/{research-report-CUbXuGX-.d.ts.map → research-report-BGKsOqkF.d.ts.map} +1 -1
- package/dist/{researcher-D6D7q9uQ.d.ts → researcher-k925Q6Jb.d.ts} +3 -3
- package/dist/{researcher-D6D7q9uQ.d.ts.map → researcher-k925Q6Jb.d.ts.map} +1 -1
- package/dist/{reward-hacking-_CAip56v.d.ts → reward-hacking-CLMvxEY_.d.ts} +2 -2
- package/dist/{reward-hacking-_CAip56v.d.ts.map → reward-hacking-CLMvxEY_.d.ts.map} +1 -1
- package/dist/rl.d.ts +7 -7
- package/dist/rl.js +5 -5
- package/dist/rollout/index.d.ts +2 -2
- package/dist/rollout/index.js +4 -4
- package/dist/{rollout-99d3Fbqv.js → rollout-DDMkK_Lw.js} +12 -7
- package/dist/{rollout-99d3Fbqv.js.map → rollout-DDMkK_Lw.js.map} +1 -1
- package/dist/{rubric-predictive-validity-BTN3nNhC.d.ts → rubric-predictive-validity-B7rsN074.d.ts} +2 -2
- package/dist/{rubric-predictive-validity-BTN3nNhC.d.ts.map → rubric-predictive-validity-B7rsN074.d.ts.map} +1 -1
- package/dist/{run-record-hti3ETmO.d.ts → run-record-CCJR7q_j.d.ts} +2 -7
- package/dist/{run-record-hti3ETmO.d.ts.map → run-record-CCJR7q_j.d.ts.map} +1 -1
- package/dist/{run-record-BFrOalUW.js → run-record-Dx64nPcX.js} +36 -22
- package/dist/{run-record-BFrOalUW.js.map → run-record-Dx64nPcX.js.map} +1 -1
- package/dist/{run-record-B7b7fLMj.js → run-record-c860wUR8.js} +2 -2
- package/dist/{run-record-B7b7fLMj.js.map → run-record-c860wUR8.js.map} +1 -1
- package/dist/{runtime-rollouts-DAtRlbBX.js → runtime-rollouts-CALol_Y4.js} +2 -2
- package/dist/{runtime-rollouts-DAtRlbBX.js.map → runtime-rollouts-CALol_Y4.js.map} +1 -1
- package/dist/search/index.d.ts +2 -2
- package/dist/search/index.js +2 -2
- package/dist/{search-kernel-BigyOZX3.d.ts → search-kernel-VeoTiwiJ.d.ts} +3 -3
- package/dist/{search-kernel-BigyOZX3.d.ts.map → search-kernel-VeoTiwiJ.d.ts.map} +1 -1
- package/dist/{search-ledger-D0pWW8kh.js → search-ledger-oyqxZhry.js} +2 -2
- package/dist/{search-ledger-D0pWW8kh.js.map → search-ledger-oyqxZhry.js.map} +1 -1
- package/dist/{search-shipper-CJQaAvvi.js → search-shipper-BwqeQ61l.js} +2 -2
- package/dist/{search-shipper-CJQaAvvi.js.map → search-shipper-BwqeQ61l.js.map} +1 -1
- package/dist/{search-summary-ByUYPfzm.js → search-summary-CNHpHFfw.js} +2 -2
- package/dist/{search-summary-ByUYPfzm.js.map → search-summary-CNHpHFfw.js.map} +1 -1
- package/dist/served-model-qhLmbutL.js +288 -0
- package/dist/served-model-qhLmbutL.js.map +1 -0
- package/dist/{server-C2OqA05E.js → server-DnoEi4Sb.js} +3 -3
- package/dist/{server-C2OqA05E.js.map → server-DnoEi4Sb.js.map} +1 -1
- package/dist/{skillopt-optimization-method-lDHnLno3.js → skillopt-optimization-method-CH9roCBs.js} +8 -7
- package/dist/{skillopt-optimization-method-lDHnLno3.js.map → skillopt-optimization-method-CH9roCBs.js.map} +1 -1
- package/dist/{statistical-heldout-Bd6PVnQD.d.ts → statistical-heldout-Bk9mrEoz.d.ts} +6 -4
- package/dist/statistical-heldout-Bk9mrEoz.d.ts.map +1 -0
- package/dist/{store-tool-spans-Bm0-YhHG.d.ts → store-tool-spans-C1lZKvvl.d.ts} +5 -5
- package/dist/{store-tool-spans-Bm0-YhHG.d.ts.map → store-tool-spans-C1lZKvvl.d.ts.map} +1 -1
- package/dist/{summary-report-figures-BoFCoiOP.d.ts → summary-report-figures-C4JW8fdy.d.ts} +2 -2
- package/dist/{summary-report-figures-BoFCoiOP.d.ts.map → summary-report-figures-C4JW8fdy.d.ts.map} +1 -1
- package/dist/supervisor-run/index.js +1 -1
- package/dist/{systemone-Dpp7I3uV.d.ts → systemone-BCtHGtds.d.ts} +7 -7
- package/dist/{systemone-Dpp7I3uV.d.ts.map → systemone-BCtHGtds.d.ts.map} +1 -1
- package/dist/{systemone-review-CrnsTRav.d.ts → systemone-review-ZAN-5m_2.d.ts} +2 -2
- package/dist/{systemone-review-CrnsTRav.d.ts.map → systemone-review-ZAN-5m_2.d.ts.map} +1 -1
- package/dist/systemone.d.ts +3 -3
- package/dist/{tool-groups-5pgmtTmE.d.ts → tool-groups-BOH1E-E4.d.ts} +3 -3
- package/dist/tool-groups-BOH1E-E4.d.ts.map +1 -0
- package/dist/{trace-questions-ETZDn5ax.d.ts → trace-questions-DBsrgY_H.d.ts} +3 -3
- package/dist/{trace-questions-ETZDn5ax.d.ts.map → trace-questions-DBsrgY_H.d.ts.map} +1 -1
- package/dist/trace-repair/index.d.ts +2 -2
- package/dist/traces.d.ts +7 -7
- package/dist/traces.js +5 -6
- package/dist/traces.js.map +1 -1
- package/dist/{tree-C4TtnQYD.js → tree-0r6gPODs.js} +3 -3
- package/dist/{tree-C4TtnQYD.js.map → tree-0r6gPODs.js.map} +1 -1
- package/dist/{types-BeJIREX-.d.ts → types-Bq8xZKCQ.d.ts} +3 -3
- package/dist/{types-BeJIREX-.d.ts.map → types-Bq8xZKCQ.d.ts.map} +1 -1
- package/dist/{types-ff0YYJnj.d.ts → types-D7X941FU.d.ts} +3 -3
- package/dist/{types-ff0YYJnj.d.ts.map → types-D7X941FU.d.ts.map} +1 -1
- package/dist/{types-Dtt11Ppr.d.ts → types-DmYd2Igl.d.ts} +2 -2
- package/dist/{types-Dtt11Ppr.d.ts.map → types-DmYd2Igl.d.ts.map} +1 -1
- package/dist/wire/index.d.ts +3 -3
- package/dist/wire/index.js +1 -1
- package/docs/evaluation-integrity.md +65 -0
- package/docs/insight-report.md +7 -1
- package/docs/rollout.md +8 -1
- package/package.json +1 -1
- package/dist/analyze-runs-AaVEG5r7.js.map +0 -1
- package/dist/analyze-runs-DfUDLaCk.d.ts.map +0 -1
- package/dist/benchmark-command-ZN7x3hTW.js.map +0 -1
- package/dist/campaign-BOoc6hc3.js.map +0 -1
- package/dist/campaign-evidence-DGTNdS_7.js.map +0 -1
- package/dist/define-agent-eval-Cw0HHdMF.js.map +0 -1
- package/dist/define-agent-eval-QdTTdbyE.d.ts.map +0 -1
- package/dist/exporters-CfKvJlti.js.map +0 -1
- package/dist/index-DshgWP9U.d.ts.map +0 -1
- package/dist/llm-client-Bj-TooRS.js.map +0 -1
- package/dist/llm-judge-DOgWUOml.js.map +0 -1
- package/dist/statistical-heldout-Bd6PVnQD.d.ts.map +0 -1
- package/dist/tool-groups-5pgmtTmE.d.ts.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"campaign-evidence-DGTNdS_7.js","names":[],"sources":["../src/campaign/coverage.ts","../src/integrity/backend-integrity.ts","../src/experiment/final-evidence.ts","../src/campaign/gates/power-preflight.ts","../src/reflective-mutation.ts","../src/campaign/score-utils.ts","../src/campaign/provenance.ts","../src/attestation.ts","../src/experiment/evidence-receipt.ts","../src/experiment/campaign-evidence.ts"],"sourcesContent":["import { contentHash } from '../verdict-cache'\nimport type {\n CampaignCellResult,\n CampaignResult,\n CampaignScenarioIdentity,\n Scenario,\n} from './types'\n\nexport interface CampaignCoverage {\n complete: boolean\n expectedCellIds: string[]\n scorableCellIds: string[]\n unscorableCells: Array<{ cellId: string; reason: string }>\n}\n\n/** Reject campaign designs whose denominator cannot be identified exactly. */\nexport function assertCampaignDesign<TScenario extends Scenario>(\n scenarios: readonly TScenario[],\n reps: number,\n): void {\n if (!Number.isSafeInteger(reps) || reps < 1) {\n throw new Error('campaign design requires reps to be a positive safe integer')\n }\n const scenarioIds = new Set<string>()\n for (const scenario of scenarios) {\n if (typeof scenario.id !== 'string' || scenario.id.trim().length === 0) {\n throw new Error('campaign design requires every scenario to have a non-empty id')\n }\n if (scenarioIds.has(scenario.id)) {\n throw new Error(`campaign design contains duplicate scenario id '${scenario.id}'`)\n }\n if (typeof scenario.kind !== 'string' || scenario.kind.trim().length === 0) {\n throw new Error('campaign design requires every scenario to have a non-empty kind')\n }\n if (\n scenario.seedGroup !== undefined &&\n (typeof scenario.seedGroup !== 'string' || scenario.seedGroup.trim().length === 0)\n ) {\n throw new Error('campaign design requires seedGroup to be a non-empty string when set')\n }\n scenarioIds.add(scenario.id)\n }\n}\n\n/** Redacted but independently verifiable identity of one complete scenario. */\nexport function campaignScenarioIdentity<TScenario extends Scenario>(\n scenario: TScenario,\n): CampaignScenarioIdentity & Pick<TScenario, 'id' | 'kind'> {\n assertCampaignDesign([scenario], 1)\n return {\n id: scenario.id,\n kind: scenario.kind,\n scenarioDigest: `sha256:${contentHash(scenario)}`,\n }\n}\n\n/** Canonical split identity reconstructed from redacted scenario identities. */\nexport function campaignSplitDigestFromIdentities(\n scenarios: readonly CampaignScenarioIdentity[],\n reps: number,\n): `sha256:${string}` {\n assertCampaignDesign(scenarios, reps)\n for (const scenario of scenarios) {\n if (!/^sha256:[a-f0-9]{64}$/.test(scenario.scenarioDigest)) {\n throw new Error(`campaign scenario '${scenario.id}' has an invalid digest`)\n }\n }\n return `sha256:${contentHash({\n schema: 'tangle.campaign-split',\n scenarios: scenarios.map(({ id, kind, scenarioDigest }) => ({ id, kind, scenarioDigest })),\n reps,\n })}`\n}\n\n/** Canonical identity of the exact scenario payloads and replicate count. */\nexport function campaignSplitDigest<TScenario extends Scenario>(\n scenarios: readonly TScenario[],\n reps: number,\n): `sha256:${string}` {\n assertCampaignDesign(scenarios, reps)\n return campaignSplitDigestFromIdentities(scenarios.map(campaignScenarioIdentity), reps)\n}\n\n/** Refuse a campaign whose retained task identities contradict its split digest. */\nexport function assertCampaignSplitIdentity(\n scenarios: readonly CampaignScenarioIdentity[],\n reps: number,\n splitDigest: string,\n): void {\n if (campaignSplitDigestFromIdentities(scenarios, reps) !== splitDigest) {\n throw new Error('campaign split digest does not match its retained scenario identities')\n }\n}\n\n/** Exact designed-denominator receipt for one campaign. */\nexport function campaignCoverage<TArtifact, TScenario extends Scenario>(\n cells: readonly CampaignCellResult<TArtifact>[],\n scenarios: readonly TScenario[],\n reps: number,\n requireJudgeScore: boolean,\n): CampaignCoverage {\n assertCampaignDesign(scenarios, reps)\n const expectedCellIds = designedCellIds(scenarios, reps)\n const cellsById = new Map<string, CampaignCellResult<TArtifact>[]>()\n for (const cell of cells) {\n const matches = cellsById.get(cell.cellId) ?? []\n matches.push(cell)\n cellsById.set(cell.cellId, matches)\n }\n\n const scorableCellIds: string[] = []\n const unscorableCells: Array<{ cellId: string; reason: string }> = []\n for (const cellId of expectedCellIds) {\n const matches = cellsById.get(cellId) ?? []\n if (matches.length === 0) {\n unscorableCells.push({ cellId, reason: 'missing campaign cell' })\n continue\n }\n if (matches.length > 1) {\n unscorableCells.push({ cellId, reason: `duplicate campaign cell (${matches.length})` })\n continue\n }\n\n const cell = matches[0]!\n const scoreEntries = Object.entries(cell.judgeScores)\n const successfulScores = scoreEntries\n .map(([, score]) => score)\n .filter((score) => score.failed !== true && Number.isFinite(score.composite))\n const nonFiniteScores = scoreEntries.filter(\n ([, score]) =>\n score.failed !== true &&\n (!Number.isFinite(score.composite) ||\n Object.values(score.dimensions).some((value) => !Number.isFinite(value))),\n )\n const reasons: string[] = []\n if (cell.error) reasons.push(cell.error)\n if (cell.artifact === null || cell.artifact === undefined) reasons.push('missing artifact')\n if (!cell.error && requireJudgeScore && successfulScores.length === 0) {\n reasons.push('no successful finite judge score')\n }\n if (scoreEntries.some(([, score]) => score.failed === true)) {\n reasons.push('judge score marked failed')\n }\n const failedPanelJudges = [\n ...new Set(scoreEntries.flatMap(([, score]) => score.failedJudges ?? [])),\n ].sort()\n if (failedPanelJudges.length > 0) {\n reasons.push(`judge panel incomplete: ${failedPanelJudges.join(', ')}`)\n }\n if (nonFiniteScores.length > 0) {\n reasons.push(\n `non-finite judge score: ${nonFiniteScores\n .map(([name]) => name)\n .sort()\n .join(', ')}`,\n )\n }\n\n if (reasons.length > 0) {\n unscorableCells.push({ cellId, reason: reasons.join('; ') })\n } else {\n scorableCellIds.push(cellId)\n }\n }\n\n const expected = new Set(expectedCellIds)\n for (const cell of cells) {\n if (cell.cellId !== `${cell.scenarioId}:${cell.rep}`) {\n unscorableCells.push({\n cellId: cell.cellId,\n reason: 'campaign cell id does not match scenario id and rep',\n })\n continue\n }\n if (!expected.has(cell.cellId)) {\n unscorableCells.push({ cellId: cell.cellId, reason: 'unexpected campaign cell' })\n }\n }\n\n return {\n complete: unscorableCells.length === 0 && scorableCellIds.length === expectedCellIds.length,\n expectedCellIds,\n scorableCellIds,\n unscorableCells,\n }\n}\n\nexport function formatCoverageFailures(coverage: CampaignCoverage): string {\n const shown = coverage.unscorableCells\n .slice(0, 3)\n .map((cell) => `${cell.cellId}: ${cell.reason}`)\n .join('; ')\n const remainder = coverage.unscorableCells.length - Math.min(3, coverage.unscorableCells.length)\n return remainder > 0 ? `${shown}; +${remainder} more` : shown || 'unknown coverage failure'\n}\n\nfunction designedCellIds<TScenario extends Scenario>(\n scenarios: readonly TScenario[],\n reps: number,\n): string[] {\n const ids: string[] = []\n for (const scenario of scenarios) {\n for (let rep = 0; rep < reps; rep++) ids.push(`${scenario.id}:${rep}`)\n }\n return ids\n}\n\n/** Require the complete designed denominator before a final comparison. */\nexport function assertCompleteCampaign<TArtifact, TScenario extends Scenario>(\n campaign: CampaignResult<TArtifact, TScenario>,\n scenarios: readonly TScenario[],\n reps: number,\n requireJudgeScore: boolean,\n label: string,\n): void {\n const coverage = campaignCoverage(campaign.cells, scenarios, reps, requireJudgeScore)\n if (!coverage.complete) {\n throw new Error(\n `${label} is incomplete (${coverage.scorableCellIds.length}/${coverage.expectedCellIds.length} designed cells scorable) — ${formatCoverageFailures(coverage)}. Refusing to compare unequal results.`,\n )\n }\n}\n","/**\n * Backend-integrity guard: distinguish \"agent failed\" from \"eval ran against\n * a stub / unconfigured backend.\" Without this guard a canonical eval can\n * silently report `0/N passed` and look like an agent-quality problem when\n * the LLM was never actually called — the failure mode we just hit running\n * the 4-vertical parallel eval (legal-sandbox-stub returned hard-coded 33-104\n * char strings; gtm/creative defaulted to a cli-bridge that wasn't running).\n *\n * The shape:\n *\n * const report = summarizeBackendIntegrity(records)\n * assertRealBackend(records) // throws BackendIntegrityError if 100% stub\n *\n * A record is \"stub-mode\" if its `tokenUsage.input === 0 && tokenUsage.output === 0`.\n * (`costUsd` alone is unreliable — some backends successfully call LLMs but\n * don't propagate pricing, producing real tokens with $0 cost.)\n *\n * Verdicts:\n * - `real` — at least one record has nonzero token usage\n * - `stub` — every record is stub-mode (eval ran blind)\n * - `mixed` — some records real, some stub (partial backend failure;\n * often the 429-cascade or auth-half-failed case)\n */\n\nimport type { CostReceipt } from '../cost-ledger'\nimport { AgentEvalError } from '../errors'\nimport type { RunRecord } from '../run-record'\n\nexport interface BackendIntegrityReport {\n /** Total records inspected. */\n totalRecords: number\n /** Records with input=0 AND output=0 (a stub fingerprint). */\n stubRecords: number\n /** Records with nonzero token usage (real LLM activity). */\n realRecords: number\n /** Records where output>0 but costUsd=0 (real LLM, broken cost ledger). */\n uncostedRecords: number\n /** Sum of input tokens across all records. */\n totalInputTokens: number\n /** Sum of output tokens across all records. */\n totalOutputTokens: number\n /** Sum of costUsd across all records. */\n totalCostUsd: number\n /** Worst-case integrity verdict. */\n verdict: 'real' | 'mixed' | 'stub'\n /** Human-readable diagnosis suitable for terminal output. */\n diagnosis: string\n}\n\n/**\n * Error thrown when an integrity assertion fails. Caller can pattern-match\n * by `code === 'AGENT_EVAL_BACKEND_STUB'` to differentiate from other\n * errors.\n */\nexport class BackendIntegrityError extends AgentEvalError {\n constructor(\n message: string,\n public readonly report: BackendIntegrityReport,\n ) {\n super('backend_integrity', message)\n }\n}\n\n/**\n * Inspect a batch of RunRecords and return an integrity report. Pure\n * function — no I/O, no logging. The caller decides what to do with the\n * verdict (print warning, throw, gate CI, etc.).\n */\nexport function summarizeBackendIntegrity(\n records: ReadonlyArray<RunRecord>,\n): BackendIntegrityReport {\n return summarizeBackendUsage(\n records.map((record) => ({\n inputTokens: record.tokenUsage.input,\n outputTokens: record.tokenUsage.output,\n costUsd: record.costUsd,\n })),\n )\n}\n\n/** Inspect settled agent calls from the canonical cost ledger. */\nexport function summarizeAgentReceiptIntegrity(\n receipts: ReadonlyArray<CostReceipt>,\n): BackendIntegrityReport {\n return summarizeBackendUsage(\n receipts\n .filter((receipt) => receipt.channel === 'agent')\n .map((receipt) => ({\n inputTokens: receipt.inputTokens,\n outputTokens: receipt.outputTokens,\n costUsd: receipt.costUsd,\n })),\n )\n}\n\ninterface BackendUsage {\n inputTokens: number\n outputTokens: number\n costUsd: number | null\n}\n\nfunction summarizeBackendUsage(records: readonly BackendUsage[]): BackendIntegrityReport {\n const totalRecords = records.length\n let stubRecords = 0\n let realRecords = 0\n let uncostedRecords = 0\n let totalInputTokens = 0\n let totalOutputTokens = 0\n let totalCostUsd = 0\n for (const rec of records) {\n totalInputTokens += rec.inputTokens\n totalOutputTokens += rec.outputTokens\n totalCostUsd += rec.costUsd ?? 0\n if (rec.inputTokens === 0 && rec.outputTokens === 0) stubRecords++\n else realRecords++\n if (rec.outputTokens > 0 && (rec.costUsd === null || rec.costUsd === 0)) uncostedRecords++\n }\n const verdict: BackendIntegrityReport['verdict'] =\n totalRecords === 0\n ? 'stub'\n : stubRecords === totalRecords\n ? 'stub'\n : stubRecords === 0\n ? 'real'\n : 'mixed'\n const diagnosis = buildDiagnosis({\n totalRecords,\n stubRecords,\n realRecords,\n uncostedRecords,\n totalInputTokens,\n totalOutputTokens,\n totalCostUsd,\n verdict,\n })\n return {\n totalRecords,\n stubRecords,\n realRecords,\n uncostedRecords,\n totalInputTokens,\n totalOutputTokens,\n totalCostUsd,\n verdict,\n diagnosis,\n }\n}\n\nfunction buildDiagnosis(r: Omit<BackendIntegrityReport, 'diagnosis'>): string {\n if (r.totalRecords === 0) {\n return 'no records — eval produced zero runs; backend likely failed before first turn'\n }\n if (r.verdict === 'stub') {\n return [\n `all ${r.totalRecords} records have zero token usage — the LLM backend was never called.`,\n 'common causes: --backend sandbox without a sandbox bridge running; stub model returning hard-coded strings;',\n 'auth misconfigured so requests were silently dropped before the LLM. Re-run with --backend tcloud and TANGLE_API_KEY set,',\n 'or boot the cli-bridge / sandbox before invoking the eval.',\n ].join(' ')\n }\n if (r.verdict === 'mixed') {\n const pct = ((r.stubRecords / r.totalRecords) * 100).toFixed(0)\n return [\n `${r.stubRecords}/${r.totalRecords} records (${pct}%) have zero token usage — the backend partially failed.`,\n 'common causes: rate-limit cascade (429s after the first N personas);',\n 'transient auth expiry mid-run; provider outage. Treat the affected records as missing data, not agent failures.',\n ].join(' ')\n }\n // verdict === 'real'\n if (r.uncostedRecords > 0) {\n const pct = ((r.uncostedRecords / r.totalRecords) * 100).toFixed(0)\n return [\n `${r.totalRecords} records with real LLM activity (in=${r.totalInputTokens}, out=${r.totalOutputTokens} tokens).`,\n `${r.uncostedRecords} (${pct}%) have output tokens but costUsd=0. Two distinct roots:`,\n '(a) cost ledger mis-wired — no usage propagation from the runtime stream into RunRecord; or',\n '(b) the model is unpriced at the source (sandbox/router returned $0 despite real tokens).',\n 'For (b), price the measured tokens against the substrate table (estimateCost) instead of leaving $0.',\n ].join(' ')\n }\n return `${r.totalRecords} records with real LLM activity (in=${r.totalInputTokens}, out=${r.totalOutputTokens} tokens, $${r.totalCostUsd.toFixed(4)}).`\n}\n\n/**\n * Throw BackendIntegrityError if the verdict is 'stub' — i.e. every record\n * shows zero LLM activity. Non-strict callers can pass `{ allowMixed: false }`\n * to also reject mixed verdicts (recommended for CI gates).\n *\n * Real backends pass through silently.\n */\nexport function assertRealBackend(\n records: ReadonlyArray<RunRecord>,\n opts: { allowMixed?: boolean } = {},\n): BackendIntegrityReport {\n const report = summarizeBackendIntegrity(records)\n return assertBackendReport(report, opts)\n}\n\nfunction assertBackendReport(\n report: BackendIntegrityReport,\n opts: { allowMixed?: boolean },\n): BackendIntegrityReport {\n const allowMixed = opts.allowMixed ?? true\n if (report.verdict === 'stub') {\n throw new BackendIntegrityError(\n `backend-integrity: ran against a stub or unconfigured backend — ${report.diagnosis}`,\n report,\n )\n }\n if (!allowMixed && report.verdict === 'mixed') {\n throw new BackendIntegrityError(\n `backend-integrity: partial backend failure rejected — ${report.diagnosis}`,\n report,\n )\n }\n return report\n}\n","import { z } from 'zod'\nimport { compareCodeUnits, type LedgerHash } from '../ledger-core/canonical'\nimport { FileLedgerJournal, type LedgerJournalCodec } from '../ledger-core/journal'\n\nconst identity = z\n .string()\n .min(1)\n .refine((value) => value.trim() === value)\nconst digest = z.string().regex(/^sha256:[a-f0-9]{64}$/)\nconst reservationSchema = z\n .object({\n requestId: identity,\n claimDigest: digest,\n populationId: identity,\n inputDigest: digest,\n unitIds: z.array(identity).min(1),\n })\n .strict()\n\n/** One final dataset reserved for one adaptive decision, across processes and campaigns. */\nexport type FinalEvidenceReservation = z.infer<typeof reservationSchema>\n\nconst measurementSchema = z\n .object({\n evaluatorDigest: digest,\n candidateDigests: z.array(digest).min(1),\n })\n .strict()\n\nexport type FinalEvidenceMeasurement = z.infer<typeof measurementSchema>\n\nconst eventSchema = z.discriminatedUnion('kind', [\n z\n .object({\n kind: z.literal('reserved'),\n eventId: identity,\n reservation: reservationSchema,\n })\n .strict(),\n z\n .object({\n kind: z.literal('exposed'),\n eventId: identity,\n requestId: identity,\n measurement: measurementSchema,\n })\n .strict(),\n])\n\ntype Event = z.infer<typeof eventSchema>\nconst schema = 'agent-eval.final-evidence.v1' as const\nconst entrySchema = z\n .object({\n schema: z.literal(schema),\n sequence: z.number().int().nonnegative(),\n previousHash: digest.nullable(),\n event: eventSchema,\n entryHash: digest,\n })\n .strict()\n\nexport interface FinalEvidenceRecord {\n reservation: FinalEvidenceReservation\n reservationHash: LedgerHash\n exposure: { measurement: FinalEvidenceMeasurement; entryHash: LedgerHash } | null\n}\n\nexport type FinalEvidenceOutcome<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; error: { kind: 'conflict' | 'invalid' | 'unavailable'; message: string } }\n\nexport interface FinalEvidenceLedger {\n reserve(\n input: FinalEvidenceReservation,\n ): Promise<FinalEvidenceOutcome<{ record: FinalEvidenceRecord; replayed: boolean }>>\n expose(\n requestId: string,\n measurement: FinalEvidenceMeasurement,\n ): Promise<FinalEvidenceOutcome<{ record: FinalEvidenceRecord; replayed: boolean }>>\n read(): Promise<FinalEvidenceOutcome<FinalEvidenceRecord[]>>\n}\n\n/** Retains the distinction between invalid input, consumed evidence, and unavailable storage. */\nexport class FinalEvidenceError extends Error {\n constructor(\n readonly kind: 'conflict' | 'invalid' | 'unavailable',\n message: string,\n ) {\n super(message)\n this.name = 'FinalEvidenceError'\n }\n}\n\n/** A consumed or conflicting dataset cannot authorize another adaptive decision. */\nexport class FinalEvidenceConflictError extends FinalEvidenceError {\n constructor(message: string) {\n super('conflict', message)\n this.name = 'FinalEvidenceConflictError'\n }\n}\n\nfunction invalid(message: string): Error {\n return new TypeError(`final evidence: ${message}`)\n}\n\nfunction normalizeReservation(input: FinalEvidenceReservation): FinalEvidenceReservation {\n const parsed = reservationSchema.parse(input)\n if (new Set(parsed.unitIds).size !== parsed.unitIds.length) {\n throw invalid('unitIds must be unique independent source identities')\n }\n return { ...parsed, unitIds: [...parsed.unitIds].sort(compareCodeUnits) }\n}\n\nfunction normalizeMeasurement(input: FinalEvidenceMeasurement): FinalEvidenceMeasurement {\n const parsed = measurementSchema.parse(input)\n return {\n ...parsed,\n candidateDigests: [...new Set(parsed.candidateDigests)].sort(compareCodeUnits),\n }\n}\n\nfunction codec(): LedgerJournalCodec<{ schema: typeof schema }, Event, FinalEvidenceRecord[]> {\n return {\n subject: 'final evidence ledger',\n header: { schema },\n integrityError: (message, options) => new Error(message, options),\n conflictError: (message) => new FinalEvidenceConflictError(message),\n parseEntry: (raw, context) => {\n const decoded = entrySchema.safeParse(raw)\n if (!decoded.success)\n throw new Error(\n `final evidence ledger ${context.path}:${context.line} is invalid: ${decoded.error.message}`,\n )\n const parsed = decoded.data\n return {\n ...parsed,\n previousHash: parsed.previousHash as LedgerHash | null,\n entryHash: parsed.entryHash as LedgerHash,\n }\n },\n checkEntryHeader: (entry) => {\n if (entry.schema !== schema) throw invalid('unsupported ledger schema')\n },\n createProjector: () => {\n const records = new Map<string, FinalEvidenceRecord>()\n const owners = new Map<string, string>()\n const inputOwners = new Map<string, string>()\n return {\n apply: (entry) => {\n const event = entry.event\n if (event.kind === 'reserved') {\n const reservation = normalizeReservation(event.reservation)\n if (\n event.eventId !== `reserve:${reservation.requestId}` ||\n records.has(reservation.requestId)\n ) {\n throw invalid('invalid or duplicate reservation identity')\n }\n const inputOwner = inputOwners.get(reservation.inputDigest)\n if (inputOwner !== undefined) {\n throw new FinalEvidenceConflictError(\n `final input is already reserved by '${inputOwner}'`,\n )\n }\n for (const unitId of reservation.unitIds) {\n const owner = owners.get(unitId)\n if (owner !== undefined) {\n throw new FinalEvidenceConflictError(\n `final unit '${unitId}' is already reserved by '${owner}'`,\n )\n }\n owners.set(unitId, reservation.requestId)\n }\n inputOwners.set(reservation.inputDigest, reservation.requestId)\n records.set(reservation.requestId, {\n reservation,\n reservationHash: entry.entryHash,\n exposure: null,\n })\n } else {\n const record = records.get(event.requestId)\n if (\n event.eventId !== `expose:${event.requestId}` ||\n !record ||\n record.exposure !== null\n ) {\n throw invalid('exposure requires one unexposed reservation')\n }\n record.exposure = {\n measurement: normalizeMeasurement(event.measurement),\n entryHash: entry.entryHash,\n }\n }\n },\n // Records are copied because a later exposure replaces a field of the\n // live record, and a returned projection must not change under its reader.\n snapshot: () => [...records.values()].map((record) => ({ ...record })),\n }\n },\n }\n}\n\nasync function outcome<T>(operation: () => Promise<T>): Promise<FinalEvidenceOutcome<T>> {\n try {\n return { succeeded: true, value: await operation() }\n } catch (error) {\n return {\n succeeded: false,\n error: {\n kind:\n error instanceof FinalEvidenceConflictError\n ? 'conflict'\n : error instanceof TypeError || error instanceof z.ZodError\n ? 'invalid'\n : 'unavailable',\n message: error instanceof Error ? error.message : String(error),\n },\n }\n }\n}\n\n/** Uses the shared locked journal and requires its trusted head on every reopen. */\nexport function openFinalEvidenceLedger(options: { path: string }): FinalEvidenceLedger {\n if (!options.path.trim()) throw invalid('path is empty')\n const journal = new FileLedgerJournal(options.path, codec(), { requireTrustedHead: true })\n return {\n reserve: (input) =>\n outcome(async () => {\n const reservation = normalizeReservation(input)\n const result = await journal.append(\n {\n kind: 'reserved',\n eventId: `reserve:${reservation.requestId}`,\n reservation,\n },\n { pinHead: true },\n )\n const record = result.projection.find(\n (item) => item.reservation.requestId === reservation.requestId,\n )\n if (!record) throw invalid('reserved record is missing after append')\n return { record, replayed: !result.appended }\n }),\n expose: (requestId, input) =>\n outcome(async () => {\n identity.parse(requestId)\n const measurement = normalizeMeasurement(input)\n const result = await journal.append(\n {\n kind: 'exposed',\n eventId: `expose:${requestId}`,\n requestId,\n measurement,\n },\n { pinHead: true },\n )\n const record = result.projection.find((item) => item.reservation.requestId === requestId)\n if (!record) throw invalid('exposed record is missing after append')\n return { record, replayed: !result.appended }\n }),\n read: () => outcome(() => journal.replay()),\n }\n}\n","/**\n * Approximate detectable lift from baseline variance and the intended sample size.\n *\n * Model: the ship rule is `CI.low(paired Δ) > deltaThreshold`. Approximating the\n * bootstrap CI as normal, `CI.low ≈ effect − z·sd_Δ/√n`, so the smallest shippable\n * effect is `MDE = deltaThreshold + z·sd_Δ/√n`. This estimates `sd_Δ` as\n * `√2·sd_baseline`, assuming equal arm variances and zero paired correlation.\n * Actual candidate variance and paired correlation can move the threshold in either direction.\n * This diagnostic does not replace the gate or guarantee a detection probability.\n *\n * Supply one baseline mean per independent observation used by the comparison.\n * With declared source units, repetitions and variants refine those means without increasing n.\n * `selfImprove` attaches this diagnostic after its final measurement.\n */\n\nexport interface PowerPreflightOptions {\n /** Baseline composites at the comparison's independent observation unit. */\n baselineComposites: number[]\n /** Independent paired observations planned for the comparison.\n * Defaults to `baselineComposites.length`. */\n pairedN?: number\n /** The ship gate's effect-size threshold. Default 0.05 (defaultProductionGate). */\n deltaThreshold?: number\n /** CI confidence the gate uses. Default 0.95. */\n confidence?: number\n /** Whether the holdout uses the gate's judge family.\n * More observations cannot establish freedom from systematic scoring bias.\n * Default false. */\n sharedScorerChannel?: boolean\n}\n\nexport interface PowerPreflight {\n /** Paired observations the comparison will have. */\n n: number\n /** Sample standard deviation of baseline observation means. */\n sd: number\n /** Approximate lift needed to put a normal interval above the gate threshold. */\n mde: number\n /** Baseline holdout composite mean. */\n baselineMean: number\n /** Headroom to a perfect 1.0 composite (the largest achievable lift on a [0,1] judge). */\n headroom: number\n /** Whether this approximation exceeds the estimated [0,1] score headroom.\n * This is a planning warning, not a proof that promotion is impossible. */\n underpowered: boolean\n /** True when composites look [0,1]-scaled; headroom/underpowered are only\n * meaningful under that convention (0-100 judges get mde/sd/n but no verdict). */\n scaleAssumed: boolean\n deltaThreshold: number\n confidence: number\n /** Notes unmeasured systematic bias when the gate shares its scoring channel. */\n sharedChannelCaveat?: string\n /** One actionable sentence for humans and logs. */\n recommendation: string\n}\n\n/** Two-sided z for the common confidence levels; interpolation is overkill here. */\nfunction zFor(confidence: number): number {\n if (confidence >= 0.99) return 2.576\n if (confidence >= 0.95) return 1.96\n if (confidence >= 0.9) return 1.645\n return 1.282\n}\n\n/** Estimate detectable lift from baseline independent observations before budgeting a comparison. */\nexport function powerPreflight(opts: PowerPreflightOptions): PowerPreflight {\n const composites = opts.baselineComposites.filter((v) => Number.isFinite(v))\n if (composites.length < 3) {\n throw new Error(\n `powerPreflight: need >= 3 finite baseline composites to estimate variance, got ${composites.length}`,\n )\n }\n const deltaThreshold = opts.deltaThreshold ?? 0.05\n const confidence = opts.confidence ?? 0.95\n const n = opts.pairedN ?? composites.length\n if (n < 2) throw new Error(`powerPreflight: pairedN must be >= 2, got ${n}`)\n\n const mean = composites.reduce((a, b) => a + b, 0) / composites.length\n const variance =\n composites.reduce((a, b) => a + (b - mean) * (b - mean), 0) / (composites.length - 1)\n const sd = Math.sqrt(variance)\n const z = zFor(confidence)\n const mde = deltaThreshold + (z * Math.SQRT2 * sd) / Math.sqrt(n)\n\n const scaleAssumed = composites.every((v) => v >= -0.001 && v <= 1.5)\n const headroom = Math.max(0, 1 - mean)\n const underpowered = scaleAssumed && mde > headroom\n\n const sharedChannelCaveat = opts.sharedScorerChannel\n ? 'Holdout and gate share one scoring channel: systematic judge bias remains outside this estimate. An independent second scoring channel can help test that bias.'\n : undefined\n\n const recommendation = underpowered\n ? `UNDERPOWERED under this approximation: detectable lift ${mde.toFixed(3)} exceeds the ${headroom.toFixed(3)} headroom above the baseline (${mean.toFixed(3)}). Raise paired n using independent observations to ~${Math.ceil(((z * Math.SQRT2 * sd) / Math.max(headroom - deltaThreshold, 0.01)) ** 2)} or reduce observation variance. Recheck with measured paired deltas.`\n : `Approximate detectable lift at n=${n}: ${mde.toFixed(3)} (baseline sd ${sd.toFixed(3)}). Compare this estimate with the effect you expect, then recheck using measured paired deltas.`\n\n return {\n n,\n sd,\n mde,\n baselineMean: mean,\n headroom,\n underpowered,\n scaleAssumed,\n deltaThreshold,\n confidence,\n ...(sharedChannelCaveat ? { sharedChannelCaveat } : {}),\n recommendation: sharedChannelCaveat\n ? `${recommendation} ${sharedChannelCaveat}`\n : recommendation,\n }\n}\n","/**\n * Reflective mutation — primitives for trace-conditioned prompt rewriting.\n *\n * Used by `prompt-evolution.ts` (and any consumer running iterative\n * improvement). Given a parent prompt + concrete trace evidence (top trials,\n * bottom trials, missed expectations), produce an LLM-ready prompt that\n * proposes targeted mutations — not blind rephrasings.\n *\n * Why this lives outside `prompt-evolution.ts`: any consumer that wants to\n * run reflective rewriting WITHOUT the population/Pareto machinery can\n * import these primitives directly.\n *\n * Quality bar (vs. naive \"mutate this prompt\"):\n * - Show parent ↔ children diff, not just one variant\n * - Quote specific missed goldens with their match phrases\n * - Surface the model's actual emitted output side-by-side with what was expected\n * - Quote concrete mutation primitives so the model has a vocabulary\n */\n\nimport { autoCloseTruncatedJson } from './json-recovery'\n\n/** Bound on rendered/carried `emitted` evidence. ONE constant shared by the\n * producer (campaignBreakdown's per-scenario excerpt) and this renderer — if\n * the two drifted, the tighter side would silently re-clip carried evidence. */\nexport const EMITTED_EVIDENCE_MAX_CHARS = 2000\n\nexport interface TrialTrace {\n /** Stable id for the trial — surfaces in the prompt for grounding. */\n id: string\n /** Score the trial received on its primary metric. */\n score: number\n /** Candidate inputs the agent was given (e.g., the fixture or scenario). */\n inputName?: string\n /**\n * Goldens / expectations this trial was tested against, with whether each\n * was matched. The reflection prompt quotes the missed ones specifically.\n */\n expectations?: Array<{ id: string; phrase: string; matched: boolean }>\n /** Free-form text — what the agent actually emitted (e.g., findings, plan). */\n emitted?: string\n /** The judge's free-form note on WHY this trial scored low — the failure\n * evidence the reflection targets. Should be a generalizable pattern (which\n * checks/lines/dimensions failed, and how), never case-specific ground\n * truth (that would teach memorization, not capability). */\n failureNote?: string\n /** Optional structured metrics (recall, precision, cost, latency). */\n metrics?: Record<string, number>\n}\n\nexport interface ReflectionContext {\n /** What is being mutated — appears in the system prompt for orientation. */\n target: string\n /** Current variant's payload — JSON-serialised for the prompt. */\n parentPayload: unknown\n /** Best-performing trials this generation. */\n topTrials: TrialTrace[]\n /** Worst-performing trials this generation — the missed-golden source. */\n bottomTrials: TrialTrace[]\n /** How many children the mutator should propose. */\n childCount: number\n /** Optional: domain-specific mutation primitives the model can pick from. */\n mutationPrimitives?: string[]\n}\n\nexport const DEFAULT_MUTATION_PRIMITIVES: string[] = [\n 'Strengthen an imperative (\"should\" → \"must\")',\n 'Add a concrete example pulled from a missed-golden phrase',\n 'Remove a redundant rule that did not improve recall',\n 'Add a counterfactual (\"if X is missing, the score is capped at Y\")',\n 'Reorder sections so the highest-impact rule is first',\n 'Replace abstract language with a domain-specific noun the trial misses',\n]\n\n/**\n * Build the LLM-ready reflection prompt. Output is plain text — pass it as\n * the user message. The system message should be small and stable (e.g.\n * \"Output ONLY a JSON object matching the schema below.\").\n */\nexport function buildReflectionPrompt(ctx: ReflectionContext): string {\n const primitives = ctx.mutationPrimitives ?? DEFAULT_MUTATION_PRIMITIVES\n const sections: string[] = []\n\n sections.push(`# Mutation target: ${ctx.target}`)\n sections.push('')\n sections.push(\n `You are tuning the prompt component named \\`${ctx.target}\\`. The current variant is shown below; you have ${ctx.topTrials.length} top trials and ${ctx.bottomTrials.length} bottom trials as evidence. Propose ${ctx.childCount} mutation${ctx.childCount === 1 ? '' : 's'} that fix specific weaknesses visible in the bottom trials. Avoid blank rephrasings.`,\n )\n sections.push('')\n\n sections.push('## Current variant')\n sections.push('```json')\n sections.push(JSON.stringify(ctx.parentPayload, null, 2))\n sections.push('```')\n sections.push('')\n\n if (ctx.bottomTrials.length > 0) {\n sections.push('## Failures (bottom trials) — what went wrong')\n sections.push('')\n for (const trial of ctx.bottomTrials) {\n sections.push(\n `### Trial \\`${trial.id}\\` — score ${trial.score.toFixed(2)}${trial.inputName ? ` (${trial.inputName})` : ''}`,\n )\n if (trial.failureNote) {\n sections.push('')\n // 1500 chars fits a real traceback / failing-assertion note; clipping\n // mid-traceback would hide the executable-judge evidence the\n // reflection targets.\n sections.push(`**Why it scored low:** ${truncate(trial.failureNote, 1500)}`)\n }\n const missed = (trial.expectations ?? []).filter((e) => !e.matched)\n if (missed.length > 0) {\n sections.push('')\n sections.push('**Missed expectations:**')\n for (const m of missed) {\n sections.push(`- \\`${m.id}\\`: should match phrase \\`${quote(m.phrase)}\\``)\n }\n }\n if (trial.emitted) {\n sections.push('')\n sections.push('**What the agent emitted:**')\n sections.push('```')\n sections.push(truncate(trial.emitted, EMITTED_EVIDENCE_MAX_CHARS))\n sections.push('```')\n }\n sections.push('')\n }\n }\n\n if (ctx.topTrials.length > 0) {\n sections.push('## Successes (top trials) — what to preserve')\n sections.push('')\n for (const trial of ctx.topTrials) {\n sections.push(\n `- \\`${trial.id}\\`: score ${trial.score.toFixed(2)}${trial.inputName ? ` (${trial.inputName})` : ''}`,\n )\n }\n sections.push('')\n }\n\n sections.push('## Allowed mutation primitives')\n sections.push('')\n for (const p of primitives) sections.push(`- ${p}`)\n sections.push('')\n\n sections.push('## Output schema')\n sections.push('')\n sections.push('Respond with a JSON object — no prose, no markdown fences:')\n sections.push('```json')\n sections.push(\n JSON.stringify(\n {\n proposals: [\n {\n label: '<short label, ≤ 40 chars>',\n rationale: '<which failure this targets and which primitive you used>',\n payload: '<full payload of the new variant — same shape as the current variant>',\n },\n ],\n },\n null,\n 2,\n ),\n )\n sections.push('```')\n\n return sections.join('\\n')\n}\n\nfunction truncate(s: string, max: number): string {\n if (s.length <= max) return s\n return `${s.slice(0, max)}… [truncated]`\n}\n\nfunction quote(s: string): string {\n return s.replace(/`/g, '\\\\`')\n}\n\nexport interface ReflectionProposal {\n label: string\n rationale: string\n payload: unknown\n}\n\n/**\n * Parse the model's JSON response back into proposals. Tolerates markdown\n * fences and surrounding prose. Returns at most `maxProposals`.\n */\nexport function parseReflectionResponse(raw: string, maxProposals?: number): ReflectionProposal[] {\n let text = raw.trim()\n if (text.startsWith('```')) text = text.replace(/^```(?:json)?\\n?/, '').replace(/\\n?```$/, '')\n\n // Try to parse as either a JSON object `{proposals: [...]}` or a bare\n // array `[...]`. LLMs frequently emit one or the other depending on how\n // they read the schema example; accept both.\n let parsed: unknown = null\n const objectStart = text.indexOf('{')\n const objectEnd = text.lastIndexOf('}')\n const arrayStart = text.indexOf('[')\n const arrayEnd = text.lastIndexOf(']')\n // Prefer whichever delimiter comes first (the model committed to that shape).\n const tryObjectFirst = objectStart >= 0 && (arrayStart < 0 || objectStart < arrayStart)\n const candidates: string[] = []\n if (tryObjectFirst) {\n if (objectStart >= 0 && objectEnd > objectStart)\n candidates.push(text.slice(objectStart, objectEnd + 1))\n if (arrayStart >= 0 && arrayEnd > arrayStart)\n candidates.push(text.slice(arrayStart, arrayEnd + 1))\n } else {\n if (arrayStart >= 0 && arrayEnd > arrayStart)\n candidates.push(text.slice(arrayStart, arrayEnd + 1))\n if (objectStart >= 0 && objectEnd > objectStart)\n candidates.push(text.slice(objectStart, objectEnd + 1))\n }\n for (const slice of candidates) {\n try {\n parsed = JSON.parse(slice)\n break\n } catch {\n // try next\n }\n }\n\n // Truncation-tolerant fallback: LLMs frequently hit a max_tokens cap\n // mid-emission, leaving N unclosed `}` / `]` at the tail. Close them in\n // order from the deepest unclosed structure outward, by walking the\n // candidate slice and tracking depth, then retrying JSON.parse. This\n // recovers any complete proposals before the cutoff and drops the rest.\n if (parsed == null) {\n for (const slice of candidates) {\n const closed = autoCloseTruncatedJson(slice)\n if (closed != null && closed !== slice) {\n try {\n parsed = JSON.parse(closed)\n break\n } catch {\n // give up on this candidate\n }\n }\n }\n }\n\n if (parsed == null) return []\n\n // Normalize: accept `{proposals: [...]}` or a bare array.\n let proposalsRaw: unknown\n if (Array.isArray(parsed)) {\n proposalsRaw = parsed\n } else if (parsed && typeof parsed === 'object') {\n proposalsRaw = (parsed as { proposals?: unknown }).proposals\n }\n if (!Array.isArray(proposalsRaw)) return []\n\n const out: ReflectionProposal[] = []\n for (const p of proposalsRaw) {\n if (!p || typeof p !== 'object') continue\n const obj = p as { label?: unknown; rationale?: unknown; payload?: unknown }\n if (!('payload' in obj)) continue\n out.push({\n label: typeof obj.label === 'string' ? obj.label : 'mutation',\n rationale: typeof obj.rationale === 'string' ? obj.rationale : '',\n payload: obj.payload,\n })\n if (maxProposals !== undefined && out.length >= maxProposals) break\n }\n return out\n}\n","/**\n * Shared campaign-score reductions used by every optimizer preset\n * (`runOptimization`, external optimization methods, `compareOptimizationMethods`).\n * \"composite of a campaign\" and \"per-scenario / per-dimension breakdown\" so\n * the optimizers cannot drift on how a surface's score is computed.\n */\n\nimport { EMITTED_EVIDENCE_MAX_CHARS } from '../reflective-mutation'\nimport { aggregatePairedHoldout, pairHoldout } from './gates/statistical-heldout'\nimport { projectCampaignCellQuality } from './run-record'\nimport type { CampaignResult, JudgeScore, Scenario } from './types'\n\nexport interface CampaignComparisonUnits {\n pairedCellN: number\n unitIds: string[]\n /** Cells with no complete quality score on either arm. */\n unscoredCellIds: string[]\n /** Present when repetitions and source variants share an independent unit. */\n independentUnitByScenarioId?: Record<string, string>\n}\n\n/** Reduce complete paired cells using the same observation units as held-out inference. */\nexport function pairedCampaignComposites<TArtifact, TScenario extends Scenario>(\n baseline: CampaignResult<TArtifact, TScenario>,\n candidate: CampaignResult<TArtifact, TScenario>,\n independentUnitByScenarioId?: ReadonlyMap<string, string>,\n): {\n before: number[]\n after: number[]\n beforeMean: number\n afterMean: number\n observations: CampaignComparisonUnits\n} {\n const scoresByCell = (campaign: CampaignResult<TArtifact, TScenario>) => {\n const scores = new Map<string, Record<string, JudgeScore>>()\n for (const cell of campaign.cells) {\n if (scores.has(cell.cellId)) {\n throw new Error(`pairedCampaignComposites: duplicate cell '${cell.cellId}'`)\n }\n const quality = projectCampaignCellQuality(cell)\n scores.set(cell.cellId, quality.score === undefined ? {} : quality.successfulJudgeScores)\n }\n return scores\n }\n const scenarioIds = new Set(\n [...baseline.cells, ...candidate.cells].map((cell) => cell.scenarioId),\n )\n const paired = pairHoldout(\n scoresByCell(candidate),\n scoresByCell(baseline),\n scenarioIds,\n (score) => score.composite,\n )\n const observations = aggregatePairedHoldout(paired, independentUnitByScenarioId)\n const scoredCellIds = new Set(paired.cellIds)\n if (observations.before.length === 0) {\n throw new Error('pairedCampaignComposites: campaigns have no paired quality scores')\n }\n return {\n before: observations.before,\n after: observations.after,\n beforeMean:\n observations.before.reduce((sum, score) => sum + score, 0) / observations.before.length,\n afterMean:\n observations.after.reduce((sum, score) => sum + score, 0) / observations.after.length,\n observations: {\n pairedCellN: paired.cellIds.length,\n unitIds: observations.unitIds,\n unscoredCellIds: baseline.cells\n .filter((cell) => !scoredCellIds.has(cell.cellId))\n .map((cell) => cell.cellId)\n .sort(),\n ...(independentUnitByScenarioId\n ? {\n independentUnitByScenarioId: Object.fromEntries(\n [...scenarioIds].sort().map((id) => [id, independentUnitByScenarioId.get(id)!]),\n ),\n }\n : {}),\n },\n }\n}\n\n/** Mean composite across cells with complete task-quality evidence.\n * Partial judge results remain on their cells but never enter this value.\n * A campaign with no complete score has no numeric mean and fails loudly. */\nexport function campaignMeanComposite<TArtifact, TScenario extends Scenario>(\n campaign: CampaignResult<TArtifact, TScenario>,\n): number {\n const mean = campaignMeanCompositeOrNull(campaign)\n if (mean === null) {\n throw new Error('campaignMeanComposite: campaign has no complete cell-quality scores')\n }\n return mean\n}\n\n/** Nullable campaign mean for wire and report fields that represent missing quality. */\nexport function campaignMeanCompositeOrNull<TArtifact, TScenario extends Scenario>(\n campaign: CampaignResult<TArtifact, TScenario>,\n): number | null {\n const scores = campaign.cells.flatMap((cell) => {\n const score = projectCampaignCellQuality(cell).score\n return score === undefined ? [] : [score]\n })\n return scores.length === 0 ? null : scores.reduce((sum, score) => sum + score, 0) / scores.length\n}\n\nexport interface CampaignBreakdown {\n /** Mean score per judge dimension across all cells. */\n dimensions: Record<string, number>\n /** Per-scenario composite (mean over reps + judges) + the judge's free-form\n * `notes` for that scenario (the \"why\" a reflective proposer grounds on) +\n * an optional `emitted` excerpt of the candidate's raw output (the \"what it\n * actually did\" a reflective proposer grounds on). */\n scenarios: Array<{ scenarioId: string; composite: number; notes?: string; emitted?: string }>\n}\n\n/** Per-candidate evidence a reflective/patch proposer grounds its next proposal\n * on: mean score per judge dimension + per-scenario composite. */\nexport function campaignBreakdown<TArtifact, TScenario extends Scenario>(\n campaign: CampaignResult<TArtifact, TScenario>,\n): CampaignBreakdown {\n const dimSums: Record<string, number> = {}\n const dimCounts: Record<string, number> = {}\n const byScenario = new Map<string, number[]>()\n const notesByScenario = new Map<string, Set<string>>()\n const emittedByScenario = new Map<string, { composite: number; text: string }>()\n for (const cell of campaign.cells) {\n const quality = projectCampaignCellQuality(cell)\n if (quality.score === undefined) continue\n const judgeScores = Object.values(quality.successfulJudgeScores)\n const cellComposite = quality.score\n const arr = byScenario.get(cell.scenarioId) ?? []\n arr.push(cellComposite)\n byScenario.set(cell.scenarioId, arr)\n // Carry the candidate's raw output as trajectory evidence when the artifact\n // is a string (the common prompt-tier shape). Across reps, keep the\n // LOWEST-composite cell's output — reflection grounds on the failure, and\n // the bottom-trial excerpt is the one buildReflectionPrompt renders.\n if (typeof cell.artifact === 'string' && cell.artifact.trim().length > 0) {\n const prev = emittedByScenario.get(cell.scenarioId)\n if (!prev || cellComposite < prev.composite) {\n emittedByScenario.set(cell.scenarioId, {\n composite: cellComposite,\n text: cell.artifact.slice(0, EMITTED_EVIDENCE_MAX_CHARS),\n })\n }\n }\n // Collect the judges' free-form notes per scenario (deduped) — the failure\n // evidence the reflective proposer grounds on. Generalizable by contract;\n // the judge must not put case-specific ground truth here.\n for (const s of judgeScores) {\n if (s.notes?.trim()) {\n const set = notesByScenario.get(cell.scenarioId) ?? new Set<string>()\n set.add(s.notes.trim())\n notesByScenario.set(cell.scenarioId, set)\n }\n }\n for (const score of judgeScores) {\n for (const [key, value] of Object.entries(score.dimensions)) {\n if (!Number.isFinite(value)) continue\n dimSums[key] = (dimSums[key] ?? 0) + value\n dimCounts[key] = (dimCounts[key] ?? 0) + 1\n }\n }\n }\n const dimensions: Record<string, number> = {}\n for (const key of Object.keys(dimSums)) {\n const count = dimCounts[key] ?? 0\n dimensions[key] = count > 0 ? (dimSums[key] ?? 0) / count : 0\n }\n const scenarios = [...byScenario.entries()].map(([scenarioId, comps]) => {\n const notesSet = notesByScenario.get(scenarioId)\n const notes = notesSet && notesSet.size > 0 ? [...notesSet].join(' | ') : undefined\n const emitted = emittedByScenario.get(scenarioId)?.text\n return {\n scenarioId,\n composite: comps.reduce((a, b) => a + b, 0) / comps.length,\n ...(notes ? { notes } : {}),\n ...(emitted ? { emitted } : {}),\n }\n })\n return { dimensions, scenarios }\n}\n","/**\n * Loop provenance — the durable, queryable record of WHAT a self-improvement\n * loop did and WHY, plus the OTel spans that let an OTLP collector pivot from\n * an eval-run to the underlying candidate→cell→gate→promote chain.\n *\n * Two artifacts, one source of truth:\n *\n * 1. `LoopProvenanceRecord` — a structured JSON record capturing every\n * candidate (surfaceHash + label + rationale + structured cause), its measured composite,\n * the gate decision + reasons + delta, the held-out lift, the explicit\n * baseline→candidate diff, and BACKEND PROVENANCE (the\n * `assertRealBackend` verdict + worker call count + model). This is the\n * ingestable audit artifact: the +lift recomputes from it, the \"because\n * Z\" rationale survives in it, and a stub backend is detectable from it.\n *\n * 2. `loopProvenanceSpans()` — the same chain emitted as OTLP-ingestable\n * `TraceSpanEvent`s, pivoted on the substrate's standard\n * `tangle.runId` / `tangle.scenarioId` / `tangle.cellId` /\n * `tangle.generation` attributes (the same pivots `/adapters/otel`\n * reads). The hosted `/v1/ingest/traces` endpoint receives the FULL loop,\n * not just the `cost.*` spans `runCampaign` already emits per cell.\n *\n * The record is built from the loop result and its settled cost receipts — no\n * second usage collector can contradict what the measured cells recorded.\n */\n\nimport { createHash } from 'node:crypto'\nimport { join } from 'node:path'\nimport type { CostReceipt } from '../cost-ledger'\nimport { defineEvaluationClaim, type EvaluationClaim } from '../experiment/claim'\nimport type { HostedClient } from '../hosted/client'\nimport type { TraceSpanEvent } from '../hosted/types'\nimport { summarizeAgentReceiptIntegrity } from '../integrity/backend-integrity'\nimport { canonicalString, compareCodeUnits, hashCanonical } from '../ledger-core/canonical'\nimport { assertCampaignSplitIdentity } from './coverage'\nimport type { ComparisonCost } from './optimization-cost'\nimport type { OptimizationMethodProvenance } from './optimization-method'\nimport type { RunImprovementLoopResult } from './presets/run-improvement-loop'\nimport {\n type CampaignComparisonUnits,\n campaignMeanComposite,\n pairedCampaignComposites,\n} from './score-utils'\nimport type { CampaignStorage } from './storage'\nimport {\n renderSurfaceDiff,\n surfaceContentHash,\n surfaceHash,\n surfaceHashMatches,\n} from './surface-identity'\nimport type {\n CampaignResult,\n GateContribution,\n GateDecision,\n GateResult,\n GenerationCandidate,\n MutableSurface,\n Scenario,\n} from './types'\n\nexport interface LoopProvenanceCandidate {\n /** Generation index this candidate was proposed in. */\n generation: number\n /** 16-char loop-identity fingerprint (matches `GenerationCandidate.surfaceHash`). */\n surfaceHash: string\n /** Full sha256 content hash — byte-identical-verifiable. */\n contentHash: string\n /** Exact scored rows that produced this candidate's search result. */\n campaignDigest: `sha256:${string}`\n /** Proposer label, when the proposer returned a `ProposedCandidate`. */\n label?: string\n /** Proposer rationale — the \"because Z\". When the proposer returned a bare\n * surface (blind mutator) this is absent. */\n rationale?: string\n /** Proposer-supplied typed attribution, carried unchanged from\n * `GenerationCandidate.attribution`. Opaque here; the producer's schema tag\n * governs interpretation. */\n attribution?: Readonly<Record<string, unknown>>\n /** Whether the candidate completed every designed cell and could be selected. */\n eligibleForPromotion: boolean\n /** Designed-denominator receipt retained even for incomplete candidates. */\n coverage: NonNullable<GenerationCandidate['coverage']>\n /** Mean composite this candidate scored on the search split, or null when unscorable. */\n composite: number | null\n /** Whether this candidate was promoted out of its generation. */\n promoted: boolean\n}\n\nexport interface LoopProvenanceBackend {\n /** `assertRealBackend`-grade verdict over the worker call records. */\n verdict: 'real' | 'mixed' | 'stub'\n /** Number of worker LLM calls captured (the audit's \"worker call count\"). */\n workerCallCount: number\n /** Distinct model ids observed across worker calls. */\n models: string[]\n totalInputTokens: number\n totalOutputTokens: number\n totalCostUsd: number\n}\n\nexport interface LoopProvenanceEvidence {\n search: {\n splitDigest: `sha256:${string}`\n baselineCampaignDigest: `sha256:${string}`\n }\n holdout: {\n splitDigest: `sha256:${string}`\n baselineCampaignDigest: `sha256:${string}`\n winnerCampaignDigest: `sha256:${string}`\n observations?: CampaignComparisonUnits\n neutralized?: {\n contentHash: `sha256:${string}`\n campaignDigest: `sha256:${string}`\n composite: number\n lift: number\n }\n }\n costReceiptsDigest: `sha256:${string}`\n}\n\nexport interface LoopProvenanceOptimizationMethod {\n name: string\n cost: ComparisonCost\n durationMs?: number\n provenance?: OptimizationMethodProvenance\n}\n\n/**\n * The durable provenance record: the baseline and winner measurements, the\n * rationale, the explicit baseline→candidate diff, and backend provenance.\n */\nexport interface LoopProvenanceRecord {\n schema: 'tangle.loop-provenance'\n /** SHA-256 over the canonical record with this field omitted. */\n recordDigest: `sha256:${string}`\n runId: string\n runDir: string\n timestamp: string\n /** Baseline + winner surface content hashes — distinguishable, byte-verifiable. */\n baselineContentHash: string\n winnerContentHash: string\n /** Proposer label/rationale for the promoted change. Absent ⇒ winner == baseline. */\n winnerLabel?: string\n winnerRationale?: string\n /** The explicit baseline→winner unified diff the gate decided on. */\n diff: string\n /** Every candidate across every generation, with its rationale and structured cause. */\n candidates: LoopProvenanceCandidate[]\n /** Complete external method identity and spend, when one authored the candidate. */\n optimizationMethod?: LoopProvenanceOptimizationMethod\n /** Exact campaign, split, surface, and receipt identities behind every summary. */\n evidence: LoopProvenanceEvidence\n /** Baseline composite on the search split that generated the candidates. */\n baselineSearchComposite: number\n claim?: EvaluationClaim\n /** The gate verdict — decision + reasons + contributing gates + delta. */\n gate: {\n decision: GateDecision\n reasons: string[]\n delta?: number\n contributingGates: GateContribution[]\n }\n /** Present iff the loop ran with `holdout: 'deferred'` — the held-out\n * comparison was intentionally not measured in this run, so the holdout\n * composites and `heldOutLift` are ABSENT rather than recorded as a\n * meaningless 0. */\n holdout?: 'deferred'\n /** baseline-on-holdout composite mean. Absent when `holdout === 'deferred'`. */\n baselineHoldoutComposite?: number\n /** winner-on-holdout composite mean. Absent when `holdout === 'deferred'`. */\n winnerHoldoutComposite?: number\n /** winnerHoldout - baselineHoldout — RECOMPUTABLE from this record. Absent\n * when `holdout === 'deferred'` (no held-out measurement ran). */\n heldOutLift?: number\n /** Backend provenance: stub-vs-real verdict + worker call count + models. */\n backend: LoopProvenanceBackend\n totalCostUsd: number\n totalDurationMs: number\n}\n\nexport interface BuildLoopProvenanceArgs<TArtifact, TScenario extends Scenario> {\n runId: string\n runDir: string\n timestamp: string\n baselineSurface: MutableSurface\n winnerSurface: MutableSurface\n winnerLabel?: string\n winnerRationale?: string\n /** Exact baseline campaign on the search split. */\n baselineSearchCampaign: CampaignResult<TArtifact, TScenario>\n /** Per-generation candidate records straight off the loop result. */\n generations: Array<{\n generationIndex: number\n candidates: GenerationCandidate[]\n promoted: string[]\n /** Surfaces measured this generation, keyed by surface hash so the content\n * hash can be computed and the loop identity rechecked from real bytes. */\n surfaces: Array<{\n surfaceHash: string\n surface: MutableSurface\n campaign: CampaignResult<TArtifact, TScenario>\n }>\n }>\n gate: GateResult\n /** Holdout policy the loop ran with. `'deferred'` ⇒ the holdout campaigns\n * below are the shared empty campaign and the record omits the holdout\n * composites + `heldOutLift`. Default `'measured'`. */\n holdout?: 'measured' | 'deferred'\n baselineOnHoldout: CampaignResult<TArtifact, TScenario>\n winnerOnHoldout: CampaignResult<TArtifact, TScenario>\n claim?: EvaluationClaim\n /** Required with a measured claim because campaign identities redact source fields. */\n independentUnitByScenarioId?: ReadonlyMap<string, string>\n neutralizedSurface?: MutableSurface\n neutralizedOnHoldout?: CampaignResult<TArtifact, TScenario>\n /** Settled run-wide receipts — agent calls are the source for backend provenance. */\n costReceipts: ReadonlyArray<CostReceipt>\n totalCostUsd: number\n totalDurationMs: number\n optimizationMethod?: LoopProvenanceOptimizationMethod\n}\n\nexport interface LoopProvenanceArgsFromResult<TArtifact, TScenario extends Scenario> {\n runId: string\n runDir: string\n timestamp: string\n baselineSurface: MutableSurface\n result: RunImprovementLoopResult<TArtifact, TScenario>\n costReceipts: ReadonlyArray<CostReceipt>\n totalCostUsd: number\n totalDurationMs: number\n independentUnitByScenarioId?: ReadonlyMap<string, string>\n}\n\n/** One translation from a completed improvement loop into durable evidence. */\nexport function loopProvenanceArgsFromResult<TArtifact, TScenario extends Scenario>(\n input: LoopProvenanceArgsFromResult<TArtifact, TScenario>,\n): BuildLoopProvenanceArgs<TArtifact, TScenario> {\n const { result } = input\n return {\n runId: input.runId,\n runDir: input.runDir,\n timestamp: input.timestamp,\n baselineSurface: input.baselineSurface,\n winnerSurface: result.winnerSurface,\n ...(result.winnerLabel ? { winnerLabel: result.winnerLabel } : {}),\n ...(result.winnerRationale ? { winnerRationale: result.winnerRationale } : {}),\n baselineSearchCampaign: result.baselineCampaign,\n generations: result.generations.map(({ record, surfaces }) => ({\n generationIndex: record.generationIndex,\n candidates: record.candidates,\n promoted: record.promoted,\n surfaces: surfaces.map(({ surfaceHash, surface, campaign }) => ({\n surfaceHash,\n surface,\n campaign,\n })),\n })),\n gate: result.gateResult,\n ...(result.holdout === 'deferred' ? { holdout: 'deferred' as const } : {}),\n baselineOnHoldout: result.baselineOnHoldout,\n winnerOnHoldout: result.winnerOnHoldout,\n ...(result.claim ? { claim: result.claim } : {}),\n ...(input.independentUnitByScenarioId\n ? { independentUnitByScenarioId: input.independentUnitByScenarioId }\n : {}),\n ...(result.neutralizedSurface && result.neutralizedOnHoldout\n ? {\n neutralizedSurface: result.neutralizedSurface,\n neutralizedOnHoldout: result.neutralizedOnHoldout,\n }\n : {}),\n costReceipts: input.costReceipts,\n totalCostUsd: input.totalCostUsd,\n totalDurationMs: input.totalDurationMs,\n }\n}\n\n/** Build the durable provenance record from a completed loop result. */\nfunction buildLoopProvenanceRecord<TArtifact, TScenario extends Scenario>(\n args: BuildLoopProvenanceArgs<TArtifact, TScenario>,\n): LoopProvenanceRecord {\n if (!args.runId.trim() || !args.runDir.trim()) {\n throw new Error('buildLoopProvenanceRecord: runId and runDir must be non-empty')\n }\n const timestampMs = Date.parse(args.timestamp)\n if (!Number.isFinite(timestampMs) || new Date(timestampMs).toISOString() !== args.timestamp) {\n throw new Error('buildLoopProvenanceRecord: timestamp must be a canonical ISO instant')\n }\n assertGateContributions(args.gate.contributingGates, 'buildLoopProvenanceRecord')\n const agentReceipts = args.costReceipts.filter((receipt) => receipt.channel === 'agent')\n const integrity = summarizeAgentReceiptIntegrity(agentReceipts)\n const models = [...new Set(agentReceipts.map((receipt) => receipt.model))].sort()\n const baselineSearchComposite = campaignMeanComposite(args.baselineSearchCampaign)\n if (!Number.isFinite(baselineSearchComposite)) {\n throw new Error('buildLoopProvenanceRecord: baselineSearchComposite must be finite')\n }\n\n const candidates: LoopProvenanceCandidate[] = []\n let incumbentSurfaceHash = surfaceHash(args.baselineSurface)\n let incumbentComposite = baselineSearchComposite\n let previousGeneration = -1\n for (const gen of args.generations) {\n if (\n !Number.isSafeInteger(gen.generationIndex) ||\n gen.generationIndex !== previousGeneration + 1\n ) {\n throw new Error(\n 'buildLoopProvenanceRecord: generation indices must be contiguous integers starting at zero',\n )\n }\n previousGeneration = gen.generationIndex\n if (gen.candidates.length === 0) {\n throw new Error('buildLoopProvenanceRecord: a recorded generation must contain a candidate')\n }\n if (new Set(gen.promoted).size !== gen.promoted.length || gen.promoted.length > 1) {\n throw new Error(\n 'buildLoopProvenanceRecord: each generation may promote at most one candidate',\n )\n }\n const promotedSet = new Set(gen.promoted)\n const surfaceByHash = new Map(gen.surfaces.map((measured) => [measured.surfaceHash, measured]))\n const candidateByHash = new Map(\n gen.candidates.map((candidate) => [candidate.surfaceHash, candidate]),\n )\n if (candidateByHash.size !== gen.candidates.length) {\n throw new Error('buildLoopProvenanceRecord: duplicate candidate surface hash')\n }\n if (surfaceByHash.size !== gen.surfaces.length) {\n throw new Error('buildLoopProvenanceRecord: duplicate candidate surface entry')\n }\n if (surfaceByHash.size !== candidateByHash.size) {\n throw new Error(\n 'buildLoopProvenanceRecord: every measured candidate requires exactly one surface',\n )\n }\n for (const promotedHash of promotedSet) {\n if (!candidateByHash.has(promotedHash)) {\n throw new Error('buildLoopProvenanceRecord: promoted hash has no measured candidate')\n }\n }\n for (const c of gen.candidates) {\n validateCandidateMeasurement(c, incumbentComposite, promotedSet.has(c.surfaceHash))\n const measured = surfaceByHash.get(c.surfaceHash)\n if (measured === undefined) {\n throw new Error('buildLoopProvenanceRecord: measured candidate is missing its surface')\n }\n const { surface, campaign } = measured\n if (!surfaceHashMatches(surface, c.surfaceHash)) {\n throw new Error(\n 'buildLoopProvenanceRecord: candidate surface hash does not match its surface bytes',\n )\n }\n if (campaign.splitDigest !== args.baselineSearchCampaign.splitDigest) {\n throw new Error(\n 'buildLoopProvenanceRecord: candidate campaign does not match the search split',\n )\n }\n const entry: LoopProvenanceCandidate = {\n generation: gen.generationIndex,\n surfaceHash: c.surfaceHash,\n contentHash: surfaceContentHash(surface),\n campaignDigest: campaignMeasurementDigest(campaign),\n eligibleForPromotion: c.eligibleForPromotion,\n coverage: {\n expectedCells: c.coverage.expectedCells,\n scorableCells: c.coverage.scorableCells,\n unscorableCells: c.coverage.unscorableCells.map((cell) => ({ ...cell })),\n },\n composite: c.composite,\n promoted: promotedSet.has(c.surfaceHash),\n }\n if (c.label) entry.label = c.label\n if (c.rationale) entry.rationale = c.rationale\n if (c.attribution) entry.attribution = c.attribution\n candidates.push(entry)\n }\n const promotedHash = gen.promoted[0]\n if (promotedHash) {\n const promoted = candidateByHash.get(promotedHash)!\n incumbentSurfaceHash = promoted.surfaceHash\n if (promoted.composite === null) {\n throw new Error('buildLoopProvenanceRecord: promoted candidate is missing a composite')\n }\n incumbentComposite = promoted.composite\n }\n }\n if (surfaceHash(args.winnerSurface) !== incumbentSurfaceHash) {\n throw new Error(\n 'buildLoopProvenanceRecord: winner surface does not match the final promoted incumbent',\n )\n }\n\n const holdoutDeferred = args.holdout === 'deferred'\n const claim = args.claim ? defineEvaluationClaim(args.claim) : undefined\n if (claim && !holdoutDeferred && args.independentUnitByScenarioId === undefined) {\n throw new Error('buildLoopProvenanceRecord: a measured claim requires its independent-unit map')\n }\n if (args.baselineOnHoldout.splitDigest !== args.winnerOnHoldout.splitDigest) {\n throw new Error('buildLoopProvenanceRecord: baseline and winner use different holdout splits')\n }\n if ((args.neutralizedSurface === undefined) !== (args.neutralizedOnHoldout === undefined)) {\n throw new Error(\n 'buildLoopProvenanceRecord: neutralized surface and campaign must be supplied together',\n )\n }\n if (\n args.neutralizedOnHoldout &&\n args.neutralizedOnHoldout.splitDigest !== args.baselineOnHoldout.splitDigest\n ) {\n throw new Error(\n 'buildLoopProvenanceRecord: neutralized campaign uses a different holdout split',\n )\n }\n if (holdoutDeferred && args.neutralizedOnHoldout) {\n throw new Error(\n 'buildLoopProvenanceRecord: a deferred holdout cannot include a neutralized measurement',\n )\n }\n const holdoutScores = holdoutDeferred\n ? undefined\n : pairedCampaignComposites(\n args.baselineOnHoldout,\n args.winnerOnHoldout,\n args.independentUnitByScenarioId,\n )\n const holdoutMeasurement =\n holdoutScores === undefined\n ? { kind: 'deferred' as const }\n : {\n kind: 'measured' as const,\n baseline: holdoutScores.beforeMean,\n winner: holdoutScores.afterMean,\n ...(args.neutralizedOnHoldout\n ? {\n neutralized: pairedCampaignComposites(\n args.baselineOnHoldout,\n args.neutralizedOnHoldout,\n args.independentUnitByScenarioId,\n ).afterMean,\n }\n : {}),\n }\n\n const diff =\n surfaceContentHash(args.baselineSurface) === surfaceContentHash(args.winnerSurface)\n ? ''\n : renderSurfaceDiff(args.winnerSurface, args.baselineSurface)\n\n const recordWithoutDigest: Omit<LoopProvenanceRecord, 'recordDigest'> = {\n schema: 'tangle.loop-provenance',\n runId: args.runId,\n runDir: args.runDir,\n timestamp: args.timestamp,\n baselineContentHash: surfaceContentHash(args.baselineSurface),\n winnerContentHash: surfaceContentHash(args.winnerSurface),\n diff,\n candidates,\n evidence: {\n search: {\n splitDigest: args.baselineSearchCampaign.splitDigest,\n baselineCampaignDigest: campaignMeasurementDigest(args.baselineSearchCampaign),\n },\n holdout: {\n splitDigest: args.baselineOnHoldout.splitDigest,\n baselineCampaignDigest: campaignMeasurementDigest(args.baselineOnHoldout),\n winnerCampaignDigest: campaignMeasurementDigest(args.winnerOnHoldout),\n ...(holdoutScores ? { observations: holdoutScores.observations } : {}),\n ...(args.neutralizedSurface &&\n args.neutralizedOnHoldout &&\n holdoutMeasurement.kind === 'measured' &&\n holdoutMeasurement.neutralized !== undefined\n ? {\n neutralized: {\n contentHash: surfaceContentHash(args.neutralizedSurface),\n campaignDigest: campaignMeasurementDigest(args.neutralizedOnHoldout),\n composite: holdoutMeasurement.neutralized,\n lift: holdoutMeasurement.neutralized - holdoutMeasurement.baseline,\n },\n }\n : {}),\n },\n costReceiptsDigest: canonicalDigest(\n [...args.costReceipts].sort((left, right) => compareCodeUnits(left.callId, right.callId)),\n ),\n },\n baselineSearchComposite,\n ...(claim ? { claim } : {}),\n gate: {\n decision: args.gate.decision,\n reasons: args.gate.reasons,\n ...(args.gate.delta === undefined ? {} : { delta: args.gate.delta }),\n contributingGates: args.gate.contributingGates.map((g) => ({\n name: g.name,\n status: g.status,\n detail: durableGateDetail(g.detail),\n })),\n },\n // Deferred holdout records the MODE, never a fabricated 0-lift: the\n // held-out comparison intentionally did not run in this loop.\n ...(holdoutMeasurement.kind === 'deferred'\n ? { holdout: 'deferred' as const }\n : {\n baselineHoldoutComposite: holdoutMeasurement.baseline,\n winnerHoldoutComposite: holdoutMeasurement.winner,\n heldOutLift: holdoutMeasurement.winner - holdoutMeasurement.baseline,\n }),\n backend: {\n verdict: integrity.verdict,\n workerCallCount: integrity.totalRecords,\n models,\n totalInputTokens: integrity.totalInputTokens,\n totalOutputTokens: integrity.totalOutputTokens,\n totalCostUsd: integrity.totalCostUsd,\n },\n totalCostUsd: args.totalCostUsd,\n totalDurationMs: args.totalDurationMs,\n }\n if (args.optimizationMethod) {\n recordWithoutDigest.optimizationMethod = durableOptimizationMethod(args.optimizationMethod)\n }\n if (args.winnerLabel) recordWithoutDigest.winnerLabel = args.winnerLabel\n if (args.winnerRationale) recordWithoutDigest.winnerRationale = args.winnerRationale\n return {\n ...recordWithoutDigest,\n recordDigest: canonicalDigest(recordWithoutDigest),\n }\n}\n\nfunction durableOptimizationMethod(\n value: LoopProvenanceOptimizationMethod,\n): LoopProvenanceOptimizationMethod {\n if (\n !value ||\n typeof value !== 'object' ||\n typeof value.name !== 'string' ||\n !value.name.trim() ||\n value.name.trim() !== value.name\n ) {\n throw new Error('buildLoopProvenanceRecord: optimization method name is invalid')\n }\n if (\n !value.cost ||\n !Number.isFinite(value.cost.totalCostUsd) ||\n value.cost.totalCostUsd < 0 ||\n typeof value.cost.accountingComplete !== 'boolean' ||\n !Array.isArray(value.cost.incompleteReasons) ||\n value.cost.incompleteReasons.some((reason) => typeof reason !== 'string' || !reason.trim()) ||\n value.cost.accountingComplete !== (value.cost.incompleteReasons.length === 0)\n ) {\n throw new Error('buildLoopProvenanceRecord: optimization method cost is invalid')\n }\n if (\n value.durationMs !== undefined &&\n (!Number.isFinite(value.durationMs) || value.durationMs < 0)\n ) {\n throw new Error('buildLoopProvenanceRecord: optimization method duration is invalid')\n }\n try {\n return JSON.parse(canonicalString(value)) as LoopProvenanceOptimizationMethod\n } catch (cause) {\n throw new Error('buildLoopProvenanceRecord: optimization method data must be canonical JSON', {\n cause,\n })\n }\n}\n\n/** Digest the exact campaign fields that can affect a measured comparison. */\nexport function campaignMeasurementDigest<TArtifact, TScenario extends Scenario>(\n campaign: CampaignResult<TArtifact, TScenario>,\n): `sha256:${string}` {\n assertCampaignSplitIdentity(campaign.scenarios, campaign.reps, campaign.splitDigest)\n return canonicalDigest({\n schema: 'tangle.campaign-measurement',\n manifestHash: campaign.manifestHash,\n splitDigest: campaign.splitDigest,\n seed: campaign.seed,\n reps: campaign.reps,\n runDir: campaign.runDir,\n scenarios: campaign.scenarios,\n cells: [...campaign.cells]\n .sort((left, right) => compareCodeUnits(left.cellId, right.cellId))\n .map((cell) => ({\n manifestHash: cell.manifestHash ?? null,\n cellId: cell.cellId,\n scenarioId: cell.scenarioId,\n rep: cell.rep,\n generation: cell.generation ?? null,\n judgeScores: cell.judgeScores,\n costUsd: cell.costUsd,\n costProvenance: cell.costProvenance,\n costCallIds: [...(cell.costCallIds ?? [])].sort(),\n tokenUsage: cell.tokenUsage,\n resolvedModels: [...(cell.resolvedModels ?? [])].sort(),\n resolvedModel: cell.resolvedModel ?? null,\n durationMs: cell.durationMs,\n seed: cell.seed,\n cached: cell.cached,\n errorStage: cell.errorStage ?? null,\n errorJudge: cell.errorJudge ?? null,\n error: cell.error ?? null,\n })),\n })\n}\n\n\n\n/** SHA-256 over the RFC 8785 canonical JSON of `value`. Throws\n * `LedgerCanonicalizationError` for a value with no canonical form. */\nexport function canonicalDigest(value: unknown): `sha256:${string}` {\n return hashCanonical(value)\n}\n\nfunction durableGateDetail(detail: unknown): unknown {\n if (detail === undefined) return null\n try {\n return JSON.parse(canonicalString(detail)) as unknown\n } catch (cause) {\n throw new Error('buildLoopProvenanceRecord: gate detail must be canonical JSON', {\n cause,\n })\n }\n}\n\nfunction assertGateContributions(\n value: unknown,\n source: string,\n): asserts value is GateContribution[] {\n if (!Array.isArray(value)) {\n throw new Error(`${source}: gate contributingGates must be an array`)\n }\n const statuses = new Set(['pass', 'fail', 'not_evaluated'])\n for (const [index, contribution] of value.entries()) {\n if (!contribution || typeof contribution !== 'object') {\n throw new Error(`${source}: gate contribution ${index} must be an object`)\n }\n const item = contribution as Record<string, unknown>\n if (typeof item.name !== 'string' || item.name.length === 0) {\n throw new Error(`${source}: gate contribution ${index} must have a non-empty name`)\n }\n if (!statuses.has(String(item.status))) {\n throw new Error(\n `${source}: gate contribution '${item.name}' must have status pass, fail, or not_evaluated`,\n )\n }\n if ('passed' in item) {\n throw new Error(\n `${source}: gate contribution '${item.name}' uses obsolete passed; use status instead`,\n )\n }\n }\n}\n\n/** A candidate's coverage receipt and composite agree, and a promoted\n * candidate is complete and beats the incumbent it replaced. Its lineage is\n * the search ledger's to prove, not this record's. */\nfunction validateCandidateMeasurement(\n candidate: GenerationCandidate,\n incumbentComposite: number,\n promoted: boolean,\n): void {\n const coverage = candidate.coverage\n if (\n !Number.isSafeInteger(coverage.expectedCells) ||\n coverage.expectedCells <= 0 ||\n !Number.isSafeInteger(coverage.scorableCells) ||\n coverage.scorableCells < 0 ||\n coverage.scorableCells > coverage.expectedCells\n ) {\n throw new Error('buildLoopProvenanceRecord: invalid candidate coverage denominator')\n }\n const unscorableIds = new Set<string>()\n for (const failure of coverage.unscorableCells) {\n if (\n typeof failure.cellId !== 'string' ||\n failure.cellId.length === 0 ||\n typeof failure.reason !== 'string' ||\n failure.reason.length === 0 ||\n unscorableIds.has(failure.cellId)\n ) {\n throw new Error('buildLoopProvenanceRecord: invalid candidate coverage failures')\n }\n unscorableIds.add(failure.cellId)\n }\n if (coverage.expectedCells - coverage.scorableCells !== coverage.unscorableCells.length) {\n throw new Error(\n 'buildLoopProvenanceRecord: candidate coverage counts do not match its failures',\n )\n }\n const complete =\n coverage.scorableCells === coverage.expectedCells && coverage.unscorableCells.length === 0\n if (candidate.eligibleForPromotion !== complete) {\n throw new Error(\n 'buildLoopProvenanceRecord: candidate eligibility contradicts its coverage receipt',\n )\n }\n if (complete) {\n if (candidate.composite === null || !Number.isFinite(candidate.composite)) {\n throw new Error('buildLoopProvenanceRecord: complete candidate composite must be finite')\n }\n } else if (candidate.composite !== null && !Number.isFinite(candidate.composite)) {\n throw new Error('buildLoopProvenanceRecord: candidate composite must be finite or null')\n }\n if (\n promoted &&\n (!complete || (candidate.composite ?? Number.NEGATIVE_INFINITY) <= incumbentComposite)\n ) {\n throw new Error('buildLoopProvenanceRecord: promoted candidate must improve the incumbent')\n }\n}\n\n// ── OTel span emission ──────────────────────────────────────────────────\n\nfunction hashId(parts: string[]): string {\n return createHash('sha256').update(parts.join(':')).digest('hex')\n}\n\n/**\n * Build the loop's OTLP-ingestable spans from a provenance record. One root\n * span per loop (`tangle.runId`), one span per generation, one span per\n * candidate (carrying its surfaceHash + label), and one span for the gate\n * decision (carrying reasons + delta + lift). Candidate + gate spans pivot on\n * the same `tangle.runId` / `tangle.generation` attributes `/adapters/otel`\n * reads, so the hosted collector reconstructs the full tree.\n *\n * Times are synthesized monotonically off a single base so the span tree is\n * orderable; the substrate does not retain per-candidate wall-clock starts.\n */\nfunction loopProvenanceSpans(\n record: LoopProvenanceRecord,\n opts: { baseTimeMs?: number } = {},\n): TraceSpanEvent[] {\n const traceId = hashId(['trace', record.runId]).slice(0, 32)\n const baseTimeMs = opts.baseTimeMs ?? (Date.parse(record.timestamp) || Date.now())\n const durationMs = Math.max(1, record.totalDurationMs)\n if (!Number.isSafeInteger(baseTimeMs) || baseTimeMs < 0) {\n throw new RangeError('loop provenance baseTimeMs must be a non-negative safe integer')\n }\n if (!Number.isSafeInteger(durationMs)) {\n throw new RangeError('loop provenance duration must be a safe integer number of milliseconds')\n }\n const baseTime = BigInt(baseTimeMs)\n const baseNano = (baseTime * 1_000_000n).toString()\n const endNano = ((baseTime + BigInt(durationMs)) * 1_000_000n).toString()\n const spans: TraceSpanEvent[] = []\n\n const rootSpanId = hashId(['root', record.runId]).slice(0, 16)\n const rootAttributes: TraceSpanEvent['attributes'] = {\n 'tangle.runId': record.runId,\n 'tangle.runDir': record.runDir,\n 'tangle.baselineContentHash': record.baselineContentHash,\n 'tangle.winnerContentHash': record.winnerContentHash,\n 'tangle.baselineSearchComposite': record.baselineSearchComposite,\n 'tangle.gateDecision': record.gate.decision,\n 'tangle.backendVerdict': record.backend.verdict,\n 'tangle.workerCallCount': record.backend.workerCallCount,\n 'tangle.totalCostUsd': record.totalCostUsd,\n }\n if (record.heldOutLift !== undefined) rootAttributes['tangle.heldOutLift'] = record.heldOutLift\n if (record.holdout) rootAttributes['tangle.holdout'] = record.holdout\n spans.push({\n traceId,\n spanId: rootSpanId,\n name: 'improvement-loop',\n startTimeUnixNano: baseNano,\n endTimeUnixNano: endNano,\n attributes: rootAttributes,\n status: { code: 'OK' },\n 'tangle.runId': record.runId,\n })\n\n // Group candidates by generation for the per-generation parent span.\n const byGen = new Map<number, LoopProvenanceCandidate[]>()\n for (const c of record.candidates) {\n const arr = byGen.get(c.generation) ?? []\n arr.push(c)\n byGen.set(c.generation, arr)\n }\n for (const [generation, cands] of [...byGen.entries()].sort((a, b) => a[0] - b[0])) {\n const genSpanId = hashId(['gen', record.runId, String(generation)]).slice(0, 16)\n const measuredComposites = cands.flatMap((candidate) =>\n candidate.composite === null ? [] : [candidate.composite],\n )\n spans.push({\n traceId,\n spanId: genSpanId,\n parentSpanId: rootSpanId,\n name: `generation-${generation}`,\n startTimeUnixNano: baseNano,\n endTimeUnixNano: endNano,\n attributes: {\n 'tangle.runId': record.runId,\n 'tangle.generation': generation,\n 'tangle.populationSize': cands.length,\n ...(measuredComposites.length > 0\n ? { 'tangle.bestComposite': Math.max(...measuredComposites) }\n : {}),\n },\n 'tangle.runId': record.runId,\n 'tangle.generation': generation,\n })\n for (let i = 0; i < cands.length; i++) {\n const c = cands[i]!\n const candSpanId = hashId(['cand', record.runId, String(generation), c.surfaceHash]).slice(\n 0,\n 16,\n )\n const attributes: TraceSpanEvent['attributes'] = {\n 'tangle.runId': record.runId,\n 'tangle.generation': generation,\n 'tangle.surfaceHash': c.surfaceHash,\n 'tangle.contentHash': c.contentHash,\n 'tangle.eligibleForPromotion': c.eligibleForPromotion,\n 'tangle.expectedCells': c.coverage.expectedCells,\n 'tangle.scorableCells': c.coverage.scorableCells,\n 'tangle.unscorableCells': c.coverage.unscorableCells.length,\n 'tangle.promoted': c.promoted,\n }\n if (c.composite !== null) attributes['tangle.composite'] = c.composite\n if (c.label) attributes['tangle.candidateLabel'] = c.label\n if (c.rationale) attributes['tangle.candidateRationale'] = c.rationale\n spans.push({\n traceId,\n spanId: candSpanId,\n parentSpanId: genSpanId,\n name: `candidate-${c.surfaceHash}`,\n startTimeUnixNano: baseNano,\n endTimeUnixNano: endNano,\n attributes,\n 'tangle.runId': record.runId,\n 'tangle.generation': generation,\n })\n }\n }\n\n // Gate span — child of root, carries the decision/reasons/delta the audit\n // needs and pivots back to the run.\n const gateSpanId = hashId(['gate', record.runId]).slice(0, 16)\n const gateAttributes: TraceSpanEvent['attributes'] = {\n 'tangle.runId': record.runId,\n 'tangle.gateDecision': record.gate.decision,\n 'tangle.gateReasons': JSON.stringify(record.gate.reasons),\n }\n const gateDelta = record.gate.delta ?? record.heldOutLift\n if (gateDelta !== undefined) gateAttributes['tangle.gateDelta'] = gateDelta\n if (record.heldOutLift !== undefined) gateAttributes['tangle.heldOutLift'] = record.heldOutLift\n if (record.baselineHoldoutComposite !== undefined) {\n gateAttributes['tangle.baselineHoldoutComposite'] = record.baselineHoldoutComposite\n }\n if (record.winnerHoldoutComposite !== undefined) {\n gateAttributes['tangle.winnerHoldoutComposite'] = record.winnerHoldoutComposite\n }\n if (record.holdout) gateAttributes['tangle.holdout'] = record.holdout\n spans.push({\n traceId,\n spanId: gateSpanId,\n parentSpanId: rootSpanId,\n name: 'gate-decision',\n startTimeUnixNano: endNano,\n endTimeUnixNano: endNano,\n attributes: gateAttributes,\n status: { code: 'OK' },\n 'tangle.runId': record.runId,\n })\n\n return spans\n}\n\n// ── Durable emission ─────────────────────────────────────────────────────\n\n/** Canonical durable paths under the run dir. */\nexport function provenanceRecordPath(runDir: string): string {\n return join(runDir, 'loop-provenance.json')\n}\n/**\n * Canonical path for the durable OTLP spans JSONL file under a loop run directory.\n */\nexport function provenanceSpansPath(runDir: string): string {\n return join(runDir, 'loop-provenance-spans.jsonl')\n}\n\nexport interface EmitLoopProvenanceResult {\n record: LoopProvenanceRecord\n spans: TraceSpanEvent[]\n /** Absolute paths the record + spans were written to, when storage persists. */\n recordPath: string\n spansPath: string\n}\n\nexport interface EmitLoopProvenanceArgs<TArtifact, TScenario extends Scenario>\n extends BuildLoopProvenanceArgs<TArtifact, TScenario> {\n /** Storage the record + spans are written through. */\n storage: CampaignStorage\n /** When set, the spans are also shipped to the hosted `/v1/ingest/traces`\n * endpoint so the collector receives the full loop, not just `cost.*`. */\n hostedClient?: HostedClient\n}\n\n/**\n * Build the provenance record + OTel spans and persist them durably under the\n * run dir (and ship spans to a hosted collector when one is wired). Returns\n * both artifacts so the caller can assert on / re-derive from them.\n *\n * Fail-loud: the durable write throws on storage failure (a swallowed write is\n * exactly the \"emitted but lost\" failure this closes). The hosted span ship is\n * the one best-effort leg — its failure is logged, not thrown, so an offline\n * collector never fails the loop (the durable artifact is the source of truth).\n */\nexport async function emitLoopProvenance<TArtifact, TScenario extends Scenario>(\n args: EmitLoopProvenanceArgs<TArtifact, TScenario>,\n): Promise<EmitLoopProvenanceResult> {\n const record = buildLoopProvenanceRecord(args)\n const spans = loopProvenanceSpans(record)\n\n args.storage.ensureDir(args.runDir)\n const recordPath = provenanceRecordPath(args.runDir)\n const spansPath = provenanceSpansPath(args.runDir)\n args.storage.write(recordPath, JSON.stringify(record, null, 2))\n args.storage.write(spansPath, spans.map((s) => JSON.stringify(s)).join('\\n'))\n\n if (args.hostedClient) {\n // Best-effort: an offline collector is logged, never thrown; the durable\n // artifact above is the source of truth.\n try {\n await args.hostedClient.ingestTraces(spans)\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n // eslint-disable-next-line no-console -- intentional: hosted span ship is best-effort\n console.warn(`[agent-eval] provenance span ingest failed (continuing): ${msg}`)\n }\n }\n\n return { record, spans, recordPath, spansPath }\n}\n","/**\n * Reproducibility attestation for any serializable report object.\n *\n * `attest()` binds a report to its content address (sha-256 over canonical\n * JSON) AND binds that address to the provenance needed to reproduce it:\n * model versions, seeds, price-table hash, code SHA, inputs hash. The outer\n * `envelopeHash` prevents provenance from being rewritten while leaving the\n * report hash valid.\n *\n * Layering: content-addressing is the substrate's job; cryptographic SIGNING\n * (who vouches for the attestation, key management, transparency logs) is the\n * consumer's layer on top. An `AttestedReport` is a stable byte-identical\n * payload a consumer can sign — the substrate never holds keys.\n *\n * Generic by design: the report parameter is ANY value `canonicalJson`\n * accepts (campaign results, fuzz capsules, scorecards, cost ledgers). Do not\n * couple this module to a specific report schema.\n */\n\nimport { contentHash } from './verdict-cache'\n\n/** Hash scheme identifier carried by every attestation. A verifier rejects\n * unknown algorithms instead of guessing. */\nexport const ATTESTATION_ALGORITHM = 'sha256/canonical-json' as const\n\nexport interface AttestationProvenance {\n /** Every model involved in producing the report, name → version/id. */\n modelVersions: Record<string, string>\n /** RNG seeds the run was driven by, when seeded. */\n seeds?: number[]\n /** Content hash of the price table used for cost figures — cost numbers\n * are only reproducible against the same prices. */\n priceTableHash?: string\n /** Git SHA of the code that produced the report. */\n codeSha: string\n /** Content hash of the input set (scenarios, dataset manifest, ...). */\n inputsHash?: string\n /** ISO-8601 timestamp, caller-supplied — the substrate stays clock-free\n * so attestation is deterministic and testable. */\n createdAt: string\n}\n\nexport interface AttestedReport {\n /** Hex sha-256 over the canonical JSON of the report. */\n reportHash: string\n provenance: AttestationProvenance\n algorithm: typeof ATTESTATION_ALGORITHM\n /** Hex sha-256 over `{ reportHash, provenance, algorithm }`. */\n envelopeHash: string\n}\n\nexport interface AttestationVerification {\n valid: boolean\n /** Populated iff `valid` is false — names the exact mismatch. */\n reason?: string\n}\n\nfunction envelopeMaterial(\n reportHash: string,\n provenance: AttestationProvenance,\n algorithm: typeof ATTESTATION_ALGORITHM,\n): object {\n return { reportHash, provenance, algorithm }\n}\n\n/**\n * Content-address a report and bind it to its provenance. Throws (via\n * `canonicalJson`) if the report or provenance contains undefined / function /\n * symbol / non-finite numbers — an attestation that cannot be unambiguously\n * serialized cannot be trusted.\n */\nexport function attest(report: unknown, provenance: AttestationProvenance): AttestedReport {\n const reportHash = contentHash(report)\n const algorithm = ATTESTATION_ALGORITHM\n return {\n reportHash,\n provenance,\n algorithm,\n envelopeHash: contentHash(envelopeMaterial(reportHash, provenance, algorithm)),\n }\n}\n\n/**\n * Verify a report against its attestation. Returns a typed outcome rather\n * than throwing: an unverifiable report (e.g. one that no longer\n * canonicalizes) is a verification failure with the cause in `reason`, not a\n * crash — verifiers run in pipelines that must record WHY, not die.\n *\n * Both the report hash and the provenance envelope must verify.\n * Missing envelope hashes cannot establish provenance and fail verification.\n */\nexport function verifyAttestation(\n report: unknown,\n attested: AttestedReport,\n): AttestationVerification {\n if (attested.algorithm !== ATTESTATION_ALGORITHM) {\n return {\n valid: false,\n reason: `unknown algorithm '${attested.algorithm}' — this verifier only checks '${ATTESTATION_ALGORITHM}'`,\n }\n }\n if (typeof attested.envelopeHash !== 'string' || !/^[0-9a-f]{64}$/.test(attested.envelopeHash)) {\n return { valid: false, reason: 'attestation envelope hash is missing or invalid' }\n }\n let recomputed: string\n try {\n recomputed = contentHash(report)\n } catch (err) {\n return {\n valid: false,\n reason: `report is not canonicalizable: ${err instanceof Error ? err.message : String(err)}`,\n }\n }\n if (recomputed !== attested.reportHash) {\n return {\n valid: false,\n reason: `report hash mismatch: attested ${attested.reportHash}, recomputed ${recomputed}`,\n }\n }\n\n let envelopeHash: string\n try {\n envelopeHash = contentHash(\n envelopeMaterial(attested.reportHash, attested.provenance, attested.algorithm),\n )\n } catch (err) {\n return {\n valid: false,\n reason: `attestation provenance is not canonicalizable: ${err instanceof Error ? err.message : String(err)}`,\n }\n }\n if (envelopeHash !== attested.envelopeHash) {\n return {\n valid: false,\n reason: `attestation envelope hash mismatch: attested ${attested.envelopeHash}, recomputed ${envelopeHash}`,\n }\n }\n\n return { valid: true }\n}\n","/**\n * Evidence receipts are the join between Runtime execution and Eval promotion.\n *\n * Runtime says what actually ran. Eval says what independently measured it.\n * This receipt binds those worlds without making either package import the other:\n * stable pursuit/run identity, exact candidate/evaluator/environment/input/output\n * content identities, and the authority class that produced the observation.\n *\n * The payload is attested with agent-eval's existing canonical report attestation.\n * Signing/key management deliberately remains outside this substrate; consumers may\n * sign the byte-stable receipt or anchor its attestation in a transparency log.\n */\n\nimport {\n type AttestationProvenance,\n type AttestedReport,\n attest,\n verifyAttestation,\n} from '../attestation'\n\nconst EVIDENCE_RECEIPT_VERSION = '1.0.0' as const\n\n/** Closed promotion vocabulary. A typo or unknown future kind is never independent by default. */\nconst EVIDENCE_AUTHORITY_KINDS = [\n 'candidate-self-report',\n 'independent-evaluator',\n 'independent-replication',\n 'human-review',\n 'production-canary',\n] as const\n\nexport type EvidenceAuthorityKind = (typeof EVIDENCE_AUTHORITY_KINDS)[number]\n\nconst INDEPENDENT_EVIDENCE_AUTHORITY_KINDS = [\n 'independent-evaluator',\n 'independent-replication',\n 'human-review',\n 'production-canary',\n] as const satisfies readonly EvidenceAuthorityKind[]\n\nexport interface EvidenceAuthority {\n readonly kind: EvidenceAuthorityKind\n /** Stable authority/service/person identifier; never inferred from model prose. */\n readonly id: string\n}\n\nexport interface EvidenceBinding {\n readonly schemaVersion: typeof EVIDENCE_RECEIPT_VERSION\n /** Stable objective identity spanning retries, forks, resumes, and multiple runs. */\n readonly pursuitId: string\n /** Concrete execution/evaluation run this evidence was produced from. */\n readonly runId: string\n /** Exact candidate/program/profile bundle under evaluation. */\n readonly candidateDigest: string\n /** Exact evaluator/checker program or registered experiment definition. */\n readonly evaluatorDigest: string\n /** Exact sandbox/container/dependency/environment identity. */\n readonly environmentDigest: string\n /** Commitment to the input set. The hidden inputs themselves need not be exposed. */\n readonly inputSetCommitment: string\n /** Content identity of the raw evaluated output/artifact set. */\n readonly outputDigest: string\n /** Content identity of the evaluation result/report/verdict body. */\n readonly resultDigest: string\n readonly authority: EvidenceAuthority\n /** Optional experiment seal that governed the evaluation. */\n readonly experimentDigest?: string\n /** Optional observer-journal chain tip covering the execution being evaluated. */\n readonly observerDigest?: string\n}\n\nexport interface EvidenceReceipt {\n readonly binding: EvidenceBinding\n readonly attestation: AttestedReport\n}\n\nexport interface EvidenceReceiptVerification {\n readonly valid: boolean\n readonly reason?: string\n}\n\nexport interface CreateEvidenceReceiptInput extends Omit<EvidenceBinding, 'schemaVersion'> {}\n\n/**\n * Mint a content-attested evidence receipt. Required identity fields are deliberately\n * non-optional: unknown evidence stays unknown and cannot accidentally look certified.\n * The attestation's input provenance must equal the receipt commitment so two competing\n * descriptions of the evaluated population cannot coexist inside one valid receipt.\n */\nexport function createEvidenceReceipt(\n input: CreateEvidenceReceiptInput,\n provenance: AttestationProvenance,\n): EvidenceReceipt {\n const inputSetCommitment = requiredIdentity(input.inputSetCommitment, 'inputSetCommitment')\n assertInputCommitment(provenance, inputSetCommitment)\n const binding: EvidenceBinding = Object.freeze({\n schemaVersion: EVIDENCE_RECEIPT_VERSION,\n pursuitId: requiredIdentity(input.pursuitId, 'pursuitId'),\n runId: requiredIdentity(input.runId, 'runId'),\n candidateDigest: requiredIdentity(input.candidateDigest, 'candidateDigest'),\n evaluatorDigest: requiredIdentity(input.evaluatorDigest, 'evaluatorDigest'),\n environmentDigest: requiredIdentity(input.environmentDigest, 'environmentDigest'),\n inputSetCommitment,\n outputDigest: requiredIdentity(input.outputDigest, 'outputDigest'),\n resultDigest: requiredIdentity(input.resultDigest, 'resultDigest'),\n authority: requiredAuthority(input.authority),\n ...(input.experimentDigest === undefined\n ? {}\n : { experimentDigest: requiredIdentity(input.experimentDigest, 'experimentDigest') }),\n ...(input.observerDigest === undefined\n ? {}\n : { observerDigest: requiredIdentity(input.observerDigest, 'observerDigest') }),\n })\n return Object.freeze({ binding, attestation: attest(binding, provenance) })\n}\n\n/**\n * Verify evidence identity and its provenance envelope. Changing the evaluator,\n * model versions, input commitment, or creation record invalidates the evidence.\n */\nexport function verifyEvidenceReceipt(receipt: EvidenceReceipt): EvidenceReceiptVerification {\n if (receipt.binding.schemaVersion !== EVIDENCE_RECEIPT_VERSION) {\n return {\n valid: false,\n reason: `unsupported evidence receipt version '${receipt.binding.schemaVersion}'`,\n }\n }\n try {\n for (const [field, value] of Object.entries({\n pursuitId: receipt.binding.pursuitId,\n runId: receipt.binding.runId,\n candidateDigest: receipt.binding.candidateDigest,\n evaluatorDigest: receipt.binding.evaluatorDigest,\n environmentDigest: receipt.binding.environmentDigest,\n inputSetCommitment: receipt.binding.inputSetCommitment,\n outputDigest: receipt.binding.outputDigest,\n resultDigest: receipt.binding.resultDigest,\n })) {\n requiredIdentity(value, field)\n }\n requiredAuthority(receipt.binding.authority)\n assertInputCommitment(receipt.attestation.provenance, receipt.binding.inputSetCommitment)\n } catch (error) {\n return { valid: false, reason: error instanceof Error ? error.message : String(error) }\n }\n\n return verifyAttestation(receipt.binding, receipt.attestation)\n}\n\n/**\n * Promotion may choose a stricter policy, but this primitive makes the basic separation\n * explicit: only a recognized independent authority is independent. Unknown/forged kinds\n * and candidate self-reports both return false.\n */\nexport function isIndependentEvidence(receipt: EvidenceReceipt): boolean {\n return (INDEPENDENT_EVIDENCE_AUTHORITY_KINDS as readonly string[]).includes(\n receipt.binding.authority?.kind,\n )\n}\n\nfunction requiredAuthority(value: unknown): EvidenceAuthority {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new TypeError('evidence receipt: authority must be an object')\n }\n const authority = value as { kind?: unknown; id?: unknown }\n if (\n typeof authority.kind !== 'string' ||\n !(EVIDENCE_AUTHORITY_KINDS as readonly string[]).includes(authority.kind)\n ) {\n throw new TypeError(`evidence receipt: unknown authority kind '${String(authority.kind)}'`)\n }\n if (typeof authority.id !== 'string') {\n throw new TypeError('evidence receipt: authority.id must be a string')\n }\n return Object.freeze({\n kind: authority.kind as EvidenceAuthorityKind,\n id: requiredIdentity(authority.id, 'authority.id'),\n })\n}\n\nfunction assertInputCommitment(\n provenance: AttestationProvenance,\n inputSetCommitment: string,\n): void {\n if (typeof provenance?.inputsHash !== 'string' || provenance.inputsHash.trim().length === 0) {\n throw new TypeError('evidence receipt: provenance.inputsHash is required')\n }\n if (provenance.inputsHash.trim() !== inputSetCommitment) {\n throw new TypeError(\n 'evidence receipt: provenance.inputsHash must equal binding.inputSetCommitment',\n )\n }\n}\n\nfunction requiredIdentity(value: string, field: string): string {\n const normalized = value.trim()\n if (normalized.length === 0) throw new TypeError(`evidence receipt: ${field} must be non-empty`)\n return normalized\n}\n","import type { AttestationProvenance } from '../attestation'\nimport { assertCampaignSplitIdentity, campaignCoverage } from '../campaign/coverage'\nimport { campaignMeasurementDigest } from '../campaign/provenance'\nimport { surfaceContentHash } from '../campaign/surface-identity'\nimport type { CampaignResult, MutableSurface, Scenario } from '../campaign/types'\nimport { hashCanonical } from '../ledger-core/canonical'\nimport { type CreateEvidenceReceiptInput, createEvidenceReceipt } from './evidence-receipt'\n\n/** Caller-owned execution context. Eval never infers evaluator authority or environment identity. */\nexport type CampaignEvidenceContext = Pick<\n CreateEvidenceReceiptInput,\n | 'pursuitId'\n | 'evaluatorDigest'\n | 'environmentDigest'\n | 'authority'\n | 'experimentDigest'\n | 'observerDigest'\n> & { provenance: Omit<AttestationProvenance, 'inputsHash'> }\n\n/** Bind a complete measured campaign to its executed surface and actual outputs. */\nexport function createCampaignEvidenceReceipt<S extends Scenario, A>(input: {\n campaign: CampaignResult<A, S>\n surface: MutableSurface\n context: CampaignEvidenceContext\n}) {\n const { campaign, surface, context } = input\n assertCampaignSplitIdentity(campaign.scenarios, campaign.reps, campaign.splitDigest)\n const coverage = campaignCoverage(campaign.cells, campaign.scenarios, campaign.reps, true)\n if (campaign.scenarios.length === 0 || !coverage.complete) {\n throw new Error('campaign evidence requires a complete, nonempty measurement')\n }\n const { provenance, ...binding } = context\n return createEvidenceReceipt(\n {\n ...binding,\n runId: campaign.runDir,\n candidateDigest: surfaceContentHash(surface),\n inputSetCommitment: campaign.splitDigest,\n outputDigest: hashCanonical(\n [...campaign.cells]\n .sort((a, b) => (a.cellId < b.cellId ? -1 : a.cellId > b.cellId ? 1 : 0))\n .map((cell) => ({ cellId: cell.cellId, artifact: cell.artifact })),\n ),\n resultDigest: campaignMeasurementDigest(campaign),\n },\n { ...provenance, inputsHash: campaign.splitDigest },\n )\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,SAAgB,qBACd,WACA,MACM;CACN,IAAI,CAAC,OAAO,cAAc,IAAI,KAAK,OAAO,GACxC,MAAM,IAAI,MAAM,6DAA6D;CAE/E,MAAM,8BAAc,IAAI,IAAY;CACpC,KAAK,MAAM,YAAY,WAAW;EAChC,IAAI,OAAO,SAAS,OAAO,YAAY,SAAS,GAAG,KAAK,CAAC,CAAC,WAAW,GACnE,MAAM,IAAI,MAAM,gEAAgE;EAElF,IAAI,YAAY,IAAI,SAAS,EAAE,GAC7B,MAAM,IAAI,MAAM,mDAAmD,SAAS,GAAG,EAAE;EAEnF,IAAI,OAAO,SAAS,SAAS,YAAY,SAAS,KAAK,KAAK,CAAC,CAAC,WAAW,GACvE,MAAM,IAAI,MAAM,kEAAkE;EAEpF,IACE,SAAS,cAAc,KAAA,MACtB,OAAO,SAAS,cAAc,YAAY,SAAS,UAAU,KAAK,CAAC,CAAC,WAAW,IAEhF,MAAM,IAAI,MAAM,sEAAsE;EAExF,YAAY,IAAI,SAAS,EAAE;CAC7B;AACF;;AAGA,SAAgB,yBACd,UAC2D;CAC3D,qBAAqB,CAAC,QAAQ,GAAG,CAAC;CAClC,OAAO;EACL,IAAI,SAAS;EACb,MAAM,SAAS;EACf,gBAAgB,UAAU,YAAY,QAAQ;CAChD;AACF;;AAGA,SAAgB,kCACd,WACA,MACoB;CACpB,qBAAqB,WAAW,IAAI;CACpC,KAAK,MAAM,YAAY,WACrB,IAAI,CAAC,wBAAwB,KAAK,SAAS,cAAc,GACvD,MAAM,IA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AAW,SAAS,MAAM,SAAS,WAAW;CACnF,MAAM,WAAW,iBAAiB,SAAS,OAAO,SAAS,WAAW,SAAS,MAAM,IAAI;CACzF,IAAI,SAAS,UAAU,WAAW,KAAK,CAAC,SAAS,UAC/C,MAAM,IAAI,MAAM,6DAA6D;CAE/E,MAAM,EAAE,YAAY,GAAG,YAAY;CACnC,OAAO,sBACL;EACE,GAAG;EACH,OAAO,SAAS;EAChB,iBAAiB,mBAAmB,OAAO;EAC3C,oBAAoB,SAAS;EAC7B,cAAc,cACZ,CAAC,GAAG,SAAS,KAAK,CAAC,CAChB,MAAM,GAAG,MAAO,EAAE,SAAS,EAAE,SAAS,KAAK,EAAE,SAAS,EAAE,SAAS,IAAI,CAAE,CAAC,CACxE,KAAK,UAAU;GAAE,QAAQ,KAAK;GAAQ,UAAU,KAAK;EAAS,EAAE,CACrE;EACA,cAAc,0BAA0B,QAAQ;CAClD,GACA;EAAE,GAAG;EAAY,YAAY,SAAS;CAAY,CACpD;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"define-agent-eval-Cw0HHdMF.js","names":[],"sources":["../src/contract/self-improve-reporting.ts","../src/contract/self-improve-method.ts","../src/contract/self-improve.ts","../src/contract/define-agent-eval.ts"],"sourcesContent":["import { campaignCellToRunRecord } from '../campaign/run-record'\nimport { pairedCampaignComposites } from '../campaign/score-utils'\nimport { surfaceContentHash } from '../campaign/surface-identity'\nimport type {\n CampaignCellResult,\n CampaignResult,\n MutableSurface,\n Scenario,\n} from '../campaign/types'\nimport { ValidationError } from '../errors'\nimport { modelHasSnapshot, type RunRecord, type RunSplitTag } from '../run-record'\n\nexport function pairedCompositeSummary<TArtifact, TScenario extends Scenario>(\n baseline: CampaignResult<TArtifact, TScenario>,\n winner: CampaignResult<TArtifact, TScenario>,\n independentUnitByScenarioId?: ReadonlyMap<string, string>,\n) {\n const scores = pairedCampaignComposites(baseline, winner, independentUnitByScenarioId)\n const perScenario = (campaign: CampaignResult<TArtifact, TScenario>) =>\n Object.fromEntries(\n Object.entries(campaign.aggregates.byScenario).map(([id, aggregate]) => [\n id,\n aggregate.meanComposite,\n ]),\n )\n return {\n baseline: { compositeMean: scores.beforeMean, perScenario: perScenario(baseline) },\n winner: { compositeMean: scores.afterMean, perScenario: perScenario(winner) },\n baselineComposites: scores.before,\n observations: scores.observations,\n }\n}\n\n/** 32-bit FNV-1a over raw UTF-16 code units, rendered as hex for a cell key.\n *\n * Frozen: the key names a persisted cell, so a change orphans every cell\n * already written. This is a cell-key function, not a general-purpose hash. */\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` identifies the executed surface; `configHash` identifies the candidate label.\n */\nexport function 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 { fileURLToPath } from 'node:url'\nimport { openAutoPr } from '../campaign/auto-pr'\nimport { campaignSplitDigest } from '../campaign/coverage'\nimport { evaluationUnitMap } from '../campaign/final-evidence'\nimport { defaultProductionGate } from '../campaign/gates/default-production-gate'\nimport {\n type ComparisonCost,\n combineComparisonCosts,\n costFromLedgerSummary,\n} from '../campaign/optimization-cost'\nimport type { OptimizationMethodResult } from '../campaign/optimization-method'\nimport { executeOptimizationMethod } from '../campaign/optimization-method'\nimport { runFinalComparison } from '../campaign/presets/run-final-comparison'\nimport { campaignMeasurementDigest, canonicalDigest } from '../campaign/provenance'\nimport type { CampaignComparisonUnits } from '../campaign/score-utils'\nimport type { SearchHistoryCoverageRow } from '../campaign/search-history-receipt'\nimport type { CampaignStorage } from '../campaign/storage'\nimport { surfaceContentHash, surfaceHash } from '../campaign/surface-identity'\nimport type { MutableSurface, Scenario } from '../campaign/types'\nimport type { CostLedgerHandle, CostLedgerSummary } from '../cost-ledger'\nimport { createCampaignEvidenceReceipt } from '../experiment/campaign-evidence'\nimport type { EvaluationClaim } from '../experiment/claim'\nimport type { EvidenceReceipt } from '../experiment/evidence-receipt'\nimport { shipBestEffort, shipSearchLedger } from '../hosted/search-shipper'\nimport { analyzeRuns } from './analyze-runs'\nimport type {\n SelfImproveMethodOptions,\n SelfImproveOptions,\n SelfImproveProposerResult,\n} from './self-improve'\nimport { cellsToRunRecords, pairedCompositeSummary } from './self-improve-reporting'\n\nexport interface SelfImproveMethodProvenance {\n schema: 'tangle.method-improvement'\n recordDigest: `sha256:${string}`\n runId: string\n runDir: string\n timestamp: string\n baselineContentHash: string\n winnerContentHash: string\n diff: string\n optimizationMethod: NonNullable<SelfImproveProposerResult<Scenario, unknown>['optimization']>\n claim?: EvaluationClaim\n evidence: {\n trainSplitDigest: `sha256:${string}`\n selectionSplitDigest: `sha256:${string}`\n holdoutSplitDigest: `sha256:${string}`\n baselineCampaignDigest: `sha256:${string}`\n winnerCampaignDigest: `sha256:${string}`\n costReceiptsDigest: `sha256:${string}`\n neutralizedCampaignDigest?: `sha256:${string}`\n holdoutObservations?: CampaignComparisonUnits\n }\n gate: Awaited<ReturnType<typeof runFinalComparison>>['gateResult']\n holdout?: 'deferred'\n baselineHoldoutComposite?: number\n winnerHoldoutComposite?: number\n heldOutLift?: number\n cost: ComparisonCost\n totalCostUsd: number\n totalDurationMs: number\n}\n\nexport interface SelfImproveMethodResult<TScenario extends Scenario, TArtifact>\n extends Omit<\n SelfImproveProposerResult<TScenario, TArtifact>,\n | 'mode'\n | 'baseline'\n | 'winner'\n | 'provenance'\n | 'generationsExplored'\n | 'cost'\n | 'raw'\n | 'optimization'\n | 'insight'\n > {\n evidence?: { baseline: EvidenceReceipt; winner: EvidenceReceipt }\n searchHistoryCoverage: SearchHistoryCoverageRow\n mode: 'method'\n /** No final measurement exists when holdout is deferred. */\n baseline: SelfImproveProposerResult<TScenario, TArtifact>['baseline'] | null\n winner: Omit<SelfImproveProposerResult<TScenario, TArtifact>['winner'], 'compositeMean'> & {\n compositeMean: number | null\n }\n provenance: SelfImproveMethodProvenance\n optimization: NonNullable<SelfImproveProposerResult<TScenario, TArtifact>['optimization']>\n /** Includes the method's reported cost and final measurements without double counting receipts. */\n cost: ComparisonCost\n /** Only calls actually recorded by the shared ledger have token and channel breakdowns. */\n ledgerCost: CostLedgerSummary\n insight?: SelfImproveProposerResult<TScenario, TArtifact>['insight']\n raw: Awaited<ReturnType<typeof runFinalComparison<TScenario, TArtifact>>> & {\n kind: 'method'\n baselineSurface: SelfImproveProposerResult<TScenario, TArtifact>['raw']['baselineSurface']\n winnerSurface: SelfImproveProposerResult<TScenario, TArtifact>['raw']['winnerSurface']\n winnerSurfaceHash: string\n method: OptimizationMethodResult\n cost: ComparisonCost\n prResult?: ReturnType<typeof openAutoPr>\n }\n}\n\ntype MethodRunArgs<TScenario extends Scenario, TArtifact> = {\n opts: SelfImproveOptions<TScenario, TArtifact> &\n Pick<SelfImproveMethodOptions<TScenario, TArtifact>, 'method'>\n train: TScenario[]\n selection: TScenario[]\n holdout: TScenario[]\n costLedger: CostLedgerHandle\n storage: CampaignStorage\n runDir: string\n startedAt: number\n}\n\ntype FinalComparison<TScenario extends Scenario, TArtifact> = Awaited<\n ReturnType<typeof runFinalComparison<TScenario, TArtifact>>\n>\n\ntype HoldoutReport = ReturnType<typeof pairedCompositeSummary>\n\nconst METHOD_FINAL_PHASE = 'selfImprove.method-final'\n\n/** Complete methods own search and selection; this path only measures their final choice. */\nexport async function runSelfImproveMethod<TScenario extends Scenario, TArtifact>(\n args: MethodRunArgs<TScenario, TArtifact>,\n): Promise<SelfImproveMethodResult<TScenario, TArtifact>> {\n const { opts, holdout, costLedger, startedAt } = args\n const budget = opts.budget ?? {}\n assertAutoPrTarget(opts)\n const evidenceContext = captureEvidenceContext(opts, budget)\n const baselineSurface = structuredClone(opts.baselineSurface)\n const { selected, cost: methodCost, history } = await searchWithMethod(args, baselineSurface)\n const totalCost = (): ComparisonCost => methodTotalCost(opts.method.name, methodCost, costLedger)\n const comparison = await measureMethodWinner(args, baselineSurface, selected, totalCost)\n const evidence = evidenceContext\n ? methodEvidenceReceipts(comparison, baselineSurface, selected, evidenceContext)\n : undefined\n const deferred = comparison.holdout === 'deferred'\n const report = deferred\n ? null\n : pairedCompositeSummary(\n comparison.baselineOnHoldout,\n comparison.winnerOnHoldout,\n opts.claim ? evaluationUnitMap(opts.claim, holdout) : undefined,\n )\n const baseline = report?.baseline ?? null\n const winner = report?.winner ?? null\n const lift = baseline && winner ? winner.compositeMean - baseline.compositeMean : undefined\n const insight = deferred\n ? undefined\n : await analyzeMethodHoldout(args, comparison, baselineSurface, selected)\n const cost = totalCost()\n const optimization = {\n name: opts.method.name,\n cost: methodCost,\n ...(selected.durationMs === undefined ? {} : { durationMs: selected.durationMs }),\n ...(selected.provenance === undefined ? {} : { provenance: selected.provenance }),\n }\n const durationMs = Date.now() - startedAt\n const receipts = costLedger.list()\n const provenance = recordMethodProvenance({\n args,\n comparison,\n baselineSurface,\n selected,\n report,\n lift,\n optimization,\n cost,\n durationMs,\n receipts,\n })\n opts.onProvenance?.(provenance)\n opts.onProgress?.({\n kind: 'gate.decided',\n decision: comparison.gateResult.decision,\n ...(lift === undefined ? {} : { lift }),\n })\n const prResult =\n opts.autoOnPromote === 'pr' && comparison.gateResult.decision === 'ship'\n ? openAutoPr({\n result: comparison.winnerOnHoldout,\n gate: comparison.gateResult,\n promotedDiff: comparison.promotedDiff,\n ghOwner: opts.ghOwner!,\n ghRepo: opts.ghRepo!,\n })\n : undefined\n const result: SelfImproveMethodResult<TScenario, TArtifact> = {\n ...(evidence ? { evidence } : {}),\n mode: 'method',\n ...(opts.claim ? { claim: opts.claim } : {}),\n ...(comparison.finalEvidence ? { finalEvidence: comparison.finalEvidence } : {}),\n searchHistoryCoverage: history,\n baseline,\n winner: {\n surface: selected.winnerSurface,\n compositeMean: winner?.compositeMean ?? null,\n perScenario: winner?.perScenario ?? {},\n label: opts.method.name,\n },\n ...(lift === undefined ? {} : { lift }),\n diff: comparison.promotedDiff,\n gateDecision: comparison.gateResult.decision,\n provenance,\n optimization,\n cost,\n ledgerCost: costLedger.summary(),\n totalCostUsd: cost.totalCostUsd,\n durationMs,\n receipts,\n ...(insight ? { insight } : {}),\n ...(selected.searchHistory ? { searchHistory: selected.searchHistory } : {}),\n raw: {\n ...comparison,\n kind: 'method',\n baselineSurface,\n winnerSurface: selected.winnerSurface,\n winnerSurfaceHash: surfaceHash(selected.winnerSurface),\n method: selected,\n cost,\n ...(prResult ? { prResult } : {}),\n },\n }\n await shipMethodSearchLedger(opts, selected)\n return result\n}\n\n/** An auto-PR needs a target repository before any spend. */\nfunction assertAutoPrTarget(opts: { autoOnPromote?: string; ghOwner?: string; ghRepo?: string }) {\n if (opts.autoOnPromote === 'pr' && (!opts.ghOwner || !opts.ghRepo)) {\n throw new Error(\"selfImprove: autoOnPromote='pr' requires ghOwner + ghRepo\")\n }\n}\n\n/** Detach the caller's evidence context; receipts need a measured holdout. */\nfunction captureEvidenceContext<TScenario extends Scenario, TArtifact>(\n opts: MethodRunArgs<TScenario, TArtifact>['opts'],\n budget: NonNullable<SelfImproveOptions<TScenario, TArtifact>['budget']>,\n) {\n const evidenceContext = opts.evidence === undefined ? undefined : structuredClone(opts.evidence)\n if (evidenceContext && budget.holdout === 'deferred')\n throw new Error('selfImprove: evidence receipts require measured holdout')\n return evidenceContext\n}\n\n/** Let the method search and select a winner on the train and selection splits. */\nfunction searchWithMethod<TScenario extends Scenario, TArtifact>(\n args: MethodRunArgs<TScenario, TArtifact>,\n baselineSurface: MutableSurface,\n) {\n const { opts, train, selection, costLedger, storage, runDir } = args\n const budget = opts.budget ?? {}\n return executeOptimizationMethod({\n method: opts.method,\n storage,\n searchHistoryPolicy: opts.searchHistoryPolicy,\n searchHistoryVerification: opts.searchHistoryVerification,\n input: {\n baselineSurface,\n trainScenarios: train,\n selectionScenarios: selection,\n dispatchWithSurface: opts.agent,\n judges: [opts.judge],\n runDir: `${runDir}/optimization/${opts.method.name.replace(/[^a-zA-Z0-9._-]/g, '_')}`,\n seed: 42,\n runOptions: {\n storage,\n maxConcurrency: budget.maxConcurrency ?? 2,\n reps: budget.reps,\n dispatchRef: opts.dispatchRef,\n dispatchTimeoutMs: opts.dispatchTimeoutMs,\n cellRetry: opts.cellRetry,\n cellPlacement: opts.cellPlacement,\n labeledStore: opts.labeledStore,\n captureSource: opts.captureSource,\n expectUsage: opts.expectUsage ?? 'assert',\n },\n costLedger,\n },\n })\n}\n\n/** Spend on the final holdout comparison, read back from the shared ledger. */\nfunction methodFinalCost(costLedger: CostLedgerHandle): ComparisonCost {\n return combineComparisonCosts(\n ['holdout.baseline', 'holdout.winner', 'holdout.neutralized', 'promotion.gate'].map(\n (phase) => ({\n label: phase,\n cost: costFromLedgerSummary(\n costLedger.summary({ phase: `${METHOD_FINAL_PHASE}.${phase}` }),\n ),\n }),\n ),\n )\n}\n\n/** The method's own spend plus the final comparison's. */\nfunction methodTotalCost(\n methodName: string,\n methodCost: ComparisonCost,\n costLedger: CostLedgerHandle,\n): ComparisonCost {\n return combineComparisonCosts([\n { label: methodName, cost: methodCost },\n { label: 'final comparison', cost: methodFinalCost(costLedger) },\n ])\n}\n\n/** Measure baseline and winner on the holdout; the gate holds when spend breaks the budget. */\nfunction measureMethodWinner<TScenario extends Scenario, TArtifact>(\n args: MethodRunArgs<TScenario, TArtifact>,\n baselineSurface: MutableSurface,\n selected: OptimizationMethodResult,\n totalCost: () => ComparisonCost,\n) {\n const { opts, holdout, costLedger, storage, runDir } = args\n const budget = opts.budget ?? {}\n const gate =\n opts.gate ??\n defaultProductionGate<TArtifact, TScenario>({\n holdoutScenarios: holdout,\n deltaThreshold: opts.claim?.minimumEffect ?? 0.05,\n independentUnitByScenarioId: opts.claim ? evaluationUnitMap(opts.claim, holdout) : undefined,\n })\n return runFinalComparison({\n claim: opts.claim,\n finalEvidence: opts.finalEvidence,\n baselineSurface,\n winnerSurface: selected.winnerSurface,\n scenarios: holdout,\n dispatchWithSurface: opts.agent,\n dispatchRef: opts.dispatchRef,\n judges: [opts.judge],\n holdout: budget.holdout,\n neutralize: opts.neutralize,\n gate: {\n ...gate,\n async decide(context) {\n const cost = totalCost()\n if (\n budget.dollars !== undefined &&\n (!cost.accountingComplete || cost.totalCostUsd > budget.dollars)\n ) {\n return {\n decision: 'hold' as const,\n reasons: ['complete method spend cannot satisfy the declared run budget'],\n contributingGates: [\n {\n name: 'budget',\n status: 'fail' as const,\n detail: { cost, budgetUsd: budget.dollars },\n },\n ],\n }\n }\n return gate.decide(context)\n },\n },\n runDir,\n storage,\n costLedger,\n costPhase: METHOD_FINAL_PHASE,\n reps: budget.reps,\n maxConcurrency: budget.maxConcurrency ?? 2,\n dispatchTimeoutMs: opts.dispatchTimeoutMs,\n cellRetry: opts.cellRetry,\n cellPlacement: opts.cellPlacement,\n expectUsage: opts.expectUsage ?? 'assert',\n label: 'selfImprove',\n })\n}\n\n/** Evidence receipts for the baseline and winner holdout campaigns. */\nfunction methodEvidenceReceipts<TScenario extends Scenario, TArtifact>(\n comparison: FinalComparison<TScenario, TArtifact>,\n baselineSurface: MutableSurface,\n selected: OptimizationMethodResult,\n evidenceContext: NonNullable<SelfImproveOptions<TScenario, TArtifact>['evidence']>,\n) {\n return {\n baseline: createCampaignEvidenceReceipt({\n campaign: comparison.baselineOnHoldout,\n surface: baselineSurface,\n context: evidenceContext,\n }),\n winner: createCampaignEvidenceReceipt({\n campaign: comparison.winnerOnHoldout,\n surface: selected.winnerSurface,\n context: evidenceContext,\n }),\n }\n}\n\n/** Analyze the measured holdout runs; a winner that is the baseline adds no second candidate. */\nfunction analyzeMethodHoldout<TScenario extends Scenario, TArtifact>(\n args: MethodRunArgs<TScenario, TArtifact>,\n comparison: FinalComparison<TScenario, TArtifact>,\n baselineSurface: MutableSurface,\n selected: OptimizationMethodResult,\n) {\n const { opts, holdout, runDir } = args\n return analyzeRuns({\n runs: [\n ...cellsToRunRecords(\n comparison.baselineOnHoldout.cells,\n 'baseline',\n runDir,\n baselineSurface,\n 'holdout',\n opts.model,\n ),\n ...(comparison.winnerOnHoldout === comparison.baselineOnHoldout\n ? []\n : cellsToRunRecords(\n comparison.winnerOnHoldout.cells,\n 'winner',\n runDir,\n selected.winnerSurface,\n 'holdout',\n opts.model,\n )),\n ],\n baselineCandidateId: 'baseline',\n independentUnitByScenarioId: opts.claim ? evaluationUnitMap(opts.claim, holdout) : undefined,\n decisionThreshold: opts.claim?.minimumEffect ?? 0.05,\n ...(comparison.winnerOnHoldout === comparison.baselineOnHoldout\n ? {}\n : { candidateCandidateId: 'winner' }),\n })\n}\n\n/** Build, persist and return the digest-sealed provenance record. */\nfunction recordMethodProvenance<TScenario extends Scenario, TArtifact>(input: {\n args: MethodRunArgs<TScenario, TArtifact>\n comparison: FinalComparison<TScenario, TArtifact>\n baselineSurface: MutableSurface\n selected: OptimizationMethodResult\n report: HoldoutReport | null\n lift: number | undefined\n optimization: SelfImproveMethodProvenance['optimizationMethod']\n cost: ComparisonCost\n durationMs: number\n receipts: ReturnType<CostLedgerHandle['list']>\n}): SelfImproveMethodProvenance {\n const { args, comparison, baselineSurface, selected, report, lift, optimization } = input\n const { opts, train, selection, holdout, storage, runDir, startedAt } = args\n const budget = opts.budget ?? {}\n const baseline = report?.baseline ?? null\n const winner = report?.winner ?? null\n const record = {\n schema: 'tangle.method-improvement' as const,\n runId: `${runDir}#${startedAt}`,\n runDir,\n timestamp: new Date(startedAt).toISOString(),\n baselineContentHash: surfaceContentHash(baselineSurface),\n winnerContentHash: surfaceContentHash(selected.winnerSurface),\n diff: comparison.promotedDiff,\n optimizationMethod: optimization,\n ...(opts.claim ? { claim: opts.claim } : {}),\n evidence: {\n trainSplitDigest: campaignSplitDigest(train, budget.reps ?? 1),\n selectionSplitDigest: campaignSplitDigest(selection, budget.reps ?? 1),\n holdoutSplitDigest: campaignSplitDigest(holdout, budget.reps ?? 1),\n baselineCampaignDigest: campaignMeasurementDigest(comparison.baselineOnHoldout),\n winnerCampaignDigest: campaignMeasurementDigest(comparison.winnerOnHoldout),\n costReceiptsDigest: canonicalDigest(input.receipts),\n ...(report ? { holdoutObservations: report.observations } : {}),\n ...(comparison.neutralizedOnHoldout\n ? { neutralizedCampaignDigest: campaignMeasurementDigest(comparison.neutralizedOnHoldout) }\n : {}),\n },\n gate: comparison.gateResult,\n ...(comparison.holdout === 'deferred' ? { holdout: 'deferred' as const } : {}),\n ...(baseline && winner\n ? {\n baselineHoldoutComposite: baseline.compositeMean,\n winnerHoldoutComposite: winner.compositeMean,\n heldOutLift: lift,\n }\n : {}),\n cost: input.cost,\n totalCostUsd: input.cost.totalCostUsd,\n totalDurationMs: input.durationMs,\n }\n // The persisted JSON and returned record must have the same canonical content.\n const serialized: Omit<SelfImproveMethodProvenance, 'recordDigest'> = JSON.parse(\n JSON.stringify(record),\n )\n const provenance: SelfImproveMethodProvenance = {\n ...serialized,\n recordDigest: canonicalDigest(serialized),\n }\n storage.ensureDir(runDir)\n storage.write(`${runDir}/method-provenance.json`, JSON.stringify(provenance, null, 2))\n return provenance\n}\n\n/** Ship the method's search ledger to the hosted tenant, when one is configured. */\nasync function shipMethodSearchLedger<TScenario extends Scenario, TArtifact>(\n opts: MethodRunArgs<TScenario, TArtifact>['opts'],\n selected: OptimizationMethodResult,\n): Promise<void> {\n if (!opts.hostedTenant) return\n const receipt = selected.searchHistory\n if (receipt) {\n const path = fileURLToPath(receipt.ledger.uri)\n await shipBestEffort(\n () =>\n shipSearchLedger({\n tenant: opts.hostedTenant!,\n ledger: { path, searchId: receipt.summary.searchId },\n runKind: 'optimization',\n }),\n path,\n )\n } else {\n console.warn(\n `[agent-eval] hostedTenant: method ${opts.method.name} recorded no search ledger, so nothing was shipped`,\n )\n }\n}\n","import { defineEvaluationClaim, type EvaluationClaim } from '../experiment/claim'\n/**\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 {\n assertIndependentEvaluationSplit,\n captureFinalEvidencePolicy,\n evaluationUnitMap,\n type FinalEvidencePolicy,\n type FinalEvidenceUse,\n reserveFinalEvidence,\n} from '../campaign/final-evidence'\nimport { defaultProductionGate } from '../campaign/gates/default-production-gate'\nimport { type PowerPreflight, powerPreflight } from '../campaign/gates/power-preflight'\nimport { captureJudge } from '../campaign/judge-snapshot'\nimport type {\n OptimizationMethod,\n OptimizationMethodProvenance,\n OptimizationMethodResult,\n} from '../campaign/optimization-method'\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 type { CampaignCellRetryPolicy } from '../campaign/run-campaign'\nimport { resolveRunDir } from '../campaign/run-dir'\nimport type { SearchHistoryReceipt } from '../campaign/search-history-receipt'\nimport {\n assertSearchHistoryAdmissionOptions,\n type SearchHistoryAdmissionOptions,\n} from '../campaign/search-history-receipt'\nimport {\n type CampaignStorage,\n createRunCostLedger,\n fsCampaignStorage,\n inMemoryCampaignStorage,\n} from '../campaign/storage'\nimport type {\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 type { CampaignEvidenceContext } from '../experiment/campaign-evidence'\nimport { createHostedClient, type HostedTenant } from '../hosted/client'\nimport { shipBestEffort, startSearchShipper } from '../hosted/search-shipper'\nimport type { RunSplitTag } from '../run-record'\nimport { analyzeRuns } from './analyze-runs'\nimport type { InsightReport } from './insight-report'\nimport {\n runSelfImproveMethod,\n type SelfImproveMethodProvenance,\n type SelfImproveMethodResult,\n} from './self-improve-method'\nimport { cellsToRunRecords, pairedCompositeSummary } from './self-improve-reporting'\n\nexport type { SelfImproveMethodProvenance, SelfImproveMethodResult } from './self-improve-method'\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 /** Repeated executions per scenario. A claim's independent-unit count stays unchanged. 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 extends SearchHistoryAdmissionOptions {\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 /** Version of execution behavior outside the candidate surface, used by measurement caches. */\n dispatchRef?: 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, or wrap `llmJudge`. */\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, evaluator manifest, 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. Premeasure with\n * `dispatchRef: surfaceDispatchRef(baselineSurface, dispatchRef)` and the same judge revision.\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 is written.\n * Receives the structured record for inline assertions / custom routing. */\n onProvenance?: (record: LoopProvenanceRecord | SelfImproveMethodProvenance) => 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 /** Bounded in-run retry of failed cells — same as\n * `RunCampaignOptions.cellRetry`, applied to baseline, candidate, and\n * held-out campaigns. Pair with `transientDispatchFailure()` so a\n * transport hiccup (a router 503, a dropped stream) is re-dispatched in\n * the same slot instead of leaving holdout coverage incomplete. Absent by\n * default: a failed cell is final. */\n cellRetry?: CampaignCellRetryPolicy\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 this run's search ledger to a hosted store (ours, your\n * self-hosted one, or any implementation of `docs/hosted-ingest-spec.md`).\n * In proposer mode it requires `searchLedger`, and the ledger ships while\n * the loop runs; in method mode the ledger the method recorded ships when\n * the method returns. A failed ship is logged and never fails the loop: the\n * local ledger is the source of truth, and `agent-eval search ship <ledger>`\n * resumes from the store's head.\n *\n * For our orchestrator: `{ endpoint: 'https://orchestrator.tangle.tools', apiKey, tenantId }`.\n * For your self-hosted one: see `examples/hosted-ingest-server/`.\n */\n hostedTenant?: HostedTenant\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 /** Which measured surface each proposal extends and which one the run\n * keeps. Default `incumbent()`: the hill climb. Pass\n * `crowdedFrontierParent({ seed })` to draw parents from the Pareto\n * frontier. Proposer mode only. See `RunOptimizationOptions.policy`. */\n policy?: RunOptimizationOptions<TScenario, TArtifact>['policy']\n\n /** Where the run's search ledger goes and the identities it records. The\n * ledger is always written; see `RunOptimizationOptions.searchLedger`. */\n searchLedger?: RunOptimizationOptions<TScenario, TArtifact>['searchLedger']\n /** Complete-method final measurement receipts; authority and environment remain caller-owned. */\n evidence?: CampaignEvidenceContext\n /** Declare the population and independent units without requiring fresh data. */\n claim?: EvaluationClaim\n /** Opt into durable fresh-evidence consumption for this final comparison. */\n finalEvidence?: FinalEvidencePolicy\n}\n\nexport interface SelfImproveProposerResult<TScenario extends Scenario, TArtifact> {\n mode: 'proposer'\n claim?: EvaluationClaim\n finalEvidence?: FinalEvidenceUse\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 /** Bounded proof envelope over this run's search ledger: always present in\n * proposer mode, and in method mode when the method recorded a search. */\n searchHistory?: SearchHistoryReceipt\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 /** Approximate detectable lift from baseline holdout observations.\n * Declared independent units determine n and baseline variance.\n * Absent with fewer than three observations or a deferred holdout. */\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\nexport type SelfImproveResult<TScenario extends Scenario, TArtifact> =\n | SelfImproveProposerResult<TScenario, TArtifact>\n | SelfImproveMethodResult<TScenario, TArtifact>\n\nexport type SelfImproveMethodOptions<TScenario extends Scenario, TArtifact> = Omit<\n SelfImproveOptions<TScenario, TArtifact>,\n 'proposer' | 'onProvenance'\n> & {\n method: OptimizationMethod<TScenario, TArtifact>\n proposer?: never\n onProvenance?: (record: SelfImproveMethodProvenance) => void\n}\n\nexport type SelfImproveProposerOptions<TScenario extends Scenario, TArtifact> = Omit<\n SelfImproveOptions<TScenario, TArtifact>,\n 'method' | 'onProvenance'\n> & {\n method?: never\n onProvenance?: (record: LoopProvenanceRecord) => void\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 assertSearchHistoryAdmissionOptions(opts)\n if (\n !opts.method &&\n (opts.searchHistoryPolicy !== undefined ||\n opts.searchHistoryVerification !== undefined ||\n opts.evidence !== undefined)\n )\n throw new Error('selfImprove: search history admission requires method')\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 if (opts.hostedTenant && !opts.searchLedger) {\n throw new Error(\n 'selfImprove: hostedTenant ships the search ledger; pass searchLedger (docs/search-ledger.md)',\n )\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) {\n throw new Error(\n 'selfImprove: method owns its rounds; budget.generations applies only to proposer mode',\n )\n }\n if (budget?.populationSize !== undefined) {\n throw new Error(\n 'selfImprove: method owns its candidates; budget.populationSize applies only to proposer mode',\n )\n }\n if (\n budget?.candidateConcurrency !== undefined ||\n budget?.maxImprovementShots !== undefined ||\n opts.analyzeGeneration !== undefined ||\n opts.findings !== undefined ||\n opts.policy !== undefined ||\n opts.premeasuredBaseline !== undefined ||\n opts.searchLedger !== undefined\n ) {\n throw new Error(\n 'selfImprove: candidateConcurrency, maxImprovementShots, analyzeGeneration, findings, policy, premeasuredBaseline, and searchLedger 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 unitByScenario?: ReadonlyMap<string, string>,\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 if (unitByScenario) {\n const selectedUnits = new Set([...selectionIds].map((id) => unitByScenario.get(id)))\n if (train.some((scenario) => selectedUnits.has(unitByScenario.get(scenario.id)))) {\n throw new Error('selfImprove: training and selection share independent units')\n }\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 if (unitByScenario) {\n const split = splitTrainHoldout(searchScenarios, fraction, unitByScenario)\n return { train: split.train, selection: split.holdout }\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\n/** 32-bit FNV-1a over raw UTF-16 code units, read as an unsigned int and used\n * only to order scenarios deterministically.\n *\n * Frozen: the order it produces assigns scenarios to partitions, so a change\n * re-partitions decisions already recorded. It masks no byte, unlike\n * `fnv1a32` in `src/partition-held-out.ts`, so the two disagree on any\n * non-ASCII id and cannot be shared. */\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/** Deterministic split by scenario identity, or by source identity for new-unit claims. */\nfunction splitTrainHoldout<TScenario extends Scenario>(\n scenarios: TScenario[],\n fraction: number,\n unitByScenario?: ReadonlyMap<string, string>,\n): { train: TScenario[]; holdout: TScenario[] } {\n if (unitByScenario) {\n const units = [...new Set(scenarios.map((scenario) => unitByScenario.get(scenario.id)!))].sort(\n (a, b) => stableScenarioHash(a) - stableScenarioHash(b) || (a < b ? -1 : a > b ? 1 : 0),\n )\n if (units.length < 2)\n throw new Error('selfImprove: splitting needs at least two independent units')\n const count = Math.max(1, Math.min(units.length - 1, Math.round(units.length * fraction)))\n const finalUnits = new Set(units.slice(0, count))\n return {\n holdout: scenarios.filter((scenario) => finalUnits.has(unitByScenario.get(scenario.id)!)),\n train: scenarios.filter((scenario) => !finalUnits.has(unitByScenario.get(scenario.id)!)),\n }\n }\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\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 function selfImprove<TScenario extends Scenario, TArtifact>(\n opts: SelfImproveMethodOptions<TScenario, TArtifact>,\n): Promise<SelfImproveMethodResult<TScenario, TArtifact>>\nexport function selfImprove<TScenario extends Scenario, TArtifact>(\n opts: SelfImproveProposerOptions<TScenario, TArtifact>,\n): Promise<SelfImproveProposerResult<TScenario, TArtifact>>\nexport function selfImprove<TScenario extends Scenario, TArtifact>(\n opts: SelfImproveOptions<TScenario, TArtifact>,\n): Promise<SelfImproveResult<TScenario, TArtifact>>\nexport async function selfImprove<TScenario extends Scenario, TArtifact>(\n opts:\n | SelfImproveOptions<TScenario, TArtifact>\n | SelfImproveMethodOptions<TScenario, TArtifact>\n | SelfImproveProposerOptions<TScenario, TArtifact>,\n): Promise<SelfImproveResult<TScenario, TArtifact>> {\n opts = {\n ...opts,\n judge: captureJudge(opts.judge),\n ...(opts.claim || opts.finalEvidence\n ? {\n claim: opts.claim && defineEvaluationClaim(opts.claim),\n finalEvidence: opts.finalEvidence && captureFinalEvidencePolicy(opts.finalEvidence),\n scenarios: structuredClone(opts.scenarios),\n selectionScenarios: opts.selectionScenarios && structuredClone(opts.selectionScenarios),\n budget: opts.budget && structuredClone(opts.budget),\n }\n : {}),\n }\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(\n opts as SelfImproveOptions<TScenario, TArtifact>,\n costLedger,\n startedAt,\n runDir,\n storage,\n )\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 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 const unitByScenario = opts.claim ? evaluationUnitMap(opts.claim, opts.scenarios) : undefined\n const splitUnitByScenario =\n opts.claim?.generalization === 'new-units' ? unitByScenario : undefined\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, splitUnitByScenario)\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 (opts.claim?.generalization === 'new-units') {\n assertIndependentEvaluationSplit(opts.claim, holdout, train)\n }\n if (opts.finalEvidence) {\n if (holdoutDeferred) throw new Error('final evidence requires measured holdout')\n if (opts.method) await reserveFinalEvidence(opts.finalEvidence, opts.claim, holdout, train)\n }\n\n if (opts.method) {\n const partitions = splitMethodPartitions(\n train,\n opts.selectionScenarios,\n budget.selectionFraction ?? 0.25,\n splitUnitByScenario,\n )\n return runSelfImproveMethod({\n opts: { ...opts, method: opts.method },\n train: partitions.train,\n selection: partitions.selection,\n holdout,\n costLedger,\n storage,\n runDir,\n startedAt,\n })\n }\n const generations = budget.generations ?? 3\n const populationSize = budget.populationSize ?? 2\n if (generations > 0 && !opts.proposer) {\n throw new Error(\n 'selfImprove: method or proposer is required when budget.generations is greater than zero',\n )\n }\n const proposer: SurfaceProposer<ProposalFinding> = 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: opts.claim?.minimumEffect ?? 0.05,\n independentUnitByScenarioId: opts.claim ? evaluationUnitMap(opts.claim, holdout) : undefined,\n })\n\n if (opts.onProgress) {\n opts.onProgress({ kind: 'baseline.started', scenarios: opts.scenarios.length })\n }\n\n const shipper =\n opts.hostedTenant && opts.searchLedger\n ? startSearchShipper({\n tenant: opts.hostedTenant,\n ledger: opts.searchLedger.ledger,\n runKind: 'optimization',\n })\n : undefined\n const result = await runImprovementLoop<TScenario, TArtifact>({\n scenarios: train,\n baselineSurface: opts.baselineSurface,\n premeasuredBaseline: opts.premeasuredBaseline,\n dispatchWithSurface: opts.agent,\n dispatchRef: opts.dispatchRef,\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 claim: opts.claim,\n finalEvidence: opts.finalEvidence,\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 cellRetry: opts.cellRetry,\n costLedger,\n expectUsage,\n labeledStore: opts.labeledStore,\n captureSource: opts.captureSource,\n analyzeGeneration: opts.analyzeGeneration,\n findings: opts.findings,\n policy: opts.policy,\n searchLedger: opts.searchLedger,\n }).finally(() => shipper && shipBestEffort(() => shipper.stop(), opts.searchLedger!.ledger.path))\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 reportUnitMap = opts.claim\n ? evaluationUnitMap(opts.claim, holdoutDeferred ? train : holdout)\n : undefined\n const report = pairedCompositeSummary(reportBaselineCampaign, reportWinnerCampaign, reportUnitMap)\n const baseline = report.baseline\n const winnerStats = report.winner\n\n // Repetitions refine a declared unit's mean without increasing the sample size.\n let power: PowerPreflight | undefined\n const baselineHoldoutComposites = holdoutDeferred ? [] : report.baselineComposites\n if (baselineHoldoutComposites.length >= 3) {\n // The shared judge's systematic bias remains outside this variance estimate.\n power = powerPreflight({\n baselineComposites: baselineHoldoutComposites,\n deltaThreshold: opts.claim?.minimumEffect ?? 0.05,\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 ...(reportWinnerCampaign === reportBaselineCampaign\n ? []\n : cellsToRunRecords(\n reportWinnerCampaign.cells,\n 'winner',\n runDir,\n result.winnerSurface,\n reportSplit,\n opts.model,\n )),\n ],\n baselineCandidateId: 'baseline',\n independentUnitByScenarioId: reportUnitMap,\n decisionThreshold: opts.claim?.minimumEffect ?? 0.05,\n ...(reportWinnerCampaign === reportBaselineCampaign ? {} : { 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 independentUnitByScenarioId: holdoutDeferred ? undefined : reportUnitMap,\n }),\n storage,\n hostedClient: opts.hostedTenant ? createHostedClient(opts.hostedTenant) : undefined,\n })\n if (opts.onProvenance) opts.onProvenance(provenance)\n\n const summary: SelfImproveProposerResult<TScenario, TArtifact> = {\n ...(opts.claim ? { claim: opts.claim } : {}),\n ...(result.finalEvidence ? { finalEvidence: result.finalEvidence } : {}),\n mode: 'proposer',\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 searchHistory: result.searchHistory,\n insight,\n ...(power ? { power } : {}),\n raw: result,\n }\n\n return summary\n}\n","import type { RunEvalOptions } from '../campaign/presets/run-eval'\nimport { runEval } from '../campaign/presets/run-eval'\nimport { inMemoryCampaignStorage } from '../campaign/storage'\nimport { surfaceDispatchRef } from '../campaign/surface-identity'\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 dispatchRef: surfaceDispatchRef(\n selectedSurface,\n campaignOpts.dispatchRef ?? defaults.dispatchRef,\n ),\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"],"mappings":";;;;;;;;;;;;AAYA,SAAgB,uBACd,UACA,QACA,6BACA;CACA,MAAM,SAAS,yBAAyB,UAAU,QAAQ,2BAA2B;CACrF,MAAM,eAAe,aACnB,OAAO,YACL,OAAO,QAAQ,SAAS,WAAW,UAAU,CAAC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ACA,WACe;CACf,IAAI,CAAC,YAAY,CAAC,WAAW,OAAO,KAAA;CACpC,OAAO,aAAa,YAAa,CAAC,GAAS,SAAS;AACtD;AAEA,SAAS,eACP,QACA,cACqC;CACrC,IAAI,WAAW,KAAA,GAAW;EACxB,IAAI,OAAO,WAAW,GACpB,MAAM,IAAI,MAAM,oDAAoD;EAEtE,OAAO;CACT;CACA,OAAO,CAAC,YAAY;AACtB;AAEA,SAAS,uBAAuB,OAAe,OAAuB;CACpE,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,GACtC,MAAM,IAAI,MAAM,oBAAoB,MAAM,4BAA4B;CAExE,OAAO;AACT"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"define-agent-eval-QdTTdbyE.d.ts","names":["_$__0.GateResult","_$__0.FinalEvidenceUse"],"sources":["../src/campaign/presets/run-final-comparison.ts","../src/contract/self-improve-method.ts","../src/contract/self-improve.ts","../src/contract/define-agent-eval.ts"],"mappings":";;;;;;;;;UAaU,uBAAuB,kBAAkB,UAAU,mBACnD,KAAK,mBAAmB,WAAW;EAC3C,iBAAiB;EACjB,eAAe;EACf,sBACE,SAAS,gBACT,UAAU,WACV,KAAK,WAAW,mBAAmB,WAAW,+BAC3C,QAAQ;EACb,MAAM,KAAK,WAAW;EACtB,QAAQ;EACR,gBAAgB;EAChB;EACA;EACA,cAAc,QAAQ,gBAAgB,UAAU,mBAAmB;;;iBAI/C,mBAAmB,kBAAkB,UAAU,WACnE,MAAM,uBAAuB,WAAW,aAAU;E,YAA5CA;;;;;;;;;;;;;;;;;;;;UCAS;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,oBAAoB,YAAY,0BAA0B;EAC1D,QAAQ;EACR;IACE;IACA;IACA;IACA;IACA;IACA;IACA;IACA,sBAAsB;;EAExB,MAAM,QAAQ,kBAAkB;EAChC;EACA;EACA;EACA;EACA,MAAM;EACN;EACA;;UAGe,wBAAwB,kBAAkB,UAAU,mB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