@tangle-network/agent-eval 2.0.7 → 2.0.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +80 -16
- package/dist/adapters/http.d.ts +2 -2
- package/dist/{agent-profile-CRdalpZv.d.ts → agent-profile-_JzxgLDM.d.ts} +11 -5
- package/dist/{agent-profile-CRdalpZv.d.ts.map → agent-profile-_JzxgLDM.d.ts.map} +1 -1
- package/dist/analyst/index.d.ts +14 -13
- package/dist/analyst/index.d.ts.map +1 -1
- package/dist/analyst/index.js +34 -13
- package/dist/analyst/index.js.map +1 -1
- package/dist/analyze-runs-Izz_ZeWg.d.ts +65 -0
- package/dist/analyze-runs-Izz_ZeWg.d.ts.map +1 -0
- package/dist/{analyze-runs-C_9cXPZn.js → analyze-runs-xhH2Qxoc.js} +6 -5
- package/dist/{analyze-runs-C_9cXPZn.js.map → analyze-runs-xhH2Qxoc.js.map} +1 -1
- package/dist/app-grade/index.d.ts +4 -4
- package/dist/app-grade/index.js +1 -1
- package/dist/{benchmark-command-DkBMUDwy.js → benchmark-command-CGQXNFj7.js} +12 -8
- package/dist/benchmark-command-CGQXNFj7.js.map +1 -0
- package/dist/benchmarks/index.d.ts +4 -4
- package/dist/benchmarks/index.js +4 -4
- package/dist/builder-eval/index.js +2 -2
- package/dist/calibration-CrORXMWx.d.ts +128 -0
- package/dist/calibration-CrORXMWx.d.ts.map +1 -0
- package/dist/{calibration-Cfoup0xz.js → calibration-Dz8mQb5P.js} +2 -2
- package/dist/{calibration-Cfoup0xz.js.map → calibration-Dz8mQb5P.js.map} +1 -1
- package/dist/campaign/index.d.ts +8 -8
- package/dist/campaign/index.js +13 -12
- package/dist/{campaign-DfSWSreo.js → campaign-eus7YRs2.js} +1590 -15
- package/dist/campaign-eus7YRs2.js.map +1 -0
- package/dist/{campaign-evidence-BojANgU7.d.ts → campaign-evidence-BOcX4w0r.d.ts} +5 -5
- package/dist/{campaign-evidence-BojANgU7.d.ts.map → campaign-evidence-BOcX4w0r.d.ts.map} +1 -1
- package/dist/{campaign-evidence-D_oBFfLc.js → campaign-evidence-KM5GTsHG.js} +5 -5
- package/dist/{campaign-evidence-D_oBFfLc.js.map → campaign-evidence-KM5GTsHG.js.map} +1 -1
- package/dist/{cluster-Bj90LK-1.d.ts → chat-client-BlTooBDA.d.ts} +9 -241
- package/dist/chat-client-BlTooBDA.d.ts.map +1 -0
- package/dist/{chat-client-CvyDOQBv.js → chat-client-Oyot5tyo.js} +2 -2
- package/dist/{chat-client-CvyDOQBv.js.map → chat-client-Oyot5tyo.js.map} +1 -1
- package/dist/{chat-json-call-DMrwmB-k.js → chat-json-call-DTmv2uNY.js} +2 -2
- package/dist/{chat-json-call-DMrwmB-k.js.map → chat-json-call-DTmv2uNY.js.map} +1 -1
- package/dist/cli.js +7 -7
- package/dist/cluster-BJ0nW3P7.d.ts +241 -0
- package/dist/cluster-BJ0nW3P7.d.ts.map +1 -0
- package/dist/{cluster-bootstrap-DPzVy3_K.js → cluster-bootstrap-CTC8Dd30.js} +3 -2
- package/dist/{cluster-bootstrap-DPzVy3_K.js.map → cluster-bootstrap-CTC8Dd30.js.map} +1 -1
- package/dist/{completion-verifier-DsotH2l3.js → completion-verifier-CCPG2Yc0.js} +3 -3
- package/dist/{completion-verifier-DsotH2l3.js.map → completion-verifier-CCPG2Yc0.js.map} +1 -1
- package/dist/{completion-verifier-Cy38EpGE.d.ts → completion-verifier-CQOC3_bm.d.ts} +2 -2
- package/dist/{completion-verifier-Cy38EpGE.d.ts.map → completion-verifier-CQOC3_bm.d.ts.map} +1 -1
- package/dist/contract/index.d.ts +14 -12
- package/dist/contract/index.js +14 -12
- package/dist/contract/index.js.map +1 -1
- package/dist/{decision-point-C46p-p9v.js → decision-point-CfqtnGop.js} +3 -3
- package/dist/{decision-point-C46p-p9v.js.map → decision-point-CfqtnGop.js.map} +1 -1
- package/dist/{default-registry-BWFPtmuI.js → default-registry-Rs5uzlfJ.js} +4 -4
- package/dist/{default-registry-BWFPtmuI.js.map → default-registry-Rs5uzlfJ.js.map} +1 -1
- package/dist/{default-registry-xoX0PMCb.d.ts → default-registry-X8McMoUV.d.ts} +6 -6
- package/dist/{default-registry-xoX0PMCb.d.ts.map → default-registry-X8McMoUV.d.ts.map} +1 -1
- package/dist/define-agent-eval-D8ntOXqV.js +96 -0
- package/dist/define-agent-eval-D8ntOXqV.js.map +1 -0
- package/dist/define-agent-eval-DH5-xi-F.d.ts +52 -0
- package/dist/define-agent-eval-DH5-xi-F.d.ts.map +1 -0
- package/dist/diagnosis/index.d.ts +3 -3
- package/dist/diagnosis/index.js +1 -1
- package/dist/{dspy-rlm-engine-r7YpKLhS.js → dspy-rlm-engine-ChE1PUM5.js} +3 -3
- package/dist/{dspy-rlm-engine-r7YpKLhS.js.map → dspy-rlm-engine-ChE1PUM5.js.map} +1 -1
- package/dist/{emitter-BjW3NnX-.js → emitter-xN9wGTVw.js} +9 -2
- package/dist/{emitter-BjW3NnX-.js.map → emitter-xN9wGTVw.js.map} +1 -1
- package/dist/{eval-campaign-Cyk-tkLh.js → eval-campaign-BciGnrGy.js} +3 -3
- package/dist/{eval-campaign-Cyk-tkLh.js.map → eval-campaign-BciGnrGy.js.map} +1 -1
- package/dist/{evaluation-X5E22NQK.d.ts → evaluation-CjZH6gW0.d.ts} +4 -4
- package/dist/{evaluation-X5E22NQK.d.ts.map → evaluation-CjZH6gW0.d.ts.map} +1 -1
- package/dist/evaluation.d.ts +1 -1
- package/dist/{exact-types-DjuabhUV.d.ts → exact-types-BIHqYBYf.d.ts} +2 -2
- package/dist/{exact-types-DjuabhUV.d.ts.map → exact-types-BIHqYBYf.d.ts.map} +1 -1
- package/dist/{execution-insight-CE20Bxq0.d.ts → execution-insight-YihQrSqd.d.ts} +2 -2
- package/dist/{execution-insight-CE20Bxq0.d.ts.map → execution-insight-YihQrSqd.d.ts.map} +1 -1
- package/dist/experiment/index.d.ts +5 -5
- package/dist/experiment/index.js +10 -184
- package/dist/experiment/index.js.map +1 -1
- package/dist/{external-optimizer-contracts-ZDBfbZ_s.js → external-optimizer-contracts-BFV8lnhl.js} +7 -2
- package/dist/{external-optimizer-contracts-ZDBfbZ_s.js.map → external-optimizer-contracts-BFV8lnhl.js.map} +1 -1
- package/dist/{external-optimizer-process-4QdcF7Kd.js → external-optimizer-process-B6emPodQ.js} +3 -3
- package/dist/{external-optimizer-process-4QdcF7Kd.js.map → external-optimizer-process-B6emPodQ.js.map} +1 -1
- package/dist/{external-optimizer-subprocess-BW0ZWUUr.js → external-optimizer-subprocess-_O06eDVA.js} +35 -376
- package/dist/external-optimizer-subprocess-_O06eDVA.js.map +1 -0
- package/dist/{feedback-trajectory-BMkJezPc.d.ts → feedback-trajectory-CoQPmSJV.d.ts} +3 -3
- package/dist/{feedback-trajectory-BMkJezPc.d.ts.map → feedback-trajectory-CoQPmSJV.d.ts.map} +1 -1
- package/dist/finding-scope-B_As3F_v.js +359 -0
- package/dist/finding-scope-B_As3F_v.js.map +1 -0
- package/dist/{findings-store-DV8WA5nD.js → findings-store-CvYUzQBR.js} +4 -4
- package/dist/{findings-store-DV8WA5nD.js.map → findings-store-CvYUzQBR.js.map} +1 -1
- package/dist/fuzz.js +1 -1
- package/dist/{index-C6TG1LwA.d.ts → index-BSb3fJyZ.d.ts} +318 -131
- package/dist/index-BSb3fJyZ.d.ts.map +1 -0
- package/dist/{index-CKjqN9_U.d.ts → index-Bk1XEkP7.d.ts} +99 -3
- package/dist/index-Bk1XEkP7.d.ts.map +1 -0
- package/dist/{index-DAFZRMlF.d.ts → index-BmWw8zN6.d.ts} +10 -8
- package/dist/index-BmWw8zN6.d.ts.map +1 -0
- package/dist/{index-DKpMyD_Z.d.ts → index-CCOaNmh2.d.ts} +7 -7
- package/dist/{index-DKpMyD_Z.d.ts.map → index-CCOaNmh2.d.ts.map} +1 -1
- package/dist/{index-xEM_SoCl.d.ts → index-ZffK_5sD.d.ts} +22 -20
- package/dist/index-ZffK_5sD.d.ts.map +1 -0
- package/dist/{index-BqAPIToS.d.ts → index-aRalB_Ma.d.ts} +3 -3
- package/dist/{index-BqAPIToS.d.ts.map → index-aRalB_Ma.d.ts.map} +1 -1
- package/dist/index.d.ts +33 -29
- package/dist/index.js +28 -25
- package/dist/index.js.map +1 -1
- package/dist/{analyze-runs-xjKBBqIB.d.ts → insight-report-DYofCMLx.d.ts} +4 -64
- package/dist/insight-report-DYofCMLx.d.ts.map +1 -0
- package/dist/{integrity-BF0tJK21.js → integrity-DacT3oJ1.js} +2 -2
- package/dist/{integrity-BF0tJK21.js.map → integrity-DacT3oJ1.js.map} +1 -1
- package/dist/{integrity-B9320cw1.d.ts → integrity-DotDLWtj.d.ts} +2 -2
- package/dist/{integrity-B9320cw1.d.ts.map → integrity-DotDLWtj.d.ts.map} +1 -1
- package/dist/{judge-gate-DqlzOBOm.js → judge-gate-CpD3wmcf.js} +3 -3
- package/dist/{judge-gate-DqlzOBOm.js.map → judge-gate-CpD3wmcf.js.map} +1 -1
- package/dist/{llm-client-Dw4x6EdE.js → llm-client-Dk8lBnMh.js} +15 -2
- package/dist/{llm-client-Dw4x6EdE.js.map → llm-client-Dk8lBnMh.js.map} +1 -1
- package/dist/llm-judge-DYmEdo3M.js +476 -0
- package/dist/llm-judge-DYmEdo3M.js.map +1 -0
- package/dist/{matrix-CqZSpwgN.d.ts → matrix-BDl7hoBr.d.ts} +6 -2
- package/dist/matrix-BDl7hoBr.d.ts.map +1 -0
- package/dist/measure-validity-plan-BReXzcVh.d.ts +201 -0
- package/dist/measure-validity-plan-BReXzcVh.d.ts.map +1 -0
- package/dist/measure-validity-plan-CJkBNzX_.js +154 -0
- package/dist/measure-validity-plan-CJkBNzX_.js.map +1 -0
- package/dist/meta-eval/index.d.ts +5 -3
- package/dist/meta-eval/index.js +808 -15
- package/dist/meta-eval/index.js.map +1 -1
- package/dist/multishot/golden/index.d.ts +1 -1
- package/dist/multishot/index.d.ts +497 -4
- package/dist/multishot/index.d.ts.map +1 -1
- package/dist/multishot/index.js +1000 -48
- package/dist/multishot/index.js.map +1 -1
- package/dist/node-transport-DJno8V46.js +62 -0
- package/dist/node-transport-DJno8V46.js.map +1 -0
- package/dist/openapi.json +1 -1
- package/dist/{llm-judge-DQJTQx01.js → optimization-method-4JlbMxd2.js} +38 -513
- package/dist/optimization-method-4JlbMxd2.js.map +1 -0
- package/dist/{outcome-observations-DL3CC8w1.js → outcome-observations-DEh8_V_P.js} +31 -6
- package/dist/outcome-observations-DEh8_V_P.js.map +1 -0
- package/dist/outcome-store-CHtuvstd.d.ts +56 -0
- package/dist/outcome-store-CHtuvstd.d.ts.map +1 -0
- package/dist/{paired-arms-DZhH3FGu.js → paired-arms-CJH5Q0wx.js} +3 -2
- package/dist/{paired-arms-DZhH3FGu.js.map → paired-arms-CJH5Q0wx.js.map} +1 -1
- package/dist/{paired-promotion-decision-Dn3-jaq4.js → paired-promotion-decision-BtfVwEAk.js} +3 -2
- package/dist/{paired-promotion-decision-Dn3-jaq4.js.map → paired-promotion-decision-BtfVwEAk.js.map} +1 -1
- package/dist/{paired-promotion-decision-ChHBuuHV.d.ts → paired-promotion-decision-DJlI4z_k.d.ts} +2 -2
- package/dist/{paired-promotion-decision-ChHBuuHV.d.ts.map → paired-promotion-decision-DJlI4z_k.d.ts.map} +1 -1
- package/dist/{paired-promotion-power-BlzXdgMD.js → paired-promotion-power-DG1avBKf.js} +3 -3
- package/dist/{paired-promotion-power-BlzXdgMD.js.map → paired-promotion-power-DG1avBKf.js.map} +1 -1
- package/dist/paired-tests-CXcD_B80.js +688 -0
- package/dist/paired-tests-CXcD_B80.js.map +1 -0
- package/dist/pareto-DIVE5D0T.js +81 -0
- package/dist/pareto-DIVE5D0T.js.map +1 -0
- package/dist/pipelines/index.d.ts +2 -1
- package/dist/pipelines/index.d.ts.map +1 -1
- package/dist/pipelines/index.js +1 -1
- package/dist/{sequential-BphITa5b.js → power-COie_o6E.js} +181 -4
- package/dist/power-COie_o6E.js.map +1 -0
- package/dist/{prime-protocol-Cv6_47rh.d.ts → prime-protocol-BRMk6dGI.d.ts} +2 -2
- package/dist/{prime-protocol-Cv6_47rh.d.ts.map → prime-protocol-BRMk6dGI.d.ts.map} +1 -1
- package/dist/{promotion-gate-CGkxh36r.d.ts → promotion-gate-B0VTBoXg.d.ts} +2 -2
- package/dist/{promotion-gate-CGkxh36r.d.ts.map → promotion-gate-B0VTBoXg.d.ts.map} +1 -1
- package/dist/{promotion-policy-CxDIh-9p.js → promotion-policy-BgI7PsQn.js} +4 -4
- package/dist/{promotion-policy-CxDIh-9p.js.map → promotion-policy-BgI7PsQn.js.map} +1 -1
- package/dist/{proposal-findings-DedMih-u.js → proposal-findings-CfRFCFXS.js} +2 -2
- package/dist/{proposal-findings-DedMih-u.js.map → proposal-findings-CfRFCFXS.js.map} +1 -1
- package/dist/{registry-CIjC6SdV.d.ts → registry-BeInzotS.d.ts} +4 -4
- package/dist/{registry-CIjC6SdV.d.ts.map → registry-BeInzotS.d.ts.map} +1 -1
- package/dist/{release-confidence-BLHOMK5Q.js → release-confidence-Cndq1hwi.js} +2 -2
- package/dist/{release-confidence-BLHOMK5Q.js.map → release-confidence-Cndq1hwi.js.map} +1 -1
- package/dist/reporting.d.ts +5 -5
- package/dist/reporting.js +6 -5
- package/dist/reporting.js.map +1 -1
- package/dist/{research-report-D6XIK0eK.d.ts → research-report-CL5_UqCX.d.ts} +2 -2
- package/dist/{research-report-D6XIK0eK.d.ts.map → research-report-CL5_UqCX.d.ts.map} +1 -1
- package/dist/{researcher---DhHG4J.d.ts → researcher-BOpZP_Ja.d.ts} +4 -4
- package/dist/{researcher---DhHG4J.d.ts.map → researcher-BOpZP_Ja.d.ts.map} +1 -1
- package/dist/{reward-hacking-DKAflk2c.js → reward-hacking-DMTm1OBd.js} +2 -2
- package/dist/{reward-hacking-DKAflk2c.js.map → reward-hacking-DMTm1OBd.js.map} +1 -1
- package/dist/rl.d.ts +9 -8
- package/dist/rl.d.ts.map +1 -1
- package/dist/rl.js +11 -10
- package/dist/rl.js.map +1 -1
- package/dist/rollout/index.d.ts +2 -2
- package/dist/rollout/index.js +1 -1
- package/dist/{rollout-B_lrpd9a.js → rollout--rSr43Pd.js} +2 -2
- package/dist/{rollout-B_lrpd9a.js.map → rollout--rSr43Pd.js.map} +1 -1
- package/dist/{rollout-nodes-Vas6OSxX.js → rollout-nodes-DFxKpIr2.js} +39 -10
- package/dist/rollout-nodes-DFxKpIr2.js.map +1 -0
- package/dist/{rubric-predictive-validity--6z0q8s6.js → rubric-predictive-validity-BXJ92Jp_.js} +3 -9
- package/dist/rubric-predictive-validity-BXJ92Jp_.js.map +1 -0
- package/dist/{rubric-predictive-validity-C9wc7f_D.d.ts → rubric-predictive-validity-DH94_0Q1.d.ts} +3 -56
- package/dist/rubric-predictive-validity-DH94_0Q1.d.ts.map +1 -0
- package/dist/{run-improvement-loop-BfwOUudy.d.ts → run-improvement-loop-BeHu5D9Z.d.ts} +396 -11
- package/dist/run-improvement-loop-BeHu5D9Z.d.ts.map +1 -0
- package/dist/{run-record-Bqg0NZ_e.js → run-record-CuO8ErrI.js} +3 -2
- package/dist/run-record-CuO8ErrI.js.map +1 -0
- package/dist/{runtime-rollouts-drQynu3t.js → runtime-rollouts-CE0MbQPq.js} +55 -8
- package/dist/runtime-rollouts-CE0MbQPq.js.map +1 -0
- package/dist/search/index.d.ts +2 -2
- package/dist/search/index.js +2 -2
- package/dist/{search-kernel-DJq9bUDU.d.ts → search-kernel-CJZ-ZSV1.d.ts} +3 -3
- package/dist/{search-kernel-DJq9bUDU.d.ts.map → search-kernel-CJZ-ZSV1.d.ts.map} +1 -1
- package/dist/{pareto-Bg75Gajo.js → search-kernel-mZc79S6N.js} +6 -88
- package/dist/search-kernel-mZc79S6N.js.map +1 -0
- package/dist/{search-summary-B1x1Vmzh.js → search-summary-CCgP2qXz.js} +4 -4
- package/dist/{search-summary-B1x1Vmzh.js.map → search-summary-CCgP2qXz.js.map} +1 -1
- package/dist/{define-agent-eval-Cjc0wWnO.d.ts → self-improve-B1fsNejr.d.ts} +8 -54
- package/dist/self-improve-B1fsNejr.d.ts.map +1 -0
- package/dist/{define-agent-eval-B6uE3gNu.js → self-improve-C_Bcdmv8.js} +9 -97
- package/dist/self-improve-C_Bcdmv8.js.map +1 -0
- package/dist/{sequential-BhbTSxpt.d.ts → sequential-CHplorpC.d.ts} +2 -2
- package/dist/{sequential-BhbTSxpt.d.ts.map → sequential-CHplorpC.d.ts.map} +1 -1
- package/dist/{sequential-ux_XrjBf.js → sequential-DR-pnYQ7.js} +3 -3
- package/dist/{sequential-ux_XrjBf.js.map → sequential-DR-pnYQ7.js.map} +1 -1
- package/dist/{server-1fzBCxMh.js → server-aZFmRucn.js} +3 -3
- package/dist/{server-1fzBCxMh.js.map → server-aZFmRucn.js.map} +1 -1
- package/dist/{skillopt-optimization-method-D_swD0Cy.js → skillopt-optimization-method-DHk1K757.js} +95 -40
- package/dist/skillopt-optimization-method-DHk1K757.js.map +1 -0
- package/dist/{statistical-heldout-CaS4T-43.js → statistical-heldout-CL_7mI5C.js} +3 -3
- package/dist/{statistical-heldout-CaS4T-43.js.map → statistical-heldout-CL_7mI5C.js.map} +1 -1
- package/dist/{statistics-DSidA5I2.js → statistics-AKnVFnK-.js} +233 -700
- package/dist/statistics-AKnVFnK-.js.map +1 -0
- package/dist/statistics.d.ts +3 -3
- package/dist/statistics.js +3 -2
- package/dist/{store-tool-spans-DniaFwjM.d.ts → store-tool-spans-M3WxeRrG.d.ts} +4 -4
- package/dist/{store-tool-spans-DniaFwjM.d.ts.map → store-tool-spans-M3WxeRrG.d.ts.map} +1 -1
- package/dist/{summary-report-CI4J6gxU.js → summary-report-DyBkOC6V.js} +15 -7
- package/dist/summary-report-DyBkOC6V.js.map +1 -0
- package/dist/summary-report-figures-CJHygLgw.d.ts.map +1 -1
- package/dist/supervisor-run/index.d.ts +12 -2
- package/dist/supervisor-run/index.d.ts.map +1 -1
- package/dist/supervisor-run/index.js +3 -3
- package/dist/{systemone-DzY-2Zri.d.ts → systemone-4PadCE4C.d.ts} +8 -7
- package/dist/systemone-4PadCE4C.d.ts.map +1 -0
- package/dist/{systemone-review-CXecR_m-.d.ts → systemone-review-DpAXWDkL.d.ts} +2 -2
- package/dist/{systemone-review-CXecR_m-.d.ts.map → systemone-review-DpAXWDkL.d.ts.map} +1 -1
- package/dist/systemone.d.ts +3 -3
- package/dist/systemone.js +1 -1
- package/dist/{tool-groups-DF6OqhoG.d.ts → tool-groups-SlnoQNyT.d.ts} +2 -2
- package/dist/tool-groups-SlnoQNyT.d.ts.map +1 -0
- package/dist/tool-waste-B01AMpID.d.ts +121 -0
- package/dist/tool-waste-B01AMpID.d.ts.map +1 -0
- package/dist/{tool-waste-u7JJ_BlE.js → tool-waste-BZnYSa6J.js} +3 -2
- package/dist/{tool-waste-u7JJ_BlE.js.map → tool-waste-BZnYSa6J.js.map} +1 -1
- package/dist/{trace-questions-DO8y3J-E.d.ts → trace-questions-ybyF0B6N.d.ts} +2 -2
- package/dist/{trace-questions-DO8y3J-E.d.ts.map → trace-questions-ybyF0B6N.d.ts.map} +1 -1
- package/dist/trace-repair/index.d.ts +1 -1
- package/dist/trace-repair/index.js +1 -1
- package/dist/traces.d.ts +4 -4
- package/dist/traces.js +1 -1
- package/dist/trajectory-B3o6Ald_.d.ts +100 -0
- package/dist/trajectory-B3o6Ald_.d.ts.map +1 -0
- package/dist/trajectory-replay/index.js +1 -1
- package/dist/{tree-DQMlcNFI.js → tree-CiIe-f3f.js} +6 -4
- package/dist/{tree-DQMlcNFI.js.map → tree-CiIe-f3f.js.map} +1 -1
- package/dist/{types-fuOwNq1C.d.ts → types-B1W3v8dT.d.ts} +3 -2
- package/dist/types-B1W3v8dT.d.ts.map +1 -0
- package/dist/{types-BMSDkS8l.d.ts → types-D5XtEH9Q.d.ts} +11 -4
- package/dist/{types-BMSDkS8l.d.ts.map → types-D5XtEH9Q.d.ts.map} +1 -1
- package/dist/types-DK4vNv5q.js.map +1 -1
- package/dist/{types-D_PfKC59.d.ts → types-an-CUndX.d.ts} +2 -2
- package/dist/{types-D_PfKC59.d.ts.map → types-an-CUndX.d.ts.map} +1 -1
- package/dist/{types-BLv2Ngla.d.ts → types-xVtEOBhO.d.ts} +31 -8
- package/dist/types-xVtEOBhO.d.ts.map +1 -0
- package/dist/wire/index.d.ts +2 -2
- package/dist/wire/index.js +1 -1
- package/dist/world/index.d.ts +529 -0
- package/dist/world/index.d.ts.map +1 -0
- package/dist/world/index.js +1356 -0
- package/dist/world/index.js.map +1 -0
- package/docs/campaign-proposers.md +7 -0
- package/docs/concepts.md +2 -0
- package/docs/design/statistics-decisions.md +48 -0
- package/docs/eval-surface-map.md +5 -2
- package/docs/feature-guide.md +3 -1
- package/docs/multi-turn-optimization.md +84 -0
- package/docs/outcome-validity.md +108 -0
- package/docs/public-api.md +89 -34
- package/docs/{multi-shot-optimization.md → trajectory-optimization.md} +1 -1
- package/docs/world.md +104 -0
- package/package.json +6 -1
- package/dist/analyze-runs-xjKBBqIB.d.ts.map +0 -1
- package/dist/benchmark-command-DkBMUDwy.js.map +0 -1
- package/dist/campaign-DfSWSreo.js.map +0 -1
- package/dist/cluster-Bj90LK-1.d.ts.map +0 -1
- package/dist/define-agent-eval-B6uE3gNu.js.map +0 -1
- package/dist/define-agent-eval-Cjc0wWnO.d.ts.map +0 -1
- package/dist/external-optimizer-subprocess-BW0ZWUUr.js.map +0 -1
- package/dist/index-C6TG1LwA.d.ts.map +0 -1
- package/dist/index-CKjqN9_U.d.ts.map +0 -1
- package/dist/index-DAFZRMlF.d.ts.map +0 -1
- package/dist/index-xEM_SoCl.d.ts.map +0 -1
- package/dist/interval-CWyxqDpE.d.ts +0 -43
- package/dist/interval-CWyxqDpE.d.ts.map +0 -1
- package/dist/llm-judge-DQJTQx01.js.map +0 -1
- package/dist/matrix-CqZSpwgN.d.ts.map +0 -1
- package/dist/outcome-observations-DL3CC8w1.js.map +0 -1
- package/dist/pareto-Bg75Gajo.js.map +0 -1
- package/dist/rollout-nodes-Vas6OSxX.js.map +0 -1
- package/dist/rubric-predictive-validity--6z0q8s6.js.map +0 -1
- package/dist/rubric-predictive-validity-C9wc7f_D.d.ts.map +0 -1
- package/dist/run-improvement-loop-BfwOUudy.d.ts.map +0 -1
- package/dist/run-record-Bqg0NZ_e.js.map +0 -1
- package/dist/runtime-rollouts-drQynu3t.js.map +0 -1
- package/dist/sequential-BphITa5b.js.map +0 -1
- package/dist/skillopt-optimization-method-D_swD0Cy.js.map +0 -1
- package/dist/statistics-DSidA5I2.js.map +0 -1
- package/dist/summary-report-CI4J6gxU.js.map +0 -1
- package/dist/systemone-DzY-2Zri.d.ts.map +0 -1
- package/dist/tool-groups-DF6OqhoG.d.ts.map +0 -1
- package/dist/tool-waste-CIhtU1ad.d.ts +0 -217
- package/dist/tool-waste-CIhtU1ad.d.ts.map +0 -1
- package/dist/types-BLv2Ngla.d.ts.map +0 -1
- package/dist/types-fuOwNq1C.d.ts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/meta-eval/correlation-study.ts","../../src/meta-eval/evaluator-admission.ts","../../src/meta-eval/judge-panel-calibration.ts","../../src/meta-eval/plants.ts"],"sourcesContent":["/**\n * Correlation study — \"does our eval score predict real-world outcomes?\"\n *\n * Joins traces and outcomes by runId and reports descriptive correlations.\n * Independent runs are the bootstrap observation unit.\n * Association alone does not establish causation or held-out predictive performance.\n */\n\nimport { runMetricExtractor } from '../trace/query'\nimport type { Run } from '../trace/schema'\nimport type { TraceStore } from '../trace/store'\nimport {\n assertUniqueObservationIds,\n correlationSummary,\n hasVariation,\n reduceOutcomeMetric,\n validateObservationOptions,\n} from './outcome-observations'\nimport type { DeploymentOutcome, OutcomeFilter, OutcomeStore } from './outcome-store'\n\nexport interface EvalMetricSpec {\n id: string\n /** Extract a scalar from a run. Omit it and `id` must name one of\n * `RUN_METRICS`; any other `id` is refused. */\n extract?: (run: Run, store: TraceStore) => Promise<number | null>\n}\n\nexport interface OutcomePair {\n evalMetric: string\n outcomeMetric: string\n}\n\nexport interface CorrelationResult {\n evalMetric: string\n outcomeMetric: string\n n: number\n pearson: number\n spearman: number\n /** 95% bootstrap CI for Pearson. */\n pearsonCi95: { lower: number; upper: number } | null\n /** 95% bootstrap CI for Spearman; null when no resample is estimable. */\n spearmanCi95: { lower: number; upper: number } | null\n /** Rough verdict: 'strong' ≥ 0.7, 'moderate' ≥ 0.4, else 'weak'. */\n verdict: 'strong' | 'moderate' | 'weak'\n}\n\nexport interface CorrelationStudyResult {\n pairs: CorrelationResult[]\n /** Declared pairs without an estimable correlation, including their usable sample count. */\n excludedPairs: Array<\n OutcomePair & {\n n: number\n reason: 'insufficient_samples' | 'constant_eval_metric' | 'constant_outcome'\n }\n >\n joinedSamples: number\n skippedRuns: number\n}\n\nexport interface CorrelationStudyOptions {\n /** Only join outcomes captured within this window after run.startedAt. */\n maxCaptureLagMs?: number\n /** Restrict to a subset of outcomes (cohort, region, source). */\n outcomeFilter?: OutcomeFilter\n /** Which outcome per run to use when multiple exist. Default 'latest'. */\n reduction?: 'latest' | 'mean' | 'max'\n /** Bootstrap iterations for the CI. Default 500. */\n bootstrapIterations?: number\n /** Seed for the bootstrap resampler. Absent, the seed is derived from the\n * paired observations, so the same study reproduces the same interval. */\n seed?: number\n}\n\nexport async function correlationStudy(\n traceStore: TraceStore,\n outcomeStore: OutcomeStore,\n evalMetrics: EvalMetricSpec[],\n outcomeMetricNames: string[],\n options: CorrelationStudyOptions = {},\n): Promise<CorrelationStudyResult> {\n const reduction = options.reduction ?? 'latest'\n const iterations = options.bootstrapIterations ?? 500\n const seed = options.seed\n validateObservationOptions(reduction, iterations, seed)\n assertUniqueObservationIds(\n evalMetrics.map((metric) => metric.id),\n 'eval metric',\n )\n assertUniqueObservationIds(outcomeMetricNames, 'outcome metric')\n const maxLag = options.maxCaptureLagMs ?? Infinity\n if (maxLag < 0 || Number.isNaN(maxLag)) {\n throw new Error('maxCaptureLagMs must be nonnegative')\n }\n const extractors = evalMetrics.map((metric) => ({\n ...metric,\n extract: metric.extract ?? runMetricExtractor(metric.id),\n }))\n const metricNames = [...outcomeMetricNames]\n const runs = await traceStore.listRuns()\n assertUniqueObservationIds(\n runs.map((run) => run.runId),\n 'runId',\n )\n const outcomes = await outcomeStore.list(options.outcomeFilter)\n const outcomesByRun = new Map<string, DeploymentOutcome[]>()\n for (const o of outcomes) {\n const arr = outcomesByRun.get(o.runId) ?? []\n arr.push(o)\n outcomesByRun.set(o.runId, arr)\n }\n\n const pairs: Array<{ evalMetric: string; outcomeMetric: string; xs: number[]; ys: number[] }> = []\n for (const em of extractors) {\n for (const om of metricNames) {\n pairs.push({ evalMetric: em.id, outcomeMetric: om, xs: [], ys: [] })\n }\n }\n\n let joined = 0\n let skipped = 0\n for (const run of runs) {\n const os = outcomesByRun.get(run.runId)\n if (!os || os.length === 0) {\n skipped++\n continue\n }\n const eligible = os.filter((o) => {\n const lag = o.capturedAt - run.startedAt\n return lag >= 0 && lag <= maxLag\n })\n if (eligible.length === 0) {\n skipped++\n continue\n }\n\n let joinedThisRun = false\n for (const em of extractors) {\n const x = await em.extract(run, traceStore)\n if (x === null || !Number.isFinite(x)) continue\n\n for (const om of metricNames) {\n const y = reduceOutcomeMetric(eligible, om, reduction)\n if (y === null) continue\n const pair = pairs.find((p) => p.evalMetric === em.id && p.outcomeMetric === om)!\n pair.xs.push(x)\n pair.ys.push(y)\n joinedThisRun = true\n }\n }\n if (joinedThisRun) joined++\n else skipped++\n }\n\n const excludedPairs: CorrelationStudyResult['excludedPairs'] = []\n const results: CorrelationResult[] = []\n for (const p of pairs) {\n const reason =\n p.xs.length < 3\n ? 'insufficient_samples'\n : !hasVariation(p.xs)\n ? 'constant_eval_metric'\n : !hasVariation(p.ys)\n ? 'constant_outcome'\n : null\n if (reason !== null) {\n excludedPairs.push({\n evalMetric: p.evalMetric,\n outcomeMetric: p.outcomeMetric,\n n: p.xs.length,\n reason,\n })\n continue\n }\n const summary = correlationSummary(p.xs, p.ys, iterations, seed)\n const verdict: CorrelationResult['verdict'] =\n Math.abs(summary.pearson) >= 0.7\n ? 'strong'\n : Math.abs(summary.pearson) >= 0.4\n ? 'moderate'\n : 'weak'\n results.push({\n evalMetric: p.evalMetric,\n outcomeMetric: p.outcomeMetric,\n n: p.xs.length,\n ...summary,\n verdict,\n })\n }\n return { pairs: results, excludedPairs, joinedSamples: joined, skippedRuns: skipped }\n}\n","import { z } from 'zod'\nimport { ValidationError } from '../errors'\nimport { type ComputedInterval, computeInterval } from '../experiment/ast/interval'\nimport { compareCodeUnits, hashCanonical, type LedgerHash } from '../ledger-core/canonical'\n\nconst identity = z\n .string()\n .min(1)\n .refine((value) => value.trim() === value)\nexport const evaluatorAdmissionPolicySchema = z\n .object({\n confidence: z.number().finite().gt(0).lt(1),\n maxFalseAcceptanceRate: z.number().finite().min(0).lt(1),\n maxFalseRejectionRate: z.number().finite().min(0).lt(1),\n })\n .strict()\n\n/** Register both error limits before inspecting audit judgments. */\nexport type EvaluatorAdmissionPolicy = z.infer<typeof evaluatorAdmissionPolicySchema>\n\nexport const evaluatorAuditObservationSchema = z\n .object({\n id: identity,\n independentUnitId: identity,\n evidenceRef: identity,\n expected: z.enum(['accept', 'reject']),\n observed: z.enum(['accept', 'reject', 'unknown']),\n exposure: z.enum(['fresh', 'development']),\n })\n .strict()\n\n/** Actual control judgments. Variants from one source retain one independent identity. */\nexport type EvaluatorAuditObservation = z.infer<typeof evaluatorAuditObservationSchema>\n\nconst inputSchema = z\n .object({\n evaluatorDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/),\n population: identity,\n samplingFrame: identity,\n authority: z\n .object({\n evaluatorAuthorId: identity,\n auditorId: identity,\n independenceEvidenceRef: identity,\n })\n .strict(),\n policy: evaluatorAdmissionPolicySchema,\n observations: z.array(evaluatorAuditObservationSchema),\n })\n .strict()\n\nexport type EvaluatorAuditInput = z.infer<typeof inputSchema>\n\nexport interface EvaluatorErrorRate {\n /** Eligible control judgments in this class, including unknown judgments. */\n cases: number\n independentUnits: number\n /** Units with at least one observed mistake. */\n errorUnits: number\n /** Units with unknown judgments and no observed mistake yet. */\n unresolvedUnits: number\n unknownCases: number\n /** Missing judgments do not become measured zeros. */\n errorRate: number | null\n /** Exact bounds conservatively include every possible outcome of unknown judgments. */\n interval: ComputedInterval | null\n limit: number\n verdict: 'pass' | 'fail' | 'inconclusive'\n}\n\nexport interface EvaluatorAdmissionReport {\n evaluatorDigest: LedgerHash\n policyDigest: LedgerHash\n inputDigest: LedgerHash\n reportDigest: LedgerHash\n population: string\n samplingFrame: string\n authority: EvaluatorAuditInput['authority']\n policy: EvaluatorAdmissionPolicy\n /** Joint coverage for the two reported error-rate intervals. */\n confidence: number\n intervalConfidence: number\n verdict: 'admit' | 'reject' | 'inconclusive'\n reasons: string[]\n observations: EvaluatorAuditObservation[]\n coverage: {\n cases: number\n independentUnits: number\n eligibleCases: number\n eligibleIndependentUnits: number\n excludedCases: number\n unknownCases: number\n }\n exclusions: Array<{ id: string; independentUnitId: string; reason: 'development-exposure' }>\n falseAcceptance: EvaluatorErrorRate\n falseRejection: EvaluatorErrorRate\n}\n\nfunction errorRate(\n rows: readonly EvaluatorAuditObservation[],\n expected: 'accept' | 'reject',\n limit: number,\n level: number,\n): EvaluatorErrorRate {\n const cases = rows.filter((row) => row.expected === expected)\n const units = new Map<string, { error: boolean; unknown: boolean }>()\n for (const row of cases) {\n const unit = units.get(row.independentUnitId) ?? { error: false, unknown: false }\n unit.unknown ||= row.observed === 'unknown'\n unit.error ||= row.observed !== 'unknown' && row.observed !== expected\n units.set(row.independentUnitId, unit)\n }\n const n = units.size\n const errorUnits = [...units.values()].filter((unit) => unit.error).length\n const unresolvedUnits = [...units.values()].filter((unit) => unit.unknown && !unit.error).length\n const unknownCases = cases.filter((row) => row.observed === 'unknown').length\n // Unknown judgments contribute to n; their most favorable and adverse outcomes bound the rate.\n const interval =\n n === 0\n ? null\n : {\n lower: computeInterval(\n { kind: 'clopper-pearson', level },\n {\n kind: 'binomial',\n successes: errorUnits,\n trials: n,\n },\n ).lower,\n upper: computeInterval(\n { kind: 'clopper-pearson', level },\n {\n kind: 'binomial',\n successes: errorUnits + unresolvedUnits,\n trials: n,\n },\n ).upper,\n level,\n }\n const verdict =\n interval && interval.lower > limit\n ? 'fail'\n : interval && interval.upper <= limit\n ? 'pass'\n : 'inconclusive'\n return {\n cases: cases.length,\n independentUnits: n,\n errorUnits,\n unresolvedUnits,\n unknownCases,\n errorRate: n === 0 || unresolvedUnits > 0 ? null : errorUnits / n,\n interval,\n limit,\n verdict,\n }\n}\n\nfunction eligibleControls<\n T extends Pick<EvaluatorAuditObservation, 'id' | 'independentUnitId' | 'exposure'>,\n>(observations: T[]) {\n const ids = new Set<string>()\n for (const row of observations) {\n if (ids.has(row.id))\n throw new ValidationError(`duplicate evaluator audit observation '${row.id}'`)\n ids.add(row.id)\n }\n observations.sort((a, b) => compareCodeUnits(a.id, b.id))\n const developmentUnits = new Set(\n observations\n .filter((row) => row.exposure === 'development')\n .map((row) => row.independentUnitId),\n )\n const eligible = observations.filter((row) => !developmentUnits.has(row.independentUnitId))\n const exclusions = observations\n .filter((row) => developmentUnits.has(row.independentUnitId))\n .map((row) => ({\n id: row.id,\n independentUnitId: row.independentUnitId,\n reason: 'development-exposure' as const,\n }))\n return { eligible, exclusions }\n}\n\nfunction simultaneousIntervalConfidence(confidence: number): number {\n const level = 1 - (1 - confidence) / 2\n if (level >= 1)\n throw new ValidationError(\n 'evaluator audit confidence is too close to one for simultaneous intervals',\n )\n return level\n}\n\nconst capacitySchema = z\n .object({\n policy: evaluatorAdmissionPolicySchema,\n controls: z\n .array(evaluatorAuditObservationSchema.omit({ observed: true, evidenceRef: true }))\n .default([]),\n })\n .strict()\n\nexport type EvaluatorAuditPlanInput = z.input<typeof capacitySchema>\n\n/** The zero-error eligibility floor, not a statistical power calculation. */\nfunction zeroErrorUpperBound(trials: number, level: number): number {\n return -Math.expm1(Math.log((1 - level) / 2) / trials)\n}\n\nfunction minimumAuditUnits(limit: number, level: number): number | null {\n if (limit === 0) return null\n const estimate = Math.ceil(Math.log((1 - level) / 2) / Math.log1p(-limit))\n if (!Number.isFinite(estimate) || estimate > Number.MAX_SAFE_INTEGER) return null\n const clears = (trials: number) => zeroErrorUpperBound(trials, level) <= limit\n let minimum = Math.max(1, estimate)\n while (minimum > 1 && clears(minimum - 1)) minimum -= 1\n while (!clears(minimum)) {\n if (minimum === Number.MAX_SAFE_INTEGER) return null\n minimum += 1\n }\n return minimum\n}\n\n/**\n * Can the fixed control roster meet the policy even with zero errors?\n * Planning uses the admission rule's exact bounds and source-unit exclusions.\n * It accepts no judgments or authority and returns no admission report.\n */\nexport function planEvaluatorAudit(input: EvaluatorAuditPlanInput) {\n const parsed = capacitySchema.safeParse(input)\n if (!parsed.success)\n throw new ValidationError(`invalid evaluator audit plan: ${parsed.error.message}`)\n const { policy, controls } = parsed.data\n const { eligible } = eligibleControls(controls)\n const level = simultaneousIntervalConfidence(policy.confidence)\n const capacity = (expected: EvaluatorAuditObservation['expected'], limit: number) => {\n const independentUnits = new Set(\n eligible.filter((row) => row.expected === expected).map((row) => row.independentUnitId),\n ).size\n const bestPossibleUpperBound =\n independentUnits === 0 ? null : zeroErrorUpperBound(independentUnits, level)\n const minimumIndependentUnits = minimumAuditUnits(limit, level)\n return {\n independentUnits,\n bestPossibleUpperBound,\n limit,\n minimumIndependentUnits,\n additionalIndependentUnits:\n minimumIndependentUnits === null\n ? null\n : Math.max(0, minimumIndependentUnits - independentUnits),\n }\n }\n const falseAcceptance = capacity('reject', policy.maxFalseAcceptanceRate)\n const falseRejection = capacity('accept', policy.maxFalseRejectionRate)\n const sufficient = [falseAcceptance, falseRejection].every(\n (rate) => rate.bestPossibleUpperBound !== null && rate.bestPossibleUpperBound <= rate.limit,\n )\n return { sufficient, falseAcceptance, falseRejection }\n}\n\nexport type EvaluatorAuditPlan = ReturnType<typeof planEvaluatorAudit>\n\n/**\n * Audit frozen judgments using independent source units and exact binomial bounds.\n * A unit fails a class when any control in that class is misjudged.\n * The execution owner enforces auditor separation, fresh sampling, and evidence authenticity.\n */\nexport function auditEvaluator(input: EvaluatorAuditInput): EvaluatorAdmissionReport {\n const parsed = inputSchema.safeParse(input)\n if (!parsed.success) throw new ValidationError(`invalid evaluator audit: ${parsed.error.message}`)\n const audit = parsed.data\n if (audit.authority.evaluatorAuthorId === audit.authority.auditorId) {\n throw new ValidationError('evaluator admission requires a separate declared audit authority')\n }\n const { eligible, exclusions } = eligibleControls(audit.observations)\n const intervalConfidence = simultaneousIntervalConfidence(audit.policy.confidence)\n const falseAcceptance = errorRate(\n eligible,\n 'reject',\n audit.policy.maxFalseAcceptanceRate,\n intervalConfidence,\n )\n const falseRejection = errorRate(\n eligible,\n 'accept',\n audit.policy.maxFalseRejectionRate,\n intervalConfidence,\n )\n const rates = [falseAcceptance, falseRejection]\n const verdict = rates.some((rate) => rate.verdict === 'fail')\n ? 'reject'\n : rates.every((rate) => rate.verdict === 'pass')\n ? 'admit'\n : 'inconclusive'\n const reasons: string[] = []\n for (const [name, rate] of [\n ['false acceptance', falseAcceptance],\n ['false rejection', falseRejection],\n ] as const) {\n if (rate.independentUnits === 0) reasons.push(`${name}: no eligible independent units`)\n else if (rate.unknownCases > 0)\n reasons.push(`${name}: ${rate.unknownCases} judgments are unknown`)\n if (rate.verdict === 'fail') reasons.push(`${name}: lower error bound exceeds ${rate.limit}`)\n else if (rate.verdict === 'inconclusive' && rate.interval)\n reasons.push(`${name}: upper error bound does not establish the required limit`)\n }\n if (verdict === 'admit')\n reasons.push(\n 'both error bounds meet the registered limits, including the worst case for unknown judgments',\n )\n const body: Omit<EvaluatorAdmissionReport, 'reportDigest'> = {\n evaluatorDigest: audit.evaluatorDigest as LedgerHash,\n policyDigest: hashCanonical(audit.policy),\n inputDigest: hashCanonical(audit),\n population: audit.population,\n samplingFrame: audit.samplingFrame,\n authority: audit.authority,\n policy: audit.policy,\n confidence: audit.policy.confidence,\n intervalConfidence,\n verdict,\n reasons,\n observations: audit.observations,\n coverage: {\n cases: audit.observations.length,\n independentUnits: new Set(audit.observations.map((row) => row.independentUnitId)).size,\n eligibleCases: eligible.length,\n eligibleIndependentUnits: new Set(eligible.map((row) => row.independentUnitId)).size,\n excludedCases: exclusions.length,\n unknownCases: eligible.filter((row) => row.observed === 'unknown').length,\n },\n exclusions,\n falseAcceptance,\n falseRejection,\n }\n return { ...body, reportDigest: hashCanonical(body) }\n}\n\nconst probabilityThresholdsSchema = z\n .object({\n rejectAtOrBelow: z.number().finite().min(0).max(1),\n acceptAtOrAbove: z.number().finite().min(0).max(1),\n })\n .strict()\n .refine((value) => value.rejectAtOrBelow < value.acceptAtOrAbove, {\n message: 'rejection and acceptance thresholds must not overlap',\n })\nconst probabilityObservationSchema = evaluatorAuditObservationSchema\n .omit({ observed: true })\n .extend({ acceptProbability: z.number().finite().min(0).max(1).nullable() })\n .strict()\nconst probabilityAuditSchema = inputSchema.extend({\n thresholds: probabilityThresholdsSchema,\n observations: z.array(probabilityObservationSchema),\n})\n\n/** A frozen caller-owned rule over P(accept), not the provider's entropy/confidence statistic. */\nexport type ProbabilityPolicyAuditInput = z.infer<typeof probabilityAuditSchema>\n\nexport interface ProbabilityPolicyAuditReport extends EvaluatorAdmissionReport {\n probabilityPolicy: {\n sourceEvaluatorDigest: LedgerHash\n thresholds: ProbabilityPolicyAuditInput['thresholds']\n /** Retain probabilities by observation id so the reported mapping can be reproduced. */\n observations: Array<{ id: string; acceptProbability: number | null }>\n }\n}\n\n/**\n * Audit a fixed probability-to-decision rule with the existing independent-unit error bounds.\n * No threshold search, model calls, promotion, or assumption of calibrated probabilities.\n * Null scores and the open interval between thresholds remain unknown, never correct by default.\n */\nexport function auditProbabilityPolicy(\n input: ProbabilityPolicyAuditInput,\n): ProbabilityPolicyAuditReport {\n const parsed = probabilityAuditSchema.safeParse(input)\n if (!parsed.success) {\n throw new ValidationError(`invalid probability policy audit: ${parsed.error.message}`)\n }\n const { thresholds, observations, ...source } = parsed.data\n observations.sort((a, b) => compareCodeUnits(a.id, b.id))\n const probabilityPolicy = {\n sourceEvaluatorDigest: source.evaluatorDigest as LedgerHash,\n thresholds,\n observations: observations.map(({ id, acceptProbability }) => ({ id, acceptProbability })),\n }\n const audit = auditEvaluator({\n ...source,\n evaluatorDigest: hashCanonical({\n kind: 'probability-policy-v1',\n sourceEvaluatorDigest: source.evaluatorDigest,\n thresholds,\n }),\n observations: observations.map(({ acceptProbability, ...observation }) => ({\n ...observation,\n observed:\n acceptProbability === null\n ? 'unknown'\n : acceptProbability >= thresholds.acceptAtOrAbove\n ? 'accept'\n : acceptProbability <= thresholds.rejectAtOrBelow\n ? 'reject'\n : 'unknown',\n })),\n })\n const { reportDigest: _baseDigest, ...baseReport } = audit\n const body = {\n ...baseReport,\n // Bind the actual probabilities too, including changes that select the same action.\n inputDigest: hashCanonical(parsed.data),\n probabilityPolicy,\n }\n return { ...body, reportDigest: hashCanonical(body) }\n}\n","/**\n * Judge-panel calibration: score a hand-graded gold set with every judge model\n * on a panel, under one weighted rubric, and measure each (judge × dimension)\n * against the human grades with `calibrateJudge`.\n *\n * The caller owns the domain: the rubric text and weights, the system prompt,\n * the gold items and the judge list. This module owns the mechanics every\n * product repeats — the rubric prompt, the JSON call with retries, the\n * sequential (item × judge) sweep, null-grade handling, and the per-cell\n * calibration — plus `gateJudgeCalibration`, the pass/warn/fail rule over the\n * resulting cells.\n *\n * Calls run one at a time. Subscription bridges serialise per subprocess, and\n * concurrent requests from a full panel get killed under load.\n *\n * A gold cell with a null or missing human grade is still scored (the judge's\n * score lands in `rawScores`, useful for inter-judge agreement) but never\n * enters that dimension's calibration.\n */\n\nimport {\n type CalibrationResult,\n type CandidateScore,\n calibrateJudge,\n type GoldenItem,\n} from '../judge-calibration'\nimport { withJudgeRetry } from '../judge-retry'\nimport { callLlmJson, type LlmClientOptions } from '../llm-client'\n\n/** One rubric dimension: the guide the judge scores against and its weight in the composite. */\nexport interface RubricDimensionGuide {\n weight: number\n guide: string\n}\n\nexport interface JudgeCalibrationGoldItem<D extends string> {\n id: string\n /** Text after `Scenario:` in the judge prompt. Defaults to `id`. */\n scenarioLabel?: string\n /** The input the candidate answered. */\n scenario: string\n /** The output the judges score. */\n candidateOutput: string\n /** Human grade per dimension in [0,1]. `null` (whole item or one dimension)\n * means not graded: the item is still judged but excluded from calibration. */\n humanGrade: Partial<Record<D, number | null>> | null\n}\n\nexport interface JudgePanelPrompt {\n /** The judge's system prompt. */\n system: string\n /** Line above the rubric. Default: score each dimension in [0,1]. */\n rubricHeading?: string\n /** Line above the candidate output. Default `Candidate output to score:`. */\n candidateHeading?: string\n /** Candidate output is cut to this many characters. Default 12000. */\n maxCandidateChars?: number\n /** Lines after the JSON-shape instruction. */\n closingLines?: readonly string[]\n}\n\nexport interface CalibrateJudgePanelInput<D extends string> {\n rubric: Readonly<Record<D, RubricDimensionGuide>>\n /** Dimensions to score, in prompt order. Defaults to the rubric's keys. */\n dimensions?: readonly D[]\n items: readonly JudgeCalibrationGoldItem<D>[]\n judges: readonly string[]\n /** Endpoint and credential for every judge call. */\n llm: LlmClientOptions\n prompt: JudgePanelPrompt\n /** Default 1200. */\n maxTokens?: number\n /** Per-attempt timeout. Default 300000. */\n timeoutMs?: number\n /** Attempts per (item × judge); every error is retried. Default 3. */\n maxAttempts?: number\n /** Progress lines (one per item and judge, then the metrics table). */\n log?: (line: string) => void\n}\n\n/** A judge's calibration on one dimension. `golden` and `scores` hold the same\n * items: the human-graded ones this judge scored. */\nexport interface JudgeDimensionCalibration {\n calibration: CalibrationResult\n golden: GoldenItem[]\n scores: CandidateScore[]\n}\n\n/** What one judge returned for one item: a score per dimension and its rationale. */\nexport type JudgePanelOutput<D extends string> = Partial<Record<D, number>> & { rationale?: string }\n\nexport interface JudgePanelCalibration<D extends string> {\n judges: string[]\n dimensions: D[]\n perJudge: Record<string, Record<D, JudgeDimensionCalibration>>\n /** Every score each judge returned, graded items or not, clamped to [0,1]. */\n rawScores: Record<string, Record<D, CandidateScore[]>>\n /** Parsed judge output per item; `null` when every attempt failed. */\n outputs: Record<string, Record<string, JudgePanelOutput<D> | null>>\n /** Item ids with no human grade, per dimension. */\n ungradedItems: Record<D, string[]>\n /** (judge × item) cells where every attempt failed. */\n failures: Array<{ judge: string; itemId: string; errors: string[] }>\n elapsedMs: number\n}\n\nconst DEFAULT_RUBRIC_HEADING =\n 'Rubric (score each dimension in [0,1]; 1 = perfectly satisfies the guide, 0 = fails):'\n\nfunction clampUnit(n: number): number {\n if (!Number.isFinite(n)) return 0\n if (n < 0) return 0\n if (n > 1) return 1\n return n\n}\n\nfunction humanScore<D extends string>(item: JudgeCalibrationGoldItem<D>, d: D): number | null {\n const v = item.humanGrade?.[d]\n return typeof v === 'number' && Number.isFinite(v) ? v : null\n}\n\nfunction shortModel(model: string): string {\n return (model.split('/').pop() ?? model).padEnd(28)\n}\n\nfunction judgeUserPrompt<D extends string>(\n input: CalibrateJudgePanelInput<D>,\n dimensions: readonly D[],\n item: JudgeCalibrationGoldItem<D>,\n): string {\n const rubricLines = dimensions\n .map((d) => `- ${d} (weight ${input.rubric[d].weight}): ${input.rubric[d].guide}`)\n .join('\\n')\n const jsonShape = `{${dimensions.map((d) => `\"${d}\":number`).join(',')},\"rationale\":string}`\n return [\n `Scenario: ${item.scenarioLabel ?? item.id}`,\n `Input: ${item.scenario}`,\n '',\n input.prompt.rubricHeading ?? DEFAULT_RUBRIC_HEADING,\n rubricLines,\n '',\n input.prompt.candidateHeading ?? 'Candidate output to score:',\n '---',\n item.candidateOutput.slice(0, input.prompt.maxCandidateChars ?? 12_000),\n '---',\n '',\n `Respond ONLY with a JSON object exactly of shape: ${jsonShape}.`,\n ...(input.prompt.closingLines ?? []),\n ].join('\\n')\n}\n\n/** Run every judge on every gold item and calibrate each (judge × dimension). */\nexport async function calibrateJudgePanel<D extends string>(\n input: CalibrateJudgePanelInput<D>,\n): Promise<JudgePanelCalibration<D>> {\n const dimensions = [...(input.dimensions ?? (Object.keys(input.rubric) as D[]))]\n const judges = [...input.judges]\n const log = input.log ?? (() => {})\n const perDim = <T>(make: () => T) =>\n Object.fromEntries(dimensions.map((d) => [d, make()])) as Record<D, T>\n\n const rawScores: JudgePanelCalibration<D>['rawScores'] = {}\n const outputs: JudgePanelCalibration<D>['outputs'] = {}\n const goldenByJudge: Record<string, Record<D, GoldenItem[]>> = {}\n const scoresByJudge: Record<string, Record<D, CandidateScore[]>> = {}\n for (const judge of judges) {\n rawScores[judge] = perDim(() => [] as CandidateScore[])\n outputs[judge] = {}\n goldenByJudge[judge] = perDim(() => [] as GoldenItem[])\n scoresByJudge[judge] = perDim(() => [] as CandidateScore[])\n }\n const ungradedItems = perDim(() => [] as string[])\n for (const item of input.items) {\n for (const d of dimensions) if (humanScore(item, d) === null) ungradedItems[d].push(item.id)\n }\n const failures: JudgePanelCalibration<D>['failures'] = []\n\n const startedAt = Date.now()\n for (let i = 0; i < input.items.length; i++) {\n const item = input.items[i] as JudgeCalibrationGoldItem<D>\n log(` [${(i + 1).toString().padStart(2)}/${input.items.length}] ${item.id}`)\n const userPrompt = judgeUserPrompt(input, dimensions, item)\n for (const judge of judges) {\n const outcome = await withJudgeRetry(\n async (_model, signal) =>\n (\n await callLlmJson<JudgePanelOutput<D>>(\n {\n model: judge,\n messages: [\n { role: 'system', content: input.prompt.system },\n { role: 'user', content: userPrompt },\n ],\n jsonMode: true,\n temperature: 0,\n maxTokens: input.maxTokens ?? 1200,\n timeoutMs: input.timeoutMs ?? 300_000,\n },\n { ...input.llm, signal },\n )\n ).value,\n {\n maxAttempts: input.maxAttempts ?? 3,\n timeoutMs: input.timeoutMs ?? 300_000,\n isRetryable: () => true,\n backoffMs: (attempt) => 2_000 * (attempt + 1),\n },\n )\n const out = outcome.succeeded ? outcome.value : null\n outputs[judge]![item.id] = out\n if (!out) {\n const errors = outcome.attemptErrors.map((e) => e.error)\n failures.push({ judge, itemId: item.id, errors })\n log(` ${shortModel(judge)} - FAILED (${errors.at(-1) ?? 'no attempt'})`)\n continue\n }\n let judged = 0\n let expected = 0\n let covered = 0\n for (const d of dimensions) {\n const score = clampUnit(Number((out as Record<string, unknown>)[d]))\n rawScores[judge]![d].push({ itemId: item.id, score })\n const human = humanScore(item, d)\n if (human === null) continue\n goldenByJudge[judge]![d].push({ itemId: item.id, humanScore: human })\n scoresByJudge[judge]![d].push({ itemId: item.id, score })\n const weight = input.rubric[d].weight\n judged += score * weight\n expected += human * weight\n covered += weight\n }\n const pct = (n: number) => `${(n * 100).toFixed(0)}%`\n log(\n covered > 0\n ? ` ${shortModel(judge)} judged=${pct(judged / covered)} expected=${pct(expected / covered)} delta=${pct((judged - expected) / covered)} cover=${pct(covered)}`\n : ` ${shortModel(judge)} judged (ungraded item)`,\n )\n }\n }\n const elapsedMs = Date.now() - startedAt\n\n const perJudge: JudgePanelCalibration<D>['perJudge'] = {}\n for (const judge of judges) {\n log(` ${judge}`)\n perJudge[judge] = {} as Record<D, JudgeDimensionCalibration>\n for (const d of dimensions) {\n const golden = goldenByJudge[judge]![d]\n const scores = scoresByJudge[judge]![d]\n const calibration = calibrateJudge(golden, scores)\n perJudge[judge]![d] = { calibration, golden, scores }\n log(\n ` ${d.padEnd(34)} n=${calibration.n.toString().padStart(2)} kappa=${calibration.kappa.toFixed(2)} r=${calibration.pearson.toFixed(2)} MAE=${calibration.mae.toFixed(3)}`,\n )\n }\n }\n\n return { judges, dimensions, perJudge, rawScores, outputs, ungradedItems, failures, elapsedMs }\n}\n\n/** Thresholds for `gateJudgeCalibration`. */\nexport interface JudgeCalibrationGateConfig {\n /** Pearson below this (and at or above `pearsonWarn`) warns. */\n pearsonFloor: number\n /** Pearson below this fails. */\n pearsonWarn: number\n /** MAE above this fails. */\n maeCeiling: number\n /** Cells with fewer graded items are reported as insufficient and never fail. */\n minSamples: number\n}\n\nexport type JudgeCalibrationCellVerdict = 'pass' | 'warn' | 'fail' | 'insufficient'\n\nexport interface JudgeCalibrationGateCell {\n judge: string\n dim: string\n n: number\n pearson: number\n mae: number\n verdict: JudgeCalibrationCellVerdict\n reasons: string[]\n}\n\nexport interface JudgeCalibrationGate {\n pass: boolean\n config: JudgeCalibrationGateConfig\n failCount: number\n warnCount: number\n insufficientCount: number\n cells: JudgeCalibrationGateCell[]\n}\n\n/** Pass/warn/fail every (judge × dimension) cell; the gate passes with zero fail cells. */\nexport function gateJudgeCalibration(\n perJudge: Record<string, Record<string, { calibration: CalibrationResult }>>,\n config: JudgeCalibrationGateConfig,\n): JudgeCalibrationGate {\n const cells: JudgeCalibrationGateCell[] = []\n for (const [judge, dims] of Object.entries(perJudge)) {\n for (const [dim, { calibration: cal }] of Object.entries(dims)) {\n const reasons: string[] = []\n let verdict: JudgeCalibrationCellVerdict = 'pass'\n if (cal.n < config.minSamples) {\n verdict = 'insufficient'\n reasons.push(`n=${cal.n} < minSamples=${config.minSamples}`)\n } else {\n if (Number.isFinite(cal.pearson) && cal.pearson < config.pearsonFloor) {\n if (cal.pearson < config.pearsonWarn) {\n verdict = 'fail'\n reasons.push(\n `pearson=${cal.pearson.toFixed(2)} < floor=${config.pearsonFloor.toFixed(2)} (below warn=${config.pearsonWarn.toFixed(2)})`,\n )\n } else {\n verdict = 'warn'\n reasons.push(\n `pearson=${cal.pearson.toFixed(2)} in warn band [${config.pearsonWarn.toFixed(2)}, ${config.pearsonFloor.toFixed(2)})`,\n )\n }\n }\n if (Number.isFinite(cal.mae) && cal.mae > config.maeCeiling) {\n verdict = 'fail'\n reasons.push(`mae=${cal.mae.toFixed(3)} > ceiling=${config.maeCeiling.toFixed(3)}`)\n }\n }\n cells.push({ judge, dim, n: cal.n, pearson: cal.pearson, mae: cal.mae, verdict, reasons })\n }\n }\n const count = (v: JudgeCalibrationCellVerdict) => cells.filter((c) => c.verdict === v).length\n const failCount = count('fail')\n return {\n pass: failCount === 0,\n config,\n failCount,\n warnCount: count('warn'),\n insufficientCount: count('insufficient'),\n cells,\n }\n}\n","/**\n * Plants — seeded known-wrong items that measure the grader, not the work.\n *\n * A grading run reports how the work scored. It cannot report whether the\n * grader would have noticed a wrong answer, because every item it saw was\n * authored in good faith. A plant closes that hole: an item authored wrong by\n * construction is mixed into the live set, graded by the same path as\n * everything else, and the share of plants the grader refused is the catch\n * rate.\n *\n * Measured motive: a sibling lab ran a deliverable gate that accepted any\n * non-empty submission. It produced six false certifications in seventeen\n * deliveries, and no agent lied — the gate never asked a question the format\n * could fail. A catch rate is the number that would have shown it on day one.\n *\n * This module composes existing primitives rather than adding parallel ones:\n *\n * - A plant IS a {@link GoldenItem} from `../judge-calibration`. Its\n * `humanScore` is the grade a working grader owes the item, so the same\n * array feeds `calibrateJudge` unchanged.\n * - The grader's output is `CandidateScore[]`, the array `calibrateJudge` and\n * `snapshotFromSentinelSet` already consume.\n * - \"Caught\" is `snapshotFromSentinelSet`'s join with the labels inverted:\n * the grade lands on the side of `acceptThreshold` the seed demands.\n * - The manifest is sealed with `hashCanonical` from `../ledger-core/canonical`,\n * the digest the sealed-experiment path uses, so the answer key cannot be\n * revised once the results are in.\n *\n * Authoring the wrong item is the step before all of that, and it is where the\n * measurement silently breaks. {@link plantByPerturbation} takes a claim a\n * grader verified and alters exactly one load-bearing value in its evidence,\n * so the grader is asked a question it must fail. Hand-rolled perturbation\n * bumps a number that is part of an identity — `python3`, `file42.txt`, `1.5`,\n * `utf-8` — and the check stops EXECUTING; the plant then measures the\n * environment rather than the grader. {@link perturbEvidence} refuses those\n * digit runs by construction.\n *\n * Blindness has two halves, and this module owns one. It never puts a plant\n * flag on a graded item: `seedPlants` returns the mixed set and a manifest,\n * and only the manifest knows which ids are seeded. Keeping the manifest out\n * of the graded workspace and publishing its `seal` before grading is the\n * caller's half; {@link catchRate} refuses a manifest whose contents no longer\n * match its seal.\n *\n * Refusals, because a catch rate that cannot refuse is not a measurement:\n *\n * - a seeded id with no result makes the report `incomplete`, never a rate\n * over the results that did come back;\n * - zero seeded plants makes it `not_evaluated`, never 1.0;\n * - a result for an id the manifest never handed out is refused outright.\n */\n\nimport { CaptureIntegrityError, ValidationError } from '../errors'\nimport type { GoldenItem } from '../judge-calibration'\nimport { hashCanonical, type LedgerHash } from '../ledger-core/canonical'\nimport { mulberry32 } from '../statistics/random'\n\n/**\n * How a plant item was authored wrong. The class is reported separately in\n * {@link CatchRateReport.byKind} because a grader is routinely sharp on one\n * and blind to another.\n */\nexport type PlantKind =\n /** A load-bearing value is altered: a number off by one, a comparison flipped. */\n | 'wrong-value'\n /** The item carries its own check, and that check passes without testing the claim. */\n | 'self-certifying'\n /** The check names an input that does not exist, so it cannot run at all. */\n | 'unreachable-input'\n /** A copy of an item already in the set, which is owed a duplicate flag rather than a second grade. */\n | 'duplicate'\n\nconst PLANT_KINDS: readonly PlantKind[] = [\n 'wrong-value',\n 'self-certifying',\n 'unreachable-input',\n 'duplicate',\n]\n\n/** What a working grader owes a seeded item. */\nexport type PlantExpectation = 'reject' | 'accept'\n\nconst PLANT_EXPECTATIONS: readonly PlantExpectation[] = ['reject', 'accept']\n\n/** The label boundary a plant record is checked against at definition time. */\nconst RECORD_LABEL_BOUNDARY = 0.5\n\nexport interface Plant {\n /** Name of the plant record. Reported in `missedIds` and `missingIds`. */\n id: string\n kind: PlantKind\n /** The seeded item, indistinguishable from a real one once mixed. */\n item: GoldenItem\n /** The verdict a working grader owes this item. */\n expectedVerdict: PlantExpectation\n}\n\n/**\n * Build one plant record and refuse an incoherent one.\n *\n * The refusal that matters is the last: a record whose `expectedVerdict`\n * disagrees with `item.humanScore` inverts the measurement silently, because\n * the same item then reads as wrong here and as correct to every calibration\n * instrument that joins on the id.\n *\n * `item` is copied field by field so a later mutation of the caller's object\n * cannot change what the manifest sealed, and `group` is dropped when it is\n * absent so the record always has a canonical JSON form.\n */\nexport function definePlant(input: {\n id: string\n kind: PlantKind\n item: GoldenItem\n expectedVerdict: PlantExpectation\n}): Plant {\n const { id, kind, item, expectedVerdict } = input\n if (typeof id !== 'string' || id.trim() === '') {\n throw new ValidationError('definePlant: id must be a non-empty string')\n }\n if (!PLANT_KINDS.includes(kind)) {\n throw new ValidationError(\n `definePlant: plant \"${id}\" has kind ${JSON.stringify(kind)}; expected one of ${PLANT_KINDS.join(', ')}`,\n )\n }\n if (!PLANT_EXPECTATIONS.includes(expectedVerdict)) {\n throw new ValidationError(\n `definePlant: plant \"${id}\" has expectedVerdict ${JSON.stringify(expectedVerdict)}; expected one of ${PLANT_EXPECTATIONS.join(', ')}`,\n )\n }\n if (typeof item.itemId !== 'string' || item.itemId.trim() === '') {\n throw new ValidationError(`definePlant: plant \"${id}\" has an empty item.itemId`)\n }\n if (!Number.isFinite(item.humanScore) || item.humanScore < 0 || item.humanScore > 1) {\n throw new ValidationError(\n `definePlant: plant \"${id}\" has humanScore ${item.humanScore}; expected a finite number in [0, 1]`,\n )\n }\n if (item.group !== undefined && typeof item.group !== 'string') {\n throw new ValidationError(`definePlant: plant \"${id}\" has a non-string item.group`)\n }\n if (item.humanScore === RECORD_LABEL_BOUNDARY) {\n throw new ValidationError(\n `definePlant: plant \"${id}\" has humanScore ${RECORD_LABEL_BOUNDARY}, which states neither a rejection nor an acceptance`,\n )\n }\n const labelSays: PlantExpectation = item.humanScore < RECORD_LABEL_BOUNDARY ? 'reject' : 'accept'\n if (labelSays !== expectedVerdict) {\n throw new ValidationError(\n `definePlant: plant \"${id}\" expects the grader to ${expectedVerdict} it, but humanScore ${item.humanScore} says ${labelSays}`,\n )\n }\n return {\n id,\n kind,\n item: {\n itemId: item.itemId,\n humanScore: item.humanScore,\n ...(item.group === undefined ? {} : { group: item.group }),\n },\n expectedVerdict,\n }\n}\n\n/**\n * A claim's executable evidence: the command a grader runs and the output it\n * must produce.\n */\nexport interface PlantEvidence {\n /** The command a grader runs to test the claim. */\n check?: string\n /** The output that command must produce for the claim to stand. */\n expect?: string\n}\n\n/** Which evidence field {@link perturbEvidence} altered. */\nexport type PerturbedField = 'check' | 'expect'\n\n/** How {@link perturbEvidence} altered it. */\nexport type PerturbationKind = 'number-off-by-one' | 'comparison-flipped'\n\nexport interface EvidencePerturbation {\n /** The evidence with exactly one value altered. */\n evidence: PlantEvidence\n /** Which field changed. */\n field: PerturbedField\n /** How it changed. */\n how: PerturbationKind\n /**\n * The exact substring that was replaced. A comparison token carries its\n * surrounding spaces, because the spaces are what make ` -ge ` a comparison\n * and not part of a word.\n */\n original: string\n /** What replaced it. */\n perturbed: string\n}\n\n/**\n * Characters that make a digit run part of something larger than a number.\n *\n * A run that touches one of these is an identity — `python3`, `file42.txt`,\n * `1.5`, `utf-8` — and bumping it renames a program, a file, a version, or an\n * encoding instead of falsifying the claim. The check then stops EXECUTING,\n * and a plant that cannot run measures the environment rather than the grader:\n * it reads as caught, for a reason that has nothing to do with the seeded\n * defect.\n */\nconst NUMBER_GLUE = /[A-Za-z0-9_./-]/\n\n/**\n * Comparison tokens that mean one thing only, each with its inversion.\n *\n * A bare `>` or `<` is absent on purpose: in a shell check it is a\n * redirection, so flipping it rewrites where output goes rather than what the\n * test asks, and the check stops testing the claim.\n */\nconst COMPARISON_FLIPS: readonly (readonly [string, string])[] = [\n [' -ge ', ' -lt '],\n [' -gt ', ' -le '],\n [' -le ', ' -gt '],\n [' -lt ', ' -ge '],\n [' -eq ', ' -ne '],\n [' -ne ', ' -eq '],\n ['>=', '<'],\n ['<=', '>'],\n ['==', '!='],\n ['!=', '=='],\n]\n\ninterface Span {\n start: number\n end: number\n}\n\n/**\n * The last digit run in `text` that is a number and nothing else, or null.\n *\n * The last is taken because a measured value trails its label — `count=42`,\n * `n>=5 OK cells=8` — and because the choice has to be deterministic: the same\n * claim must always yield the same plant, or two runs of the same authoring\n * step seed two different answer keys for one item.\n */\nfunction lastStandaloneNumber(text: string): Span | null {\n const digits = /\\d+/g\n let found: Span | null = null\n let match = digits.exec(text)\n while (match !== null) {\n const start = match.index\n const end = start + match[0].length\n // charAt returns '' outside the string, and NUMBER_GLUE never matches ''.\n if (!NUMBER_GLUE.test(text.charAt(start - 1)) && !NUMBER_GLUE.test(text.charAt(end))) {\n found = { start, end }\n }\n match = digits.exec(text)\n }\n return found\n}\n\n/**\n * The first flippable comparison in `text`, or null.\n *\n * Any single flip inverts the test wherever it sits, so unlike the number rule\n * there is no safety ordering among the matches. The first is taken so the\n * result is fixed by the head of the command and does not move when a later\n * comparison is added.\n */\nfunction firstComparison(text: string): { span: Span; flipped: string } | null {\n for (let index = 0; index < text.length; index += 1) {\n for (const [token, flipped] of COMPARISON_FLIPS) {\n if (text.startsWith(token, index)) {\n return { span: { start: index, end: index + token.length }, flipped }\n }\n }\n }\n return null\n}\n\nfunction replaceSpan(text: string, span: Span, value: string): string {\n return text.slice(0, span.start) + value + text.slice(span.end)\n}\n\n/**\n * Rebuild the evidence with one field replaced. An absent field is dropped\n * rather than set to undefined, so the record always has a canonical JSON form.\n */\nfunction withField(\n check: string | undefined,\n expect: string | undefined,\n field: PerturbedField,\n value: string,\n): PlantEvidence {\n const nextCheck = field === 'check' ? value : check\n const nextExpect = field === 'expect' ? value : expect\n return {\n ...(nextCheck === undefined ? {} : { check: nextCheck }),\n ...(nextExpect === undefined ? {} : { expect: nextExpect }),\n }\n}\n\nfunction offByOne(\n check: string | undefined,\n expect: string | undefined,\n field: PerturbedField,\n text: string,\n span: Span,\n): EvidencePerturbation {\n const original = text.slice(span.start, span.end)\n const perturbed = (BigInt(original) + 1n).toString()\n return {\n evidence: withField(check, expect, field, replaceSpan(text, span, perturbed)),\n field,\n how: 'number-off-by-one',\n original,\n perturbed,\n }\n}\n\n/**\n * Derive a known-wrong version of a claim's evidence by altering exactly one\n * value, or return null when no value can be altered safely.\n *\n * Exactly one value changes. A perturbation that moves two does not name the\n * defect it seeded, so a grader that catches it says nothing about which defect\n * the grader can see.\n *\n * The preference order IS the safety order:\n *\n * 1. the last standalone number in `expect` — it falsifies the claim while the\n * command still runs exactly as it did;\n * 2. a flipped comparison in `check` — it inverts a test that was passing;\n * 3. the last standalone number in `check` — last because a number in a command\n * can name an input (a port, a width, a version) rather than a threshold,\n * and renaming an input breaks execution, not the claim.\n *\n * \"Standalone\" excludes a digit run glued to a word, a dot, a slash, or a\n * hyphen: `python3`, `file42.txt`, `1.5`, `utf-8`. That exclusion is why this\n * helper exists. Hand-rolled perturbation bumps one of those, the check stops\n * executing, and the plant measures the environment instead of the grader.\n *\n * A number is bumped with BigInt, so a value wider than\n * `Number.MAX_SAFE_INTEGER` moves by exactly one. Bumped as a `number` it\n * rounds back to itself, and the plant is then a correct claim the grader is\n * right to verify.\n */\nexport function perturbEvidence(evidence: PlantEvidence): EvidencePerturbation | null {\n const check = typeof evidence.check === 'string' ? evidence.check : undefined\n const expect = typeof evidence.expect === 'string' ? evidence.expect : undefined\n\n if (expect !== undefined) {\n const span = lastStandaloneNumber(expect)\n if (span !== null) return offByOne(check, expect, 'expect', expect, span)\n }\n if (check !== undefined) {\n const comparison = firstComparison(check)\n if (comparison !== null) {\n return {\n evidence: withField(\n check,\n expect,\n 'check',\n replaceSpan(check, comparison.span, comparison.flipped),\n ),\n field: 'check',\n how: 'comparison-flipped',\n original: check.slice(comparison.span.start, comparison.span.end),\n perturbed: comparison.flipped,\n }\n }\n const span = lastStandaloneNumber(check)\n if (span !== null) return offByOne(check, expect, 'check', check, span)\n }\n return null\n}\n\nexport interface PerturbedPlant {\n plant: Plant\n /** The perturbed evidence to write into the item the grader is handed. */\n evidence: PlantEvidence\n field: PerturbedField\n how: PerturbationKind\n original: string\n perturbed: string\n}\n\n/**\n * Derive a reject-direction plant from a claim a grader verified, by perturbing\n * one value.\n *\n * {@link definePlant} takes a {@link GoldenItem} and never authors a wrong item\n * from a right one, so until now every caller hand-rolled the perturbation.\n * This is that step, done once and the same way every time: the claim's\n * evidence is altered by {@link perturbEvidence}, the result is a `wrong-value`\n * plant the grader owes a `reject`, and the record itself is built by\n * `definePlant` so every refusal there still applies — in particular the one\n * that catches an `expectedVerdict` its `humanScore` contradicts.\n *\n * Returns null when nothing in the evidence can be perturbed. That is not a\n * failure: a claim with no executable evidence cannot be made wrong in a way a\n * grader could execute, and seeding it would measure prose.\n *\n * Refuses an empty `id` or `itemId`. Both name the record — one in the manifest\n * and in `missedIds`, the other in the join with the results — and a miss\n * nobody can look up is not a measurement.\n */\nexport function plantByPerturbation(input: {\n id: string\n itemId: string\n evidence: PlantEvidence\n /** Score for the perturbed item. Must sit below the run's accept threshold. Default 0. */\n humanScore?: number\n group?: string\n}): PerturbedPlant | null {\n const { id, itemId, evidence, humanScore = 0, group } = input\n if (typeof id !== 'string' || id.trim() === '') {\n throw new ValidationError('plantByPerturbation: id must be a non-empty string')\n }\n if (typeof itemId !== 'string' || itemId.trim() === '') {\n throw new ValidationError(`plantByPerturbation: plant \"${id}\" has an empty itemId`)\n }\n const perturbation = perturbEvidence(evidence)\n if (perturbation === null) return null\n const plant = definePlant({\n id,\n kind: 'wrong-value',\n item: { itemId, humanScore, ...(group === undefined ? {} : { group }) },\n expectedVerdict: 'reject',\n })\n return {\n plant,\n evidence: perturbation.evidence,\n field: perturbation.field,\n how: perturbation.how,\n original: perturbation.original,\n perturbed: perturbation.perturbed,\n }\n}\n\nexport interface PlantManifest {\n /**\n * Digest over the seeded order, the plants, and the threshold. Publish it\n * before the grading run: a manifest edited afterwards to match the results\n * no longer matches its seal, and {@link catchRate} refuses it.\n */\n seal: LedgerHash\n /** The seed that fixed the mix order. */\n seed: number\n /** The grade at or above which the graded policy's own gate accepts an item. */\n acceptThreshold: number\n /** Every item id in the seeded set, in the order handed out. */\n itemIds: string[]\n /** The seeded plants. This is the answer key; keep it out of the graded workspace. */\n plants: Plant[]\n}\n\nexport interface SeededGradingSet {\n /**\n * The mixed set in seeded order. Operator-side: it still carries every\n * item's `humanScore`, so hand the graded policy the payload each `itemId`\n * names, never this array.\n */\n items: GoldenItem[]\n manifest: PlantManifest\n}\n\nexport interface SeedPlantsOptions {\n /**\n * Fixes the mix order. The same dataset, plants, threshold, and seed always\n * produce the same seeded order and the same seal.\n */\n seed?: number\n /**\n * The grade at or above which the graded policy's own gate accepts an item.\n * Supply the threshold your gate uses; the default suits a judge scoring in\n * [0, 1] with a pass at the midpoint.\n */\n acceptThreshold?: number\n}\n\n/**\n * Mix plants into a grading set and seal which items they are.\n *\n * Refusals: a duplicate id anywhere in the mixed set (the join is by id, so a\n * repeat makes one of the two unscoreable), a plant whose item id collides\n * with a dataset item (it would shadow real work and grade it as a plant), a\n * dataset item with no usable label, and a plant whose expectation the run's\n * `acceptThreshold` contradicts.\n */\nexport function seedPlants(\n dataset: readonly GoldenItem[],\n plants: readonly Plant[],\n options: SeedPlantsOptions = {},\n): SeededGradingSet {\n const seed = options.seed ?? 7\n const acceptThreshold = options.acceptThreshold ?? 0.5\n if (!Number.isFinite(seed)) {\n throw new ValidationError(`seedPlants: seed must be a finite number, got ${seed}`)\n }\n if (!Number.isFinite(acceptThreshold) || acceptThreshold <= 0 || acceptThreshold > 1) {\n throw new ValidationError(\n `seedPlants: acceptThreshold must be a finite number in (0, 1], got ${acceptThreshold}`,\n )\n }\n\n const datasetItems: GoldenItem[] = []\n const seen = new Set<string>()\n for (const item of dataset) {\n if (typeof item.itemId !== 'string' || item.itemId.trim() === '') {\n throw new ValidationError('seedPlants: a dataset item has an empty itemId')\n }\n if (!Number.isFinite(item.humanScore)) {\n throw new ValidationError(\n `seedPlants: dataset item \"${item.itemId}\" has a non-finite humanScore`,\n )\n }\n if (seen.has(item.itemId)) {\n throw new ValidationError(`seedPlants: duplicate dataset itemId \"${item.itemId}\"`)\n }\n seen.add(item.itemId)\n datasetItems.push({\n itemId: item.itemId,\n humanScore: item.humanScore,\n ...(item.group === undefined ? {} : { group: item.group }),\n })\n }\n\n const sealedPlants: Plant[] = []\n const plantIds = new Set<string>()\n for (const plant of plants) {\n const record = definePlant(plant)\n if (plantIds.has(record.id)) {\n throw new ValidationError(`seedPlants: duplicate plant id \"${record.id}\"`)\n }\n if (seen.has(record.item.itemId)) {\n throw new ValidationError(\n `seedPlants: plant \"${record.id}\" reuses itemId \"${record.item.itemId}\", which is already in the set`,\n )\n }\n const thresholdSays: PlantExpectation =\n record.item.humanScore >= acceptThreshold ? 'accept' : 'reject'\n if (thresholdSays !== record.expectedVerdict) {\n throw new ValidationError(\n `seedPlants: plant \"${record.id}\" expects the grader to ${record.expectedVerdict} it, but humanScore ${record.item.humanScore} is on the ${thresholdSays} side of acceptThreshold ${acceptThreshold}`,\n )\n }\n plantIds.add(record.id)\n seen.add(record.item.itemId)\n sealedPlants.push(record)\n }\n\n const items = shuffled(\n [...datasetItems, ...sealedPlants.map((plant) => plant.item)],\n mulberry32(seed),\n )\n const itemIds = items.map((item) => item.itemId)\n const manifest: PlantManifest = {\n seal: sealManifest({ seed, acceptThreshold, itemIds, plants: sealedPlants }),\n seed,\n acceptThreshold,\n itemIds,\n plants: sealedPlants,\n }\n return { items, manifest }\n}\n\n/**\n * Order by one independent uniform key per item, which is a uniform\n * permutation and a pure function of the seed. A comparator that returns a\n * fresh random sign instead is neither: it is not a consistent ordering, so\n * the permutation it produces is biased and depends on the sort algorithm.\n */\nfunction shuffled<T>(items: readonly T[], random: () => number): T[] {\n return items\n .map((item) => ({ item, key: random() }))\n .sort((left, right) => left.key - right.key)\n .map((entry) => entry.item)\n}\n\nfunction sealManifest(contents: Omit<PlantManifest, 'seal'>): LedgerHash {\n return hashCanonical({\n scheme: 'agent-eval.plant-manifest.v1',\n seed: contents.seed,\n acceptThreshold: contents.acceptThreshold,\n itemIds: contents.itemIds,\n plants: contents.plants,\n })\n}\n\n/**\n * One grader outcome for one item. `score: null` says the grader ran and\n * declined to decide — the check never tested the item's defect. Any\n * `CandidateScore` from a judge run is already a valid outcome.\n */\nexport interface PlantOutcome {\n itemId: string\n score: number | null\n}\n\n/**\n * `evaluated` — a rate stands. `incomplete` — a seeded id had no result.\n * `not_evaluated` — nothing was seeded, or nothing seeded was decided.\n */\nexport type CatchRateStatus = 'evaluated' | 'incomplete' | 'not_evaluated'\n\nexport interface PlantKindCounts {\n seeded: number\n caught: number\n missed: number\n indecisive: number\n /** caught / (caught + missed), or null when the report is not `evaluated`. */\n rate: number | null\n}\n\n/**\n * How the same grader treated the unseeded items of the same set. No labels\n * are needed to read it: a grader that refuses everything scores `rate` 1.0\n * on reject-plants, and a `rejectionRate` of 1.0 here is what separates that\n * reflex from discrimination.\n */\nexport interface UnseededRejection {\n n: number\n decided: number\n rejected: number\n /** rejected / decided, or null when nothing unseeded was decided. */\n rejectionRate: number | null\n}\n\nexport interface CatchRateReport {\n status: CatchRateStatus\n /** Why the status is not `evaluated`. Absent when it is. */\n reason?: string\n seeded: number\n caught: number\n missed: number\n /**\n * The grader returned a result and declined to decide. Counted apart: it\n * enters neither side of `rate`.\n */\n indecisive: number\n /** caught / (caught + missed), or null unless the status is `evaluated`. */\n rate: number | null\n /** One entry per kind actually seeded. A kind nobody seeded is absent, never zero. */\n byKind: Partial<Record<PlantKind, PlantKindCounts>>\n /** Plant ids the grader graded as the seed says it must not. */\n missedIds: string[]\n /** Plant ids with no result at all — the reason a status is `incomplete`. */\n missingIds: string[]\n unseeded: UnseededRejection\n}\n\n/**\n * Score a grading run against its sealed manifest.\n *\n * Refusals: a manifest whose contents no longer match its seal, a result for\n * an id the manifest never handed out, and a repeated result id. Each says\n * the results and the manifest describe different runs, and a rate computed\n * across two runs is a fabrication.\n */\nexport function catchRate(\n results: readonly PlantOutcome[],\n manifest: PlantManifest,\n): CatchRateReport {\n const expectedSeal = sealManifest({\n seed: manifest.seed,\n acceptThreshold: manifest.acceptThreshold,\n itemIds: manifest.itemIds,\n plants: manifest.plants,\n })\n if (expectedSeal !== manifest.seal) {\n throw new CaptureIntegrityError(\n `catchRate: manifest contents hash to ${expectedSeal} but the manifest carries seal ${manifest.seal} — the plant set changed after it was sealed`,\n )\n }\n\n const handedOut = new Set(manifest.itemIds)\n const scoreByItemId = new Map<string, number | null>()\n for (const result of results) {\n if (!handedOut.has(result.itemId)) {\n throw new ValidationError(\n `catchRate: result for \"${result.itemId}\", which this manifest never handed out`,\n )\n }\n if (scoreByItemId.has(result.itemId)) {\n throw new ValidationError(`catchRate: duplicate result for \"${result.itemId}\"`)\n }\n if (result.score !== null && !Number.isFinite(result.score)) {\n throw new ValidationError(\n `catchRate: result for \"${result.itemId}\" has score ${result.score}; expected a finite number or null`,\n )\n }\n scoreByItemId.set(result.itemId, result.score)\n }\n\n const byKind: Partial<Record<PlantKind, PlantKindCounts>> = {}\n const missedIds: string[] = []\n const missingIds: string[] = []\n let caught = 0\n let missed = 0\n let indecisive = 0\n\n for (const plant of manifest.plants) {\n let counts = byKind[plant.kind]\n if (counts === undefined) {\n counts = { seeded: 0, caught: 0, missed: 0, indecisive: 0, rate: null }\n byKind[plant.kind] = counts\n }\n counts.seeded += 1\n if (!scoreByItemId.has(plant.item.itemId)) {\n missingIds.push(plant.id)\n continue\n }\n const score = scoreByItemId.get(plant.item.itemId) ?? null\n if (score === null) {\n indecisive += 1\n counts.indecisive += 1\n continue\n }\n const graderSaid: PlantExpectation = score >= manifest.acceptThreshold ? 'accept' : 'reject'\n if (graderSaid === plant.expectedVerdict) {\n caught += 1\n counts.caught += 1\n } else {\n missed += 1\n counts.missed += 1\n missedIds.push(plant.id)\n }\n }\n\n const seeded = manifest.plants.length\n const decided = caught + missed\n const report: CatchRateReport = {\n status: 'evaluated',\n seeded,\n caught,\n missed,\n indecisive,\n rate: null,\n byKind,\n missedIds,\n missingIds,\n unseeded: unseededRejection(manifest, scoreByItemId),\n }\n\n if (seeded === 0) {\n return {\n ...report,\n status: 'not_evaluated',\n reason: 'no plant was seeded, so the grader was never asked a question it could fail',\n }\n }\n if (missingIds.length > 0) {\n return {\n ...report,\n status: 'incomplete',\n reason: `${missingIds.length} of ${seeded} seeded plants have no result: ${missingIds.join(', ')}`,\n }\n }\n if (decided === 0) {\n return {\n ...report,\n status: 'not_evaluated',\n reason: `all ${seeded} seeded plants are indecisive: no check tested the seeded defect`,\n }\n }\n\n for (const counts of Object.values(byKind)) {\n const kindDecided = counts.caught + counts.missed\n counts.rate = kindDecided === 0 ? null : counts.caught / kindDecided\n }\n report.rate = caught / decided\n return report\n}\n\nfunction unseededRejection(\n manifest: PlantManifest,\n scoreByItemId: ReadonlyMap<string, number | null>,\n): UnseededRejection {\n const plantItemIds = new Set(manifest.plants.map((plant) => plant.item.itemId))\n let n = 0\n let decided = 0\n let rejected = 0\n for (const itemId of manifest.itemIds) {\n if (plantItemIds.has(itemId)) continue\n n += 1\n const score = scoreByItemId.get(itemId)\n if (score === undefined || score === null) continue\n decided += 1\n if (score < manifest.acceptThreshold) rejected += 1\n }\n return { n, decided, rejected, rejectionRate: decided === 0 ? null : rejected / decided }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAyEA,eAAsB,iBACpB,YACA,cACA,aACA,oBACA,UAAmC,CAAC,GACH;CACjC,MAAM,YAAY,QAAQ,aAAa;CACvC,MAAM,aAAa,QAAQ,uBAAuB;CAClD,MAAM,OAAO,QAAQ;CACrB,2BAA2B,WAAW,YAAY,IAAI;CACtD,2BACE,YAAY,KAAK,WAAW,OAAO,EAAE,GACrC,aACF;CACA,2BAA2B,oBAAoB,gBAAgB;CAC/D,MAAM,SAAS,QAAQ,mBAAmB;CAC1C,IAAI,SAAS,KAAK,OAAO,MAAM,MAAM,GACnC,MAAM,IAAI,MAAM,qCAAqC;CAEvD,MAAM,aAAa,YAAY,KAAK,YAAY;EAC9C,GAAG;EACH,SAAS,OAAO,WAAW,mBAAmB,OAAO,EAAE;CACzD,EAAE;CACF,MAAM,cAAc,CAAC,GAAG,kBAAkB;CAC1C,MAAM,OAAO,MAAM,WAAW,SAAS;CACvC,2BACE,KAAK,KAAK,QAAQ,IAAI,KAAK,GAC3B,OACF;CACA,MAAM,WAAW,MAAM,aAAa,KAAK,QAAQ,aAAa;CAC9D,MAAM,gCAAgB,IAAI,IAAiC;CAC3D,KAAK,MAAM,KAAK,UAAU;EACxB,MAAM,MAAM,cAAc,IAAI,EAAE,KAAK,KAAK,CAAC;EAC3C,IAAI,KAAK,CAAC;EACV,cAAc,IAAI,EAAE,OAAO,GAAG;CAChC;CAEA,MAAM,QAA0F,CAAC;CACjG,KAAK,MAAM,MAAM,YACf,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;CACnB,MAAM,eAAe,IAAI,IAAI,SAAS,OAAO,KAAK,UAAU,MAAM,KAAK,MAAM,CAAC;CAC9E,IAAI,IAAI;CACR,IAAI,UAAU;CACd,IAAI,WAAW;CACf,KAAK,MAAM,UAAU,SAAS,SAAS;EACrC,IAAI,aAAa,IAAI,MAAM,GAAG;EAC9B,KAAK;EACL,MAAM,QAAQ,cAAc,IAAI,MAAM;EACtC,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM;EAC3C,WAAW;EACX,IAAI,QAAQ,SAAS,iBAAiB,YAAY;CACpD;CACA,OAAO;EAAE;EAAG;EAAS;EAAU,eAAe,YAAY,IAAI,OAAO,WAAW;CAAQ;AAC1F"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/meta-eval/correlation-study.ts","../../src/meta-eval/evaluator-admission.ts","../../src/meta-eval/judge-panel-calibration.ts","../../src/meta-eval/measure-records.ts","../../src/meta-eval/measure-selection.ts","../../src/meta-eval/measure-validity.ts","../../src/meta-eval/plants.ts"],"sourcesContent":["/**\n * Correlation study — \"does our eval score predict real-world outcomes?\"\n *\n * Joins traces and outcomes by runId and reports descriptive correlations.\n * Independent runs are the bootstrap observation unit.\n * Association alone does not establish causation or held-out predictive performance.\n */\n\nimport { runMetricExtractor } from '../trace/query'\nimport type { Run } from '../trace/schema'\nimport type { TraceStore } from '../trace/store'\nimport {\n assertUniqueObservationIds,\n correlationSummary,\n groupOutcomesByRun,\n hasVariation,\n reduceOutcomeMetric,\n validateObservationOptions,\n} from './outcome-observations'\nimport type { OutcomeFilter, OutcomeStore } from './outcome-store'\n\nexport interface EvalMetricSpec {\n id: string\n /** Extract a scalar from a run. Omit it and `id` must name one of\n * `RUN_METRICS`; any other `id` is refused. */\n extract?: (run: Run, store: TraceStore) => Promise<number | null>\n}\n\nexport interface OutcomePair {\n evalMetric: string\n outcomeMetric: string\n}\n\nexport interface CorrelationResult {\n evalMetric: string\n outcomeMetric: string\n n: number\n pearson: number\n spearman: number\n /** 95% bootstrap CI for Pearson. */\n pearsonCi95: { lower: number; upper: number } | null\n /** 95% bootstrap CI for Spearman; null when no resample is estimable. */\n spearmanCi95: { lower: number; upper: number } | null\n /** Rough verdict: 'strong' ≥ 0.7, 'moderate' ≥ 0.4, else 'weak'. */\n verdict: 'strong' | 'moderate' | 'weak'\n}\n\nexport interface CorrelationStudyResult {\n pairs: CorrelationResult[]\n /** Declared pairs without an estimable correlation, including their usable sample count. */\n excludedPairs: Array<\n OutcomePair & {\n n: number\n reason: 'insufficient_samples' | 'constant_eval_metric' | 'constant_outcome'\n }\n >\n joinedSamples: number\n skippedRuns: number\n}\n\nexport interface CorrelationStudyOptions {\n /** Only join outcomes captured within this window after run.startedAt. */\n maxCaptureLagMs?: number\n /** Restrict to a subset of outcomes (cohort, region, source). */\n outcomeFilter?: OutcomeFilter\n /** Which outcome per run to use when multiple exist. Default 'latest'. */\n reduction?: 'latest' | 'mean' | 'max'\n /** Bootstrap iterations for the CI. Default 500. */\n bootstrapIterations?: number\n /** Seed for the bootstrap resampler. Absent, the seed is derived from the\n * paired observations, so the same study reproduces the same interval. */\n seed?: number\n}\n\nexport async function correlationStudy(\n traceStore: TraceStore,\n outcomeStore: OutcomeStore,\n evalMetrics: EvalMetricSpec[],\n outcomeMetricNames: string[],\n options: CorrelationStudyOptions = {},\n): Promise<CorrelationStudyResult> {\n const reduction = options.reduction ?? 'latest'\n const iterations = options.bootstrapIterations ?? 500\n const seed = options.seed\n validateObservationOptions(reduction, iterations, seed)\n assertUniqueObservationIds(\n evalMetrics.map((metric) => metric.id),\n 'eval metric',\n )\n assertUniqueObservationIds(outcomeMetricNames, 'outcome metric')\n const maxLag = options.maxCaptureLagMs ?? Infinity\n if (maxLag < 0 || Number.isNaN(maxLag)) {\n throw new Error('maxCaptureLagMs must be nonnegative')\n }\n const extractors = evalMetrics.map((metric) => ({\n ...metric,\n extract: metric.extract ?? runMetricExtractor(metric.id),\n }))\n const metricNames = [...outcomeMetricNames]\n const runs = await traceStore.listRuns()\n assertUniqueObservationIds(\n runs.map((run) => run.runId),\n 'runId',\n )\n const outcomesByRun = groupOutcomesByRun(await outcomeStore.list(options.outcomeFilter))\n\n const pairs: Array<{ evalMetric: string; outcomeMetric: string; xs: number[]; ys: number[] }> = []\n for (const em of extractors) {\n for (const om of metricNames) {\n pairs.push({ evalMetric: em.id, outcomeMetric: om, xs: [], ys: [] })\n }\n }\n\n let joined = 0\n let skipped = 0\n for (const run of runs) {\n const os = outcomesByRun.get(run.runId)\n if (!os || os.length === 0) {\n skipped++\n continue\n }\n const eligible = os.filter((o) => {\n const lag = o.capturedAt - run.startedAt\n return lag >= 0 && lag <= maxLag\n })\n if (eligible.length === 0) {\n skipped++\n continue\n }\n\n let joinedThisRun = false\n for (const em of extractors) {\n const x = await em.extract(run, traceStore)\n if (x === null || !Number.isFinite(x)) continue\n\n for (const om of metricNames) {\n const y = reduceOutcomeMetric(eligible, om, reduction)\n if (y === null) continue\n const pair = pairs.find((p) => p.evalMetric === em.id && p.outcomeMetric === om)!\n pair.xs.push(x)\n pair.ys.push(y)\n joinedThisRun = true\n }\n }\n if (joinedThisRun) joined++\n else skipped++\n }\n\n const excludedPairs: CorrelationStudyResult['excludedPairs'] = []\n const results: CorrelationResult[] = []\n for (const p of pairs) {\n const reason =\n p.xs.length < 3\n ? 'insufficient_samples'\n : !hasVariation(p.xs)\n ? 'constant_eval_metric'\n : !hasVariation(p.ys)\n ? 'constant_outcome'\n : null\n if (reason !== null) {\n excludedPairs.push({\n evalMetric: p.evalMetric,\n outcomeMetric: p.outcomeMetric,\n n: p.xs.length,\n reason,\n })\n continue\n }\n const summary = correlationSummary(p.xs, p.ys, iterations, seed)\n const verdict: CorrelationResult['verdict'] =\n Math.abs(summary.pearson) >= 0.7\n ? 'strong'\n : Math.abs(summary.pearson) >= 0.4\n ? 'moderate'\n : 'weak'\n results.push({\n evalMetric: p.evalMetric,\n outcomeMetric: p.outcomeMetric,\n n: p.xs.length,\n ...summary,\n verdict,\n })\n }\n return { pairs: results, excludedPairs, joinedSamples: joined, skippedRuns: skipped }\n}\n","import { z } from 'zod'\nimport { ValidationError } from '../errors'\nimport { type ComputedInterval, computeInterval } from '../experiment/ast/interval'\nimport { compareCodeUnits, hashCanonical, type LedgerHash } from '../ledger-core/canonical'\n\nconst identity = z\n .string()\n .min(1)\n .refine((value) => value.trim() === value)\nexport const evaluatorAdmissionPolicySchema = z\n .object({\n confidence: z.number().finite().gt(0).lt(1),\n maxFalseAcceptanceRate: z.number().finite().min(0).lt(1),\n maxFalseRejectionRate: z.number().finite().min(0).lt(1),\n })\n .strict()\n\n/** Register both error limits before inspecting audit judgments. */\nexport type EvaluatorAdmissionPolicy = z.infer<typeof evaluatorAdmissionPolicySchema>\n\nexport const evaluatorAuditObservationSchema = z\n .object({\n id: identity,\n independentUnitId: identity,\n evidenceRef: identity,\n expected: z.enum(['accept', 'reject']),\n observed: z.enum(['accept', 'reject', 'unknown']),\n exposure: z.enum(['fresh', 'development']),\n })\n .strict()\n\n/** Actual control judgments. Variants from one source retain one independent identity. */\nexport type EvaluatorAuditObservation = z.infer<typeof evaluatorAuditObservationSchema>\n\nconst inputSchema = z\n .object({\n evaluatorDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/),\n population: identity,\n samplingFrame: identity,\n authority: z\n .object({\n evaluatorAuthorId: identity,\n auditorId: identity,\n independenceEvidenceRef: identity,\n })\n .strict(),\n policy: evaluatorAdmissionPolicySchema,\n observations: z.array(evaluatorAuditObservationSchema),\n })\n .strict()\n\nexport type EvaluatorAuditInput = z.infer<typeof inputSchema>\n\nexport interface EvaluatorErrorRate {\n /** Eligible control judgments in this class, including unknown judgments. */\n cases: number\n independentUnits: number\n /** Units with at least one observed mistake. */\n errorUnits: number\n /** Units with unknown judgments and no observed mistake yet. */\n unresolvedUnits: number\n unknownCases: number\n /** Missing judgments do not become measured zeros. */\n errorRate: number | null\n /** Exact bounds conservatively include every possible outcome of unknown judgments. */\n interval: ComputedInterval | null\n limit: number\n verdict: 'pass' | 'fail' | 'inconclusive'\n}\n\nexport interface EvaluatorAdmissionReport {\n evaluatorDigest: LedgerHash\n policyDigest: LedgerHash\n inputDigest: LedgerHash\n reportDigest: LedgerHash\n population: string\n samplingFrame: string\n authority: EvaluatorAuditInput['authority']\n policy: EvaluatorAdmissionPolicy\n /** Joint coverage for the two reported error-rate intervals. */\n confidence: number\n intervalConfidence: number\n verdict: 'admit' | 'reject' | 'inconclusive'\n reasons: string[]\n observations: EvaluatorAuditObservation[]\n coverage: {\n cases: number\n independentUnits: number\n eligibleCases: number\n eligibleIndependentUnits: number\n excludedCases: number\n unknownCases: number\n }\n exclusions: Array<{ id: string; independentUnitId: string; reason: 'development-exposure' }>\n falseAcceptance: EvaluatorErrorRate\n falseRejection: EvaluatorErrorRate\n}\n\nfunction errorRate(\n rows: readonly EvaluatorAuditObservation[],\n expected: 'accept' | 'reject',\n limit: number,\n level: number,\n): EvaluatorErrorRate {\n const cases = rows.filter((row) => row.expected === expected)\n const units = new Map<string, { error: boolean; unknown: boolean }>()\n for (const row of cases) {\n const unit = units.get(row.independentUnitId) ?? { error: false, unknown: false }\n unit.unknown ||= row.observed === 'unknown'\n unit.error ||= row.observed !== 'unknown' && row.observed !== expected\n units.set(row.independentUnitId, unit)\n }\n const n = units.size\n const errorUnits = [...units.values()].filter((unit) => unit.error).length\n const unresolvedUnits = [...units.values()].filter((unit) => unit.unknown && !unit.error).length\n const unknownCases = cases.filter((row) => row.observed === 'unknown').length\n // Unknown judgments contribute to n; their most favorable and adverse outcomes bound the rate.\n const interval =\n n === 0\n ? null\n : {\n lower: computeInterval(\n { kind: 'clopper-pearson', level },\n {\n kind: 'binomial',\n successes: errorUnits,\n trials: n,\n },\n ).lower,\n upper: computeInterval(\n { kind: 'clopper-pearson', level },\n {\n kind: 'binomial',\n successes: errorUnits + unresolvedUnits,\n trials: n,\n },\n ).upper,\n level,\n }\n const verdict =\n interval && interval.lower > limit\n ? 'fail'\n : interval && interval.upper <= limit\n ? 'pass'\n : 'inconclusive'\n return {\n cases: cases.length,\n independentUnits: n,\n errorUnits,\n unresolvedUnits,\n unknownCases,\n errorRate: n === 0 || unresolvedUnits > 0 ? null : errorUnits / n,\n interval,\n limit,\n verdict,\n }\n}\n\nfunction eligibleControls<\n T extends Pick<EvaluatorAuditObservation, 'id' | 'independentUnitId' | 'exposure'>,\n>(observations: T[]) {\n const ids = new Set<string>()\n for (const row of observations) {\n if (ids.has(row.id))\n throw new ValidationError(`duplicate evaluator audit observation '${row.id}'`)\n ids.add(row.id)\n }\n observations.sort((a, b) => compareCodeUnits(a.id, b.id))\n const developmentUnits = new Set(\n observations\n .filter((row) => row.exposure === 'development')\n .map((row) => row.independentUnitId),\n )\n const eligible = observations.filter((row) => !developmentUnits.has(row.independentUnitId))\n const exclusions = observations\n .filter((row) => developmentUnits.has(row.independentUnitId))\n .map((row) => ({\n id: row.id,\n independentUnitId: row.independentUnitId,\n reason: 'development-exposure' as const,\n }))\n return { eligible, exclusions }\n}\n\nfunction simultaneousIntervalConfidence(confidence: number): number {\n const level = 1 - (1 - confidence) / 2\n if (level >= 1)\n throw new ValidationError(\n 'evaluator audit confidence is too close to one for simultaneous intervals',\n )\n return level\n}\n\nconst capacitySchema = z\n .object({\n policy: evaluatorAdmissionPolicySchema,\n controls: z\n .array(evaluatorAuditObservationSchema.omit({ observed: true, evidenceRef: true }))\n .default([]),\n })\n .strict()\n\nexport type EvaluatorAuditPlanInput = z.input<typeof capacitySchema>\n\n/** The zero-error eligibility floor, not a statistical power calculation. */\nfunction zeroErrorUpperBound(trials: number, level: number): number {\n return -Math.expm1(Math.log((1 - level) / 2) / trials)\n}\n\nfunction minimumAuditUnits(limit: number, level: number): number | null {\n if (limit === 0) return null\n const estimate = Math.ceil(Math.log((1 - level) / 2) / Math.log1p(-limit))\n if (!Number.isFinite(estimate) || estimate > Number.MAX_SAFE_INTEGER) return null\n const clears = (trials: number) => zeroErrorUpperBound(trials, level) <= limit\n let minimum = Math.max(1, estimate)\n while (minimum > 1 && clears(minimum - 1)) minimum -= 1\n while (!clears(minimum)) {\n if (minimum === Number.MAX_SAFE_INTEGER) return null\n minimum += 1\n }\n return minimum\n}\n\n/**\n * Can the fixed control roster meet the policy even with zero errors?\n * Planning uses the admission rule's exact bounds and source-unit exclusions.\n * It accepts no judgments or authority and returns no admission report.\n */\nexport function planEvaluatorAudit(input: EvaluatorAuditPlanInput) {\n const parsed = capacitySchema.safeParse(input)\n if (!parsed.success)\n throw new ValidationError(`invalid evaluator audit plan: ${parsed.error.message}`)\n const { policy, controls } = parsed.data\n const { eligible } = eligibleControls(controls)\n const level = simultaneousIntervalConfidence(policy.confidence)\n const capacity = (expected: EvaluatorAuditObservation['expected'], limit: number) => {\n const independentUnits = new Set(\n eligible.filter((row) => row.expected === expected).map((row) => row.independentUnitId),\n ).size\n const bestPossibleUpperBound =\n independentUnits === 0 ? null : zeroErrorUpperBound(independentUnits, level)\n const minimumIndependentUnits = minimumAuditUnits(limit, level)\n return {\n independentUnits,\n bestPossibleUpperBound,\n limit,\n minimumIndependentUnits,\n additionalIndependentUnits:\n minimumIndependentUnits === null\n ? null\n : Math.max(0, minimumIndependentUnits - independentUnits),\n }\n }\n const falseAcceptance = capacity('reject', policy.maxFalseAcceptanceRate)\n const falseRejection = capacity('accept', policy.maxFalseRejectionRate)\n const sufficient = [falseAcceptance, falseRejection].every(\n (rate) => rate.bestPossibleUpperBound !== null && rate.bestPossibleUpperBound <= rate.limit,\n )\n return { sufficient, falseAcceptance, falseRejection }\n}\n\nexport type EvaluatorAuditPlan = ReturnType<typeof planEvaluatorAudit>\n\n/**\n * Audit frozen judgments using independent source units and exact binomial bounds.\n * A unit fails a class when any control in that class is misjudged.\n * The execution owner enforces auditor separation, fresh sampling, and evidence authenticity.\n */\nexport function auditEvaluator(input: EvaluatorAuditInput): EvaluatorAdmissionReport {\n const parsed = inputSchema.safeParse(input)\n if (!parsed.success) throw new ValidationError(`invalid evaluator audit: ${parsed.error.message}`)\n const audit = parsed.data\n if (audit.authority.evaluatorAuthorId === audit.authority.auditorId) {\n throw new ValidationError('evaluator admission requires a separate declared audit authority')\n }\n const { eligible, exclusions } = eligibleControls(audit.observations)\n const intervalConfidence = simultaneousIntervalConfidence(audit.policy.confidence)\n const falseAcceptance = errorRate(\n eligible,\n 'reject',\n audit.policy.maxFalseAcceptanceRate,\n intervalConfidence,\n )\n const falseRejection = errorRate(\n eligible,\n 'accept',\n audit.policy.maxFalseRejectionRate,\n intervalConfidence,\n )\n const rates = [falseAcceptance, falseRejection]\n const verdict = rates.some((rate) => rate.verdict === 'fail')\n ? 'reject'\n : rates.every((rate) => rate.verdict === 'pass')\n ? 'admit'\n : 'inconclusive'\n const reasons: string[] = []\n for (const [name, rate] of [\n ['false acceptance', falseAcceptance],\n ['false rejection', falseRejection],\n ] as const) {\n if (rate.independentUnits === 0) reasons.push(`${name}: no eligible independent units`)\n else if (rate.unknownCases > 0)\n reasons.push(`${name}: ${rate.unknownCases} judgments are unknown`)\n if (rate.verdict === 'fail') reasons.push(`${name}: lower error bound exceeds ${rate.limit}`)\n else if (rate.verdict === 'inconclusive' && rate.interval)\n reasons.push(`${name}: upper error bound does not establish the required limit`)\n }\n if (verdict === 'admit')\n reasons.push(\n 'both error bounds meet the registered limits, including the worst case for unknown judgments',\n )\n const body: Omit<EvaluatorAdmissionReport, 'reportDigest'> = {\n evaluatorDigest: audit.evaluatorDigest as LedgerHash,\n policyDigest: hashCanonical(audit.policy),\n inputDigest: hashCanonical(audit),\n population: audit.population,\n samplingFrame: audit.samplingFrame,\n authority: audit.authority,\n policy: audit.policy,\n confidence: audit.policy.confidence,\n intervalConfidence,\n verdict,\n reasons,\n observations: audit.observations,\n coverage: {\n cases: audit.observations.length,\n independentUnits: new Set(audit.observations.map((row) => row.independentUnitId)).size,\n eligibleCases: eligible.length,\n eligibleIndependentUnits: new Set(eligible.map((row) => row.independentUnitId)).size,\n excludedCases: exclusions.length,\n unknownCases: eligible.filter((row) => row.observed === 'unknown').length,\n },\n exclusions,\n falseAcceptance,\n falseRejection,\n }\n return { ...body, reportDigest: hashCanonical(body) }\n}\n\nconst probabilityThresholdsSchema = z\n .object({\n rejectAtOrBelow: z.number().finite().min(0).max(1),\n acceptAtOrAbove: z.number().finite().min(0).max(1),\n })\n .strict()\n .refine((value) => value.rejectAtOrBelow < value.acceptAtOrAbove, {\n message: 'rejection and acceptance thresholds must not overlap',\n })\nconst probabilityObservationSchema = evaluatorAuditObservationSchema\n .omit({ observed: true })\n .extend({ acceptProbability: z.number().finite().min(0).max(1).nullable() })\n .strict()\nconst probabilityAuditSchema = inputSchema.extend({\n thresholds: probabilityThresholdsSchema,\n observations: z.array(probabilityObservationSchema),\n})\n\n/** A frozen caller-owned rule over P(accept), not the provider's entropy/confidence statistic. */\nexport type ProbabilityPolicyAuditInput = z.infer<typeof probabilityAuditSchema>\n\nexport interface ProbabilityPolicyAuditReport extends EvaluatorAdmissionReport {\n probabilityPolicy: {\n sourceEvaluatorDigest: LedgerHash\n thresholds: ProbabilityPolicyAuditInput['thresholds']\n /** Retain probabilities by observation id so the reported mapping can be reproduced. */\n observations: Array<{ id: string; acceptProbability: number | null }>\n }\n}\n\n/**\n * Audit a fixed probability-to-decision rule with the existing independent-unit error bounds.\n * No threshold search, model calls, promotion, or assumption of calibrated probabilities.\n * Null scores and the open interval between thresholds remain unknown, never correct by default.\n */\nexport function auditProbabilityPolicy(\n input: ProbabilityPolicyAuditInput,\n): ProbabilityPolicyAuditReport {\n const parsed = probabilityAuditSchema.safeParse(input)\n if (!parsed.success) {\n throw new ValidationError(`invalid probability policy audit: ${parsed.error.message}`)\n }\n const { thresholds, observations, ...source } = parsed.data\n observations.sort((a, b) => compareCodeUnits(a.id, b.id))\n const probabilityPolicy = {\n sourceEvaluatorDigest: source.evaluatorDigest as LedgerHash,\n thresholds,\n observations: observations.map(({ id, acceptProbability }) => ({ id, acceptProbability })),\n }\n const audit = auditEvaluator({\n ...source,\n evaluatorDigest: hashCanonical({\n kind: 'probability-policy-v1',\n sourceEvaluatorDigest: source.evaluatorDigest,\n thresholds,\n }),\n observations: observations.map(({ acceptProbability, ...observation }) => ({\n ...observation,\n observed:\n acceptProbability === null\n ? 'unknown'\n : acceptProbability >= thresholds.acceptAtOrAbove\n ? 'accept'\n : acceptProbability <= thresholds.rejectAtOrBelow\n ? 'reject'\n : 'unknown',\n })),\n })\n const { reportDigest: _baseDigest, ...baseReport } = audit\n const body = {\n ...baseReport,\n // Bind the actual probabilities too, including changes that select the same action.\n inputDigest: hashCanonical(parsed.data),\n probabilityPolicy,\n }\n return { ...body, reportDigest: hashCanonical(body) }\n}\n","/**\n * Judge-panel calibration: score a hand-graded gold set with every judge model\n * on a panel, under one weighted rubric, and measure each (judge × dimension)\n * against the human grades with `calibrateJudge`.\n *\n * The caller owns the domain: the rubric text and weights, the system prompt,\n * the gold items and the judge list. This module owns the mechanics every\n * product repeats — the rubric prompt, the JSON call with retries, the\n * sequential (item × judge) sweep, null-grade handling, and the per-cell\n * calibration — plus `gateJudgeCalibration`, the pass/warn/fail rule over the\n * resulting cells.\n *\n * Calls run one at a time. Subscription bridges serialise per subprocess, and\n * concurrent requests from a full panel get killed under load.\n *\n * A gold cell with a null or missing human grade is still scored (the judge's\n * score lands in `rawScores`, useful for inter-judge agreement) but never\n * enters that dimension's calibration.\n */\n\nimport {\n type CalibrationResult,\n type CandidateScore,\n calibrateJudge,\n type GoldenItem,\n} from '../judge-calibration'\nimport { withJudgeRetry } from '../judge-retry'\nimport { callLlmJson, type LlmClientOptions } from '../llm-client'\n\n/** One rubric dimension: the guide the judge scores against and its weight in the composite. */\nexport interface RubricDimensionGuide {\n weight: number\n guide: string\n}\n\nexport interface JudgeCalibrationGoldItem<D extends string> {\n id: string\n /** Text after `Scenario:` in the judge prompt. Defaults to `id`. */\n scenarioLabel?: string\n /** The input the candidate answered. */\n scenario: string\n /** The output the judges score. */\n candidateOutput: string\n /** Human grade per dimension in [0,1]. `null` (whole item or one dimension)\n * means not graded: the item is still judged but excluded from calibration. */\n humanGrade: Partial<Record<D, number | null>> | null\n}\n\nexport interface JudgePanelPrompt {\n /** The judge's system prompt. */\n system: string\n /** Line above the rubric. Default: score each dimension in [0,1]. */\n rubricHeading?: string\n /** Line above the candidate output. Default `Candidate output to score:`. */\n candidateHeading?: string\n /** Candidate output is cut to this many characters. Default 12000. */\n maxCandidateChars?: number\n /** Lines after the JSON-shape instruction. */\n closingLines?: readonly string[]\n}\n\nexport interface CalibrateJudgePanelInput<D extends string> {\n rubric: Readonly<Record<D, RubricDimensionGuide>>\n /** Dimensions to score, in prompt order. Defaults to the rubric's keys. */\n dimensions?: readonly D[]\n items: readonly JudgeCalibrationGoldItem<D>[]\n judges: readonly string[]\n /** Endpoint and credential for every judge call. */\n llm: LlmClientOptions\n prompt: JudgePanelPrompt\n /** Default 1200. */\n maxTokens?: number\n /** Per-attempt timeout. Default 300000. */\n timeoutMs?: number\n /** Attempts per (item × judge); every error is retried. Default 3. */\n maxAttempts?: number\n /** Progress lines (one per item and judge, then the metrics table). */\n log?: (line: string) => void\n}\n\n/** A judge's calibration on one dimension. `golden` and `scores` hold the same\n * items: the human-graded ones this judge scored. */\nexport interface JudgeDimensionCalibration {\n calibration: CalibrationResult\n golden: GoldenItem[]\n scores: CandidateScore[]\n}\n\n/** What one judge returned for one item: a score per dimension and its rationale. */\nexport type JudgePanelOutput<D extends string> = Partial<Record<D, number>> & { rationale?: string }\n\nexport interface JudgePanelCalibration<D extends string> {\n judges: string[]\n dimensions: D[]\n perJudge: Record<string, Record<D, JudgeDimensionCalibration>>\n /** Every score each judge returned, graded items or not, clamped to [0,1]. */\n rawScores: Record<string, Record<D, CandidateScore[]>>\n /** Parsed judge output per item; `null` when every attempt failed. */\n outputs: Record<string, Record<string, JudgePanelOutput<D> | null>>\n /** Item ids with no human grade, per dimension. */\n ungradedItems: Record<D, string[]>\n /** (judge × item) cells where every attempt failed. */\n failures: Array<{ judge: string; itemId: string; errors: string[] }>\n elapsedMs: number\n}\n\nconst DEFAULT_RUBRIC_HEADING =\n 'Rubric (score each dimension in [0,1]; 1 = perfectly satisfies the guide, 0 = fails):'\n\nfunction clampUnit(n: number): number {\n if (!Number.isFinite(n)) return 0\n if (n < 0) return 0\n if (n > 1) return 1\n return n\n}\n\nfunction humanScore<D extends string>(item: JudgeCalibrationGoldItem<D>, d: D): number | null {\n const v = item.humanGrade?.[d]\n return typeof v === 'number' && Number.isFinite(v) ? v : null\n}\n\nfunction shortModel(model: string): string {\n return (model.split('/').pop() ?? model).padEnd(28)\n}\n\nfunction judgeUserPrompt<D extends string>(\n input: CalibrateJudgePanelInput<D>,\n dimensions: readonly D[],\n item: JudgeCalibrationGoldItem<D>,\n): string {\n const rubricLines = dimensions\n .map((d) => `- ${d} (weight ${input.rubric[d].weight}): ${input.rubric[d].guide}`)\n .join('\\n')\n const jsonShape = `{${dimensions.map((d) => `\"${d}\":number`).join(',')},\"rationale\":string}`\n return [\n `Scenario: ${item.scenarioLabel ?? item.id}`,\n `Input: ${item.scenario}`,\n '',\n input.prompt.rubricHeading ?? DEFAULT_RUBRIC_HEADING,\n rubricLines,\n '',\n input.prompt.candidateHeading ?? 'Candidate output to score:',\n '---',\n item.candidateOutput.slice(0, input.prompt.maxCandidateChars ?? 12_000),\n '---',\n '',\n `Respond ONLY with a JSON object exactly of shape: ${jsonShape}.`,\n ...(input.prompt.closingLines ?? []),\n ].join('\\n')\n}\n\n/** Run every judge on every gold item and calibrate each (judge × dimension). */\nexport async function calibrateJudgePanel<D extends string>(\n input: CalibrateJudgePanelInput<D>,\n): Promise<JudgePanelCalibration<D>> {\n const dimensions = [...(input.dimensions ?? (Object.keys(input.rubric) as D[]))]\n const judges = [...input.judges]\n const log = input.log ?? (() => {})\n const perDim = <T>(make: () => T) =>\n Object.fromEntries(dimensions.map((d) => [d, make()])) as Record<D, T>\n\n const rawScores: JudgePanelCalibration<D>['rawScores'] = {}\n const outputs: JudgePanelCalibration<D>['outputs'] = {}\n const goldenByJudge: Record<string, Record<D, GoldenItem[]>> = {}\n const scoresByJudge: Record<string, Record<D, CandidateScore[]>> = {}\n for (const judge of judges) {\n rawScores[judge] = perDim(() => [] as CandidateScore[])\n outputs[judge] = {}\n goldenByJudge[judge] = perDim(() => [] as GoldenItem[])\n scoresByJudge[judge] = perDim(() => [] as CandidateScore[])\n }\n const ungradedItems = perDim(() => [] as string[])\n for (const item of input.items) {\n for (const d of dimensions) if (humanScore(item, d) === null) ungradedItems[d].push(item.id)\n }\n const failures: JudgePanelCalibration<D>['failures'] = []\n\n const startedAt = Date.now()\n for (let i = 0; i < input.items.length; i++) {\n const item = input.items[i] as JudgeCalibrationGoldItem<D>\n log(` [${(i + 1).toString().padStart(2)}/${input.items.length}] ${item.id}`)\n const userPrompt = judgeUserPrompt(input, dimensions, item)\n for (const judge of judges) {\n const outcome = await withJudgeRetry(\n async (_model, signal) =>\n (\n await callLlmJson<JudgePanelOutput<D>>(\n {\n model: judge,\n messages: [\n { role: 'system', content: input.prompt.system },\n { role: 'user', content: userPrompt },\n ],\n jsonMode: true,\n temperature: 0,\n maxTokens: input.maxTokens ?? 1200,\n timeoutMs: input.timeoutMs ?? 300_000,\n },\n { ...input.llm, signal },\n )\n ).value,\n {\n maxAttempts: input.maxAttempts ?? 3,\n timeoutMs: input.timeoutMs ?? 300_000,\n isRetryable: () => true,\n backoffMs: (attempt) => 2_000 * (attempt + 1),\n },\n )\n const out = outcome.succeeded ? outcome.value : null\n outputs[judge]![item.id] = out\n if (!out) {\n const errors = outcome.attemptErrors.map((e) => e.error)\n failures.push({ judge, itemId: item.id, errors })\n log(` ${shortModel(judge)} - FAILED (${errors.at(-1) ?? 'no attempt'})`)\n continue\n }\n let judged = 0\n let expected = 0\n let covered = 0\n for (const d of dimensions) {\n const score = clampUnit(Number((out as Record<string, unknown>)[d]))\n rawScores[judge]![d].push({ itemId: item.id, score })\n const human = humanScore(item, d)\n if (human === null) continue\n goldenByJudge[judge]![d].push({ itemId: item.id, humanScore: human })\n scoresByJudge[judge]![d].push({ itemId: item.id, score })\n const weight = input.rubric[d].weight\n judged += score * weight\n expected += human * weight\n covered += weight\n }\n const pct = (n: number) => `${(n * 100).toFixed(0)}%`\n log(\n covered > 0\n ? ` ${shortModel(judge)} judged=${pct(judged / covered)} expected=${pct(expected / covered)} delta=${pct((judged - expected) / covered)} cover=${pct(covered)}`\n : ` ${shortModel(judge)} judged (ungraded item)`,\n )\n }\n }\n const elapsedMs = Date.now() - startedAt\n\n const perJudge: JudgePanelCalibration<D>['perJudge'] = {}\n for (const judge of judges) {\n log(` ${judge}`)\n perJudge[judge] = {} as Record<D, JudgeDimensionCalibration>\n for (const d of dimensions) {\n const golden = goldenByJudge[judge]![d]\n const scores = scoresByJudge[judge]![d]\n const calibration = calibrateJudge(golden, scores)\n perJudge[judge]![d] = { calibration, golden, scores }\n log(\n ` ${d.padEnd(34)} n=${calibration.n.toString().padStart(2)} kappa=${calibration.kappa.toFixed(2)} r=${calibration.pearson.toFixed(2)} MAE=${calibration.mae.toFixed(3)}`,\n )\n }\n }\n\n return { judges, dimensions, perJudge, rawScores, outputs, ungradedItems, failures, elapsedMs }\n}\n\n/** Thresholds for `gateJudgeCalibration`. */\nexport interface JudgeCalibrationGateConfig {\n /** Pearson below this (and at or above `pearsonWarn`) warns. */\n pearsonFloor: number\n /** Pearson below this fails. */\n pearsonWarn: number\n /** MAE above this fails. */\n maeCeiling: number\n /** Cells with fewer graded items are reported as insufficient and never fail. */\n minSamples: number\n}\n\nexport type JudgeCalibrationCellVerdict = 'pass' | 'warn' | 'fail' | 'insufficient'\n\nexport interface JudgeCalibrationGateCell {\n judge: string\n dim: string\n n: number\n pearson: number\n mae: number\n verdict: JudgeCalibrationCellVerdict\n reasons: string[]\n}\n\nexport interface JudgeCalibrationGate {\n pass: boolean\n config: JudgeCalibrationGateConfig\n failCount: number\n warnCount: number\n insufficientCount: number\n cells: JudgeCalibrationGateCell[]\n}\n\n/** Pass/warn/fail every (judge × dimension) cell; the gate passes with zero fail cells. */\nexport function gateJudgeCalibration(\n perJudge: Record<string, Record<string, { calibration: CalibrationResult }>>,\n config: JudgeCalibrationGateConfig,\n): JudgeCalibrationGate {\n const cells: JudgeCalibrationGateCell[] = []\n for (const [judge, dims] of Object.entries(perJudge)) {\n for (const [dim, { calibration: cal }] of Object.entries(dims)) {\n const reasons: string[] = []\n let verdict: JudgeCalibrationCellVerdict = 'pass'\n if (cal.n < config.minSamples) {\n verdict = 'insufficient'\n reasons.push(`n=${cal.n} < minSamples=${config.minSamples}`)\n } else {\n if (Number.isFinite(cal.pearson) && cal.pearson < config.pearsonFloor) {\n if (cal.pearson < config.pearsonWarn) {\n verdict = 'fail'\n reasons.push(\n `pearson=${cal.pearson.toFixed(2)} < floor=${config.pearsonFloor.toFixed(2)} (below warn=${config.pearsonWarn.toFixed(2)})`,\n )\n } else {\n verdict = 'warn'\n reasons.push(\n `pearson=${cal.pearson.toFixed(2)} in warn band [${config.pearsonWarn.toFixed(2)}, ${config.pearsonFloor.toFixed(2)})`,\n )\n }\n }\n if (Number.isFinite(cal.mae) && cal.mae > config.maeCeiling) {\n verdict = 'fail'\n reasons.push(`mae=${cal.mae.toFixed(3)} > ceiling=${config.maeCeiling.toFixed(3)}`)\n }\n }\n cells.push({ judge, dim, n: cal.n, pearson: cal.pearson, mae: cal.mae, verdict, reasons })\n }\n }\n const count = (v: JudgeCalibrationCellVerdict) => cells.filter((c) => c.verdict === v).length\n const failCount = count('fail')\n return {\n pass: failCount === 0,\n config,\n failCount,\n warnCount: count('warn'),\n insufficientCount: count('insufficient'),\n cells,\n }\n}\n","/**\n * Changes and the outcomes joined to them, shared by the measure validity\n * study and the guard drift check. Internal to `meta-eval`; `MeasuredChange`\n * is public through the barrel.\n */\n\nimport { ValidationError } from '../errors'\nimport type {\n MeasureValidityOutcome,\n MeasureValidityPlan,\n} from '../experiment/measure-validity-plan'\nimport { reduceOutcomeObservation } from './outcome-observations'\nimport type { DeploymentOutcome } from './outcome-store'\n\n/** A change and the numbers known when it was made. */\nexport interface MeasuredChange {\n /** Joins `DeploymentOutcome.runId`. */\n id: string\n /** Epoch milliseconds when the change was made. */\n at: number\n /** Independent unit, such as a repository, session or customer. Intervals resample whole units. */\n unit: string\n /** Finite values; an absent key is unmeasured, never zero. */\n measures: Record<string, number>\n /** The measure before and after the change, when both were recorded. */\n movements?: Record<string, { before: number; after: number }>\n}\n\nexport interface JoinedOutcome {\n /** 0 or 1 for binary (1 is better); the direction-aligned value for continuous. */\n better: number\n capturedAt: number\n}\n\nexport interface PreparedChange {\n change: MeasuredChange\n preCut: boolean\n outcomes: Map<string, JoinedOutcome>\n}\n\nexport function validateChanges(\n changes: readonly MeasuredChange[],\n plan: MeasureValidityPlan,\n requireUniqueIds: boolean,\n): void {\n const ids = new Set<string>()\n for (const [index, change] of changes.entries()) {\n const where = `change ${index}${typeof change?.id === 'string' ? ` (${change.id})` : ''}`\n if (typeof change?.id !== 'string' || change.id.trim().length === 0) {\n throw new ValidationError(`${where}: id must be a nonempty string`)\n }\n if (requireUniqueIds && ids.has(change.id)) {\n throw new ValidationError(`${where}: duplicate change id`)\n }\n ids.add(change.id)\n if (!Number.isFinite(change.at)) throw new ValidationError(`${where}: at must be finite`)\n if (typeof change.unit !== 'string' || change.unit.length === 0) {\n throw new ValidationError(`${where}: unit must be a nonempty string`)\n }\n for (const measure of plan.measures) {\n const value = change.measures?.[measure.id]\n if (value !== undefined && !Number.isFinite(value)) {\n throw new ValidationError(\n `${where}: measure ${measure.id} must be finite; omit it when unmeasured`,\n )\n }\n const movement = change.movements?.[measure.id]\n if (movement === undefined) continue\n if (!Number.isFinite(movement.before) || !Number.isFinite(movement.after)) {\n throw new ValidationError(`${where}: movement of ${measure.id} must be finite`)\n }\n if (measure.noise === undefined) {\n throw new ValidationError(\n `${where}: records a movement of ${measure.id} but the plan declares no noise for it`,\n )\n }\n }\n }\n}\n\n/**\n * The observations a change may join, each excluded one counted under the\n * first reason that applies. `asOf` is when the outcomes were read: nothing\n * captured after it can have been known.\n */\nexport function eligibleObservations(\n observations: readonly DeploymentOutcome[],\n change: MeasuredChange,\n plan: MeasureValidityPlan,\n preCut: boolean,\n asOf?: number,\n) {\n const counts = {\n capturedBeforeChange: 0,\n capturedAfterAsOf: 0,\n capturedAfterCutForPreCutChange: 0,\n beyondMaxCaptureLag: 0,\n }\n const eligible: DeploymentOutcome[] = []\n for (const observation of observations) {\n if (observation.capturedAt < change.at) counts.capturedBeforeChange++\n else if (asOf !== undefined && observation.capturedAt > asOf) counts.capturedAfterAsOf++\n else if (\n plan.maxCaptureLagMs !== undefined &&\n observation.capturedAt - change.at > plan.maxCaptureLagMs\n )\n counts.beyondMaxCaptureLag++\n // A direction fitted before the cut may read only outcomes known by the cut.\n else if (preCut && observation.capturedAt > plan.cut) counts.capturedAfterCutForPreCutChange++\n else eligible.push(observation)\n }\n return { eligible, ...counts }\n}\n\nexport function joinOutcomes(\n eligible: readonly DeploymentOutcome[],\n change: MeasuredChange,\n outcomes: readonly MeasureValidityOutcome[],\n reduction: MeasureValidityPlan['reduction'],\n): Map<string, JoinedOutcome> {\n const joined = new Map<string, JoinedOutcome>()\n for (const outcome of outcomes) {\n const reduced = reduceOutcomeObservation(eligible, outcome.id, reduction)\n if (reduced === null) continue\n if (outcome.kind === 'binary' && reduced.value !== 0 && reduced.value !== 1) {\n throw new ValidationError(\n `change ${change.id}: binary outcome ${outcome.id} reduced to ${reduced.value}; record 0 or 1`,\n )\n }\n const higher = outcome.direction === 'higher-is-better'\n joined.set(outcome.id, {\n better:\n outcome.kind === 'binary'\n ? higher\n ? reduced.value\n : 1 - reduced.value\n : higher\n ? reduced.value\n : -reduced.value,\n capturedAt: reduced.capturedAt,\n })\n }\n return joined\n}\n\nexport function statisticOf(outcome: MeasureValidityOutcome): 'auc' | 'spearman' {\n return outcome.kind === 'binary' ? 'auc' : 'spearman'\n}\n","/**\n * The subset of admitted measures to climb, the guards kept unoptimized beside\n * it, and the check that a climbed measure has not drifted away from them.\n *\n * Selection reads only changes before the cut: each candidate is standardized\n * by its before-cut median and robust scale and aligned to its direction, and\n * greedy forward selection adds the measure that most raises the equal-weight\n * composite's statistic, skipping a candidate redundant with one already\n * climbed. Equal weights are deliberate: fitted weights on a few hundred\n * changes overfit, and unit weights lose little when measures share a cause.\n */\n\nimport { ValidationError } from '../errors'\nimport type {\n MeasureValidityOutcome,\n MeasureValidityPlan,\n} from '../experiment/measure-validity-plan'\nimport {\n associationEstimate,\n type ClusteredAssociation,\n clusteredAssociation,\n} from '../statistics/clustered-association'\nimport { spearmanR } from '../statistics/descriptive'\nimport { sampleMedian } from '../statistics/samples'\nimport { clusterBootstrapMean } from './cluster-bootstrap'\nimport {\n eligibleObservations,\n joinOutcomes,\n type MeasuredChange,\n type PreparedChange,\n statisticOf,\n validateChanges,\n} from './measure-records'\nimport type { MeasureOutcomeValidity, MeasureValidityReport } from './measure-validity'\nimport { groupOutcomesByRun } from './outcome-observations'\nimport type { OutcomeStore } from './outcome-store'\n\nexport interface MeasureReference {\n /** Before-cut median and robust scale; `z = direction * (x - center) / scale`. */\n center: number\n scale: number\n /** Mean of the aligned `z` before the cut. */\n meanZ: number\n}\n\nexport interface ClimbedMeasure {\n measure: string\n direction: 'higher' | 'lower'\n /** Gain the measure added to the before-cut composite statistic; the first is its gain over the null. */\n preCutGain: number\n postCutEstimate: number\n leadTimeMs: { median: number; min: number; max: number } | null\n cost: number | null\n reference: MeasureReference\n}\n\nexport interface GuardMeasure {\n measure: string\n direction: 'higher' | 'lower'\n reason: 'redundant' | 'no-gain' | 'size-limit'\n redundantWith: string | null\n /** Largest absolute before-cut rank correlation with a climbed measure. */\n correlation: number | null\n reference: MeasureReference\n}\n\nexport interface MeasureSelection {\n outcome: string\n climb: ClimbedMeasure[]\n /** Admitted measures to keep unoptimized; a climbed measure drifting away from them is visible. */\n guards: GuardMeasure[]\n /**\n * Measures admitted on the pooled test that cannot be climbed: the outcome's\n * exposure itself, measures that predict only by tracking it, only across\n * units, that do not move under change or move against the outcome, or\n * whose after-cut estimate (inside exposure bins when the outcome has an\n * exposure) is closer to the null than `selection.minEffect`.\n */\n excluded: Array<{\n measure: string\n reason:\n | 'exposure'\n | 'through-exposure'\n | 'pooled-only'\n | 'insensitive'\n | 'moves-against-outcome'\n | 'below-minimum-effect'\n }>\n /**\n * Equal-weight mean of the climbed measures' aligned z. The post-cut score\n * reads the changes admission read, so it describes the subset; the next\n * batch is its independent check.\n */\n composite: {\n preCut: { n: number; estimate: number } | null\n postCut: ClusteredAssociation | null\n }\n /** Before-cut outcome reference for drift checks on later batches. */\n outcomeReference:\n | { kind: 'binary'; betterRate: number }\n | { kind: 'continuous'; center: number; scale: number; meanZ: number }\n | null\n}\n\n// ── Guard drift ──────────────────────────────────────────────────────\n\nexport interface GuardDriftInput {\n report: MeasureValidityReport\n outcome: string\n /** Changes made after the study, read against the study's before-cut references. */\n batch: readonly MeasuredChange[]\n /** Largest rise of a climbed measure over its guards, in before-cut scale units, that is not drift. */\n tolerance: number\n /** Outcomes for the batch, when known; drift itself needs none. */\n outcomes?: OutcomeStore\n}\n\nexport interface GuardDriftInterval {\n n: number\n units: number\n estimate: number\n low: number\n high: number\n}\n\nexport interface GuardDriftMeasure {\n measure: string\n status: 'drift' | 'within-tolerance' | 'insufficient'\n /** The climbed measure's aligned z, minus its before-cut mean. */\n shift: GuardDriftInterval | null\n /** The mean of its guards' aligned z, each minus its before-cut mean. */\n guardShift: GuardDriftInterval | null\n /** Per change, shift minus guard shift: drift when its lower bound exceeds the tolerance. */\n divergence: GuardDriftInterval | null\n}\n\nexport interface GuardDriftReport {\n outcome: string\n guards: string[]\n status: 'drift' | 'no-drift' | 'no-guards' | 'insufficient'\n measures: GuardDriftMeasure[]\n /** Better-outcome rate minus the before-cut rate (binary), or the aligned z shift (continuous). */\n outcomeShift: GuardDriftInterval | null\n}\n\n/**\n * Whether a climbed measure rose while its guards did not, in a batch of\n * later changes. Guards are measured at change time, so this reads before the\n * outcome arrives; the outcome shift is reported when the batch has outcomes.\n */\nexport async function guardDrift(input: GuardDriftInput): Promise<GuardDriftReport> {\n const { report, tolerance } = input\n if (!Number.isFinite(tolerance) || tolerance < 0) {\n throw new ValidationError('guardDrift: tolerance must be finite and nonnegative')\n }\n const selection = report.selections.find((row) => row.outcome === input.outcome)\n if (!selection) {\n throw new ValidationError(\n `guardDrift: the report has no selection for outcome ${input.outcome}`,\n )\n }\n const plan = report.plan\n validateChanges(input.batch, plan, false)\n const guards = selection.guards\n const interval = (rows: Array<{ unit: string; value: number }>): GuardDriftInterval | null => {\n const units = new Set(rows.map((row) => row.unit)).size\n if (rows.length === 0 || units < plan.minUnits) return null\n const result = clusterBootstrapMean(\n rows.map((row) => ({ cluster: row.unit, value: row.value })),\n {\n confidence: plan.confidence,\n resamples: plan.resamples,\n ...(plan.seed === undefined ? {} : { seed: plan.seed }),\n },\n )\n return { n: rows.length, units, estimate: result.mean, low: result.low, high: result.high }\n }\n const centered = (\n change: MeasuredChange,\n measure: string,\n direction: 'higher' | 'lower',\n reference: MeasureReference,\n ) => {\n const value = change.measures[measure]\n return value === undefined ? null : alignedZ(value, direction, reference) - reference.meanZ\n }\n\n const measures: GuardDriftMeasure[] = selection.climb.map((climbed) => {\n const shiftRows: Array<{ unit: string; value: number }> = []\n const guardRows: Array<{ unit: string; value: number }> = []\n const divergenceRows: Array<{ unit: string; value: number }> = []\n for (const change of input.batch) {\n const own = centered(change, climbed.measure, climbed.direction, climbed.reference)\n const guardValues = guards\n .map((guard) => centered(change, guard.measure, guard.direction, guard.reference))\n .filter((value): value is number => value !== null)\n if (own !== null) shiftRows.push({ unit: change.unit, value: own })\n if (guardValues.length === 0) continue\n const guardMean = guardValues.reduce((sum, value) => sum + value, 0) / guardValues.length\n guardRows.push({ unit: change.unit, value: guardMean })\n if (own !== null) divergenceRows.push({ unit: change.unit, value: own - guardMean })\n }\n const divergence = guards.length === 0 ? null : interval(divergenceRows)\n return {\n measure: climbed.measure,\n status:\n divergence === null\n ? 'insufficient'\n : divergence.low > tolerance\n ? 'drift'\n : 'within-tolerance',\n shift: interval(shiftRows),\n guardShift: guards.length === 0 ? null : interval(guardRows),\n divergence,\n }\n })\n\n let outcomeShift: GuardDriftInterval | null = null\n const outcomeSpec = plan.outcomes.find((row) => row.id === input.outcome)!\n const reference = selection.outcomeReference\n if (input.outcomes && reference) {\n const byRun = groupOutcomesByRun(await input.outcomes.list())\n const rows: Array<{ unit: string; value: number }> = []\n for (const change of input.batch) {\n const { eligible } = eligibleObservations(byRun.get(change.id) ?? [], change, plan, false)\n const joined = joinOutcomes(eligible, change, [outcomeSpec], plan.reduction).get(\n outcomeSpec.id,\n )\n if (!joined) continue\n rows.push({\n unit: change.unit,\n value:\n reference.kind === 'binary'\n ? joined.better - reference.betterRate\n : (joined.better - reference.center) / reference.scale - reference.meanZ,\n })\n }\n outcomeShift = interval(rows)\n }\n\n return {\n outcome: input.outcome,\n guards: guards.map((guard) => guard.measure),\n status:\n selection.climb.length === 0 || guards.length === 0\n ? 'no-guards'\n : measures.some((row) => row.status === 'drift')\n ? 'drift'\n : measures.every((row) => row.status === 'insufficient')\n ? 'insufficient'\n : 'no-drift',\n measures,\n outcomeShift,\n }\n}\n\nexport function outcomeReference(\n outcome: MeasureValidityOutcome,\n pre: readonly PreparedChange[],\n): MeasureSelection['outcomeReference'] {\n const values = pre.flatMap((row) => {\n const joined = row.outcomes.get(outcome.id)\n return joined === undefined ? [] : [joined.better]\n })\n if (values.length === 0) return null\n if (outcome.kind === 'binary') {\n return {\n kind: 'binary',\n betterRate: values.reduce((sum, value) => sum + value, 0) / values.length,\n }\n }\n const scaled = robustScale(values)\n if (scaled === null) return null\n const meanZ =\n values.reduce((sum, value) => sum + (value - scaled.center) / scaled.scale, 0) / values.length\n return { kind: 'continuous', ...scaled, meanZ }\n}\n\n// ── Selection ────────────────────────────────────────────────────────\n\nexport function robustScale(values: readonly number[]): { center: number; scale: number } | null {\n const center = sampleMedian(values)\n if (center === null) return null\n const mad = sampleMedian(values.map((value) => Math.abs(value - center)))! * 1.4826\n if (mad > 0) return { center, scale: mad }\n if (values.length < 2) return null\n const mean = values.reduce((sum, value) => sum + value, 0) / values.length\n const sd = Math.sqrt(\n values.reduce((sum, value) => sum + (value - mean) ** 2, 0) / (values.length - 1),\n )\n return sd > 0 ? { center, scale: sd } : null\n}\n\nexport function alignedZ(\n value: number,\n direction: 'higher' | 'lower',\n reference: { center: number; scale: number },\n): number {\n return ((direction === 'higher' ? 1 : -1) * (value - reference.center)) / reference.scale\n}\n\nexport function selectMeasures(\n outcome: MeasureValidityOutcome,\n pairs: readonly MeasureOutcomeValidity[],\n pre: readonly PreparedChange[],\n post: readonly PreparedChange[],\n plan: MeasureValidityPlan,\n outcomeRef: MeasureSelection['outcomeReference'],\n): MeasureSelection {\n const statistic = statisticOf(outcome)\n const nullValue = statistic === 'auc' ? 0.5 : 0\n const admitted = pairs.filter(\n (pair) =>\n pair.outcome === outcome.id &&\n (pair.label === 'predicts' ||\n pair.label === 'predicts-through-exposure' ||\n pair.label === 'predicts-pooled-only'),\n )\n const excluded: MeasureSelection['excluded'] = []\n const references = new Map<string, MeasureReference>()\n const candidates: MeasureOutcomeValidity[] = []\n for (const pair of admitted) {\n if (pair.measure === pair.exposure) {\n excluded.push({ measure: pair.measure, reason: 'exposure' })\n continue\n }\n if (pair.label === 'predicts-through-exposure') {\n excluded.push({ measure: pair.measure, reason: 'through-exposure' })\n continue\n }\n if (pair.label === 'predicts-pooled-only') {\n excluded.push({ measure: pair.measure, reason: 'pooled-only' })\n continue\n }\n const movement = pair.movement?.label\n if (movement === 'insensitive' || movement === 'moves-against-outcome') {\n excluded.push({ measure: pair.measure, reason: movement })\n continue\n }\n // The label is statistical; climbing also needs an effect worth the effort,\n // read inside exposure bins when the outcome has an exposure, since the\n // pooled estimate then carries the exposure's own effect.\n const floor = plan.selection.minEffect?.[statistic]\n const effect = pair.exposure === null ? pair.postCut.association : pair.postCut.withinExposure\n if (floor !== undefined && (effect === null || effect.estimate - effect.null < floor)) {\n excluded.push({ measure: pair.measure, reason: 'below-minimum-effect' })\n continue\n }\n const values = pre.flatMap((row) => {\n const value = row.change.measures[pair.measure]\n return value === undefined ? [] : [value]\n })\n const scaled = robustScale(values)\n if (scaled === null) continue\n const z = values.map((value) => alignedZ(value, pair.direction!, scaled))\n references.set(pair.measure, {\n ...scaled,\n meanZ: z.reduce((sum, value) => sum + value, 0) / z.length,\n })\n candidates.push(pair)\n }\n const pairOf = new Map(candidates.map((pair) => [pair.measure, pair]))\n const compositeRows = (rows: readonly PreparedChange[], set: readonly string[]) =>\n rows.flatMap((row) => {\n const joined = row.outcomes.get(outcome.id)\n if (joined === undefined) return []\n let sum = 0\n for (const measure of set) {\n const value = row.change.measures[measure]\n if (value === undefined) return []\n sum += alignedZ(value, pairOf.get(measure)!.direction!, references.get(measure)!)\n }\n return [{ x: sum / set.length, y: joined.better, unit: row.change.unit }]\n })\n const objective = (set: readonly string[]) => {\n const rows = compositeRows(pre, set)\n return rows.length < 3 ? Number.NaN : associationEstimate(statistic, rows)\n }\n const redundancy = (measure: string, climbed: readonly string[]) => {\n let best: { with: string; correlation: number } | null = null\n for (const other of climbed) {\n const xs: number[] = []\n const ys: number[] = []\n for (const row of pre) {\n const x = row.change.measures[measure]\n const y = row.change.measures[other]\n if (x === undefined || y === undefined) continue\n xs.push(x)\n ys.push(y)\n }\n if (xs.length < 3) continue\n const correlation = Math.abs(spearmanR(xs, ys))\n if (Number.isFinite(correlation) && (best === null || correlation > best.correlation)) {\n best = { with: other, correlation }\n }\n }\n return best\n }\n\n const climb: Array<{ measure: string; gain: number }> = []\n const guards: GuardMeasure[] = []\n let remaining = candidates.map((pair) => pair.measure)\n let current = nullValue\n const guard = (measure: string, reason: GuardMeasure['reason']): GuardMeasure => {\n const nearest = redundancy(\n measure,\n climb.map((row) => row.measure),\n )\n return {\n measure,\n direction: pairOf.get(measure)!.direction!,\n reason,\n redundantWith: reason === 'redundant' ? (nearest?.with ?? null) : null,\n correlation: nearest?.correlation ?? null,\n reference: references.get(measure)!,\n }\n }\n while (remaining.length > 0) {\n const climbed = climb.map((row) => row.measure)\n remaining = remaining.filter((measure) => {\n const nearest = redundancy(measure, climbed)\n if (nearest === null || nearest.correlation < plan.selection.maxRedundancy) return true\n guards.push(guard(measure, 'redundant'))\n return false\n })\n if (remaining.length === 0 || climb.length >= plan.selection.maxMeasures) break\n let best: { measure: string; value: number } | null = null\n for (const measure of remaining) {\n const value = objective([...climbed, measure])\n if (Number.isFinite(value) && (best === null || value > best.value)) best = { measure, value }\n }\n if (best === null) break\n const gain = best.value - current\n // The first measure must beat the null; each later one must add the plan's minimum gain.\n if (climb.length === 0 ? !(gain > 0) : !(gain >= plan.selection.minGain)) break\n climb.push({ measure: best.measure, gain })\n current = best.value\n remaining = remaining.filter((measure) => measure !== best.measure)\n }\n const sizeLimited = climb.length >= plan.selection.maxMeasures\n for (const measure of remaining)\n guards.push(guard(measure, sizeLimited ? 'size-limit' : 'no-gain'))\n\n const climbedIds = climb.map((row) => row.measure)\n const postRows = climbedIds.length === 0 ? [] : compositeRows(post, climbedIds)\n const postUnits = new Set(postRows.map((row) => row.unit)).size\n const composite: MeasureSelection['composite'] = {\n preCut:\n climbedIds.length === 0\n ? null\n : { n: compositeRows(pre, climbedIds).length, estimate: current },\n postCut:\n postRows.length >= plan.minJoined &&\n postUnits >= plan.minUnits &&\n Number.isFinite(associationEstimate(statistic, postRows))\n ? clusteredAssociation(postRows, {\n statistic,\n alternative: 'greater',\n resamples: plan.resamples,\n confidence: plan.confidence,\n ...(plan.seed === undefined ? {} : { seed: plan.seed }),\n })\n : null,\n }\n return {\n outcome: outcome.id,\n climb: climb.map(({ measure, gain }) => {\n const pair = pairOf.get(measure)!\n return {\n measure,\n direction: pair.direction!,\n preCutGain: gain,\n postCutEstimate: pair.postCut.association!.estimate,\n leadTimeMs: pair.leadTimeMs,\n cost: plan.measures.find((row) => row.id === measure)!.cost ?? null,\n reference: references.get(measure)!,\n }\n }),\n guards,\n excluded,\n composite,\n outcomeReference: outcomeRef,\n }\n}\n","/**\n * Which recorded numbers predict a result decided later, on changes they were\n * not chosen on, and which few of them to climb.\n *\n * A change has an id, a time, an independent unit and numbers known when it\n * was made. Outcomes join to it through `DeploymentOutcome.runId` and carry\n * their own capture time. The sealed plan's cut splits the changes: changes\n * before it, with outcomes known by it, fix each measure's direction, the\n * standardization and the selected subset; every reported statistic comes from\n * changes at or after it with those choices fixed. Intervals resample whole\n * units. Each test is one-sided, in the direction fixed before the cut, and\n * Benjamini-Hochberg at the plan's level runs across every pair tested, again\n * across every tested pair whose within-unit statistic is tested, and again\n * across every tested pair with a within-exposure statistic, whatever its\n * pooled result. A\n * pooled statistic compares changes across units; a within-unit statistic\n * compares changes of the same unit, so a measure that only tells units apart\n * is visible as `predicts-pooled-only`. An outcome may name an exposure, a\n * measure it grows with for another reason (a bigger change has more to fix);\n * every other measure is then also tested inside bins of the exposure, and one\n * that predicts only by tracking it is `predicts-through-exposure`.\n *\n * Prediction is not causation. An admitted measure forecasts the outcome of\n * changes like these; it does not show that raising the measure raises the\n * outcome. Records that show cause assign changes at random or interleave\n * them, so the measure moves for reasons unrelated to the outcome.\n */\n\nimport { ValidationError } from '../errors'\nimport {\n type MeasureValidityOutcome,\n type MeasureValidityPlan,\n type MeasureValidityPlanOutcome,\n type SealedMeasureValidityPlan,\n verifyMeasureValidityPlan,\n} from '../experiment/measure-validity-plan'\nimport { interpolatedQuantile } from '../math/quantile'\nimport {\n associationEstimate,\n type ClusteredAssociation,\n clusteredAssociation,\n} from '../statistics/clustered-association'\nimport { benjaminiHochberg } from '../statistics/multiplicity'\nimport { sampleMedian } from '../statistics/samples'\nimport { clusterBootstrapMean } from './cluster-bootstrap'\nimport {\n eligibleObservations,\n joinOutcomes,\n type MeasuredChange,\n type PreparedChange,\n statisticOf,\n validateChanges,\n} from './measure-records'\nimport { type MeasureSelection, outcomeReference, selectMeasures } from './measure-selection'\nimport { groupOutcomesByRun } from './outcome-observations'\nimport type { OutcomeStore } from './outcome-store'\n\nexport interface MeasureValidityInput {\n plan: SealedMeasureValidityPlan\n changes: readonly MeasuredChange[]\n outcomes: OutcomeStore\n /**\n * Epoch milliseconds at which the outcomes were read. An observation\n * captured after it is excluded, and a change after the cut counts for an\n * outcome with `windowMs` only when its window closed by it. Required when\n * any outcome declares `windowMs`; at or after the cut.\n */\n asOf?: number\n}\n\nexport type MeasureValidityReason =\n | 'below-minimum-count'\n | 'too-few-units'\n | 'too-little-variation'\n | 'no-pre-cut-direction'\n | 'constant-after-cut'\n | 'not-significant'\n | 'direction-reversed'\n | 'within-unit-not-shown'\n | 'within-unit-untested'\n | 'within-exposure-not-shown'\n | 'within-exposure-untested'\n\nexport interface MeasureCoverage {\n measure: string\n changes: number\n measured: number\n share: number\n preCut: { changes: number; measured: number }\n postCut: { changes: number; measured: number }\n /** Changes recording a before and after value. */\n movements: number\n}\n\nexport interface MeasureMovementValidity {\n label:\n | 'moves-with-outcome'\n | 'agreement-not-shown'\n | 'moves-against-outcome'\n | 'insensitive'\n | 'insufficient'\n /** Changes after the cut that record a movement. */\n changes: number\n units: number\n /** Changes whose `|after - before|` exceeds the declared noise. */\n moved: number\n /** Share of changes that moved beyond noise, with a whole-unit interval. */\n sensitivity: { estimate: number; low: number; high: number } | null\n /**\n * Among moved changes with an outcome, the AUC of the movement's direction\n * (aligned to the measure's predictive direction) for the better outcome.\n * This is balanced agreement: 0.5 under no relation whatever the base rates.\n */\n agreement: ClusteredAssociation | null\n qValue: number | null\n}\n\nexport interface MeasureOutcomeValidity {\n measure: string\n outcome: string\n statistic: 'auc' | 'spearman'\n /**\n * `predicts`: the pooled test passes, the test inside exposure bins passes\n * when the outcome names an exposure, and the within-unit test passes when\n * it is tested (`reason` is `within-unit-untested` when it is not).\n * `predicts-through-exposure`: the pooled test passes and the test inside\n * exposure bins does not, so the measure may predict only by tracking the\n * exposure. `predicts-pooled-only`: the pooled test passes and the tested\n * within-unit test does not, so the ranking may come from differences\n * between units rather than between changes. `not-shown`: tested and not\n * admitted. `insufficient`: not tested; `reason` says why.\n */\n label:\n | 'predicts'\n | 'predicts-through-exposure'\n | 'predicts-pooled-only'\n | 'not-shown'\n | 'insufficient'\n reason: MeasureValidityReason | null\n /** Which end of the measure predicts the better outcome, fixed before the cut. */\n direction: 'higher' | 'lower' | null\n /** The outcome's declared exposure measure, or null; the exposure's own pair has no exposure test. */\n exposure: string | null\n /** Which end predicts the better outcome inside exposure bins, fixed before the cut on that statistic. */\n withinExposureDirection: 'higher' | 'lower' | null\n /**\n * Before the cut, outcome known by the cut: the measure as recorded against\n * the better outcome, pooled and inside exposure bins.\n */\n preCut: { n: number; units: number; estimate: number | null; withinExposure: number | null }\n /**\n * After the cut, measure aligned to its fixed direction: above the null\n * favors the better outcome. Every test is one-sided in that direction.\n * `withinUnit` is estimated when at least two units hold a comparable pair\n * and tested (given a q-value) only when `minUnits` do. `withinExposure`\n * compares changes in the same exposure bin, aligned to\n * `withinExposureDirection`.\n */\n postCut: {\n n: number\n units: number\n /** Joined changes whose value differs from the measure's most common value. */\n minority: number\n association: ClusteredAssociation | null\n qValue: number | null\n withinUnit: ClusteredAssociation | null\n withinUnitQValue: number | null\n withinExposure: ClusteredAssociation | null\n withinExposureQValue: number | null\n }\n /** Outcome capture time minus change time over the joined changes after the cut. */\n leadTimeMs: { median: number; min: number; max: number } | null\n movement: MeasureMovementValidity | null\n}\n\n/** An outcome's exposure and the bins fixed before the cut. */\nexport interface MeasureExposureBins {\n outcome: string\n measure: string\n bins: number\n /**\n * Interior edges at the exposure's quantiles over the changes before the cut\n * joined to the outcome, with repeats removed; a value at an edge falls in\n * the lower bin.\n */\n edges: number[]\n}\n\nexport interface MeasureValidityReport {\n planDigest: string\n plan: MeasureValidityPlan\n claim: { causal: false; scope: string; causeRequires: string }\n /** How every p-value feeding the false-discovery correction was computed. */\n hypothesis: string\n changes: { total: number; preCut: number; postCut: number }\n units: { preCut: number; postCut: number; both: number }\n /** Outcome observations not joined, by reason. */\n /** When the outcomes were read, as given; null when not given. */\n asOf: number | null\n excludedObservations: {\n capturedBeforeChange: number\n /** Captured after `asOf`. */\n capturedAfterAsOf: number\n capturedAfterCutForPreCutChange: number\n beyondMaxCaptureLag: number\n /**\n * Change-outcome pairs before the cut with an outcome known by the cut\n * whose `windowMs` had not closed at the cut.\n */\n windowOpenAtCut: number\n /**\n * Change-outcome pairs after the cut with an outcome known by `asOf`\n * whose `windowMs` had not closed at `asOf`.\n */\n windowOpenAtEnd: number\n }\n exposures: MeasureExposureBins[]\n coverage: MeasureCoverage[]\n pairs: MeasureOutcomeValidity[]\n /** Pairs given a pooled p-value: the false-discovery family. */\n tested: number\n /**\n * Pairs given a pooled p-value whose within-unit statistic is tested, whatever\n * their pooled result: a second Benjamini-Hochberg family at the same level.\n */\n withinUnitTested: number\n /**\n * Pairs given a pooled p-value with a statistic inside exposure bins, whatever\n * their pooled result: a third Benjamini-Hochberg family at the same level.\n */\n withinExposureTested: number\n /** Pairs labelled `predicts`. */\n admitted: number\n /** Pairs whose movement agreement was tested: a second family at the same level. */\n movementTested: number\n selections: MeasureSelection[]\n}\n\nconst HYPOTHESIS =\n 'one-sided: the measure, aligned to the direction fixed before the cut, is above the null for the better outcome; Benjamini-Hochberg per family at the plan level'\n\nconst CLAIM = {\n causal: false as const,\n scope: 'held-out prediction: the measure forecasts the outcome of changes after the cut',\n causeRequires:\n 'randomized or interleaved assignment of changes, so the measure moves for reasons unrelated to the outcome',\n}\n\n/** Rank every planned measure against every planned outcome on changes after the cut. */\nexport async function measureValidityStudy(\n input: MeasureValidityInput,\n): Promise<MeasureValidityReport> {\n const sealed = structuredClone(input.plan)\n if (!verifyMeasureValidityPlan(sealed)) {\n throw new ValidationError(\n 'measureValidityStudy: the plan seal does not verify; seal it with sealMeasureValidityPlan before reading changes after the cut',\n )\n }\n const plan = sealed.plan\n const asOf = input.asOf\n if (asOf !== undefined && !(Number.isFinite(asOf) && asOf >= plan.cut)) {\n throw new ValidationError(\n 'measureValidityStudy: asOf must be finite epoch milliseconds at or after the cut',\n )\n }\n const windowed = plan.outcomes.filter((outcome) => outcome.windowMs !== undefined)\n if (asOf === undefined && windowed.length > 0) {\n throw new ValidationError(\n `measureValidityStudy: outcome ${windowed[0]!.id} declares windowMs, so asOf, the time the outcomes were read, is required`,\n )\n }\n validateChanges(input.changes, plan, true)\n const byRun = groupOutcomesByRun(await input.outcomes.list())\n const excluded = {\n capturedBeforeChange: 0,\n capturedAfterAsOf: 0,\n capturedAfterCutForPreCutChange: 0,\n beyondMaxCaptureLag: 0,\n windowOpenAtCut: 0,\n windowOpenAtEnd: 0,\n }\n const prepared = input.changes.map((change) => {\n const preCut = change.at < plan.cut\n const { eligible, ...counts } = eligibleObservations(\n byRun.get(change.id) ?? [],\n change,\n plan,\n preCut,\n asOf,\n )\n excluded.capturedBeforeChange += counts.capturedBeforeChange\n excluded.capturedAfterAsOf += counts.capturedAfterAsOf\n excluded.capturedAfterCutForPreCutChange += counts.capturedAfterCutForPreCutChange\n excluded.beyondMaxCaptureLag += counts.beyondMaxCaptureLag\n const outcomes = joinOutcomes(eligible, change, plan.outcomes, plan.reduction)\n // A windowed outcome counts only once its window has closed, by the cut\n // before it and by the read time after it, whatever its value: otherwise\n // recent events stay and recent non-events do not.\n for (const outcome of windowed) {\n const closesBy = preCut ? plan.cut : asOf!\n if (change.at + outcome.windowMs! > closesBy && outcomes.delete(outcome.id)) {\n if (preCut) excluded.windowOpenAtCut++\n else excluded.windowOpenAtEnd++\n }\n }\n return { change, preCut, outcomes }\n })\n const pre = prepared.filter((row) => row.preCut)\n const post = prepared.filter((row) => !row.preCut)\n const preUnits = new Set(pre.map((row) => row.change.unit))\n const postUnits = new Set(post.map((row) => row.change.unit))\n\n const exposures = plan.outcomes.flatMap((outcome) =>\n outcome.exposure === undefined ? [] : [exposureBins(outcome, pre)],\n )\n const pairs: MeasureOutcomeValidity[] = []\n for (const measure of plan.measures) {\n for (const outcome of plan.outcomes) {\n const bins = exposures.find((row) => row.outcome === outcome.id) ?? null\n pairs.push(assessPair(measure.id, outcome, bins, pre, post, plan))\n }\n }\n const tested = pairs.filter((pair) => pair.postCut.association !== null)\n const { qValues } = benjaminiHochberg(\n tested.map((pair) => pair.postCut.association!.pValue),\n plan.level,\n )\n tested.forEach((pair, index) => {\n pair.postCut.qValue = qValues[index]!\n })\n // The within-unit estimate is reported from two comparable units; it is tested from `minUnits`.\n const withinTested = tested.filter(\n (pair) => pair.postCut.withinUnit !== null && pair.postCut.withinUnit.units >= plan.minUnits,\n )\n const withinQ = benjaminiHochberg(\n withinTested.map((pair) => pair.postCut.withinUnit!.pValue),\n plan.level,\n ).qValues\n withinTested.forEach((pair, index) => {\n pair.postCut.withinUnitQValue = withinQ[index]!\n })\n const exposureTested = tested.filter((pair) => pair.postCut.withinExposure !== null)\n const exposureQ = benjaminiHochberg(\n exposureTested.map((pair) => pair.postCut.withinExposure!.pValue),\n plan.level,\n ).qValues\n exposureTested.forEach((pair, index) => {\n pair.postCut.withinExposureQValue = exposureQ[index]!\n })\n for (const pair of tested) labelPair(pair, plan.level)\n\n const outcomeReferences = new Map(\n plan.outcomes.map((outcome) => [outcome.id, outcomeReference(outcome, pre)]),\n )\n for (const pair of pairs) {\n const outcome = plan.outcomes.find((row) => row.id === pair.outcome)!\n pair.movement = assessMovement(pair, outcome, post, plan, outcomeReferences.get(outcome.id)!)\n }\n const movementTested = pairs.filter((pair) => pair.movement?.agreement)\n const movementQ = benjaminiHochberg(\n movementTested.map((pair) => pair.movement!.agreement!.pValue),\n plan.level,\n ).qValues\n movementTested.forEach((pair, index) => {\n const movement = pair.movement!\n const agreement = movement.agreement!\n const q = movementQ[index]!\n movement.qValue = q\n movement.label =\n q <= plan.level\n ? 'moves-with-outcome'\n : agreement.high < agreement.null\n ? 'moves-against-outcome'\n : 'agreement-not-shown'\n })\n\n const selections = plan.outcomes.map((outcome) =>\n selectMeasures(outcome, pairs, pre, post, plan, outcomeReferences.get(outcome.id)!),\n )\n\n return {\n planDigest: sealed.digest,\n plan,\n asOf: asOf ?? null,\n claim: { ...CLAIM },\n hypothesis: HYPOTHESIS,\n changes: { total: prepared.length, preCut: pre.length, postCut: post.length },\n units: {\n preCut: preUnits.size,\n postCut: postUnits.size,\n both: [...postUnits].filter((unit) => preUnits.has(unit)).length,\n },\n excludedObservations: excluded,\n exposures,\n coverage: plan.measures.map((measure) => coverageOf(measure.id, pre, post)),\n pairs,\n tested: tested.length,\n withinUnitTested: withinTested.length,\n withinExposureTested: exposureTested.length,\n admitted: pairs.filter((pair) => pair.label === 'predicts').length,\n movementTested: movementTested.length,\n selections,\n }\n}\n\n/**\n * The pooled test admits; the test inside exposure bins and then the tested\n * within-unit test can only narrow the label.\n */\nfunction labelPair(pair: MeasureOutcomeValidity, level: number): void {\n const association = pair.postCut.association!\n if (pair.postCut.qValue! > level) {\n pair.label = 'not-shown'\n // A one-sided test cannot reject the other way; a reversal is an interval wholly past the null.\n pair.reason = association.high < association.null ? 'direction-reversed' : 'not-significant'\n return\n }\n if (pair.exposure !== null && pair.exposure !== pair.measure) {\n const within = pair.postCut.withinExposure\n if (within === null) {\n pair.label = 'predicts-through-exposure'\n pair.reason = 'within-exposure-untested'\n return\n }\n // Shown beyond the exposure only in the direction the pooled test admitted.\n if (\n pair.withinExposureDirection !== pair.direction ||\n pair.postCut.withinExposureQValue! > level\n ) {\n pair.label = 'predicts-through-exposure'\n pair.reason = 'within-exposure-not-shown'\n return\n }\n }\n if (pair.postCut.withinUnitQValue === null) {\n pair.label = 'predicts'\n pair.reason = 'within-unit-untested'\n } else if (pair.postCut.withinUnitQValue > level) {\n pair.label = 'predicts-pooled-only'\n pair.reason = 'within-unit-not-shown'\n } else {\n pair.label = 'predicts'\n pair.reason = null\n }\n}\n\n/** Bin edges at the exposure's quantiles over changes before the cut joined to the outcome. */\nfunction exposureBins(\n outcome: MeasureValidityPlanOutcome,\n pre: readonly PreparedChange[],\n): MeasureExposureBins {\n const { measure, bins } = outcome.exposure!\n const values = pre\n .flatMap((row) => {\n const value = row.change.measures[measure]\n return value === undefined || !row.outcomes.has(outcome.id) ? [] : [value]\n })\n .sort((a, b) => a - b)\n const edges: number[] = []\n if (values.length > 0) {\n for (let k = 1; k < bins; k++) {\n const edge = interpolatedQuantile(values, k / bins)\n if (edge !== edges[edges.length - 1]) edges.push(edge)\n }\n }\n return { outcome: outcome.id, measure, bins, edges }\n}\n\n/** The bin of a value: the number of edges below it. */\nfunction binOf(value: number, edges: readonly number[]): string {\n let bin = 0\n while (bin < edges.length && value > edges[bin]!) bin++\n return String(bin)\n}\n\nfunction coverageOf(\n measure: string,\n pre: readonly PreparedChange[],\n post: readonly PreparedChange[],\n): MeasureCoverage {\n const measured = (rows: readonly PreparedChange[]) =>\n rows.filter((row) => row.change.measures[measure] !== undefined).length\n const changes = pre.length + post.length\n const total = measured(pre) + measured(post)\n return {\n measure,\n changes,\n measured: total,\n share: changes === 0 ? 0 : total / changes,\n preCut: { changes: pre.length, measured: measured(pre) },\n postCut: { changes: post.length, measured: measured(post) },\n movements: [...pre, ...post].filter((row) => row.change.movements?.[measure] !== undefined)\n .length,\n }\n}\n\n// ── Prediction ───────────────────────────────────────────────────────\n\n/** Joined changes for one pair; `stratum` is the exposure bin when the exposure was measured. */\nfunction joinedRows(\n rows: readonly PreparedChange[],\n measure: string,\n outcome: string,\n exposure: MeasureExposureBins | null,\n) {\n return rows.flatMap((row) => {\n const x = row.change.measures[measure]\n const joined = row.outcomes.get(outcome)\n if (x === undefined || joined === undefined) return []\n const exposed = exposure === null ? undefined : row.change.measures[exposure.measure]\n return [\n {\n x,\n y: joined.better,\n unit: row.change.unit,\n lag: joined.capturedAt - row.change.at,\n ...(exposed === undefined ? {} : { stratum: binOf(exposed, exposure!.edges) }),\n },\n ]\n })\n}\n\nfunction assessPair(\n measure: string,\n outcome: MeasureValidityOutcome,\n exposure: MeasureExposureBins | null,\n pre: readonly PreparedChange[],\n post: readonly PreparedChange[],\n plan: MeasureValidityPlan,\n): MeasureOutcomeValidity {\n const statistic = statisticOf(outcome)\n const nullValue = statistic === 'auc' ? 0.5 : 0\n const preRows = joinedRows(pre, measure, outcome.id, exposure)\n const postRows = joinedRows(post, measure, outcome.id, exposure)\n const preEstimate = preRows.length >= 3 ? associationEstimate(statistic, preRows) : Number.NaN\n const direction = directionOf(preEstimate, nullValue)\n const testsExposure = exposure !== null && exposure.measure !== measure\n const preBinned = preRows.filter((row) => row.stratum !== undefined)\n const preWithinExposure =\n testsExposure && preBinned.length >= 3\n ? associationEstimate(statistic, preBinned, 'stratified')\n : Number.NaN\n const exposureDirection = directionOf(preWithinExposure, nullValue)\n const postUnits = new Set(postRows.map((row) => row.unit)).size\n const lags = postRows.map((row) => row.lag)\n const result: MeasureOutcomeValidity = {\n measure,\n outcome: outcome.id,\n statistic,\n label: 'insufficient',\n reason: null,\n direction,\n exposure: exposure?.measure ?? null,\n withinExposureDirection: exposureDirection,\n preCut: {\n n: preRows.length,\n units: new Set(preRows.map((row) => row.unit)).size,\n estimate: Number.isFinite(preEstimate) ? preEstimate : null,\n withinExposure: Number.isFinite(preWithinExposure) ? preWithinExposure : null,\n },\n postCut: {\n n: postRows.length,\n units: postUnits,\n minority: minorityCount(postRows.map((row) => row.x)),\n association: null,\n qValue: null,\n withinUnit: null,\n withinUnitQValue: null,\n withinExposure: null,\n withinExposureQValue: null,\n },\n leadTimeMs:\n lags.length === 0\n ? null\n : {\n median: sampleMedian(lags)!,\n min: lags.reduce((a, b) => Math.min(a, b)),\n max: lags.reduce((a, b) => Math.max(a, b)),\n },\n movement: null,\n }\n const aligned = postRows.map((row) => ({\n x: direction === 'lower' ? -row.x : row.x,\n y: row.y,\n unit: row.unit,\n }))\n if (postRows.length < plan.minJoined) result.reason = 'below-minimum-count'\n else if (postUnits < plan.minUnits) result.reason = 'too-few-units'\n else if (result.postCut.minority < plan.minMinority) result.reason = 'too-little-variation'\n else if (direction === null) result.reason = 'no-pre-cut-direction'\n else if (!Number.isFinite(associationEstimate(statistic, aligned)))\n result.reason = 'constant-after-cut'\n if (result.reason !== null) return result\n const options = {\n statistic,\n alternative: 'greater' as const,\n resamples: plan.resamples,\n confidence: plan.confidence,\n ...(plan.seed === undefined ? {} : { seed: plan.seed }),\n }\n result.postCut.association = clusteredAssociation(aligned, options)\n if (\n comparableUnits(aligned) >= 2 &&\n Number.isFinite(associationEstimate(statistic, aligned, 'within-unit'))\n ) {\n result.postCut.withinUnit = clusteredAssociation(aligned, { ...options, scope: 'within-unit' })\n }\n if (testsExposure && exposureDirection !== null) {\n const binned = postRows.flatMap((row) =>\n row.stratum === undefined\n ? []\n : [\n {\n x: exposureDirection === 'lower' ? -row.x : row.x,\n y: row.y,\n unit: row.unit,\n stratum: row.stratum,\n },\n ],\n )\n const units = new Set(binned.map((row) => row.unit)).size\n if (units >= 2 && Number.isFinite(associationEstimate(statistic, binned, 'stratified'))) {\n result.postCut.withinExposure = clusteredAssociation(binned, {\n ...options,\n scope: 'stratified',\n })\n }\n }\n return result\n}\n\nfunction directionOf(estimate: number, nullValue: number): 'higher' | 'lower' | null {\n if (!Number.isFinite(estimate)) return null\n return estimate > nullValue ? 'higher' : estimate < nullValue ? 'lower' : null\n}\n\n/** Values that differ from the most common value: the smaller class of a two-valued measure. */\nfunction minorityCount(values: readonly number[]): number {\n const counts = new Map<number, number>()\n let largest = 0\n for (const value of values) {\n const count = (counts.get(value) ?? 0) + 1\n counts.set(value, count)\n largest = Math.max(largest, count)\n }\n return values.length - largest\n}\n\n/** Units holding a comparable pair: two changes with different outcomes. */\nfunction comparableUnits(rows: readonly { y: number; unit: string }[]): number {\n const seen = new Map<string, number>()\n const comparable = new Set<string>()\n for (const row of rows) {\n const first = seen.get(row.unit)\n if (first === undefined) seen.set(row.unit, row.y)\n else if (first !== row.y) comparable.add(row.unit)\n }\n return comparable.size\n}\n\n// ── Movement under change ────────────────────────────────────────────\n\nfunction assessMovement(\n pair: MeasureOutcomeValidity,\n outcome: MeasureValidityOutcome,\n post: readonly PreparedChange[],\n plan: MeasureValidityPlan,\n reference: MeasureSelection['outcomeReference'],\n): MeasureMovementValidity | null {\n const noise = plan.measures.find((row) => row.id === pair.measure)!.noise\n const rows = post.flatMap((row) => {\n const movement = row.change.movements?.[pair.measure]\n return movement === undefined ? [] : [{ row, delta: movement.after - movement.before }]\n })\n if (noise === undefined || rows.length === 0) return null\n const units = new Set(rows.map(({ row }) => row.change.unit)).size\n const moved = rows.filter(({ delta }) => Math.abs(delta) > noise)\n const result: MeasureMovementValidity = {\n label: 'insufficient',\n changes: rows.length,\n units,\n moved: moved.length,\n sensitivity: null,\n agreement: null,\n qValue: null,\n }\n if (rows.length < plan.minJoined || units < plan.minUnits) return result\n const sensitivity = clusterBootstrapMean(\n rows.map(({ row, delta }) => ({\n cluster: row.change.unit,\n value: Math.abs(delta) > noise ? 1 : 0,\n })),\n {\n confidence: plan.confidence,\n resamples: plan.resamples,\n ...(plan.seed === undefined ? {} : { seed: plan.seed }),\n },\n )\n result.sensitivity = { estimate: sensitivity.mean, low: sensitivity.low, high: sensitivity.high }\n if (sensitivity.high < plan.minSensitivity) {\n result.label = 'insensitive'\n return result\n }\n if (pair.direction === null || reference === null) return result\n const sign = pair.direction === 'higher' ? 1 : -1\n const agreementRows = moved.flatMap(({ row, delta }) => {\n const joined = row.outcomes.get(outcome.id)\n if (joined === undefined) return []\n const better =\n reference.kind === 'binary'\n ? joined.better\n : joined.better > reference.center\n ? 1\n : joined.better < reference.center\n ? 0\n : null\n return better === null ? [] : [{ x: Math.sign(sign * delta), y: better, unit: row.change.unit }]\n })\n const agreementUnits = new Set(agreementRows.map((row) => row.unit)).size\n if (\n agreementRows.length < plan.minJoined ||\n agreementUnits < plan.minUnits ||\n !Number.isFinite(associationEstimate('auc', agreementRows))\n ) {\n return result\n }\n result.agreement = clusteredAssociation(agreementRows, {\n statistic: 'auc',\n alternative: 'greater',\n resamples: plan.resamples,\n confidence: plan.confidence,\n ...(plan.seed === undefined ? {} : { seed: plan.seed }),\n })\n return result\n}\n","/**\n * Plants — seeded known-wrong items that measure the grader, not the work.\n *\n * A grading run reports how the work scored. It cannot report whether the\n * grader would have noticed a wrong answer, because every item it saw was\n * authored in good faith. A plant closes that hole: an item authored wrong by\n * construction is mixed into the live set, graded by the same path as\n * everything else, and the share of plants the grader refused is the catch\n * rate.\n *\n * Measured motive: a sibling lab ran a deliverable gate that accepted any\n * non-empty submission. It produced six false certifications in seventeen\n * deliveries, and no agent lied — the gate never asked a question the format\n * could fail. A catch rate is the number that would have shown it on day one.\n *\n * This module composes existing primitives rather than adding parallel ones:\n *\n * - A plant IS a {@link GoldenItem} from `../judge-calibration`. Its\n * `humanScore` is the grade a working grader owes the item, so the same\n * array feeds `calibrateJudge` unchanged.\n * - The grader's output is `CandidateScore[]`, the array `calibrateJudge` and\n * `snapshotFromSentinelSet` already consume.\n * - \"Caught\" is `snapshotFromSentinelSet`'s join with the labels inverted:\n * the grade lands on the side of `acceptThreshold` the seed demands.\n * - The manifest is sealed with `hashCanonical` from `../ledger-core/canonical`,\n * the digest the sealed-experiment path uses, so the answer key cannot be\n * revised once the results are in.\n *\n * Authoring the wrong item is the step before all of that, and it is where the\n * measurement silently breaks. {@link plantByPerturbation} takes a claim a\n * grader verified and alters exactly one load-bearing value in its evidence,\n * so the grader is asked a question it must fail. Hand-rolled perturbation\n * bumps a number that is part of an identity — `python3`, `file42.txt`, `1.5`,\n * `utf-8` — and the check stops EXECUTING; the plant then measures the\n * environment rather than the grader. {@link perturbEvidence} refuses those\n * digit runs by construction.\n *\n * Blindness has two halves, and this module owns one. It never puts a plant\n * flag on a graded item: `seedPlants` returns the mixed set and a manifest,\n * and only the manifest knows which ids are seeded. Keeping the manifest out\n * of the graded workspace and publishing its `seal` before grading is the\n * caller's half; {@link catchRate} refuses a manifest whose contents no longer\n * match its seal.\n *\n * Refusals, because a catch rate that cannot refuse is not a measurement:\n *\n * - a seeded id with no result makes the report `incomplete`, never a rate\n * over the results that did come back;\n * - zero seeded plants makes it `not_evaluated`, never 1.0;\n * - a result for an id the manifest never handed out is refused outright.\n */\n\nimport { CaptureIntegrityError, ValidationError } from '../errors'\nimport type { GoldenItem } from '../judge-calibration'\nimport { hashCanonical, type LedgerHash } from '../ledger-core/canonical'\nimport { mulberry32 } from '../statistics/random'\n\n/**\n * How a plant item was authored wrong. The class is reported separately in\n * {@link CatchRateReport.byKind} because a grader is routinely sharp on one\n * and blind to another.\n */\nexport type PlantKind =\n /** A load-bearing value is altered: a number off by one, a comparison flipped. */\n | 'wrong-value'\n /** The item carries its own check, and that check passes without testing the claim. */\n | 'self-certifying'\n /** The check names an input that does not exist, so it cannot run at all. */\n | 'unreachable-input'\n /** A copy of an item already in the set, which is owed a duplicate flag rather than a second grade. */\n | 'duplicate'\n\nconst PLANT_KINDS: readonly PlantKind[] = [\n 'wrong-value',\n 'self-certifying',\n 'unreachable-input',\n 'duplicate',\n]\n\n/** What a working grader owes a seeded item. */\nexport type PlantExpectation = 'reject' | 'accept'\n\nconst PLANT_EXPECTATIONS: readonly PlantExpectation[] = ['reject', 'accept']\n\n/** The label boundary a plant record is checked against at definition time. */\nconst RECORD_LABEL_BOUNDARY = 0.5\n\nexport interface Plant {\n /** Name of the plant record. Reported in `missedIds` and `missingIds`. */\n id: string\n kind: PlantKind\n /** The seeded item, indistinguishable from a real one once mixed. */\n item: GoldenItem\n /** The verdict a working grader owes this item. */\n expectedVerdict: PlantExpectation\n}\n\n/**\n * Build one plant record and refuse an incoherent one.\n *\n * The refusal that matters is the last: a record whose `expectedVerdict`\n * disagrees with `item.humanScore` inverts the measurement silently, because\n * the same item then reads as wrong here and as correct to every calibration\n * instrument that joins on the id.\n *\n * `item` is copied field by field so a later mutation of the caller's object\n * cannot change what the manifest sealed, and `group` is dropped when it is\n * absent so the record always has a canonical JSON form.\n */\nexport function definePlant(input: {\n id: string\n kind: PlantKind\n item: GoldenItem\n expectedVerdict: PlantExpectation\n}): Plant {\n const { id, kind, item, expectedVerdict } = input\n if (typeof id !== 'string' || id.trim() === '') {\n throw new ValidationError('definePlant: id must be a non-empty string')\n }\n if (!PLANT_KINDS.includes(kind)) {\n throw new ValidationError(\n `definePlant: plant \"${id}\" has kind ${JSON.stringify(kind)}; expected one of ${PLANT_KINDS.join(', ')}`,\n )\n }\n if (!PLANT_EXPECTATIONS.includes(expectedVerdict)) {\n throw new ValidationError(\n `definePlant: plant \"${id}\" has expectedVerdict ${JSON.stringify(expectedVerdict)}; expected one of ${PLANT_EXPECTATIONS.join(', ')}`,\n )\n }\n if (typeof item.itemId !== 'string' || item.itemId.trim() === '') {\n throw new ValidationError(`definePlant: plant \"${id}\" has an empty item.itemId`)\n }\n if (!Number.isFinite(item.humanScore) || item.humanScore < 0 || item.humanScore > 1) {\n throw new ValidationError(\n `definePlant: plant \"${id}\" has humanScore ${item.humanScore}; expected a finite number in [0, 1]`,\n )\n }\n if (item.group !== undefined && typeof item.group !== 'string') {\n throw new ValidationError(`definePlant: plant \"${id}\" has a non-string item.group`)\n }\n if (item.humanScore === RECORD_LABEL_BOUNDARY) {\n throw new ValidationError(\n `definePlant: plant \"${id}\" has humanScore ${RECORD_LABEL_BOUNDARY}, which states neither a rejection nor an acceptance`,\n )\n }\n const labelSays: PlantExpectation = item.humanScore < RECORD_LABEL_BOUNDARY ? 'reject' : 'accept'\n if (labelSays !== expectedVerdict) {\n throw new ValidationError(\n `definePlant: plant \"${id}\" expects the grader to ${expectedVerdict} it, but humanScore ${item.humanScore} says ${labelSays}`,\n )\n }\n return {\n id,\n kind,\n item: {\n itemId: item.itemId,\n humanScore: item.humanScore,\n ...(item.group === undefined ? {} : { group: item.group }),\n },\n expectedVerdict,\n }\n}\n\n/**\n * A claim's executable evidence: the command a grader runs and the output it\n * must produce.\n */\nexport interface PlantEvidence {\n /** The command a grader runs to test the claim. */\n check?: string\n /** The output that command must produce for the claim to stand. */\n expect?: string\n}\n\n/** Which evidence field {@link perturbEvidence} altered. */\nexport type PerturbedField = 'check' | 'expect'\n\n/** How {@link perturbEvidence} altered it. */\nexport type PerturbationKind = 'number-off-by-one' | 'comparison-flipped'\n\nexport interface EvidencePerturbation {\n /** The evidence with exactly one value altered. */\n evidence: PlantEvidence\n /** Which field changed. */\n field: PerturbedField\n /** How it changed. */\n how: PerturbationKind\n /**\n * The exact substring that was replaced. A comparison token carries its\n * surrounding spaces, because the spaces are what make ` -ge ` a comparison\n * and not part of a word.\n */\n original: string\n /** What replaced it. */\n perturbed: string\n}\n\n/**\n * Characters that make a digit run part of something larger than a number.\n *\n * A run that touches one of these is an identity — `python3`, `file42.txt`,\n * `1.5`, `utf-8` — and bumping it renames a program, a file, a version, or an\n * encoding instead of falsifying the claim. The check then stops EXECUTING,\n * and a plant that cannot run measures the environment rather than the grader:\n * it reads as caught, for a reason that has nothing to do with the seeded\n * defect.\n */\nconst NUMBER_GLUE = /[A-Za-z0-9_./-]/\n\n/**\n * Comparison tokens that mean one thing only, each with its inversion.\n *\n * A bare `>` or `<` is absent on purpose: in a shell check it is a\n * redirection, so flipping it rewrites where output goes rather than what the\n * test asks, and the check stops testing the claim.\n */\nconst COMPARISON_FLIPS: readonly (readonly [string, string])[] = [\n [' -ge ', ' -lt '],\n [' -gt ', ' -le '],\n [' -le ', ' -gt '],\n [' -lt ', ' -ge '],\n [' -eq ', ' -ne '],\n [' -ne ', ' -eq '],\n ['>=', '<'],\n ['<=', '>'],\n ['==', '!='],\n ['!=', '=='],\n]\n\ninterface Span {\n start: number\n end: number\n}\n\n/**\n * The last digit run in `text` that is a number and nothing else, or null.\n *\n * The last is taken because a measured value trails its label — `count=42`,\n * `n>=5 OK cells=8` — and because the choice has to be deterministic: the same\n * claim must always yield the same plant, or two runs of the same authoring\n * step seed two different answer keys for one item.\n */\nfunction lastStandaloneNumber(text: string): Span | null {\n const digits = /\\d+/g\n let found: Span | null = null\n let match = digits.exec(text)\n while (match !== null) {\n const start = match.index\n const end = start + match[0].length\n // charAt returns '' outside the string, and NUMBER_GLUE never matches ''.\n if (!NUMBER_GLUE.test(text.charAt(start - 1)) && !NUMBER_GLUE.test(text.charAt(end))) {\n found = { start, end }\n }\n match = digits.exec(text)\n }\n return found\n}\n\n/**\n * The first flippable comparison in `text`, or null.\n *\n * Any single flip inverts the test wherever it sits, so unlike the number rule\n * there is no safety ordering among the matches. The first is taken so the\n * result is fixed by the head of the command and does not move when a later\n * comparison is added.\n */\nfunction firstComparison(text: string): { span: Span; flipped: string } | null {\n for (let index = 0; index < text.length; index += 1) {\n for (const [token, flipped] of COMPARISON_FLIPS) {\n if (text.startsWith(token, index)) {\n return { span: { start: index, end: index + token.length }, flipped }\n }\n }\n }\n return null\n}\n\nfunction replaceSpan(text: string, span: Span, value: string): string {\n return text.slice(0, span.start) + value + text.slice(span.end)\n}\n\n/**\n * Rebuild the evidence with one field replaced. An absent field is dropped\n * rather than set to undefined, so the record always has a canonical JSON form.\n */\nfunction withField(\n check: string | undefined,\n expect: string | undefined,\n field: PerturbedField,\n value: string,\n): PlantEvidence {\n const nextCheck = field === 'check' ? value : check\n const nextExpect = field === 'expect' ? value : expect\n return {\n ...(nextCheck === undefined ? {} : { check: nextCheck }),\n ...(nextExpect === undefined ? {} : { expect: nextExpect }),\n }\n}\n\nfunction offByOne(\n check: string | undefined,\n expect: string | undefined,\n field: PerturbedField,\n text: string,\n span: Span,\n): EvidencePerturbation {\n const original = text.slice(span.start, span.end)\n const perturbed = (BigInt(original) + 1n).toString()\n return {\n evidence: withField(check, expect, field, replaceSpan(text, span, perturbed)),\n field,\n how: 'number-off-by-one',\n original,\n perturbed,\n }\n}\n\n/**\n * Derive a known-wrong version of a claim's evidence by altering exactly one\n * value, or return null when no value can be altered safely.\n *\n * Exactly one value changes. A perturbation that moves two does not name the\n * defect it seeded, so a grader that catches it says nothing about which defect\n * the grader can see.\n *\n * The preference order IS the safety order:\n *\n * 1. the last standalone number in `expect` — it falsifies the claim while the\n * command still runs exactly as it did;\n * 2. a flipped comparison in `check` — it inverts a test that was passing;\n * 3. the last standalone number in `check` — last because a number in a command\n * can name an input (a port, a width, a version) rather than a threshold,\n * and renaming an input breaks execution, not the claim.\n *\n * \"Standalone\" excludes a digit run glued to a word, a dot, a slash, or a\n * hyphen: `python3`, `file42.txt`, `1.5`, `utf-8`. That exclusion is why this\n * helper exists. Hand-rolled perturbation bumps one of those, the check stops\n * executing, and the plant measures the environment instead of the grader.\n *\n * A number is bumped with BigInt, so a value wider than\n * `Number.MAX_SAFE_INTEGER` moves by exactly one. Bumped as a `number` it\n * rounds back to itself, and the plant is then a correct claim the grader is\n * right to verify.\n */\nexport function perturbEvidence(evidence: PlantEvidence): EvidencePerturbation | null {\n const check = typeof evidence.check === 'string' ? evidence.check : undefined\n const expect = typeof evidence.expect === 'string' ? evidence.expect : undefined\n\n if (expect !== undefined) {\n const span = lastStandaloneNumber(expect)\n if (span !== null) return offByOne(check, expect, 'expect', expect, span)\n }\n if (check !== undefined) {\n const comparison = firstComparison(check)\n if (comparison !== null) {\n return {\n evidence: withField(\n check,\n expect,\n 'check',\n replaceSpan(check, comparison.span, comparison.flipped),\n ),\n field: 'check',\n how: 'comparison-flipped',\n original: check.slice(comparison.span.start, comparison.span.end),\n perturbed: comparison.flipped,\n }\n }\n const span = lastStandaloneNumber(check)\n if (span !== null) return offByOne(check, expect, 'check', check, span)\n }\n return null\n}\n\nexport interface PerturbedPlant {\n plant: Plant\n /** The perturbed evidence to write into the item the grader is handed. */\n evidence: PlantEvidence\n field: PerturbedField\n how: PerturbationKind\n original: string\n perturbed: string\n}\n\n/**\n * Derive a reject-direction plant from a claim a grader verified, by perturbing\n * one value.\n *\n * {@link definePlant} takes a {@link GoldenItem} and never authors a wrong item\n * from a right one, so until now every caller hand-rolled the perturbation.\n * This is that step, done once and the same way every time: the claim's\n * evidence is altered by {@link perturbEvidence}, the result is a `wrong-value`\n * plant the grader owes a `reject`, and the record itself is built by\n * `definePlant` so every refusal there still applies — in particular the one\n * that catches an `expectedVerdict` its `humanScore` contradicts.\n *\n * Returns null when nothing in the evidence can be perturbed. That is not a\n * failure: a claim with no executable evidence cannot be made wrong in a way a\n * grader could execute, and seeding it would measure prose.\n *\n * Refuses an empty `id` or `itemId`. Both name the record — one in the manifest\n * and in `missedIds`, the other in the join with the results — and a miss\n * nobody can look up is not a measurement.\n */\nexport function plantByPerturbation(input: {\n id: string\n itemId: string\n evidence: PlantEvidence\n /** Score for the perturbed item. Must sit below the run's accept threshold. Default 0. */\n humanScore?: number\n group?: string\n}): PerturbedPlant | null {\n const { id, itemId, evidence, humanScore = 0, group } = input\n if (typeof id !== 'string' || id.trim() === '') {\n throw new ValidationError('plantByPerturbation: id must be a non-empty string')\n }\n if (typeof itemId !== 'string' || itemId.trim() === '') {\n throw new ValidationError(`plantByPerturbation: plant \"${id}\" has an empty itemId`)\n }\n const perturbation = perturbEvidence(evidence)\n if (perturbation === null) return null\n const plant = definePlant({\n id,\n kind: 'wrong-value',\n item: { itemId, humanScore, ...(group === undefined ? {} : { group }) },\n expectedVerdict: 'reject',\n })\n return {\n plant,\n evidence: perturbation.evidence,\n field: perturbation.field,\n how: perturbation.how,\n original: perturbation.original,\n perturbed: perturbation.perturbed,\n }\n}\n\nexport interface PlantManifest {\n /**\n * Digest over the seeded order, the plants, and the threshold. Publish it\n * before the grading run: a manifest edited afterwards to match the results\n * no longer matches its seal, and {@link catchRate} refuses it.\n */\n seal: LedgerHash\n /** The seed that fixed the mix order. */\n seed: number\n /** The grade at or above which the graded policy's own gate accepts an item. */\n acceptThreshold: number\n /** Every item id in the seeded set, in the order handed out. */\n itemIds: string[]\n /** The seeded plants. This is the answer key; keep it out of the graded workspace. */\n plants: Plant[]\n}\n\nexport interface SeededGradingSet {\n /**\n * The mixed set in seeded order. Operator-side: it still carries every\n * item's `humanScore`, so hand the graded policy the payload each `itemId`\n * names, never this array.\n */\n items: GoldenItem[]\n manifest: PlantManifest\n}\n\nexport interface SeedPlantsOptions {\n /**\n * Fixes the mix order. The same dataset, plants, threshold, and seed always\n * produce the same seeded order and the same seal.\n */\n seed?: number\n /**\n * The grade at or above which the graded policy's own gate accepts an item.\n * Supply the threshold your gate uses; the default suits a judge scoring in\n * [0, 1] with a pass at the midpoint.\n */\n acceptThreshold?: number\n}\n\n/**\n * Mix plants into a grading set and seal which items they are.\n *\n * Refusals: a duplicate id anywhere in the mixed set (the join is by id, so a\n * repeat makes one of the two unscoreable), a plant whose item id collides\n * with a dataset item (it would shadow real work and grade it as a plant), a\n * dataset item with no usable label, and a plant whose expectation the run's\n * `acceptThreshold` contradicts.\n */\nexport function seedPlants(\n dataset: readonly GoldenItem[],\n plants: readonly Plant[],\n options: SeedPlantsOptions = {},\n): SeededGradingSet {\n const seed = options.seed ?? 7\n const acceptThreshold = options.acceptThreshold ?? 0.5\n if (!Number.isFinite(seed)) {\n throw new ValidationError(`seedPlants: seed must be a finite number, got ${seed}`)\n }\n if (!Number.isFinite(acceptThreshold) || acceptThreshold <= 0 || acceptThreshold > 1) {\n throw new ValidationError(\n `seedPlants: acceptThreshold must be a finite number in (0, 1], got ${acceptThreshold}`,\n )\n }\n\n const datasetItems: GoldenItem[] = []\n const seen = new Set<string>()\n for (const item of dataset) {\n if (typeof item.itemId !== 'string' || item.itemId.trim() === '') {\n throw new ValidationError('seedPlants: a dataset item has an empty itemId')\n }\n if (!Number.isFinite(item.humanScore)) {\n throw new ValidationError(\n `seedPlants: dataset item \"${item.itemId}\" has a non-finite humanScore`,\n )\n }\n if (seen.has(item.itemId)) {\n throw new ValidationError(`seedPlants: duplicate dataset itemId \"${item.itemId}\"`)\n }\n seen.add(item.itemId)\n datasetItems.push({\n itemId: item.itemId,\n humanScore: item.humanScore,\n ...(item.group === undefined ? {} : { group: item.group }),\n })\n }\n\n const sealedPlants: Plant[] = []\n const plantIds = new Set<string>()\n for (const plant of plants) {\n const record = definePlant(plant)\n if (plantIds.has(record.id)) {\n throw new ValidationError(`seedPlants: duplicate plant id \"${record.id}\"`)\n }\n if (seen.has(record.item.itemId)) {\n throw new ValidationError(\n `seedPlants: plant \"${record.id}\" reuses itemId \"${record.item.itemId}\", which is already in the set`,\n )\n }\n const thresholdSays: PlantExpectation =\n record.item.humanScore >= acceptThreshold ? 'accept' : 'reject'\n if (thresholdSays !== record.expectedVerdict) {\n throw new ValidationError(\n `seedPlants: plant \"${record.id}\" expects the grader to ${record.expectedVerdict} it, but humanScore ${record.item.humanScore} is on the ${thresholdSays} side of acceptThreshold ${acceptThreshold}`,\n )\n }\n plantIds.add(record.id)\n seen.add(record.item.itemId)\n sealedPlants.push(record)\n }\n\n const items = shuffled(\n [...datasetItems, ...sealedPlants.map((plant) => plant.item)],\n mulberry32(seed),\n )\n const itemIds = items.map((item) => item.itemId)\n const manifest: PlantManifest = {\n seal: sealManifest({ seed, acceptThreshold, itemIds, plants: sealedPlants }),\n seed,\n acceptThreshold,\n itemIds,\n plants: sealedPlants,\n }\n return { items, manifest }\n}\n\n/**\n * Order by one independent uniform key per item, which is a uniform\n * permutation and a pure function of the seed. A comparator that returns a\n * fresh random sign instead is neither: it is not a consistent ordering, so\n * the permutation it produces is biased and depends on the sort algorithm.\n */\nfunction shuffled<T>(items: readonly T[], random: () => number): T[] {\n return items\n .map((item) => ({ item, key: random() }))\n .sort((left, right) => left.key - right.key)\n .map((entry) => entry.item)\n}\n\nfunction sealManifest(contents: Omit<PlantManifest, 'seal'>): LedgerHash {\n return hashCanonical({\n scheme: 'agent-eval.plant-manifest.v1',\n seed: contents.seed,\n acceptThreshold: contents.acceptThreshold,\n itemIds: contents.itemIds,\n plants: contents.plants,\n })\n}\n\n/**\n * One grader outcome for one item. `score: null` says the grader ran and\n * declined to decide — the check never tested the item's defect. Any\n * `CandidateScore` from a judge run is already a valid outcome.\n */\nexport interface PlantOutcome {\n itemId: string\n score: number | null\n}\n\n/**\n * `evaluated` — a rate stands. `incomplete` — a seeded id had no result.\n * `not_evaluated` — nothing was seeded, or nothing seeded was decided.\n */\nexport type CatchRateStatus = 'evaluated' | 'incomplete' | 'not_evaluated'\n\nexport interface PlantKindCounts {\n seeded: number\n caught: number\n missed: number\n indecisive: number\n /** caught / (caught + missed), or null when the report is not `evaluated`. */\n rate: number | null\n}\n\n/**\n * How the same grader treated the unseeded items of the same set. No labels\n * are needed to read it: a grader that refuses everything scores `rate` 1.0\n * on reject-plants, and a `rejectionRate` of 1.0 here is what separates that\n * reflex from discrimination.\n */\nexport interface UnseededRejection {\n n: number\n decided: number\n rejected: number\n /** rejected / decided, or null when nothing unseeded was decided. */\n rejectionRate: number | null\n}\n\nexport interface CatchRateReport {\n status: CatchRateStatus\n /** Why the status is not `evaluated`. Absent when it is. */\n reason?: string\n seeded: number\n caught: number\n missed: number\n /**\n * The grader returned a result and declined to decide. Counted apart: it\n * enters neither side of `rate`.\n */\n indecisive: number\n /** caught / (caught + missed), or null unless the status is `evaluated`. */\n rate: number | null\n /** One entry per kind actually seeded. A kind nobody seeded is absent, never zero. */\n byKind: Partial<Record<PlantKind, PlantKindCounts>>\n /** Plant ids the grader graded as the seed says it must not. */\n missedIds: string[]\n /** Plant ids with no result at all — the reason a status is `incomplete`. */\n missingIds: string[]\n unseeded: UnseededRejection\n}\n\n/**\n * Score a grading run against its sealed manifest.\n *\n * Refusals: a manifest whose contents no longer match its seal, a result for\n * an id the manifest never handed out, and a repeated result id. Each says\n * the results and the manifest describe different runs, and a rate computed\n * across two runs is a fabrication.\n */\nexport function catchRate(\n results: readonly PlantOutcome[],\n manifest: PlantManifest,\n): CatchRateReport {\n const expectedSeal = sealManifest({\n seed: manifest.seed,\n acceptThreshold: manifest.acceptThreshold,\n itemIds: manifest.itemIds,\n plants: manifest.plants,\n })\n if (expectedSeal !== manifest.seal) {\n throw new CaptureIntegrityError(\n `catchRate: manifest contents hash to ${expectedSeal} but the manifest carries seal ${manifest.seal} — the plant set changed after it was sealed`,\n )\n }\n\n const handedOut = new Set(manifest.itemIds)\n const scoreByItemId = new Map<string, number | null>()\n for (const result of results) {\n if (!handedOut.has(result.itemId)) {\n throw new ValidationError(\n `catchRate: result for \"${result.itemId}\", which this manifest never handed out`,\n )\n }\n if (scoreByItemId.has(result.itemId)) {\n throw new ValidationError(`catchRate: duplicate result for \"${result.itemId}\"`)\n }\n if (result.score !== null && !Number.isFinite(result.score)) {\n throw new ValidationError(\n `catchRate: result for \"${result.itemId}\" has score ${result.score}; expected a finite number or null`,\n )\n }\n scoreByItemId.set(result.itemId, result.score)\n }\n\n const byKind: Partial<Record<PlantKind, PlantKindCounts>> = {}\n const missedIds: string[] = []\n const missingIds: string[] = []\n let caught = 0\n let missed = 0\n let indecisive = 0\n\n for (const plant of manifest.plants) {\n let counts = byKind[plant.kind]\n if (counts === undefined) {\n counts = { seeded: 0, caught: 0, missed: 0, indecisive: 0, rate: null }\n byKind[plant.kind] = counts\n }\n counts.seeded += 1\n if (!scoreByItemId.has(plant.item.itemId)) {\n missingIds.push(plant.id)\n continue\n }\n const score = scoreByItemId.get(plant.item.itemId) ?? null\n if (score === null) {\n indecisive += 1\n counts.indecisive += 1\n continue\n }\n const graderSaid: PlantExpectation = score >= manifest.acceptThreshold ? 'accept' : 'reject'\n if (graderSaid === plant.expectedVerdict) {\n caught += 1\n counts.caught += 1\n } else {\n missed += 1\n counts.missed += 1\n missedIds.push(plant.id)\n }\n }\n\n const seeded = manifest.plants.length\n const decided = caught + missed\n const report: CatchRateReport = {\n status: 'evaluated',\n seeded,\n caught,\n missed,\n indecisive,\n rate: null,\n byKind,\n missedIds,\n missingIds,\n unseeded: unseededRejection(manifest, scoreByItemId),\n }\n\n if (seeded === 0) {\n return {\n ...report,\n status: 'not_evaluated',\n reason: 'no plant was seeded, so the grader was never asked a question it could fail',\n }\n }\n if (missingIds.length > 0) {\n return {\n ...report,\n status: 'incomplete',\n reason: `${missingIds.length} of ${seeded} seeded plants have no result: ${missingIds.join(', ')}`,\n }\n }\n if (decided === 0) {\n return {\n ...report,\n status: 'not_evaluated',\n reason: `all ${seeded} seeded plants are indecisive: no check tested the seeded defect`,\n }\n }\n\n for (const counts of Object.values(byKind)) {\n const kindDecided = counts.caught + counts.missed\n counts.rate = kindDecided === 0 ? null : counts.caught / kindDecided\n }\n report.rate = caught / decided\n return report\n}\n\nfunction unseededRejection(\n manifest: PlantManifest,\n scoreByItemId: ReadonlyMap<string, number | null>,\n): UnseededRejection {\n const plantItemIds = new Set(manifest.plants.map((plant) => plant.item.itemId))\n let n = 0\n let decided = 0\n let rejected = 0\n for (const itemId of manifest.itemIds) {\n if (plantItemIds.has(itemId)) continue\n n += 1\n const score = scoreByItemId.get(itemId)\n if (score === undefined || score === null) continue\n decided += 1\n if (score < manifest.acceptThreshold) rejected += 1\n }\n return { n, decided, rejected, rejectionRate: decided === 0 ? null : rejected / decided }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA0EA,eAAsB,iBACpB,YACA,cACA,aACA,oBACA,UAAmC,CAAC,GACH;CACjC,MAAM,YAAY,QAAQ,aAAa;CACvC,MAAM,aAAa,QAAQ,uBAAuB;CAClD,MAAM,OAAO,QAAQ;CACrB,2BAA2B,WAAW,YAAY,IAAI;CACtD,2BACE,YAAY,KAAK,WAAW,OAAO,EAAE,GACrC,aACF;CACA,2BAA2B,oBAAoB,gBAAgB;CAC/D,MAAM,SAAS,QAAQ,mBAAmB;CAC1C,IAAI,SAAS,KAAK,OAAO,MAAM,MAAM,GACnC,MAAM,IAAI,MAAM,qCAAqC;CAEvD,MAAM,aAAa,YAAY,KAAK,YAAY;EAC9C,GAAG;EACH,SAAS,OAAO,WAAW,mBAAmB,OAAO,EAAE;CACzD,EAAE;CACF,MAAM,cAAc,CAAC,GAAG,kBAAkB;CAC1C,MAAM,OAAO,MAAM,WAAW,SAAS;CACvC,2BACE,KAAK,KAAK,QAAQ,IAAI,KAAK,GAC3B,OACF;CACA,MAAM,gBAAgB,mBAAmB,MAAM,aAAa,KAAK,QAAQ,aAAa,CAAC;CAEvF,MAAM,QAA0F,CAAC;CACjG,KAAK,MAAM,MAAM,YACf,KAAK,MAAM,MAAM,aACf,MAAM,KAAK;EAAE,YAAY,GAAG;EAAI,eAAe;EAAI,IAAI,CAAC;EAAG,IAAI,CAAC;CAAE,CAAC;CAIvE,IAAI,SAAS;CACb,IAAI,UAAU;CACd,KA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