@tangle-network/agent-eval 0.223.0 → 1.0.1
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 +219 -0
- package/README.md +2 -1
- package/dist/adapters/http.d.ts +2 -2
- package/dist/{agreement-irr-BTjDN0i6.js → agreement-irr-w-t3XUTD.js} +2 -2
- package/dist/{agreement-irr-BTjDN0i6.js.map → agreement-irr-w-t3XUTD.js.map} +1 -1
- package/dist/analyst/index.d.ts +7 -7
- package/dist/analyst/index.js +11 -11
- package/dist/{analyze-runs-C-pP1sK9.d.ts → analyze-runs-BYyMShsj.d.ts} +2 -2
- package/dist/{analyze-runs-C-pP1sK9.d.ts.map → analyze-runs-BYyMShsj.d.ts.map} +1 -1
- package/dist/{analyze-runs-Ck68mbgj.js → analyze-runs-Da7P_Mc5.js} +9 -10
- package/dist/{analyze-runs-Ck68mbgj.js.map → analyze-runs-Da7P_Mc5.js.map} +1 -1
- package/dist/{benchmark-command-CH86twZj.js → benchmark-command-BeDZB3BQ.js} +11 -11
- package/dist/{benchmark-command-CH86twZj.js.map → benchmark-command-BeDZB3BQ.js.map} +1 -1
- package/dist/benchmarks/index.d.ts +4 -4
- package/dist/benchmarks/index.js +5 -5
- package/dist/builder-eval/index.js +1 -1
- package/dist/{calibration-6usfVYYo.js → calibration-DLzckXnn.js} +2 -2
- package/dist/{calibration-6usfVYYo.js.map → calibration-DLzckXnn.js.map} +1 -1
- package/dist/campaign/index.d.ts +5 -5
- package/dist/campaign/index.js +10 -10
- package/dist/{campaign-DdOgQfp8.js → campaign-DKZiYHUq.js} +15 -15
- package/dist/{campaign-DdOgQfp8.js.map → campaign-DKZiYHUq.js.map} +1 -1
- package/dist/{campaign-evidence-MjCjkb5a.js → campaign-evidence-BICB3a9Z.js} +3 -3
- package/dist/{campaign-evidence-MjCjkb5a.js.map → campaign-evidence-BICB3a9Z.js.map} +1 -1
- package/dist/{chat-client-CO3uB33i.js → chat-client-D0me8iwq.js} +2 -2
- package/dist/{chat-client-CO3uB33i.js.map → chat-client-D0me8iwq.js.map} +1 -1
- package/dist/{chat-json-call-8yUv4LFO.js → chat-json-call-C473CwTt.js} +2 -2
- package/dist/{chat-json-call-8yUv4LFO.js.map → chat-json-call-C473CwTt.js.map} +1 -1
- package/dist/cli.js +7 -7
- package/dist/{cluster-bootstrap-SbaeM44s.js → cluster-bootstrap-hNXESoc1.js} +2 -2
- package/dist/{cluster-bootstrap-SbaeM44s.js.map → cluster-bootstrap-hNXESoc1.js.map} +1 -1
- package/dist/{completion-verifier-rqbMh5-4.js → completion-verifier-ClmJV_Yc.js} +2 -2
- package/dist/{completion-verifier-rqbMh5-4.js.map → completion-verifier-ClmJV_Yc.js.map} +1 -1
- package/dist/contract/index.d.ts +8 -8
- package/dist/contract/index.js +13 -13
- package/dist/{decision-point-lhMgODOR.js → decision-point-CErE7GnP.js} +6 -6
- package/dist/decision-point-CErE7GnP.js.map +1 -0
- package/dist/{default-registry-B1DstPYg.d.ts → default-registry-DKlKVXMx.d.ts} +22 -6
- package/dist/default-registry-DKlKVXMx.d.ts.map +1 -0
- package/dist/{default-registry-C1tPEjZ4.js → default-registry-gmDeN0KT.js} +38 -7
- package/dist/default-registry-gmDeN0KT.js.map +1 -0
- package/dist/{define-agent-eval-CAffiFbN.d.ts → define-agent-eval-B9zPWFSK.d.ts} +6 -6
- package/dist/{define-agent-eval-CAffiFbN.d.ts.map → define-agent-eval-B9zPWFSK.d.ts.map} +1 -1
- package/dist/{define-agent-eval-Cc15qGik.js → define-agent-eval-BVhGn7VV.js} +6 -6
- package/dist/{define-agent-eval-Cc15qGik.js.map → define-agent-eval-BVhGn7VV.js.map} +1 -1
- package/dist/{descriptive-cPwITVfy.js → descriptive-BTzLL-aj.js} +46 -3
- package/dist/descriptive-BTzLL-aj.js.map +1 -0
- package/dist/diagnosis/index.d.ts +2 -2
- package/dist/diagnosis/index.js +2 -2
- package/dist/{dspy-rlm-engine-jDiWkul6.js → dspy-rlm-engine-C0zR2xiM.js} +2 -2
- package/dist/{dspy-rlm-engine-jDiWkul6.js.map → dspy-rlm-engine-C0zR2xiM.js.map} +1 -1
- package/dist/{eval-campaign-C_mNDshv.js → eval-campaign-DVqiBoXR.js} +3 -3
- package/dist/{eval-campaign-C_mNDshv.js.map → eval-campaign-DVqiBoXR.js.map} +1 -1
- package/dist/{evaluation-BPqUvZ66.d.ts → evaluation-B0-KVXaV.d.ts} +4 -2
- package/dist/evaluation-B0-KVXaV.d.ts.map +1 -0
- package/dist/{evaluation-B8H3GYej.js → evaluation-BBI37mRe.js} +2 -1
- package/dist/evaluation-BBI37mRe.js.map +1 -0
- package/dist/evaluation.d.ts +1 -1
- package/dist/evaluation.js +1 -1
- package/dist/{exact-types-D98BKpxo.d.ts → exact-types-CIViGj98.d.ts} +3 -3
- package/dist/{exact-types-D98BKpxo.d.ts.map → exact-types-CIViGj98.d.ts.map} +1 -1
- package/dist/experiment/index.d.ts +1 -1
- package/dist/experiment/index.js +9 -8
- package/dist/experiment/index.js.map +1 -1
- package/dist/{exporters-B5Ze_RKh.d.ts → exporters-BYBG9b1n.d.ts} +2 -2
- package/dist/{exporters-B5Ze_RKh.d.ts.map → exporters-BYBG9b1n.d.ts.map} +1 -1
- package/dist/{external-optimizer-process-BRVmaDFe.js → external-optimizer-process-DKgrrX0J.js} +2 -2
- package/dist/{external-optimizer-process-BRVmaDFe.js.map → external-optimizer-process-DKgrrX0J.js.map} +1 -1
- package/dist/{external-optimizer-subprocess-U616hV_l.js → external-optimizer-subprocess-wzMaA0oN.js} +2 -2
- package/dist/{external-optimizer-subprocess-U616hV_l.js.map → external-optimizer-subprocess-wzMaA0oN.js.map} +1 -1
- package/dist/{feedback-trajectory-SBGncrCP.d.ts → feedback-trajectory-Ck7K7AhK.d.ts} +2 -2
- package/dist/{feedback-trajectory-SBGncrCP.d.ts.map → feedback-trajectory-Ck7K7AhK.d.ts.map} +1 -1
- package/dist/{findings-store-B75Dspaq.js → findings-store-DNSvmy8U.js} +4 -4
- package/dist/{findings-store-B75Dspaq.js.map → findings-store-DNSvmy8U.js.map} +1 -1
- package/dist/fuzz.js +1 -1
- package/dist/{index-CUjeTDPv.d.ts → index-Bn-P_XAl.d.ts} +4 -4
- package/dist/{index-CUjeTDPv.d.ts.map → index-Bn-P_XAl.d.ts.map} +1 -1
- package/dist/{index-B7v2QHlD.d.ts → index-BwutH5i7.d.ts} +4 -4
- package/dist/{index-B7v2QHlD.d.ts.map → index-BwutH5i7.d.ts.map} +1 -1
- package/dist/{index-aDPVYBIM.d.ts → index-ByJ20lyu.d.ts} +7 -7
- package/dist/{index-aDPVYBIM.d.ts.map → index-ByJ20lyu.d.ts.map} +1 -1
- package/dist/{index-DUn0GNiZ.d.ts → index-CtcCSO1Y.d.ts} +4 -4
- package/dist/{index-DUn0GNiZ.d.ts.map → index-CtcCSO1Y.d.ts.map} +1 -1
- package/dist/index.d.ts +17 -17
- package/dist/index.js +38 -43
- package/dist/index.js.map +1 -1
- package/dist/{judge-calibration-DGqlfWW8.js → judge-calibration-D93UCm1k.js} +2 -2
- package/dist/{judge-calibration-DGqlfWW8.js.map → judge-calibration-D93UCm1k.js.map} +1 -1
- package/dist/{judge-gate-Di_6bifh.js → judge-gate-C9sLLJ-v.js} +3 -3
- package/dist/{judge-gate-Di_6bifh.js.map → judge-gate-C9sLLJ-v.js.map} +1 -1
- package/dist/kind-factory-VKysp1ds.js.map +1 -1
- package/dist/{llm-client-kJ9EOqjt.js → llm-client-BdSiZ4qz.js} +2 -2
- package/dist/{llm-client-kJ9EOqjt.js.map → llm-client-BdSiZ4qz.js.map} +1 -1
- package/dist/{llm-judge-D6JtIqiU.js → llm-judge-BYBLxREr.js} +14 -14
- package/dist/{llm-judge-D6JtIqiU.js.map → llm-judge-BYBLxREr.js.map} +1 -1
- package/dist/{matrix-CBUzIZs4.d.ts → matrix-4DcRFJ7Q.d.ts} +2 -2
- package/dist/{matrix-CBUzIZs4.d.ts.map → matrix-4DcRFJ7Q.d.ts.map} +1 -1
- package/dist/{internal-v6XfOeJW.js → mean-DDFhslBt.js} +48 -2
- package/dist/mean-DDFhslBt.js.map +1 -0
- package/dist/meta-eval/index.js +7 -7
- package/dist/multishot/golden/index.d.ts +1 -1
- package/dist/multishot/index.d.ts +2 -2
- package/dist/openapi.json +1 -1
- package/dist/{outcome-observations-D4snOtUb.js → outcome-observations-ahbNtxuP.js} +3 -3
- package/dist/{outcome-observations-D4snOtUb.js.map → outcome-observations-ahbNtxuP.js.map} +1 -1
- package/dist/{paired-arms-D5H_58e8.js → paired-arms-C0Vd9bGG.js} +4 -4
- package/dist/{paired-arms-D5H_58e8.js.map → paired-arms-C0Vd9bGG.js.map} +1 -1
- package/dist/{paired-binary-BR0nwHOA.js → paired-binary-B477lksS.js} +2 -2
- package/dist/{paired-binary-BR0nwHOA.js.map → paired-binary-B477lksS.js.map} +1 -1
- package/dist/{paired-promotion-decision-BiVumgvM.js → paired-promotion-decision-5Pl_qJLX.js} +3 -3
- package/dist/{paired-promotion-decision-BiVumgvM.js.map → paired-promotion-decision-5Pl_qJLX.js.map} +1 -1
- package/dist/{paired-tests-C2zUqgUW.js → paired-tests-kASEKpc-.js} +3 -37
- package/dist/paired-tests-kASEKpc-.js.map +1 -0
- package/dist/{pareto-7_LEmYGG.js → pareto-DY_x3HHg.js} +7 -7
- package/dist/{pareto-7_LEmYGG.js.map → pareto-DY_x3HHg.js.map} +1 -1
- package/dist/pipelines/index.d.ts +1 -1
- package/dist/pipelines/index.js +1 -1
- package/dist/{power-and-mde-CHvyDO_H.js → power-and-mde-CRxepy8y.js} +3 -3
- package/dist/{power-and-mde-CHvyDO_H.js.map → power-and-mde-CRxepy8y.js.map} +1 -1
- package/dist/{promotion-policy-D7B4_jEZ.js → promotion-policy-f79oklG_.js} +4 -4
- package/dist/{promotion-policy-D7B4_jEZ.js.map → promotion-policy-f79oklG_.js.map} +1 -1
- package/dist/{proposal-findings-WFQrxnfe.js → proposal-findings-duV5flPv.js} +2 -2
- package/dist/{proposal-findings-WFQrxnfe.js.map → proposal-findings-duV5flPv.js.map} +1 -1
- package/dist/{raw-provider-sink-DDLkP_eF.js → raw-provider-sink-RbaEv2vB.js} +2 -2
- package/dist/{raw-provider-sink-DDLkP_eF.js.map → raw-provider-sink-RbaEv2vB.js.map} +1 -1
- package/dist/{redact-C_wzC4c_.d.ts → redact-jrT0APTU.d.ts} +50 -35
- package/dist/redact-jrT0APTU.d.ts.map +1 -0
- package/dist/{redact-D6APJS1d.js → redact-zp_ILC4l.js} +92 -33
- package/dist/redact-zp_ILC4l.js.map +1 -0
- package/dist/redaction.d.ts +2 -0
- package/dist/redaction.js +1 -0
- package/dist/{registry-dhdDoAV8.d.ts → registry-CMtGAxOw.d.ts} +2 -2
- package/dist/{registry-dhdDoAV8.d.ts.map → registry-CMtGAxOw.d.ts.map} +1 -1
- package/dist/{release-confidence-CTUJz5mM.js → release-confidence--1iP-d3x.js} +2 -2
- package/dist/{release-confidence-CTUJz5mM.js.map → release-confidence--1iP-d3x.js.map} +1 -1
- package/dist/{render-pfAZ7IR4.js → render-aB58Be3N.js} +2 -2
- package/dist/{render-pfAZ7IR4.js.map → render-aB58Be3N.js.map} +1 -1
- package/dist/reporting.js +5 -5
- package/dist/{reward-hacking-Bjk3MAjh.js → reward-hacking-D-Vi9-fE.js} +3 -3
- package/dist/{reward-hacking-Bjk3MAjh.js.map → reward-hacking-D-Vi9-fE.js.map} +1 -1
- package/dist/rl.d.ts +3 -3
- package/dist/rl.js +9 -9
- package/dist/rollout/index.d.ts +4 -4
- package/dist/rollout/index.js +1 -1
- package/dist/{rollout-BhkMpAJT.js → rollout-BC4u-d_I.js} +3 -3
- package/dist/{rollout-BhkMpAJT.js.map → rollout-BC4u-d_I.js.map} +1 -1
- package/dist/{rubric-predictive-validity-CQp_M0vy.js → rubric-predictive-validity-BdxXDN6h.js} +2 -2
- package/dist/{rubric-predictive-validity-CQp_M0vy.js.map → rubric-predictive-validity-BdxXDN6h.js.map} +1 -1
- package/dist/{run-record-BUm-Jggo.js → run-record-B-G2Tu11.js} +2 -2
- package/dist/{run-record-BUm-Jggo.js.map → run-record-B-G2Tu11.js.map} +1 -1
- package/dist/{schema-DkFJr3Y8.d.ts → schema-CfoA9U_U.d.ts} +28 -2
- package/dist/schema-CfoA9U_U.d.ts.map +1 -0
- package/dist/search/index.d.ts +2 -2
- package/dist/search/index.js +2 -2
- package/dist/{search-kernel-CBdwFZ05.d.ts → search-kernel-BjR2Sr7w.d.ts} +2 -2
- package/dist/{search-kernel-CBdwFZ05.d.ts.map → search-kernel-BjR2Sr7w.d.ts.map} +1 -1
- package/dist/{search-summary-Bt3uuK53.js → search-summary-DedyTdiM.js} +4 -4
- package/dist/{search-summary-Bt3uuK53.js.map → search-summary-DedyTdiM.js.map} +1 -1
- package/dist/{sequential-De7BTAlV.js → sequential-Zp1tsxqI.js} +2 -2
- package/dist/{sequential-De7BTAlV.js.map → sequential-Zp1tsxqI.js.map} +1 -1
- package/dist/{server-DA6h3co5.js → server-CPKyf3bz.js} +2 -2
- package/dist/{server-DA6h3co5.js.map → server-CPKyf3bz.js.map} +1 -1
- package/dist/{skillopt-optimization-method-BKFbJEyz.js → skillopt-optimization-method-DmfZz-2d.js} +9 -9
- package/dist/{skillopt-optimization-method-BKFbJEyz.js.map → skillopt-optimization-method-DmfZz-2d.js.map} +1 -1
- package/dist/{spans-vZoW__3q.d.ts → spans-CGjHouKM.d.ts} +2 -2
- package/dist/{spans-vZoW__3q.d.ts.map → spans-CGjHouKM.d.ts.map} +1 -1
- package/dist/{statistical-heldout-C9hz_AF9.js → statistical-heldout-DYF5f10K.js} +3 -3
- package/dist/{statistical-heldout-C9hz_AF9.js.map → statistical-heldout-DYF5f10K.js.map} +1 -1
- package/dist/{statistical-heldout-Cei036nE.d.ts → statistical-heldout-bU7FBNjR.d.ts} +2 -2
- package/dist/{statistical-heldout-Cei036nE.d.ts.map → statistical-heldout-bU7FBNjR.d.ts.map} +1 -1
- package/dist/{store-tool-spans-C2g8UYm-.js → store-tool-spans-GGaCijFy.js} +19 -62
- package/dist/store-tool-spans-GGaCijFy.js.map +1 -0
- package/dist/{store-tool-spans-B3i3fl0A.d.ts → store-tool-spans-lWf6INTH.d.ts} +3 -44
- package/dist/store-tool-spans-lWf6INTH.d.ts.map +1 -0
- package/dist/{summary-report-BLnTyQKH.js → summary-report-BstMpOfy.js} +6 -7
- package/dist/{summary-report-BLnTyQKH.js.map → summary-report-BstMpOfy.js.map} +1 -1
- package/dist/supervisor-run/index.d.ts +2 -2
- package/dist/supervisor-run/index.js +1 -1
- package/dist/{systemone-Cw2txK5m.d.ts → systemone-BDVgb6XV.d.ts} +7 -9
- package/dist/systemone-BDVgb6XV.d.ts.map +1 -0
- package/dist/systemone.d.ts +2 -2
- package/dist/systemone.js +2 -2
- package/dist/{tool-waste-CLJ46AbT.js → tool-waste-CRJqOASv.js} +3 -3
- package/dist/{tool-waste-CLJ46AbT.js.map → tool-waste-CRJqOASv.js.map} +1 -1
- package/dist/trace-repair/index.js +2 -2
- package/dist/traces.d.ts +18 -39
- package/dist/traces.d.ts.map +1 -1
- package/dist/traces.js +51 -57
- package/dist/traces.js.map +1 -1
- package/dist/{tree-DnBkWXun.js → tree-C2N31CoI.js} +5 -6
- package/dist/{tree-DnBkWXun.js.map → tree-C2N31CoI.js.map} +1 -1
- package/dist/{types-C54Uk_a1.d.ts → types-BF-xQGQn.d.ts} +2 -2
- package/dist/{types-C54Uk_a1.d.ts.map → types-BF-xQGQn.d.ts.map} +1 -1
- package/dist/{types-C-aOqgt2.d.ts → types-DNB9hIXa.d.ts} +2 -2
- package/dist/{types-C-aOqgt2.d.ts.map → types-DNB9hIXa.d.ts.map} +1 -1
- package/dist/{types-0oMg7zee.d.ts → types-yofaDmQa.d.ts} +2 -2
- package/dist/{types-0oMg7zee.d.ts.map → types-yofaDmQa.d.ts.map} +1 -1
- package/dist/wire/index.d.ts +7 -7
- package/dist/wire/index.js +1 -1
- package/docs/design/statistics-decisions.md +1 -0
- package/docs/redaction.md +24 -1
- package/docs/systemone.md +6 -0
- package/package.json +10 -5
- package/dist/decision-point-lhMgODOR.js.map +0 -1
- package/dist/default-registry-B1DstPYg.d.ts.map +0 -1
- package/dist/default-registry-C1tPEjZ4.js.map +0 -1
- package/dist/descriptive-cPwITVfy.js.map +0 -1
- package/dist/evaluation-B8H3GYej.js.map +0 -1
- package/dist/evaluation-BPqUvZ66.d.ts.map +0 -1
- package/dist/internal-v6XfOeJW.js.map +0 -1
- package/dist/mean-BPuUNznQ.js +0 -16
- package/dist/mean-BPuUNznQ.js.map +0 -1
- package/dist/paired-tests-C2zUqgUW.js.map +0 -1
- package/dist/redact-C_wzC4c_.d.ts.map +0 -1
- package/dist/redact-D6APJS1d.js.map +0 -1
- package/dist/schema-DkFJr3Y8.d.ts.map +0 -1
- package/dist/store-tool-spans-B3i3fl0A.d.ts.map +0 -1
- package/dist/store-tool-spans-C2g8UYm-.js.map +0 -1
- package/dist/systemone-Cw2txK5m.d.ts.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { u as CostProvenance } from "./cost-ledger-Czro9wmo.js";
|
|
2
|
-
import { C as JudgeDimension, w as JudgeScore } from "./types-
|
|
2
|
+
import { C as JudgeDimension, w as JudgeScore } from "./types-BF-xQGQn.js";
|
|
3
3
|
import { o as MatrixResult } from "./index-DwUGehqX.js";
|
|
4
4
|
import { AgentProfile } from "@tangle-network/agent-interface";
|
|
5
5
|
interface MultishotMessage {
|
|
@@ -381,4 +381,4 @@ interface RunMultishotMatrixResult {
|
|
|
381
381
|
}
|
|
382
382
|
declare function runMultishotMatrix<TPersona extends MultishotPersona>(opts: RunMultishotMatrixOptions<TPersona>): Promise<RunMultishotMatrixResult>;
|
|
383
383
|
export { MultishotTransportRequest as A, MultishotMessage as C, MultishotToolDefinition as D, MultishotShape as E, MultishotTransportToolCall as M, assertMultishotShotResult as N, MultishotToolExecutor as O, MultishotFatalToolError as S, MultishotResult as T, renderDimensions as _, MultishotCellOutput as a, MultishotArtifact as b, RunMultishotMatrixResult as c, MultishotShot as d, RunMultishotOptions as f, MultishotJudgeConfig as g, JudgeRunResult as h, ConversationJudgeInput as i, MultishotTransportResponse as j, MultishotTransport as k, computeCellComposite as l, DEFAULT_JUDGE_MODEL as m, CellCompositeInput as n, MultishotJudges as o, runMultishot as p, CellCompositeScore as r, RunMultishotMatrixOptions as s, ArtifactJudgeInput as t, runMultishotMatrix as u, renderJsonFooter as v, MultishotPersona as w, MultishotDriverEmptyError as x, runJudge as y };
|
|
384
|
-
//# sourceMappingURL=matrix-
|
|
384
|
+
//# sourceMappingURL=matrix-4DcRFJ7Q.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"matrix-
|
|
1
|
+
{"version":3,"file":"matrix-4DcRFJ7Q.d.ts","names":[],"sources":["../src/multishot/types.ts","../src/multishot/judges.ts","../src/multishot/multishot.ts","../src/multishot/matrix.ts"],"mappings":";;;;UAIiB;EACf;EACA;EACA;EACA,YAAY;IAAQ;IAAY;IAAc,MAAM;;;UAGrC;EACf;EACA;EACA;IAAc;IAAc,MAAM;;EAClC;;UAGe;EACf,YAAY;EACZ,WAAW;EACX;EACA;;;EAGA;;;;;;;;EAQA,iBAAiB;;UAGF;EACf;EACA;IACE;IACA;IACA,YAAY;;;;;;UAOC;EACf;EACA,UAAU,MAAM;EAChB,QAAQ;EACR;EACA;EACA,SAAS;;UAGM;EACf;EACA;EACA;IAAY;IAAc;;;UAGX;EACf;IAAW;IAAyB,aAAa;;EACjD;IAAU;IAAwB;;;;EAGlC;;;;EAIA;;;;;;;;KASU,sBACV,KAAK,8BACF,QAAQ;KAED,yBACV,MAAM,yBACN;;EAEE,WAAW;EACX,SAAS;MAER;EAAU;EAAiB;;UAEf;;EAEf;;GAEC;;;;;;;;UASc,eAAe,iBAAiB;;EAE/C,eAAe,SAAS;;;EAGxB,2BAA2B,SAAS;;cAGzB,kCAAkC;WACjB;EAAA,YAAA;;cAMjB,gCAAgC;E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EA;;EAEA;;EAEA;;;;EAIA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;;;EAIA,gBAAgB;;EAEhB,iBAAiB;;;EAGjB,gBAAgB;;;;;;;;;;;;;;;EAehB,UAAU,cAAc;;;;;UAMT;EACf;EACA;EACA;;UAoBe;EACf,cAAc;;EAEd,cAAc,cAAc;;EAE5B,iBAAiB,cAAc;;;;;;;iBAQjB,qBAAqB,OAAO;EAC1C;EACA;EACA;EACA;;UAuBe;EACf,QAAQ,aAAa;;iBAGD,mBAAmB,iBAAiB,kBACxD,MAAM,0BAA0B,YAC/B,QAAQ"}
|
|
@@ -69,6 +69,39 @@ function betaContinuedFraction(x, a, b) {
|
|
|
69
69
|
}
|
|
70
70
|
return fraction;
|
|
71
71
|
}
|
|
72
|
+
// src/math/student-t.ts
|
|
73
|
+
/**
|
|
74
|
+
* Student-t CDF via the regularized incomplete beta function.
|
|
75
|
+
*/
|
|
76
|
+
function studentTCdf(t, degreesOfFreedom) {
|
|
77
|
+
if (degreesOfFreedom <= 0) return .5;
|
|
78
|
+
const beta = regularizedIncompleteBeta(degreesOfFreedom / (degreesOfFreedom + t * t), degreesOfFreedom / 2, .5);
|
|
79
|
+
return t >= 0 ? 1 - .5 * beta : .5 * beta;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Inverse Student-t CDF, solved against {@link studentTCdf}.
|
|
83
|
+
*
|
|
84
|
+
* The CDF is monotone, so bracket expansion followed by bisection is stable
|
|
85
|
+
* across fractional degrees of freedom and does not need a separate
|
|
86
|
+
* approximation with a different error profile.
|
|
87
|
+
*/
|
|
88
|
+
function studentTQuantile(probability, degreesOfFreedom) {
|
|
89
|
+
if (!Number.isFinite(probability) || probability < 0 || probability > 1) throw new RangeError(`studentTQuantile: probability must be in [0,1], got ${probability}`);
|
|
90
|
+
if (!Number.isFinite(degreesOfFreedom) || degreesOfFreedom <= 0) throw new RangeError(`studentTQuantile: degreesOfFreedom must be positive and finite, got ${degreesOfFreedom}`);
|
|
91
|
+
if (probability === 0) return Number.NEGATIVE_INFINITY;
|
|
92
|
+
if (probability === 1) return Number.POSITIVE_INFINITY;
|
|
93
|
+
if (probability === .5) return 0;
|
|
94
|
+
if (probability < .5) return -studentTQuantile(1 - probability, degreesOfFreedom);
|
|
95
|
+
let low = 0;
|
|
96
|
+
let high = 1;
|
|
97
|
+
while (studentTCdf(high, degreesOfFreedom) < probability) high *= 2;
|
|
98
|
+
for (let iteration = 0; iteration < 64; iteration++) {
|
|
99
|
+
const middle = (low + high) / 2;
|
|
100
|
+
if (studentTCdf(middle, degreesOfFreedom) < probability) low = middle;
|
|
101
|
+
else high = middle;
|
|
102
|
+
}
|
|
103
|
+
return (low + high) / 2;
|
|
104
|
+
}
|
|
72
105
|
// src/statistics/internal.ts
|
|
73
106
|
/**
|
|
74
107
|
* Shared internals for the statistics modules. Nothing here is part of the
|
|
@@ -207,6 +240,19 @@ function symmetricTwoSampleSeed(a, b) {
|
|
|
207
240
|
const reversed = seedFromData([sortedB, sortedA]) >>> 0;
|
|
208
241
|
return Math.min(forward, reversed);
|
|
209
242
|
}
|
|
210
|
-
|
|
243
|
+
// src/statistics/mean.ts
|
|
244
|
+
/** Arithmetic mean. An empty input has no mean and returns NaN. */
|
|
245
|
+
function mean(values) {
|
|
246
|
+
return values.reduce((sum, value) => sum + value, 0) / values.length;
|
|
247
|
+
}
|
|
248
|
+
/** Arithmetic mean, or null for an empty input. */
|
|
249
|
+
function meanOrNull(values) {
|
|
250
|
+
return values.length === 0 ? null : mean(values);
|
|
251
|
+
}
|
|
252
|
+
/** Arithmetic mean, or 0 for an empty input. */
|
|
253
|
+
function meanOrZero(values) {
|
|
254
|
+
return values.length === 0 ? 0 : mean(values);
|
|
255
|
+
}
|
|
256
|
+
export { binomialHalfUpperTail as a, medianInPlace as c, studentTCdf as d, studentTQuantile as f, assertFiniteSample as i, symmetricTwoSampleSeed as l, regularizedIncompleteBeta as m, meanOrNull as n, binomialSignTwoSided as o, lnGamma as p, meanOrZero as r, makeRng as s, mean as t, zQuantile as u };
|
|
211
257
|
|
|
212
|
-
//# sourceMappingURL=
|
|
258
|
+
//# sourceMappingURL=mean-DDFhslBt.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mean-DDFhslBt.js","names":[],"sources":["../src/math/special-functions.ts","../src/math/student-t.ts","../src/statistics/internal.ts","../src/statistics/mean.ts"],"sourcesContent":["/** Lanczos approximation to ln Gamma(z). */\nexport function lnGamma(z: number): number {\n const g = 7\n const coefficients = [\n 0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313,\n -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6,\n 1.5056327351493116e-7,\n ]\n if (z < 0.5) {\n return Math.log(Math.PI / Math.sin(Math.PI * z)) - lnGamma(1 - z)\n }\n z -= 1\n let x = coefficients[0]!\n for (let i = 1; i < g + 2; i++) x += coefficients[i]! / (z + i)\n const t = z + g + 0.5\n return 0.5 * Math.log(2 * Math.PI) + (z + 0.5) * Math.log(t) - t + Math.log(x)\n}\n\n/**\n * Regularized incomplete beta function I_x(a, b).\n *\n * The Lentz continued fraction converges only for `x < (a+1)/(a+b+2)`; outside\n * that domain it must be reached through the symmetry `I_x(a,b) = 1 −\n * I_{1−x}(b,a)`. `studentTCdf` drives `x → 1` as `|t| → 0`, so the mirrored\n * branch is the one every near-null t-statistic takes.\n */\nexport function regularizedIncompleteBeta(x: number, a: number, b: number): number {\n if (x <= 0) return 0\n if (x >= 1) return 1\n const logBeta = lnGamma(a) + lnGamma(b) - lnGamma(a + b)\n // x^a·(1−x)^b / B(a,b) — symmetric under (x,a,b) → (1−x,b,a), so the\n // mirrored branch reuses it unchanged.\n const front = Math.exp(Math.log(x) * a + Math.log(1 - x) * b - logBeta)\n if (x < (a + 1) / (a + b + 2)) {\n return (front * betaContinuedFraction(x, a, b)) / a\n }\n return 1 - (front * betaContinuedFraction(1 - x, b, a)) / b\n}\n\n/** Modified Lentz evaluation of the beta continued fraction at `x`. */\nfunction betaContinuedFraction(x: number, a: number, b: number): number {\n const maxIterations = 300\n const epsilon = 3e-15\n let c = 1\n let d = 1 - ((a + b) * x) / (a + 1)\n if (Math.abs(d) < 1e-30) d = 1e-30\n d = 1 / d\n let fraction = d\n for (let m = 1; m <= maxIterations; m++) {\n const m2 = 2 * m\n let numerator = (m * (b - m) * x) / ((a + m2 - 1) * (a + m2))\n d = 1 + numerator * d\n if (Math.abs(d) < 1e-30) d = 1e-30\n c = 1 + numerator / c\n if (Math.abs(c) < 1e-30) c = 1e-30\n d = 1 / d\n fraction *= d * c\n numerator = -((a + m) * (a + b + m) * x) / ((a + m2) * (a + m2 + 1))\n d = 1 + numerator * d\n if (Math.abs(d) < 1e-30) d = 1e-30\n c = 1 + numerator / c\n if (Math.abs(c) < 1e-30) c = 1e-30\n d = 1 / d\n const delta = d * c\n fraction *= delta\n if (Math.abs(delta - 1) < epsilon) break\n }\n return fraction\n}\n","import { regularizedIncompleteBeta } from './special-functions'\n\n/**\n * Student-t CDF via the regularized incomplete beta function.\n */\nexport function studentTCdf(t: number, degreesOfFreedom: number): number {\n if (degreesOfFreedom <= 0) return 0.5\n\n const x = degreesOfFreedom / (degreesOfFreedom + t * t)\n const beta = regularizedIncompleteBeta(x, degreesOfFreedom / 2, 0.5)\n return t >= 0 ? 1 - 0.5 * beta : 0.5 * beta\n}\n\n/**\n * Inverse Student-t CDF, solved against {@link studentTCdf}.\n *\n * The CDF is monotone, so bracket expansion followed by bisection is stable\n * across fractional degrees of freedom and does not need a separate\n * approximation with a different error profile.\n */\nexport function studentTQuantile(probability: number, degreesOfFreedom: number): number {\n if (!Number.isFinite(probability) || probability < 0 || probability > 1) {\n throw new RangeError(`studentTQuantile: probability must be in [0,1], got ${probability}`)\n }\n if (!Number.isFinite(degreesOfFreedom) || degreesOfFreedom <= 0) {\n throw new RangeError(\n `studentTQuantile: degreesOfFreedom must be positive and finite, got ${degreesOfFreedom}`,\n )\n }\n if (probability === 0) return Number.NEGATIVE_INFINITY\n if (probability === 1) return Number.POSITIVE_INFINITY\n if (probability === 0.5) return 0\n if (probability < 0.5) return -studentTQuantile(1 - probability, degreesOfFreedom)\n\n let low = 0\n let high = 1\n while (studentTCdf(high, degreesOfFreedom) < probability) high *= 2\n for (let iteration = 0; iteration < 64; iteration++) {\n const middle = (low + high) / 2\n if (studentTCdf(middle, degreesOfFreedom) < probability) low = middle\n else high = middle\n }\n return (low + high) / 2\n}\n","/**\n * Shared internals for the statistics modules. Nothing here is part of the\n * public statistics surface — `./index` does not re-export this module.\n */\n\nimport { ValidationError } from '../errors'\nimport { interpolatedQuantile } from '../math/quantile'\nimport { lnGamma } from '../math/special-functions'\nimport { mulberry32 } from './random'\n\n/** Every rank test refuses non-finite input. Beyond the arithmetic being\n * undefined, the tie-grouping scan compares values with `===`, and\n * `NaN === NaN` is false, so a NaN would leave the group boundary unable to\n * advance and spin the loop forever. */\nexport function assertFiniteSample(fn: string, label: string, xs: readonly number[]): void {\n for (let i = 0; i < xs.length; i++) {\n if (!Number.isFinite(xs[i])) {\n throw new ValidationError(`${fn}: ${label}[${i}] must be finite, got ${xs[i]}`)\n }\n }\n}\n\n/**\n * Two-sided exact p-value for b successes out of (b + c) Bernoulli(0.5) trials —\n * the exact-binomial core of {@link mcnemar}. `min(1, 2·P(X ≤ min(b,c)))`. No\n * discordant pairs ⇒ no evidence ⇒ p = 1. Summed in log space (lnGamma) so it\n * stays exact at large discordant counts without overflow.\n */\nexport function binomialSignTwoSided(b: number, c: number): number {\n const nd = b + c\n if (nd === 0) return 1\n return Math.min(1, 2 * binomialHalfLowerTail(Math.min(b, c), nd))\n}\n\n/** P(X >= successes) for X ~ Binomial(n, 0.5). */\nexport function binomialHalfUpperTail(successes: number, n: number): number {\n if (successes <= 0) return 1\n if (successes > n) return 0\n\n // Use the smaller side of the distribution. For lower thresholds the\n // complement sums at most half the mass; for upper thresholds symmetry\n // maps the upper tail to a lower tail without subtraction.\n if (successes <= n / 2) {\n return Math.max(0, 1 - binomialHalfLowerTail(successes - 1, n))\n }\n return binomialHalfLowerTail(n - successes, n)\n}\n\n/** P(X <= maxSuccesses) for X ~ Binomial(n, 0.5), accumulated in log space. */\nfunction binomialHalfLowerTail(maxSuccesses: number, n: number): number {\n if (maxSuccesses < 0) return 0\n if (maxSuccesses >= n) return 1\n if (maxSuccesses === 0) return 2 ** -n\n\n const logHalfN = n * Math.log(0.5)\n let logTail = Number.NEGATIVE_INFINITY\n for (let i = 0; i <= maxSuccesses; i++) {\n const logChoose = lnGamma(n + 1) - lnGamma(i + 1) - lnGamma(n - i + 1)\n logTail = logAddExp(logTail, logChoose + logHalfN)\n }\n return Math.min(1, Math.exp(logTail))\n}\n\nfunction logAddExp(a: number, b: number): number {\n if (a === Number.NEGATIVE_INFINITY) return b\n if (b === Number.NEGATIVE_INFINITY) return a\n const max = Math.max(a, b)\n const min = Math.min(a, b)\n return max + Math.log1p(Math.exp(min - max))\n}\n\n/** Standard-normal inverse CDF (Acklam approximation). */\nexport function zQuantile(p: number): number {\n if (p <= 0 || p >= 1) {\n if (p === 0) return -Infinity\n if (p === 1) return Infinity\n return NaN\n }\n const a = [\n -3.969683028665376e1, 2.209460984245205e2, -2.759285104469687e2, 1.38357751867269e2,\n -3.066479806614716e1, 2.506628277459239,\n ]\n const b = [\n -5.447609879822406e1, 1.615858368580409e2, -1.556989798598866e2, 6.680131188771972e1,\n -1.328068155288572e1,\n ]\n const c = [\n -7.784894002430293e-3, -3.223964580411365e-1, -2.400758277161838, -2.549732539343734,\n 4.374664141464968, 2.938163982698783,\n ]\n const d = [7.784695709041462e-3, 3.224671290700398e-1, 2.445134137142996, 3.754408661907416]\n const pLow = 0.02425\n const pHigh = 1 - pLow\n let q: number\n let r: number\n if (p < pLow) {\n q = Math.sqrt(-2 * Math.log(p))\n return (\n (((((c[0]! * q + c[1]!) * q + c[2]!) * q + c[3]!) * q + c[4]!) * q + c[5]!) /\n ((((d[0]! * q + d[1]!) * q + d[2]!) * q + d[3]!) * q + 1)\n )\n }\n if (p <= pHigh) {\n q = p - 0.5\n r = q * q\n return (\n ((((((a[0]! * r + a[1]!) * r + a[2]!) * r + a[3]!) * r + a[4]!) * r + a[5]!) * q) /\n (((((b[0]! * r + b[1]!) * r + b[2]!) * r + b[3]!) * r + b[4]!) * r + 1)\n )\n }\n q = Math.sqrt(-2 * Math.log(1 - p))\n return (\n -(((((c[0]! * q + c[1]!) * q + c[2]!) * q + c[3]!) * q + c[4]!) * q + c[5]!) /\n ((((d[0]! * q + d[1]!) * q + d[2]!) * q + d[3]!) * q + 1)\n )\n}\n\nexport function medianInPlace(xs: number[]): number {\n if (xs.length === 0) return 0\n xs.sort((a, b) => a - b)\n return interpolatedQuantile(xs, 0.5)\n}\n\n/**\n * PRNG for every resampling path in this module.\n *\n * With no caller seed the seed is DERIVED FROM THE DATA rather than taken from\n * `Math.random`, so re-running the same input reproduces the same interval —\n * a gate verdict that cannot be re-derived is not evidence. Distinct data\n * still gets a distinct stream. Same pattern as `promotion-gate.ts`.\n */\nexport function makeRng(\n seed: number | undefined,\n ...series: readonly (readonly number[])[]\n): () => number {\n return mulberry32(seed ?? seedFromData(series))\n}\n\n/** FNV-1a over the IEEE-754 bytes of every observation. */\nfunction seedFromData(series: readonly (readonly number[])[]): number {\n const view = new DataView(new ArrayBuffer(8))\n // 32-bit FNV-1a over the IEEE-754 BYTES of each observation, not over a\n // string. Frozen: it seeds the unseeded bootstrap from the data itself, so a\n // change moves every interval this package has already published. The\n // string-input variants elsewhere cannot be substituted here.\n let hash = 0x811c9dc5\n for (const xs of series) {\n for (const x of xs) {\n view.setFloat64(0, x)\n for (let byte = 0; byte < 8; byte++) {\n hash = Math.imul(hash ^ view.getUint8(byte), 0x01000193)\n }\n }\n // Separator, so ([1],[2]) and ([1,2],[]) do not collide.\n hash = Math.imul(hash ^ 0xff, 0x01000193)\n }\n return hash | 0\n}\n\n/** Order-independent seed for a symmetric two-sample statistic. */\nexport function symmetricTwoSampleSeed(a: readonly number[], b: readonly number[]): number {\n const sortedA = [...a].sort((left, right) => left - right)\n const sortedB = [...b].sort((left, right) => left - right)\n const forward = seedFromData([sortedA, sortedB]) >>> 0\n const reversed = seedFromData([sortedB, sortedA]) >>> 0\n return Math.min(forward, reversed)\n}\n","/** Arithmetic mean. An empty input has no mean and returns NaN. */\nexport function mean(values: readonly number[]): number {\n return values.reduce((sum, value) => sum + value, 0) / values.length\n}\n\n/** Arithmetic mean, or null for an empty input. */\nexport function meanOrNull(values: readonly number[]): number | null {\n return values.length === 0 ? null : mean(values)\n}\n\n/** Arithmetic mean, or 0 for an empty input. */\nexport function meanOrZero(values: readonly number[]): number {\n return values.length === 0 ? 0 : mean(values)\n}\n"],"mappings":";;;;;AACA,SAAgB,QAAQ,GAAmB;CACzC,MAAM,IAAI;CACV,MAAM,eAAe;EACnB;EAAqB;EAAmB;EAAqB;EAC7D;EAAqB;EAAoB;EAAsB;EAC/D;CACF;CACA,IAAI,IAAI,IACN,OAAO,KAAK,IAAI,KAAK,KAAK,KAAK,IAAI,KAAK,KAAK,CAAC,CAAC,IAAI,QAAQ,IAAI,CAAC;CAElE,KAAK;CACL,IAAI,IAAI,aAAa;CACrB,KAAK,IAAI,IAAI,GAAG,IAAI,GAAO,KAAK,KAAK,aAAa,MAAO,IAAI;CAC7D,MAAM,IAAI,IAAI,IAAI;CAClB,OAAO,KAAM,KAAK,IAAI,IAAI,KAAK,EAAE,KAAK,IAAI,MAAO,KAAK,IAAI,CAAC,IAAI,IAAI,KAAK,IAAI,CAAC;AAC/E;;;;;;;;;AAUA,SAAgB,0BAA0B,GAAW,GAAW,GAAmB;CACjF,IAAI,KAAK,GAAG,OAAO;CACnB,IAAI,KAAK,GAAG,OAAO;CACnB,MAAM,UAAU,QAAQ,CAAC,IAAI,QAAQ,CAAC,IAAI,QAAQ,IAAI,CAAC;CAGvD,MAAM,QAAQ,KAAK,IAAI,KAAK,IAAI,CAAC,IAAI,IAAI,KAAK,IAAI,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M,MAAM,QAAQ;EACvB,KAAK,MAAM,KAAK,IAAI;GAClB,KAAK,WAAW,GAAG,CAAC;GACpB,KAAK,IAAI,OAAO,GAAG,OAAO,GAAG,QAC3B,OAAO,KAAK,KAAK,OAAO,KAAK,SAAS,IAAI,GAAG,QAAU;EAE3D;EAEA,OAAO,KAAK,KAAK,OAAO,KAAM,QAAU;CAC1C;CACA,OAAO,OAAO;AAChB;;AAGA,SAAgB,uBAAuB,GAAsB,GAA8B;CACzF,MAAM,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,MAAM,UAAU,OAAO,KAAK;CACzD,MAAM,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,MAAM,UAAU,OAAO,KAAK;CACzD,MAAM,UAAU,aAAa,CAAC,SAAS,OAAO,CAAC,MAAM;CACrD,MAAM,WAAW,aAAa,CAAC,SAAS,OAAO,CAAC,MAAM;CACtD,OAAO,KAAK,IAAI,SAAS,QAAQ;AACnC;;;ACrKA,SAAgB,KAAK,QAAmC;CACtD,OAAO,OAAO,QAAQ,KAAK,UAAU,MAAM,OAAO,CAAC,IAAI,OAAO;AAChE;;AAGA,SAAgB,WAAW,QAA0C;CACnE,OAAO,OAAO,WAAW,IAAI,OAAO,KAAK,MAAM;AACjD;;AAGA,SAAgB,WAAW,QAAmC;CAC5D,OAAO,OAAO,WAAW,IAAI,IAAI,KAAK,MAAM;AAC9C"}
|
package/dist/meta-eval/index.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
import { n as CaptureIntegrityError, s as ValidationError } from "../errors-DeEEV9Vx.js";
|
|
2
2
|
import { a as hashCanonical, i as compareCodeUnits } from "../canonical-CicJlINA.js";
|
|
3
3
|
import { t as mulberry32 } from "../random-DrzcgC7F.js";
|
|
4
|
-
import { a as selfPreference, i as positionalBias, n as calibrateJudgeContinuous, o as verbosityBias, r as continuousAgreement, t as calibrateJudge } from "../judge-calibration-
|
|
4
|
+
import { a as selfPreference, i as positionalBias, n as calibrateJudgeContinuous, o as verbosityBias, r as continuousAgreement, t as calibrateJudge } from "../judge-calibration-D93UCm1k.js";
|
|
5
5
|
import { s as runMetricExtractor } from "../query-CGXzO9d4.js";
|
|
6
|
-
import { n as callLlmJson } from "../llm-client-
|
|
7
|
-
import { a as validateObservationOptions, i as reduceOutcomeMetric, n as correlationSummary, r as hasVariation, t as assertUniqueObservationIds } from "../outcome-observations-
|
|
8
|
-
import { a as rankedProbabilityScore, i as multiclassBrierScore, n as calibrationCurve, r as calibrationFromPairs, t as brierScore } from "../calibration-
|
|
9
|
-
import { a as judgeGateDecision, c as snapshotFromJudgeAgreement, d as judgeSentinelReport, f as snapshotFromAgreement, g as withJudgeRetry, h as validateSentinelSnapshot, i as assertJudgeMayGate, l as evalHealthStamp, m as snapshotFromSentinelSet, n as JudgeGateRefusedError, o as measureJudgeAgreement, p as snapshotFromCalibration, r as addCalibrationVerdicts, s as registerCalibrationSet, t as DEFAULT_JUDGE_GATE_POLICY, u as fileSentinelStore } from "../judge-gate-
|
|
6
|
+
import { n as callLlmJson } from "../llm-client-BdSiZ4qz.js";
|
|
7
|
+
import { a as validateObservationOptions, i as reduceOutcomeMetric, n as correlationSummary, r as hasVariation, t as assertUniqueObservationIds } from "../outcome-observations-ahbNtxuP.js";
|
|
8
|
+
import { a as rankedProbabilityScore, i as multiclassBrierScore, n as calibrationCurve, r as calibrationFromPairs, t as brierScore } from "../calibration-DLzckXnn.js";
|
|
9
|
+
import { a as judgeGateDecision, c as snapshotFromJudgeAgreement, d as judgeSentinelReport, f as snapshotFromAgreement, g as withJudgeRetry, h as validateSentinelSnapshot, i as assertJudgeMayGate, l as evalHealthStamp, m as snapshotFromSentinelSet, n as JudgeGateRefusedError, o as measureJudgeAgreement, p as snapshotFromCalibration, r as addCalibrationVerdicts, s as registerCalibrationSet, t as DEFAULT_JUDGE_GATE_POLICY, u as fileSentinelStore } from "../judge-gate-C9sLLJ-v.js";
|
|
10
10
|
import { t as computeInterval } from "../interval-Bd2f4CRT.js";
|
|
11
|
-
import { t as clusterBootstrapMean } from "../cluster-bootstrap-
|
|
12
|
-
import { t as rubricPredictiveValidity } from "../rubric-predictive-validity-
|
|
11
|
+
import { t as clusterBootstrapMean } from "../cluster-bootstrap-hNXESoc1.js";
|
|
12
|
+
import { t as rubricPredictiveValidity } from "../rubric-predictive-validity-BdxXDN6h.js";
|
|
13
13
|
import { n as InMemoryOutcomeStore, r as OutcomeStoreError, t as FileSystemOutcomeStore } from "../outcome-store-TarrcfHG.js";
|
|
14
14
|
import { z } from "zod";
|
|
15
15
|
// src/meta-eval/correlation-study.ts
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as MultishotTransportRequest, D as MultishotToolDefinition, T as MultishotResult, c as RunMultishotMatrixResult, f as RunMultishotOptions, s as RunMultishotMatrixOptions, w as MultishotPersona } from "../../matrix-
|
|
1
|
+
import { A as MultishotTransportRequest, D as MultishotToolDefinition, T as MultishotResult, c as RunMultishotMatrixResult, f as RunMultishotOptions, s as RunMultishotMatrixOptions, w as MultishotPersona } from "../../matrix-4DcRFJ7Q.js";
|
|
2
2
|
interface CompareOptions {
|
|
3
3
|
/** Stop after this many mismatches. A structural divergence high in the
|
|
4
4
|
* tree would otherwise report every leaf below it. */
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { C as JudgeDimension, w as JudgeScore } from "../types-
|
|
2
|
-
import { A as MultishotTransportRequest, C as MultishotMessage, D as MultishotToolDefinition, E as MultishotShape, M as MultishotTransportToolCall, N as assertMultishotShotResult, O as MultishotToolExecutor, S as MultishotFatalToolError, T as MultishotResult, _ as renderDimensions, a as MultishotCellOutput, b as MultishotArtifact, c as RunMultishotMatrixResult, d as MultishotShot, f as RunMultishotOptions, g as MultishotJudgeConfig, h as JudgeRunResult, i as ConversationJudgeInput, j as MultishotTransportResponse, k as MultishotTransport, l as computeCellComposite, m as DEFAULT_JUDGE_MODEL, n as CellCompositeInput, o as MultishotJudges, p as runMultishot, r as CellCompositeScore, s as RunMultishotMatrixOptions, t as ArtifactJudgeInput, u as runMultishotMatrix, v as renderJsonFooter, w as MultishotPersona, x as MultishotDriverEmptyError, y as runJudge } from "../matrix-
|
|
1
|
+
import { C as JudgeDimension, w as JudgeScore } from "../types-BF-xQGQn.js";
|
|
2
|
+
import { A as MultishotTransportRequest, C as MultishotMessage, D as MultishotToolDefinition, E as MultishotShape, M as MultishotTransportToolCall, N as assertMultishotShotResult, O as MultishotToolExecutor, S as MultishotFatalToolError, T as MultishotResult, _ as renderDimensions, a as MultishotCellOutput, b as MultishotArtifact, c as RunMultishotMatrixResult, d as MultishotShot, f as RunMultishotOptions, g as MultishotJudgeConfig, h as JudgeRunResult, i as ConversationJudgeInput, j as MultishotTransportResponse, k as MultishotTransport, l as computeCellComposite, m as DEFAULT_JUDGE_MODEL, n as CellCompositeInput, o as MultishotJudges, p as runMultishot, r as CellCompositeScore, s as RunMultishotMatrixOptions, t as ArtifactJudgeInput, u as runMultishotMatrix, v as renderJsonFooter, w as MultishotPersona, x as MultishotDriverEmptyError, y as runJudge } from "../matrix-4DcRFJ7Q.js";
|
|
3
3
|
import { AgentProfile } from "@tangle-network/agent-interface";
|
|
4
4
|
/** Prompt and completion tokens one leg reported. */
|
|
5
5
|
interface MultishotLegTokens {
|
package/dist/openapi.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"openapi": "3.1.0",
|
|
3
3
|
"info": {
|
|
4
4
|
"title": "@tangle-network/agent-eval — wire protocol",
|
|
5
|
-
"version": "0.
|
|
5
|
+
"version": "1.0.1",
|
|
6
6
|
"description": "HTTP and stdio RPC interface to agent-eval. The TypeScript runtime is the source of truth; this spec is the contract that cross-language clients (Python, Rust, Go) generate from.\n\nWire-protocol version: 1.1.0. Bumps on breaking changes to request/response schemas.",
|
|
7
7
|
"contact": {
|
|
8
8
|
"name": "Tangle Network",
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { s as makeRng } from "./mean-DDFhslBt.js";
|
|
2
|
+
import { i as pearsonR, o as spearmanR } from "./descriptive-BTzLL-aj.js";
|
|
3
3
|
// src/meta-eval/outcome-observations.ts
|
|
4
4
|
/** Reduce observations of one named metric; unrelated keys cannot supply a value. */
|
|
5
5
|
function reduceOutcomeMetric(outcomes, metric, reduction) {
|
|
@@ -74,4 +74,4 @@ function interval(values) {
|
|
|
74
74
|
}
|
|
75
75
|
export { validateObservationOptions as a, reduceOutcomeMetric as i, correlationSummary as n, validateOutcomeMetricSpecifications as o, hasVariation as r, assertUniqueObservationIds as t };
|
|
76
76
|
|
|
77
|
-
//# sourceMappingURL=outcome-observations-
|
|
77
|
+
//# sourceMappingURL=outcome-observations-ahbNtxuP.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"outcome-observations-
|
|
1
|
+
{"version":3,"file":"outcome-observations-ahbNtxuP.js","names":[],"sources":["../src/meta-eval/outcome-observations.ts"],"sourcesContent":["import { pearsonR, spearmanR } from '../statistics'\nimport { makeRng } from '../statistics/internal'\nimport type { DeploymentOutcome } from './outcome-store'\n\nexport type OutcomeReduction = 'latest' | 'mean' | 'max'\n\nexport interface CorrelationInterval {\n lower: number\n upper: number\n}\n\n/** Reduce observations of one named metric; unrelated keys cannot supply a value. */\nexport function reduceOutcomeMetric(\n outcomes: readonly DeploymentOutcome[],\n metric: string,\n reduction: OutcomeReduction,\n): number | null {\n const observations = outcomes.flatMap((outcome) => {\n const value = outcome.metrics[metric]\n return Number.isFinite(outcome.capturedAt) &&\n typeof value === 'number' &&\n Number.isFinite(value)\n ? [{ capturedAt: outcome.capturedAt, value }]\n : []\n })\n if (observations.length === 0) return null\n if (reduction === 'mean') {\n return observations.reduce(\n (sum, observation) => sum + observation.value / observations.length,\n 0,\n )\n }\n if (reduction === 'max') return Math.max(...observations.map((observation) => observation.value))\n return observations.reduce((a, b) => (b.capturedAt > a.capturedAt ? b : a)).value\n}\n\nexport function hasVariation(values: readonly number[]): boolean {\n return values.some((value) => value !== values[0])\n}\n\nexport function correlationSummary(\n xs: number[],\n ys: number[],\n iterations: number,\n seed: number | undefined,\n): {\n pearson: number\n spearman: number\n pearsonCi95: CorrelationInterval | null\n spearmanCi95: CorrelationInterval | null\n} {\n const rng = makeRng(seed, xs, ys)\n const pearsons: number[] = []\n const spearmans: number[] = []\n for (let b = 0; b < iterations; b++) {\n const rx: number[] = []\n const ry: number[] = []\n for (let i = 0; i < xs.length; i++) {\n const index = Math.floor(rng() * xs.length)\n rx.push(xs[index]!)\n ry.push(ys[index]!)\n }\n // A constant resample has no estimable correlation, even when both sides agree.\n if (!hasVariation(rx) || !hasVariation(ry)) continue\n const pearson = pearsonR(rx, ry)\n const spearman = spearmanR(rx, ry)\n if (Number.isFinite(pearson)) pearsons.push(pearson)\n if (Number.isFinite(spearman)) spearmans.push(spearman)\n }\n return {\n pearson: pearsonR(xs, ys),\n spearman: spearmanR(xs, ys),\n pearsonCi95: interval(pearsons),\n spearmanCi95: interval(spearmans),\n }\n}\n\nexport function validateObservationOptions(\n reduction: OutcomeReduction,\n iterations: number,\n seed: number | undefined,\n): void {\n if (!['latest', 'mean', 'max'].includes(reduction)) {\n throw new Error('outcome reduction must be latest, mean, or max')\n }\n if (!Number.isSafeInteger(iterations) || iterations < 1) {\n throw new Error('bootstrap iterations must be a positive safe integer')\n }\n if (seed !== undefined && !Number.isFinite(seed)) {\n throw new Error('bootstrap seed must be finite')\n }\n}\n\nexport function assertUniqueObservationIds(ids: readonly string[], name: string): void {\n if (ids.some((id) => typeof id !== 'string' || id.trim().length === 0)) {\n throw new Error(`${name} must be a nonempty string`)\n }\n if (new Set(ids).size !== ids.length) throw new Error(`duplicate ${name} in outcome study`)\n}\n\nexport function validateOutcomeMetricSpecifications(\n metrics: readonly { id: string; direction: string }[],\n): void {\n if (!Array.isArray(metrics) || metrics.length === 0) {\n throw new Error('outcomeMetrics must declare at least one outcome metric and direction')\n }\n for (const metric of metrics) {\n if (!metric || typeof metric.id !== 'string' || metric.id.trim().length === 0) {\n throw new Error('each outcome metric must have a nonempty id and explicit direction')\n }\n if (metric.direction !== 'higher-is-better' && metric.direction !== 'lower-is-better') {\n throw new Error(\n `outcome metric ${metric.id} must declare higher-is-better or lower-is-better`,\n )\n }\n }\n assertUniqueObservationIds(\n metrics.map((metric) => metric.id),\n 'outcome metric',\n )\n}\n\nfunction interval(values: number[]): CorrelationInterval | null {\n if (values.length === 0) return null\n values.sort((a, b) => a - b)\n return {\n lower: Math.max(-1, values[Math.floor(0.025 * values.length)]!),\n upper: Math.min(1, values[Math.min(values.length - 1, Math.floor(0.975 * values.length))]!),\n }\n}\n"],"mappings":";;;;AAYA,SAAgB,oBACd,UACA,QACA,WACe;CACf,MAAM,eAAe,SAAS,SAAS,YAAY;EACjD,MAAM,QAAQ,QAAQ,QAAQ;EAC9B,OAAO,OAAO,SAAS,QAAQ,UAAU,KACvC,OAAO,UAAU,YACjB,OAAO,SAAS,KAAK,IACnB,CAAC;GAAE,YAAY,QAAQ;GAAY;EAAM,CAAC,IAC1C,CAAC;CACP,CAAC;CACD,IAAI,aAAa,WAAW,GAAG,OAAO;CACtC,IAAI,cAAc,QAChB,OAAO,aAAa,QACjB,KAAK,gBAAgB,MAAM,YAAY,QAAQ,aAAa,QAC7D,CACF;CAEF,IAAI,cAAc,OAAO,OAAO,KAAK,IAAI,GAAG,aAAa,KAAK,gBAAgB,YAAY,KAAK,CAAC;CAChG,OAAO,aAAa,QAAQ,GAAG,MAAO,EAAE,aAAa,EAAE,aAAa,IAAI,CAAE,CAAC,CAAC;AAC9E;AAEA,SAAgB,aAAa,QAAoC;CAC/D,OAAO,OAAO,MAAM,UAAU,UAAU,OAAO,EAAE;AACnD;AAEA,SAAgB,mBACd,IACA,IACA,YACA,MAMA;CACA,MAAM,MAAM,QAAQ,MAAM,IAAI,EAAE;CAChC,MAAM,WAAqB,CAAC;CAC5B,MAAM,YAAsB,CAAC;CAC7B,KAAK,IAAI,IAAI,GAAG,IAAI,YAAY,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CAAC,MAAM,QAAQ,OAAO,KAAK,QAAQ,WAAW,GAChD,MAAM,IAAI,MAAM,uEAAuE;CAEzF,KAAK,MAAM,UAAU,SAAS;EAC5B,IAAI,CAAC,UAAU,OAAO,OAAO,OAAO,YAAY,OAAO,GAAG,KAAK,CAAC,CAAC,WAAW,GAC1E,MAAM,IAAI,MAAM,oEAAoE;EAEtF,IAAI,OAAO,cAAc,sBAAsB,OAAO,cAAc,mBAClE,MAAM,IAAI,MACR,kBAAkB,OAAO,GAAG,kDAC9B;CAEJ;CACA,2BACE,QAAQ,KAAK,WAAW,OAAO,EAAE,GACjC,gBACF;AACF;AAEA,SAAS,SAAS,QAA8C;CAC9D,IAAI,OAAO,WAAW,GAAG,OAAO;CAChC,OAAO,MAAM,GAAG,MAAM,IAAI,CAAC;CAC3B,OAAO;EACL,OAAO,KAAK,IAAI,IAAI,OAAO,KAAK,MAAM,OAAQ,OAAO,MAAM,EAAG;EAC9D,OAAO,KAAK,IAAI,GAAG,OAAO,KAAK,IAAI,OAAO,SAAS,GAAG,KAAK,MAAM,OAAQ,OAAO,MAAM,CAAC,EAAG;CAC5F;AACF"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { s as ValidationError } from "./errors-DeEEV9Vx.js";
|
|
2
2
|
import { a as findingTreatmentSchema } from "./finding-composition-DlvE1Qul.js";
|
|
3
|
-
import {
|
|
4
|
-
import { r as pairedRiskDifference, t as mcnemar } from "./paired-binary-
|
|
5
|
-
import { r as pairedBootstrap } from "./paired-tests-
|
|
3
|
+
import { i as assertFiniteSample, l as symmetricTwoSampleSeed, o as binomialSignTwoSided, p as lnGamma, s as makeRng } from "./mean-DDFhslBt.js";
|
|
4
|
+
import { r as pairedRiskDifference, t as mcnemar } from "./paired-binary-B477lksS.js";
|
|
5
|
+
import { r as pairedBootstrap } from "./paired-tests-kASEKpc-.js";
|
|
6
6
|
// src/arm-populations.ts
|
|
7
7
|
const keyOf = (row) => JSON.stringify([
|
|
8
8
|
row.arm,
|
|
@@ -737,4 +737,4 @@ function metricValue(row, name) {
|
|
|
737
737
|
}
|
|
738
738
|
export { wilcoxonSignedRank as a, mannWhitneyU as i, pairArms as n, normalCdf as o, pairRunRecords as r, comparePairedArms as t };
|
|
739
739
|
|
|
740
|
-
//# sourceMappingURL=paired-arms-
|
|
740
|
+
//# sourceMappingURL=paired-arms-C0Vd9bGG.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"paired-arms-D5H_58e8.js","names":[],"sources":["../src/arm-populations.ts","../src/math/normal.ts","../src/statistics/rank-tests.ts","../src/paired-arms.ts"],"sourcesContent":["import type { FindingTreatment } from './analyst/finding-composition'\nimport { findingTreatmentSchema } from './analyst/finding-composition'\nimport type { PairedArmRow } from './paired-arms'\n\n/** Expected seed identities must be supplied independently of completed observations. */\nexport interface ArmAssignment {\n pairKey: string\n repKey?: string\n arm: string\n treatment?: FindingTreatment[]\n}\nexport interface ArmPopulationSummary {\n n: number\n passed: number\n failed: number\n missingOutcomes: number\n /** Unknown unless every unit's outcome was observed; missing is never a failed check. */\n passRate: number | null\n metrics: Record<string, { n: number; missing: number; sum: number | null; mean: number | null }>\n}\nexport interface ArmPopulationReading {\n arm: string\n assignments: ArmAssignment[]\n missingObservations: number\n formation: { formed: number; notFormed: number; unknown: number }\n asAssigned: ArmPopulationSummary\n asFormed: ArmPopulationSummary\n}\n\nconst keyOf = (row: ArmAssignment): string =>\n JSON.stringify([row.arm, row.pairKey, row.repKey ?? null])\nfunction checkIdentity(row: ArmAssignment): void {\n for (const value of [row.arm, row.pairKey, ...(row.repKey === undefined ? [] : [row.repKey])]) {\n if (typeof value !== 'string' || !value.trim())\n throw new TypeError('Arm assignments require nonempty identities')\n }\n if (row.treatment !== undefined) {\n if (!Array.isArray(row.treatment)) throw new TypeError('Arm treatment must be an array')\n for (const value of row.treatment) findingTreatmentSchema.parse(value)\n if (new Set(row.treatment.map((t) => t.id)).size !== row.treatment.length)\n throw new TypeError('Duplicate arm treatment id')\n }\n}\nfunction checkObservation(row: PairedArmRow): void {\n checkIdentity(row)\n if (row.pass != null && typeof row.pass !== 'boolean')\n throw new TypeError('Invalid arm pass value')\n if (row.formation !== undefined) {\n if (row.formation === null || typeof row.formation !== 'object')\n throw new TypeError('Invalid formation verdict')\n if (row.formation.formed !== null && typeof row.formation.formed !== 'boolean')\n throw new TypeError('Invalid formation state')\n if (row.formation.reason !== undefined && typeof row.formation.reason !== 'string')\n throw new TypeError('Invalid formation reason')\n }\n for (const value of Object.values(row.metrics ?? {})) {\n if (value !== null && !Number.isFinite(value)) throw new TypeError('Non-finite arm metric')\n }\n}\n\n/** One roster join serves comparison and both denominators; no outcomes are inferred from formation. */\nexport function prepareArmPopulations(\n observations: readonly PairedArmRow[],\n assignments: readonly ArmAssignment[],\n options: { baselineArm: string; treatmentArm: string; metricNames?: string[] },\n): { rows: PairedArmRow[]; readings: ArmPopulationReading[] } {\n const arms = [options.baselineArm, options.treatmentArm]\n const roster = new Map<string, ArmAssignment>()\n for (const entry of assignments) {\n if (!arms.includes(entry.arm)) continue\n checkIdentity(entry)\n const key = keyOf(entry)\n if (roster.has(key)) throw new TypeError('Duplicate arm assignment')\n roster.set(key, structuredClone(entry))\n }\n for (const arm of arms)\n if (![...roster.values()].some((r) => r.arm === arm))\n throw new TypeError(`No assignment roster for arm '${arm}'`)\n const actual = new Map<string, PairedArmRow>()\n for (const row of observations) {\n if (!arms.includes(row.arm)) continue\n checkObservation(row)\n const key = keyOf(row)\n if (!roster.has(key)) throw new TypeError('Observed seed is outside the assignment roster')\n if (actual.has(key)) throw new TypeError('Duplicate arm observation')\n actual.set(key, row)\n }\n const ordered = [...roster.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n // Placeholder rows carry identities only. They never manufacture pass, metrics or formation.\n const rows = ordered.map(([key, entry]) => actual.get(key) ?? entry)\n const metricNames =\n options.metricNames ??\n [...new Set([...actual.values()].flatMap((r) => Object.keys(r.metrics ?? {})))].sort()\n const readings = arms.map((arm) => {\n const declared = ordered.filter(([, r]) => r.arm === arm)\n const asAssigned = declared.map(([key]) => actual.get(key))\n const asFormed = asAssigned.filter(\n (row): row is PairedArmRow => row?.formation?.formed === true,\n )\n return {\n arm,\n assignments: declared.map(([, r]) => r),\n missingObservations: asAssigned.filter((r) => r === undefined).length,\n formation: {\n formed: asFormed.length,\n notFormed: asAssigned.filter((r) => r?.formation?.formed === false).length,\n unknown: asAssigned.filter((r) => r?.formation?.formed == null).length,\n },\n asAssigned: summarize(asAssigned, metricNames),\n asFormed: summarize(asFormed, metricNames),\n }\n })\n return { rows, readings }\n}\n\nfunction summarize(\n rows: readonly (PairedArmRow | undefined)[],\n names: readonly string[],\n): ArmPopulationSummary {\n const passed = rows.filter((r) => r?.pass === true).length\n const failed = rows.filter((r) => r?.pass === false).length\n const missingOutcomes = rows.length - passed - failed\n const metrics = Object.fromEntries(\n names.map((name) => {\n const values = rows.map((r) => r?.metrics?.[name]).filter((x): x is number => x != null)\n const sum = values.length ? values.reduce((s, v) => s + v, 0) : null\n return [\n name,\n {\n n: values.length,\n missing: rows.length - values.length,\n sum,\n mean: sum === null ? null : sum / values.length,\n },\n ]\n }),\n )\n return {\n n: rows.length,\n passed,\n failed,\n missingOutcomes,\n passRate: rows.length && !missingOutcomes ? passed / rows.length : null,\n metrics,\n }\n}\n","/**\n * Standard normal cumulative distribution using Abramowitz and Stegun 7.1.26.\n *\n * The approximation is evaluated as erf(x / sqrt(2)). Computing the negative\n * tail from the complementary term avoids cancellation when x is far below 0.\n * The maximum absolute CDF error is approximately 7.5e-8.\n */\nexport function normalCdf(x: number): number {\n if (x === 0) return 0.5\n\n const a1 = 0.254829592\n const a2 = -0.284496736\n const a3 = 1.421413741\n const a4 = -1.453152027\n const a5 = 1.061405429\n const p = 0.3275911\n\n const scaled = Math.abs(x) / Math.SQRT2\n const t = 1 / (1 + p * scaled)\n const complement = ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp(-scaled * scaled)\n\n return x < 0 ? complement / 2 : 1 - complement / 2\n}\n","import { ValidationError } from '../errors'\nimport { normalCdf } from '../math/normal'\nimport { lnGamma } from '../math/special-functions'\nimport {\n assertFiniteSample,\n binomialSignTwoSided,\n makeRng,\n symmetricTwoSampleSeed,\n} from './internal'\n\n// ── Rank tests: exact by default ─────────────────────────────────────\n//\n// At 3–10 repetitions per arm the binding constraint on a rank test is\n// combinatorial, not numerical. Three versus three admits only 20 splits, so\n// the attainable two-sided p-grid starts at 0.1000 and α = 0.05 is out of\n// reach at that design; a normal approximation reports 0.0495, a p-value that\n// describes no attainable outcome. No better approximation fixes this — adding\n// the tie correction moves `[0,0,0]` versus `[1,1,1]` from 0.0495 to 0.0469,\n// further from its exact 0.1000, not closer.\n//\n// So both null distributions are enumerated exactly inside bounded state and\n// work budgets, by convolution over the observed midranks (identical to\n// enumerating every split / sign pattern, and cheaper), which conditions on the\n// realised tie pattern for free. Above those budgets the default is a seeded\n// Monte Carlo permutation. The asymptotic path is never chosen automatically,\n// and asking for it inside the exact-feasible range throws.\n//\n// Every result carries `method` and `pFloor` so a downstream gate can SEE the\n// discreteness rather than infer it: a gate handed data whose `pFloor` exceeds\n// its alpha is underpowered by construction, which is a true statement about\n// the experiment, not a false one about the effect.\n\n/** How a rank test's p-value was actually computed. */\nexport type RankTestMethod = 'exact' | 'permutation' | 'asymptotic'\n\n/**\n * What the caller asks for. `'auto'` selects `'exact'` inside the enumeration\n * threshold and `'permutation'` above it, and never selects `'asymptotic'`.\n */\nexport type RankTestMethodRequest = 'auto' | 'exact' | 'asymptotic'\n\nexport interface RankTestOptions {\n /** Default `'auto'`. `'asymptotic'` inside the exact-feasible range throws. */\n method?: RankTestMethodRequest\n /** Resamples on the Monte Carlo permutation path. Default 100000. */\n permutations?: number\n /** Seed for the permutation path. Omitted ⇒ derived from the data itself, so\n * the result is reproducible either way. */\n seed?: number\n}\n\n/** Maximum dynamic-programming cells used by an exact two-sample rank test. */\nconst MANN_WHITNEY_EXACT_MAX_STATES = 8_192\n/** Maximum inner-loop transitions used by an exact two-sample rank test. */\nconst MANN_WHITNEY_EXACT_MAX_WORK = 250_000\n/** Non-zero differences up to which the signed-rank null is enumerated exactly. */\nconst WILCOXON_EXACT_MAX_N = 20\n/** Resamples used when a rank test falls back to Monte Carlo permutation. */\nconst DEFAULT_PERMUTATIONS = 100_000\n\nexport interface MannWhitneyResult {\n /** `min(U_a, U_b)` — the conventional reported statistic. */\n u: number\n /** U for sample `a`. Carries the direction of the effect, which `u` discards. */\n uA: number\n /** Two-sided p-value. */\n p: number\n /** How `p` was computed. */\n method: RankTestMethod\n /** Smallest two-sided p this design can produce. `p` can never be below it. */\n pFloor: number\n}\n\n/**\n * Mann-Whitney U — two independent samples, no distributional assumption.\n *\n * Exact conditional (permutation) p by default when the dynamic program fits\n * {@link MANN_WHITNEY_EXACT_MAX_STATES} cells and\n * {@link MANN_WHITNEY_EXACT_MAX_WORK} transitions, seeded Monte Carlo\n * permutation above those limits. This keeps imbalanced designs such as 1+24\n * exact without admitting expensive balanced designs merely because they have\n * the same total size. Throws on non-finite input and on `method:\n * 'asymptotic'` where an exact answer is available. Empty input yields `p = 1,\n * pFloor = 1` — no design, no attainable evidence.\n */\nexport function mannWhitneyU(\n a: number[],\n b: number[],\n opts: RankTestOptions = {},\n): MannWhitneyResult {\n assertFiniteSample('mannWhitneyU', 'a', a)\n assertFiniteSample('mannWhitneyU', 'b', b)\n\n const n1 = a.length\n const n2 = b.length\n if (n1 === 0 || n2 === 0) return { u: 0, uA: 0, p: 1, method: 'exact', pFloor: 1 }\n\n const total = n1 + n2\n const combined = [\n ...a.map((v) => ({ v, fromA: true })),\n ...b.map((v) => ({ v, fromA: false })),\n ].sort((x, y) => x.v - y.v)\n\n const { midranks, tieTerm } = midranksWithTieTerm(combined.map((entry) => entry.v))\n let rankSumA = 0\n for (let k = 0; k < total; k++) {\n if (combined[k]!.fromA) rankSumA += midranks[k]!\n }\n\n const uA = rankSumA - (n1 * (n1 + 1)) / 2\n const u = Math.min(uA, n1 * n2 - uA)\n // Midranks are integers or halves, so doubling makes the null convolution\n // integral. U is centred on n₁n₂/2, hence a doubled centre of n₁n₂.\n const doubled = midranks.map((rank) => Math.round(rank * 2))\n const doubledDeviation = Math.abs(2 * uA - n1 * n2)\n const selectedN = Math.min(n1, n2)\n const otherN = total - selectedN\n const exactCost = exactTwoSampleCost(doubled, selectedN)\n\n const designFloor = exactTwoSampleFloor(doubled, selectedN)\n const method = selectRankTestMethod(\n 'mannWhitneyU',\n opts.method ?? 'auto',\n `n1=${n1}, n2=${n2}`,\n exactCost.states <= MANN_WHITNEY_EXACT_MAX_STATES &&\n exactCost.work <= MANN_WHITNEY_EXACT_MAX_WORK,\n designFloor,\n `${MANN_WHITNEY_EXACT_MAX_STATES.toLocaleString('en-US')} states and ` +\n `${MANN_WHITNEY_EXACT_MAX_WORK.toLocaleString('en-US')} transitions`,\n )\n\n if (method === 'exact') {\n const { p, pFloor } = exactTwoSampleP(doubled, selectedN, otherN, doubledDeviation)\n return { u, uA, p, method, pFloor }\n }\n\n if (method === 'asymptotic') {\n return {\n u,\n uA,\n p: asymptoticTwoSidedP(doubledDeviation / 2, twoSampleSigma(n1, n2, total, tieTerm)),\n method,\n pFloor: designFloor,\n }\n }\n\n const permutations = resolvePermutations('mannWhitneyU', opts.permutations)\n const rng = opts.seed === undefined ? makeRng(symmetricTwoSampleSeed(a, b)) : makeRng(opts.seed)\n let atLeastAsExtreme = 0\n const pool = [...doubled]\n for (let iteration = 0; iteration < permutations; iteration++) {\n let doubledRankSum = 0\n for (let k = 0; k < selectedN; k++) {\n const pick = k + Math.floor(rng() * (total - k))\n const swapped = pool[pick]!\n pool[pick] = pool[k]!\n pool[k] = swapped\n doubledRankSum += swapped\n }\n if (\n Math.abs(doubledRankSum - selectedN * (selectedN + 1) - selectedN * otherN) >=\n doubledDeviation\n ) {\n atLeastAsExtreme++\n }\n }\n const pFloor = Math.max(1 / (permutations + 1), designFloor)\n return {\n u,\n uA,\n p: Math.max((1 + atLeastAsExtreme) / (permutations + 1), pFloor),\n method,\n pFloor,\n }\n}\n\nexport interface WilcoxonSignedRankResult {\n /** W⁺, the rank sum of the positive differences. (scipy reports\n * `min(W⁺, W⁻)`; compare statistics only after converting.) */\n w: number\n /** Two-sided p-value. */\n p: number\n /** How `p` was computed. */\n method: RankTestMethod\n /** Smallest two-sided p this design can produce. */\n pFloor: number\n /** Non-zero differences — zero differences are dropped and carry no rank. */\n nNonZero: number\n}\n\n/**\n * Wilcoxon signed-rank — paired, no distributional assumption on the deltas.\n *\n * Exact conditional (sign-flip) p by default at `n ≤\n * {@link WILCOXON_EXACT_MAX_N}` non-zero differences, seeded Monte Carlo\n * permutation above it. Throws on non-finite input and on `method:\n * 'asymptotic'` where an exact answer is available.\n *\n * `n` is the count of NON-ZERO differences: exact ties are dropped before\n * ranking, so a run of tied pairs shrinks the design and raises `pFloor`.\n * All-tied input yields `p = 1, pFloor = 1` — no attainable evidence, which\n * `pFloor` states rather than leaving `p = 1` to be read as a measured null.\n */\nexport function wilcoxonSignedRank(\n before: number[],\n after: number[],\n opts: RankTestOptions = {},\n): WilcoxonSignedRankResult {\n if (before.length !== after.length) {\n throw new ValidationError(\n `wilcoxonSignedRank: unequal sample sizes (${before.length} vs ${after.length})`,\n )\n }\n assertFiniteSample('wilcoxonSignedRank', 'before', before)\n assertFiniteSample('wilcoxonSignedRank', 'after', after)\n\n const diffs = before.map((b, i) => after[i]! - b).filter((d) => d !== 0)\n const n = diffs.length\n if (n === 0) return { w: 0, p: 1, method: 'exact', pFloor: 1, nNonZero: 0 }\n\n // When every non-zero difference has the same magnitude, the signed-rank\n // null reduces exactly to a binomial sign distribution. This is the common\n // pass/fail shape ({-1, 0, +1}); recognizing it avoids a 100k-draw\n // permutation for every repeated gate evaluation while preserving the exact\n // p-value and attainable floor. Explicit method requests still retain their\n // documented behavior.\n const abs = Math.abs(diffs[0]!)\n const allEqualAbs = diffs.every((d) => Math.abs(d) === abs)\n if ((opts.method === undefined || opts.method === 'auto') && allEqualAbs) {\n const positive = diffs.filter((d) => d > 0).length\n const negative = n - positive\n return {\n w: (positive * (n + 1)) / 2,\n p: binomialSignTwoSided(positive, negative),\n method: 'exact',\n pFloor: Math.min(1, 2 ** (1 - n)),\n nNonZero: n,\n }\n }\n\n const order = diffs.map((d, i) => ({ abs: Math.abs(d), i })).sort((x, y) => x.abs - y.abs)\n const { midranks, tieTerm } = midranksWithTieTerm(order.map((entry) => entry.abs))\n const ranks: number[] = new Array(n)\n for (let k = 0; k < n; k++) ranks[order[k]!.i] = midranks[k]!\n\n let wPlus = 0\n for (let k = 0; k < n; k++) if (diffs[k]! > 0) wPlus += ranks[k]!\n\n // Midranks are integers or halves; doubling makes the convolution integral.\n // Σ midranks = n(n+1)/2 whatever the tie pattern, so E[W⁺] = n(n+1)/4 and\n // the doubled centre is n(n+1)/2.\n const doubled = midranks.map((rank) => Math.round(rank * 2))\n const doubledDeviation = Math.abs(2 * wPlus - (n * (n + 1)) / 2)\n\n const designFloor = Math.min(1, 2 ** (1 - n))\n const method = selectRankTestMethod(\n 'wilcoxonSignedRank',\n opts.method ?? 'auto',\n `n=${n} non-zero differences`,\n n <= WILCOXON_EXACT_MAX_N,\n designFloor,\n `${WILCOXON_EXACT_MAX_N} non-zero differences`,\n )\n\n if (method === 'exact') {\n const { p, pFloor } = exactSignedRankP(doubled, doubledDeviation)\n return { w: wPlus, p, method, pFloor, nNonZero: n }\n }\n\n if (method === 'asymptotic') {\n const variance = (n * (n + 1) * (2 * n + 1)) / 24 - tieTerm / 48\n return {\n w: wPlus,\n p: asymptoticTwoSidedP(doubledDeviation / 2, Math.sqrt(variance)),\n method,\n pFloor: designFloor,\n nNonZero: n,\n }\n }\n\n const permutations = resolvePermutations('wilcoxonSignedRank', opts.permutations)\n const rng = makeRng(opts.seed, before, after)\n const doubledCentre = (n * (n + 1)) / 2\n let atLeastAsExtreme = 0\n for (let iteration = 0; iteration < permutations; iteration++) {\n let doubledWPlus = 0\n for (let k = 0; k < n; k++) if (rng() < 0.5) doubledWPlus += doubled[k]!\n if (Math.abs(doubledWPlus - doubledCentre) >= doubledDeviation) atLeastAsExtreme++\n }\n return {\n w: wPlus,\n p: (1 + atLeastAsExtreme) / (permutations + 1),\n method,\n pFloor: Math.max(1 / (permutations + 1), designFloor),\n nNonZero: n,\n }\n}\n\n/**\n * Average ranks over an ASCENDING-sorted array, plus `Σ(t³ − t)` over tie\n * groups of size `t` — the correction term both asymptotic rank-test variances\n * need.\n */\nfunction midranksWithTieTerm(sorted: readonly number[]): { midranks: number[]; tieTerm: number } {\n const midranks = new Array<number>(sorted.length)\n let tieTerm = 0\n let i = 0\n while (i < sorted.length) {\n let j = i\n while (j < sorted.length && sorted[j] === sorted[i]) j++\n const average = (i + 1 + j) / 2\n for (let k = i; k < j; k++) midranks[k] = average\n const groupSize = j - i\n if (groupSize > 1) tieTerm += groupSize ** 3 - groupSize\n i = j\n }\n return { midranks, tieTerm }\n}\n\nfunction selectRankTestMethod(\n fn: string,\n request: RankTestMethodRequest,\n design: string,\n exactFeasible: boolean,\n designFloor: number,\n threshold: string,\n): RankTestMethod {\n if (request === 'auto') return exactFeasible ? 'exact' : 'permutation'\n if (request === 'exact') {\n if (exactFeasible) return 'exact'\n throw new ValidationError(\n `${fn}: method 'exact' is out of range at ${design} — enumeration is bounded by ` +\n `${threshold}. Use 'auto' for the seeded Monte Carlo permutation, which converges ` +\n 'to the same answer.',\n )\n }\n if (exactFeasible) {\n throw new ValidationError(\n `${fn}: method 'asymptotic' is refused at ${design} — the exact p-grid at this design ` +\n `starts at ${formatProbability(designFloor)}, so an asymptotic p below it describes no ` +\n `attainable outcome. Use method 'exact' (the default) or add repetitions past ` +\n `${threshold}.`,\n )\n }\n return 'asymptotic'\n}\n\nfunction resolvePermutations(fn: string, permutations: number | undefined): number {\n if (permutations === undefined) return DEFAULT_PERMUTATIONS\n if (!Number.isInteger(permutations) || permutations < 1) {\n throw new ValidationError(`${fn}: permutations must be a positive integer, got ${permutations}`)\n }\n return permutations\n}\n\n/** Two-sided normal-approximation tail with the continuity correction. */\nfunction asymptoticTwoSidedP(deviation: number, sigma: number): number {\n if (!(sigma > 0)) return 1\n return Math.min(1, 2 * (1 - normalCdf(Math.max(0, deviation - 0.5) / sigma)))\n}\n\n/** SD of U under the permutation null, corrected for the realised ties. The\n * tie term reduces (N+1) and reaches it exactly when every value is tied, so\n * the variance floors at 0 rather than going negative. */\nfunction twoSampleSigma(n1: number, n2: number, total: number, tieTerm: number): number {\n if (total < 2) return 0\n const variance = ((n1 * n2) / 12) * (total + 1 - tieTerm / (total * (total - 1)))\n return Math.sqrt(Math.max(0, variance))\n}\n\nfunction logChoose(n: number, k: number): number {\n return lnGamma(n + 1) - lnGamma(k + 1) - lnGamma(n - k + 1)\n}\n\nfunction formatProbability(value: number): string {\n return value >= 1e-4 || value === 0 ? value.toFixed(4) : value.toExponential(3)\n}\n\n/**\n * Exact DP allocation and loop count for this observed rank vector.\n *\n * The smaller arm is sufficient because selecting its complement produces the\n * same two-sided U deviation while using fewer rows in the state table.\n */\nfunction exactTwoSampleCost(\n doubledRanks: readonly number[],\n selectedN: number,\n): { states: number; work: number } {\n const maxSum = doubledRanks.reduce((sum, rank) => sum + rank, 0)\n let work = 0\n for (let placed = 0; placed < doubledRanks.length; placed++) {\n work += Math.min(selectedN, placed + 1) * (maxSum - doubledRanks[placed]! + 1)\n }\n return {\n states: (selectedN + 1) * (maxSum + 1),\n work,\n }\n}\n\n/**\n * Smallest attainable two-sided p under the observed ties.\n *\n * Only subsets with the minimum or maximum rank sum can attain the largest\n * deviation. Their multiplicity is the number of ways to choose within the\n * tie group at each boundary, so this calculation is exact without allocating\n * the full null distribution.\n */\nfunction exactTwoSampleFloor(doubledRanks: readonly number[], selectedN: number): number {\n const total = doubledRanks.length\n const otherN = total - selectedN\n const minimumSum = doubledRanks.slice(0, selectedN).reduce((sum, rank) => sum + rank, 0)\n const maximumSum = doubledRanks.slice(total - selectedN).reduce((sum, rank) => sum + rank, 0)\n if (minimumSum === maximumSum) return 1\n\n const centre = selectedN * (selectedN + 1) + selectedN * otherN\n const minimumDeviation = Math.abs(minimumSum - centre)\n const maximumDeviation = Math.abs(maximumSum - centre)\n const totalLogWays = logChoose(total, selectedN)\n const minimumMass = Math.exp(\n logExtremeSubsetWays(doubledRanks, selectedN, 'minimum') - totalLogWays,\n )\n const maximumMass = Math.exp(\n logExtremeSubsetWays(doubledRanks, selectedN, 'maximum') - totalLogWays,\n )\n\n if (minimumDeviation > maximumDeviation) return minimumMass\n if (maximumDeviation > minimumDeviation) return maximumMass\n return Math.min(1, minimumMass + maximumMass)\n}\n\nfunction logExtremeSubsetWays(\n sortedRanks: readonly number[],\n selectedN: number,\n side: 'minimum' | 'maximum',\n): number {\n const boundaryIndex = side === 'minimum' ? selectedN - 1 : sortedRanks.length - selectedN\n const boundary = sortedRanks[boundaryIndex]!\n let first = boundaryIndex\n let afterLast = boundaryIndex + 1\n while (first > 0 && sortedRanks[first - 1] === boundary) first--\n while (afterLast < sortedRanks.length && sortedRanks[afterLast] === boundary) afterLast++\n\n const tieSize = afterLast - first\n const fixed = side === 'minimum' ? first : sortedRanks.length - afterLast\n return logChoose(tieSize, selectedN - fixed)\n}\n\n/**\n * Exact conditional two-sided p for the two-sample rank test.\n *\n * Convolves the observed doubled midranks into the null distribution of group\n * a's rank sum over every `C(n₁+n₂, n₁)` split — identical to enumerating the\n * splits, but `O(N·n₁·ΣR)` instead of `O(C(N,n₁)·n₁n₂)`. Conditioning on the\n * realised multiset makes the tie handling exact rather than a correction.\n *\n * The null is symmetric about `n₁n₂/2` (negating every value maps `U → n₁n₂ −\n * U` and permutes the split set onto itself), so the two-sided p is the mass\n * at least as far from the centre as the observation.\n */\nfunction exactTwoSampleP(\n doubledRanks: readonly number[],\n n1: number,\n n2: number,\n doubledDeviation: number,\n): { p: number; pFloor: number } {\n const maxSum = doubledRanks.reduce((sum, rank) => sum + rank, 0)\n const width = maxSum + 1\n // ways[k][s] = number of size-k subsets whose doubled rank sum is s.\n const ways: Float64Array[] = Array.from({ length: n1 + 1 }, () => new Float64Array(width))\n ways[0]![0] = 1\n let placed = 0\n for (const rank of doubledRanks) {\n for (let k = Math.min(n1, placed + 1); k >= 1; k--) {\n const from = ways[k - 1]!\n const into = ways[k]!\n for (let sum = maxSum - rank; sum >= 0; sum--) {\n const count = from[sum]!\n if (count !== 0) into[sum + rank]! += count\n }\n }\n placed++\n }\n\n // U = rankSum − n₁(n₁+1)/2, so doubled U = s − n₁(n₁+1), and the doubled\n // centre 2·(n₁n₂/2) is n₁n₂.\n const shift = n1 * (n1 + 1) + n1 * n2\n const chosen = ways[n1]!\n let totalWays = 0\n let extremeWays = 0\n let tailWays = 0\n let maxDeviation = -1\n for (let sum = 0; sum < width; sum++) {\n const count = chosen[sum]!\n if (count === 0) continue\n totalWays += count\n const deviation = Math.abs(sum - shift)\n if (deviation >= doubledDeviation) tailWays += count\n if (deviation > maxDeviation) {\n maxDeviation = deviation\n extremeWays = count\n } else if (deviation === maxDeviation) {\n extremeWays += count\n }\n }\n return { p: tailWays / totalWays, pFloor: extremeWays / totalWays }\n}\n\n/**\n * Exact conditional two-sided p for the paired signed-rank test.\n *\n * Convolves the observed doubled absolute midranks over all `2ⁿ` sign\n * assignments in `O(n·ΣR)`. Probabilities rather than counts keep `2ⁿ` off the\n * arithmetic. The null is symmetric about `n(n+1)/4`.\n */\nfunction exactSignedRankP(\n doubledRanks: readonly number[],\n doubledDeviation: number,\n): { p: number; pFloor: number } {\n const maxSum = doubledRanks.reduce((sum, rank) => sum + rank, 0)\n const width = maxSum + 1\n let mass = new Float64Array(width)\n mass[0] = 1\n for (const rank of doubledRanks) {\n const next = new Float64Array(width)\n for (let sum = 0; sum < width; sum++) {\n const probability = mass[sum]!\n if (probability === 0) continue\n next[sum]! += probability * 0.5\n next[sum + rank]! += probability * 0.5\n }\n mass = next\n }\n\n const centre = maxSum / 2\n let tail = 0\n let extreme = 0\n let maxDeviation = -1\n for (let sum = 0; sum < width; sum++) {\n const probability = mass[sum]!\n if (probability === 0) continue\n const deviation = Math.abs(sum - centre)\n if (deviation >= doubledDeviation) tail += probability\n if (deviation > maxDeviation) {\n maxDeviation = deviation\n extreme = probability\n } else if (deviation === maxDeviation) {\n extreme += probability\n }\n }\n return { p: Math.min(1, tail), pFloor: Math.min(1, extreme) }\n}\n","/**\n * Matched-pair arm comparison — \"did the treatment arm beat the baseline arm\n * on the SAME work items?\"\n *\n * An arm A/B over run records is only trustworthy when it is PAIRED: the same\n * task/scenario/seed evaluated under both arms, compared item-by-item, so\n * inter-item difficulty variance cancels instead of masquerading as an arm\n * effect. This module owns the two error-prone steps every consumer otherwise\n * hand-rolls:\n *\n * 1. Pairing — matching rows across arms by `pairKey` (and by `repKey`\n * within multi-rep items), with leftovers REPORTED rather than silently\n * dropped (a silently unbalanced pairing biases every paired statistic\n * downstream). Pairing never keys on outcome content: matching reps by\n * their outcomes deflates discordant-pair counts and makes McNemar\n * anti-conservative, so reps pair only by (`pairKey`, `repKey`) identity.\n * 2. Composition — feeding the matched pairs to the correct paired\n * estimators that already live in `statistics`: `mcnemar` +\n * `pairedRiskDifference` for pass/fail, `pairedBootstrap` +\n * `wilcoxonSignedRank` for continuous metrics. No statistic is\n * re-implemented here.\n *\n * The row shape is deliberately structural — callers project a `RunRecord`\n * (or any record) into `{ pairKey, arm, pass?, metrics? }`. Arm names are\n * caller-supplied parameters; the module ships no domain literal.\n */\n\nimport type { FindingTreatment } from './analyst/finding-composition'\nimport {\n type ArmAssignment,\n type ArmPopulationReading,\n prepareArmPopulations,\n} from './arm-populations'\nimport { ValidationError } from './errors'\nimport type { RunRecord } from './run-record'\nimport type { McNemarResult, PairedBootstrapOptions, PairedBootstrapResult } from './statistics'\nimport {\n mcnemar,\n pairedBootstrap,\n pairedRiskDifference,\n type RiskDifferenceResult,\n wilcoxonSignedRank,\n} from './statistics'\n\n/** One arm observation of one work item. Structural on purpose: callers\n * project their own record type (e.g. a `RunRecord`) into this shape. */\nexport interface PairedArmRow {\n /** Matching key — rows sharing a `pairKey` across both arms form pairs\n * (typically the task/scenario/seed identity). */\n pairKey: string\n /** Rep identity within a `pairKey` (e.g. a seed or rep number). Required on\n * every row of a `pairKey` that has more than one rep in either arm; reps\n * then pair only on exact (`pairKey`, `repKey`) match, never on outcome\n * content. Optional when each arm has at most one rep of the item. */\n repKey?: string\n /** Arm label this row was produced under. */\n arm: string\n /** Binary outcome; omit or null when no pass/fail outcome was observed. */\n pass?: boolean | null\n /** Actual formation verdict from the execution owner; absence/null stays unknown. */\n formation?: { formed: boolean | null; reason?: string }\n /** Recorded treatment provenance; assigned bundles live on the independent roster. */\n treatment?: FindingTreatment[]\n /** Named finite measurements; null/absent readings are unknown, not zero. */\n metrics?: Record<string, number | null>\n}\n\nexport interface PairArmsOptions {\n /** Arm treated as the control side of every pair. */\n baselineArm: string\n /** Arm treated as the treatment side of every pair. */\n treatmentArm: string\n}\n\n/** One matched (baseline, treatment) observation of the same work item. */\nexport interface MatchedPair {\n pairKey: string\n /** 0-based position of this pair within its `pairKey`, ordered by sorted\n * `repKey` (always 0 for a single-rep item). The rep identity itself is on\n * the rows (`baseline.repKey` / `treatment.repKey`). */\n repIndex: number\n baseline: PairedArmRow\n treatment: PairedArmRow\n}\n\nexport interface PairArmsResult {\n /** Matched pairs, ordered by (`pairKey`, `repIndex`). */\n pairs: MatchedPair[]\n /** Baseline rows left without a treatment counterpart — reported, never\n * silently dropped. */\n unpairedBaseline: PairedArmRow[]\n /** Treatment rows left without a baseline counterpart. */\n unpairedTreatment: PairedArmRow[]\n}\n\n/**\n * Match rows across two arms into (baseline, treatment) pairs by `pairKey`.\n *\n * A `pairKey` with at most one row per arm pairs directly, no `repKey`\n * needed. A `pairKey` with multiple reps in either arm requires `repKey` on\n * every one of its rows, and reps pair only on exact (`pairKey`, `repKey`)\n * match — pairing is keyed purely on row identity, never on outcome content\n * (outcome-keyed matching deflates discordant counts and biases McNemar), and\n * is therefore independent of input order. Reps whose `repKey` has no\n * counterpart in the other arm, and items present in only one arm, land in\n * the unpaired lists — reported, never truncated.\n *\n * Fail-loud: throws when either named arm has zero rows (an unknown arm\n * name would otherwise read as \"everything unpaired\"), when the two arm\n * names are equal, when a multi-rep `pairKey` has a row without `repKey`, or\n * when a (`pairKey`, arm) group repeats a `repKey` (the match would be\n * ambiguous).\n */\nexport function pairArms(rows: readonly PairedArmRow[], opts: PairArmsOptions): PairArmsResult {\n const { baselineArm, treatmentArm } = opts\n if (baselineArm === treatmentArm) {\n throw new ValidationError(\n `pairArms: baselineArm and treatmentArm are both '${baselineArm}' — an arm cannot be compared to itself`,\n )\n }\n\n // arm → pairKey → rows\n const byArm = new Map<string, Map<string, PairedArmRow[]>>()\n const armsSeen = new Set<string>()\n for (const row of rows) {\n armsSeen.add(row.arm)\n if (row.arm !== baselineArm && row.arm !== treatmentArm) continue\n const byKey = byArm.get(row.arm) ?? new Map<string, PairedArmRow[]>()\n const group = byKey.get(row.pairKey) ?? []\n group.push(row)\n byKey.set(row.pairKey, group)\n byArm.set(row.arm, byKey)\n }\n\n for (const arm of [baselineArm, treatmentArm]) {\n if (!byArm.has(arm)) {\n const seen = [...armsSeen].sort().join(', ') || '<none>'\n throw new ValidationError(`pairArms: no rows for arm '${arm}' (arms present: ${seen})`)\n }\n }\n\n const baselineByKey = byArm.get(baselineArm)!\n const treatmentByKey = byArm.get(treatmentArm)!\n\n const allKeys = [...new Set([...baselineByKey.keys(), ...treatmentByKey.keys()])].sort()\n const pairs: MatchedPair[] = []\n const unpairedBaseline: PairedArmRow[] = []\n const unpairedTreatment: PairedArmRow[] = []\n for (const pairKey of allKeys) {\n const b = baselineByKey.get(pairKey) ?? []\n const t = treatmentByKey.get(pairKey) ?? []\n\n if (b.length <= 1 && t.length <= 1) {\n if (b.length === 1 && t.length === 1) {\n const baseline = b[0]!\n const treatment = t[0]!\n if (baseline.repKey !== undefined || treatment.repKey !== undefined) {\n if (\n baseline.repKey === undefined ||\n treatment.repKey === undefined ||\n baseline.repKey !== treatment.repKey\n ) {\n unpairedBaseline.push(baseline)\n unpairedTreatment.push(treatment)\n continue\n }\n }\n pairs.push({ pairKey, repIndex: 0, baseline, treatment })\n } else {\n unpairedBaseline.push(...b)\n unpairedTreatment.push(...t)\n }\n continue\n }\n\n const bByRep = indexByRepKey(b, pairKey, baselineArm)\n const tByRep = indexByRepKey(t, pairKey, treatmentArm)\n const repKeys = [...new Set([...bByRep.keys(), ...tByRep.keys()])].sort()\n let repIndex = 0\n for (const repKey of repKeys) {\n const baseline = bByRep.get(repKey)\n const treatment = tByRep.get(repKey)\n if (baseline !== undefined && treatment !== undefined) {\n pairs.push({ pairKey, repIndex: repIndex++, baseline, treatment })\n } else if (baseline !== undefined) {\n unpairedBaseline.push(baseline)\n } else if (treatment !== undefined) {\n unpairedTreatment.push(treatment)\n }\n }\n }\n\n return { pairs, unpairedBaseline, unpairedTreatment }\n}\n\n/** Index a multi-rep (pairKey, arm) group by `repKey`, enforcing that every\n * row carries one and that no repKey repeats within the group. */\nfunction indexByRepKey(\n group: readonly PairedArmRow[],\n pairKey: string,\n arm: string,\n): Map<string, PairedArmRow> {\n const byRep = new Map<string, PairedArmRow>()\n for (const row of group) {\n if (row.repKey === undefined) {\n throw new ValidationError(\n `pairArms: pairKey '${pairKey}' has multiple reps in an arm, but a row in arm '${arm}' ` +\n `is missing repKey — multi-rep items require an explicit repKey on every row so reps ` +\n `pair by identity (pairing reps by outcome or by index would bias the paired statistics)`,\n )\n }\n if (byRep.has(row.repKey)) {\n throw new ValidationError(\n `pairArms: duplicate repKey '${row.repKey}' for pairKey '${pairKey}' in arm '${arm}' — ` +\n `(pairKey, repKey) must uniquely identify a rep within an arm`,\n )\n }\n byRep.set(row.repKey, row)\n }\n return byRep\n}\n\n/** Paired pass/fail comparison over the pairs where BOTH sides carry `pass`. */\nexport interface PairedCorrectness {\n /** Discordant pairs where the treatment passed and the baseline failed. */\n b10: number\n /** Discordant pairs where the baseline passed and the treatment failed. */\n b01: number\n /** Exact McNemar significance over the paired outcomes (`b === b10`, `c === b01`). */\n mcnemar: McNemarResult\n /** Paired effect size: p(treatment) − p(baseline) with a paired-variance CI. */\n riskDifference: RiskDifferenceResult\n}\n\n/** Paired delta summary for one named metric (delta = treatment − baseline). */\nexport interface PairedMetricDelta {\n name: string\n /** Pairs where BOTH sides carry a finite value for this metric. */\n n: number\n /** Pairs where at least one side does not carry the metric. */\n nMissing: number\n /** Median paired delta, or null when `n === 0`. */\n medianDelta: number | null\n /** Mean paired delta, or null when `n === 0`. */\n meanDelta: number | null\n /** Bootstrap CI on the paired delta (`pairedBootstrap`); null when\n * `n === 0` — a zero-width [0, 0] interval on no data would read as a\n * measured tight null. */\n bootstrapCi: PairedBootstrapResult | null\n /** Wilcoxon signed-rank test on the paired deltas; null when `n === 0`. */\n wilcoxon: { w: number; p: number } | null\n}\n\nexport interface ComparePairedArmsOptions extends PairArmsOptions {\n /** Supply all expected seeds to report as-assigned and as-formed populations. */\n assignments?: readonly ArmAssignment[]\n /** Metrics to compare. Default: every metric name observed on any matched\n * pair, sorted. A name that appears on no pair is still reported (with\n * `n = 0`) so a misspelled metric is visible instead of vanishing. */\n metricNames?: string[]\n /** Passed through to `pairedBootstrap` — set `seed` for reproducible CIs. */\n bootstrap?: PairedBootstrapOptions\n}\n\nexport interface PairedArmsComparison {\n /** Absent when the assignment population is unknown (no roster supplied). */\n armPopulations?: ArmPopulationReading[]\n nPairs: number\n nUnpairedBaseline: number\n nUnpairedTreatment: number\n /** null when no matched pair carries `pass` on both sides — a pass/fail\n * verdict over rows that never measured pass/fail would be fabricated. */\n correctness: PairedCorrectness | null\n metricDeltas: PairedMetricDelta[]\n}\n\n/**\n * Full matched-pair arm comparison: pair via {@link pairArms}, then compose\n * the paired estimators from `statistics` over the matched pairs.\n *\n * Correctness uses only the pairs where both sides carry `pass` (`mcnemar.n`\n * is that subset's size); each metric uses only the pairs where both sides\n * carry a finite value for it, with the remainder counted in `nMissing`.\n * Deltas are treatment − baseline throughout. With an assignment roster, pairing\n * covers declared seed identities; missing observations remain identity-only rows\n * and never contribute fabricated outcomes or metrics. Per-arm summaries report\n * every assignment and the explicitly formed subset separately.\n *\n * Fail-loud: inherits {@link pairArms}'s unknown-arm throw, and throws on a\n * non-finite metric value — silently treating corrupt telemetry as \"metric\n * absent\" would misreport it as missing coverage.\n */\nexport function comparePairedArms(\n rows: readonly PairedArmRow[],\n opts: ComparePairedArmsOptions,\n): PairedArmsComparison {\n const populations =\n opts.assignments === undefined ? undefined : prepareArmPopulations(rows, opts.assignments, opts)\n const { pairs, unpairedBaseline, unpairedTreatment } = pairArms(populations?.rows ?? rows, opts)\n\n let correctness: PairedCorrectness | null = null\n const baselinePass: number[] = []\n const treatmentPass: number[] = []\n for (const pair of pairs) {\n if (pair.baseline.pass == null || pair.treatment.pass == null) continue\n baselinePass.push(pair.baseline.pass ? 1 : 0)\n treatmentPass.push(pair.treatment.pass ? 1 : 0)\n }\n if (baselinePass.length > 0) {\n const mc = mcnemar(baselinePass, treatmentPass)\n correctness = {\n b10: mc.b,\n b01: mc.c,\n mcnemar: mc,\n riskDifference: pairedRiskDifference(baselinePass, treatmentPass),\n }\n }\n\n const metricNames =\n opts.metricNames ??\n [\n ...new Set(\n pairs.flatMap((p) => [\n ...Object.keys(p.baseline.metrics ?? {}),\n ...Object.keys(p.treatment.metrics ?? {}),\n ]),\n ),\n ].sort()\n\n const metricDeltas: PairedMetricDelta[] = metricNames.map((name) => {\n const before: number[] = []\n const after: number[] = []\n let nMissing = 0\n for (const pair of pairs) {\n const b = metricValue(pair.baseline, name)\n const t = metricValue(pair.treatment, name)\n if (b === undefined || t === undefined) {\n nMissing++\n continue\n }\n before.push(b)\n after.push(t)\n }\n const bootstrapCi = before.length === 0 ? null : pairedBootstrap(before, after, opts.bootstrap)\n return {\n name,\n n: before.length,\n nMissing,\n medianDelta: bootstrapCi?.median ?? null,\n meanDelta: bootstrapCi?.mean ?? null,\n bootstrapCi,\n wilcoxon: before.length === 0 ? null : wilcoxonSignedRank(before, after),\n }\n })\n\n return {\n ...(populations ? { armPopulations: populations.readings } : {}),\n nPairs: pairs.length,\n nUnpairedBaseline: unpairedBaseline.length,\n nUnpairedTreatment: unpairedTreatment.length,\n correctness,\n metricDeltas,\n }\n}\n\nexport interface MatchedRunRecordPair {\n pairKey: string\n repKey: string\n baseline: RunRecord\n treatment: RunRecord\n}\n\nexport interface PairRunRecordsResult {\n pairs: MatchedRunRecordPair[]\n unpairedBaseline: RunRecord[]\n unpairedTreatment: RunRecord[]\n}\n\ninterface RunRecordArmRow extends PairedArmRow {\n run: RunRecord\n repKey: string\n}\n\n/**\n * Pair two RunRecord arms by the identity of the evaluated work:\n * `(experimentId, scenarioId, seed)`.\n *\n * Falling back to array order, candidate id, or experiment id can compare\n * different tasks and fabricate lift. Duplicate identities throw.\n */\nexport function pairRunRecords(\n baselineRuns: readonly RunRecord[],\n treatmentRuns: readonly RunRecord[],\n): PairRunRecordsResult {\n const baselineRows = runRecordArmRows(baselineRuns, 'baseline')\n const treatmentRows = runRecordArmRows(treatmentRuns, 'treatment')\n validateRunRecordArmRows(baselineRows, 'baseline')\n validateRunRecordArmRows(treatmentRows, 'treatment')\n if (baselineRows.length === 0 || treatmentRows.length === 0) {\n return {\n pairs: [],\n unpairedBaseline: baselineRows.map((row) => row.run),\n unpairedTreatment: treatmentRows.map((row) => row.run),\n }\n }\n\n const result = pairArms([...baselineRows, ...treatmentRows], {\n baselineArm: 'baseline',\n treatmentArm: 'treatment',\n })\n return {\n pairs: result.pairs.map((pair) => {\n const baseline = pair.baseline as RunRecordArmRow\n const treatment = pair.treatment as RunRecordArmRow\n return {\n pairKey: pair.pairKey,\n repKey: baseline.repKey,\n baseline: baseline.run,\n treatment: treatment.run,\n }\n }),\n unpairedBaseline: result.unpairedBaseline.map((row) => (row as RunRecordArmRow).run),\n unpairedTreatment: result.unpairedTreatment.map((row) => (row as RunRecordArmRow).run),\n }\n}\n\nfunction runRecordArmRows(runs: readonly RunRecord[], arm: string): RunRecordArmRow[] {\n return runs.map((run) => {\n const scenarioId = run.scenarioId.trim()\n if (!scenarioId) {\n throw new ValidationError(\n `pairRunRecords: run '${run.runId}' is missing scenarioId; paired comparisons require explicit scenario identity`,\n )\n }\n return {\n pairKey: JSON.stringify([run.experimentId, scenarioId]),\n repKey: String(run.seed),\n arm,\n run,\n }\n })\n}\n\nfunction validateRunRecordArmRows(rows: readonly RunRecordArmRow[], arm: string): void {\n const byPairKey = new Map<string, RunRecordArmRow[]>()\n for (const row of rows) {\n const group = byPairKey.get(row.pairKey) ?? []\n group.push(row)\n byPairKey.set(row.pairKey, group)\n }\n for (const [pairKey, group] of byPairKey) {\n if (group.length > 1) indexByRepKey(group, pairKey, arm)\n }\n}\n\nfunction metricValue(row: PairedArmRow, name: string): number | undefined {\n const v = row.metrics?.[name]\n if (v == null) return undefined\n if (!Number.isFinite(v)) {\n throw new ValidationError(\n `comparePairedArms: non-finite value for metric '${name}' on pairKey '${row.pairKey}' (arm '${row.arm}'): ${v}`,\n )\n }\n return v\n}\n"],"mappings":";;;;;;AA6BA,MAAM,SAAS,QACb,KAAK,UAAU;CAAC,IAAI;CAAK,IAAI;CAAS,IAAI,UAAU;AAAI,CAAC;AAC3D,SAAS,cAAc,KAA0B;CAC/C,KAAK,MAAM,SAAS;EAAC,IAAI;EAAK,IAAI;EAAS,GAAI,IAAI,WAAW,KAAA,IAAY,CAAC,IAAI,CAAC,IAAI,MAAM;CAAE,GAC1F,IAAI,OAAO,UAAU,YAAY,CAAC,MAAM,KAAK,GAC3C,MAAM,IAAI,UAAU,6CAA6C;CAErE,IAAI,IAAI,cAAc,KAAA,GAAW;EAC/B,IAAI,CAAC,MAAM,QAAQ,IAAI,SAAS,GAAG,MAAM,IAAI,UAAU,gCAAgC;EACvF,KAAK,MAAM,SAAS,IAAI,WAAW,uBAAuB,MAAM,KAAK;EACrE,IAAI,IAAI,IAAI,IAAI,UAAU,KAAK,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,S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C,IAAI,CAAC,YACH,MAAM,IAAI,gBACR,wBAAwB,IAAI,MAAM,+EACpC;EAEF,OAAO;GACL,SAAS,KAAK,UAAU,CAAC,IAAI,cAAc,UAAU,CAAC;GACtD,QAAQ,OAAO,IAAI,IAAI;GACvB;GACA;EACF;CACF,CAAC;AACH;AAEA,SAAS,yBAAyB,MAAkC,KAAmB;CACrF,MAAM,4BAAY,IAAI,IAA+B;CACrD,KAAK,MAAM,OAAO,MAAM;EACtB,MAAM,QAAQ,UAAU,IAAI,IAAI,OAAO,KAAK,CAAC;EAC7C,MAAM,KAAK,GAAG;EACd,UAAU,IAAI,IAAI,SAAS,KAAK;CAClC;CACA,KAAK,MAAM,CAAC,SAAS,UAAU,WAC7B,IAAI,MAAM,SAAS,GAAG,cAAc,OAAO,SAAS,GAAG;AAE3D;AAEA,SAAS,YAAY,KAAmB,MAAkC;CACxE,MAAM,IAAI,IAAI,UAAU;CACxB,IAAI,KAAK,MAAM,OAAO,KAAA;CACtB,IAAI,CAAC,OAAO,SAAS,CAAC,GACpB,MAAM,IAAI,gBACR,mDAAmD,KAAK,gBAAgB,IAAI,QAAQ,UAAU,IAAI,IAAI,MAAM,GAC9G;CAEF,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"paired-arms-C0Vd9bGG.js","names":[],"sources":["../src/arm-populations.ts","../src/math/normal.ts","../src/statistics/rank-tests.ts","../src/paired-arms.ts"],"sourcesContent":["import type { FindingTreatment } from './analyst/finding-composition'\nimport { findingTreatmentSchema } from './analyst/finding-composition'\nimport type { PairedArmRow } from './paired-arms'\n\n/** Expected seed identities must be supplied independently of completed observations. */\nexport interface ArmAssignment {\n pairKey: string\n repKey?: string\n arm: string\n treatment?: FindingTreatment[]\n}\nexport interface ArmPopulationSummary {\n n: number\n passed: number\n failed: number\n missingOutcomes: number\n /** Unknown unless every unit's outcome was observed; missing is never a failed check. */\n passRate: number | null\n metrics: Record<string, { n: number; missing: number; sum: number | null; mean: number | null }>\n}\nexport interface ArmPopulationReading {\n arm: string\n assignments: ArmAssignment[]\n missingObservations: number\n formation: { formed: number; notFormed: number; unknown: number }\n asAssigned: ArmPopulationSummary\n asFormed: ArmPopulationSummary\n}\n\nconst keyOf = (row: ArmAssignment): string =>\n JSON.stringify([row.arm, row.pairKey, row.repKey ?? null])\nfunction checkIdentity(row: ArmAssignment): void {\n for (const value of [row.arm, row.pairKey, ...(row.repKey === undefined ? [] : [row.repKey])]) {\n if (typeof value !== 'string' || !value.trim())\n throw new TypeError('Arm assignments require nonempty identities')\n }\n if (row.treatment !== undefined) {\n if (!Array.isArray(row.treatment)) throw new TypeError('Arm treatment must be an array')\n for (const value of row.treatment) findingTreatmentSchema.parse(value)\n if (new Set(row.treatment.map((t) => t.id)).size !== row.treatment.length)\n throw new TypeError('Duplicate arm treatment id')\n }\n}\nfunction checkObservation(row: PairedArmRow): void {\n checkIdentity(row)\n if (row.pass != null && typeof row.pass !== 'boolean')\n throw new TypeError('Invalid arm pass value')\n if (row.formation !== undefined) {\n if (row.formation === null || typeof row.formation !== 'object')\n throw new TypeError('Invalid formation verdict')\n if (row.formation.formed !== null && typeof row.formation.formed !== 'boolean')\n throw new TypeError('Invalid formation state')\n if (row.formation.reason !== undefined && typeof row.formation.reason !== 'string')\n throw new TypeError('Invalid formation reason')\n }\n for (const value of Object.values(row.metrics ?? {})) {\n if (value !== null && !Number.isFinite(value)) throw new TypeError('Non-finite arm metric')\n }\n}\n\n/** One roster join serves comparison and both denominators; no outcomes are inferred from formation. */\nexport function prepareArmPopulations(\n observations: readonly PairedArmRow[],\n assignments: readonly ArmAssignment[],\n options: { baselineArm: string; treatmentArm: string; metricNames?: string[] },\n): { rows: PairedArmRow[]; readings: ArmPopulationReading[] } {\n const arms = [options.baselineArm, options.treatmentArm]\n const roster = new Map<string, ArmAssignment>()\n for (const entry of assignments) {\n if (!arms.includes(entry.arm)) continue\n checkIdentity(entry)\n const key = keyOf(entry)\n if (roster.has(key)) throw new TypeError('Duplicate arm assignment')\n roster.set(key, structuredClone(entry))\n }\n for (const arm of arms)\n if (![...roster.values()].some((r) => r.arm === arm))\n throw new TypeError(`No assignment roster for arm '${arm}'`)\n const actual = new Map<string, PairedArmRow>()\n for (const row of observations) {\n if (!arms.includes(row.arm)) continue\n checkObservation(row)\n const key = keyOf(row)\n if (!roster.has(key)) throw new TypeError('Observed seed is outside the assignment roster')\n if (actual.has(key)) throw new TypeError('Duplicate arm observation')\n actual.set(key, row)\n }\n const ordered = [...roster.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n // Placeholder rows carry identities only. They never manufacture pass, metrics or formation.\n const rows = ordered.map(([key, entry]) => actual.get(key) ?? entry)\n const metricNames =\n options.metricNames ??\n [...new Set([...actual.values()].flatMap((r) => Object.keys(r.metrics ?? {})))].sort()\n const readings = arms.map((arm) => {\n const declared = ordered.filter(([, r]) => r.arm === arm)\n const asAssigned = declared.map(([key]) => actual.get(key))\n const asFormed = asAssigned.filter(\n (row): row is PairedArmRow => row?.formation?.formed === true,\n )\n return {\n arm,\n assignments: declared.map(([, r]) => r),\n missingObservations: asAssigned.filter((r) => r === undefined).length,\n formation: {\n formed: asFormed.length,\n notFormed: asAssigned.filter((r) => r?.formation?.formed === false).length,\n unknown: asAssigned.filter((r) => r?.formation?.formed == null).length,\n },\n asAssigned: summarize(asAssigned, metricNames),\n asFormed: summarize(asFormed, metricNames),\n }\n })\n return { rows, readings }\n}\n\nfunction summarize(\n rows: readonly (PairedArmRow | undefined)[],\n names: readonly string[],\n): ArmPopulationSummary {\n const passed = rows.filter((r) => r?.pass === true).length\n const failed = rows.filter((r) => r?.pass === false).length\n const missingOutcomes = rows.length - passed - failed\n const metrics = Object.fromEntries(\n names.map((name) => {\n const values = rows.map((r) => r?.metrics?.[name]).filter((x): x is number => x != null)\n const sum = values.length ? values.reduce((s, v) => s + v, 0) : null\n return [\n name,\n {\n n: values.length,\n missing: rows.length - values.length,\n sum,\n mean: sum === null ? null : sum / values.length,\n },\n ]\n }),\n )\n return {\n n: rows.length,\n passed,\n failed,\n missingOutcomes,\n passRate: rows.length && !missingOutcomes ? passed / rows.length : null,\n metrics,\n }\n}\n","/**\n * Standard normal cumulative distribution using Abramowitz and Stegun 7.1.26.\n *\n * The approximation is evaluated as erf(x / sqrt(2)). Computing the negative\n * tail from the complementary term avoids cancellation when x is far below 0.\n * The maximum absolute CDF error is approximately 7.5e-8.\n */\nexport function normalCdf(x: number): number {\n if (x === 0) return 0.5\n\n const a1 = 0.254829592\n const a2 = -0.284496736\n const a3 = 1.421413741\n const a4 = -1.453152027\n const a5 = 1.061405429\n const p = 0.3275911\n\n const scaled = Math.abs(x) / Math.SQRT2\n const t = 1 / (1 + p * scaled)\n const complement = ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp(-scaled * scaled)\n\n return x < 0 ? complement / 2 : 1 - complement / 2\n}\n","import { ValidationError } from '../errors'\nimport { normalCdf } from '../math/normal'\nimport { lnGamma } from '../math/special-functions'\nimport {\n assertFiniteSample,\n binomialSignTwoSided,\n makeRng,\n symmetricTwoSampleSeed,\n} from './internal'\n\n// ── Rank tests: exact by default ─────────────────────────────────────\n//\n// At 3–10 repetitions per arm the binding constraint on a rank test is\n// combinatorial, not numerical. Three versus three admits only 20 splits, so\n// the attainable two-sided p-grid starts at 0.1000 and α = 0.05 is out of\n// reach at that design; a normal approximation reports 0.0495, a p-value that\n// describes no attainable outcome. No better approximation fixes this — adding\n// the tie correction moves `[0,0,0]` versus `[1,1,1]` from 0.0495 to 0.0469,\n// further from its exact 0.1000, not closer.\n//\n// So both null distributions are enumerated exactly inside bounded state and\n// work budgets, by convolution over the observed midranks (identical to\n// enumerating every split / sign pattern, and cheaper), which conditions on the\n// realised tie pattern for free. Above those budgets the default is a seeded\n// Monte Carlo permutation. The asymptotic path is never chosen automatically,\n// and asking for it inside the exact-feasible range throws.\n//\n// Every result carries `method` and `pFloor` so a downstream gate can SEE the\n// discreteness rather than infer it: a gate handed data whose `pFloor` exceeds\n// its alpha is underpowered by construction, which is a true statement about\n// the experiment, not a false one about the effect.\n\n/** How a rank test's p-value was actually computed. */\nexport type RankTestMethod = 'exact' | 'permutation' | 'asymptotic'\n\n/**\n * What the caller asks for. `'auto'` selects `'exact'` inside the enumeration\n * threshold and `'permutation'` above it, and never selects `'asymptotic'`.\n */\nexport type RankTestMethodRequest = 'auto' | 'exact' | 'asymptotic'\n\nexport interface RankTestOptions {\n /** Default `'auto'`. `'asymptotic'` inside the exact-feasible range throws. */\n method?: RankTestMethodRequest\n /** Resamples on the Monte Carlo permutation path. Default 100000. */\n permutations?: number\n /** Seed for the permutation path. Omitted ⇒ derived from the data itself, so\n * the result is reproducible either way. */\n seed?: number\n}\n\n/** Maximum dynamic-programming cells used by an exact two-sample rank test. */\nconst MANN_WHITNEY_EXACT_MAX_STATES = 8_192\n/** Maximum inner-loop transitions used by an exact two-sample rank test. */\nconst MANN_WHITNEY_EXACT_MAX_WORK = 250_000\n/** Non-zero differences up to which the signed-rank null is enumerated exactly. */\nconst WILCOXON_EXACT_MAX_N = 20\n/** Resamples used when a rank test falls back to Monte Carlo permutation. */\nconst DEFAULT_PERMUTATIONS = 100_000\n\nexport interface MannWhitneyResult {\n /** `min(U_a, U_b)` — the conventional reported statistic. */\n u: number\n /** U for sample `a`. Carries the direction of the effect, which `u` discards. */\n uA: number\n /** Two-sided p-value. */\n p: number\n /** How `p` was computed. */\n method: RankTestMethod\n /** Smallest two-sided p this design can produce. `p` can never be below it. */\n pFloor: number\n}\n\n/**\n * Mann-Whitney U — two independent samples, no distributional assumption.\n *\n * Exact conditional (permutation) p by default when the dynamic program fits\n * {@link MANN_WHITNEY_EXACT_MAX_STATES} cells and\n * {@link MANN_WHITNEY_EXACT_MAX_WORK} transitions, seeded Monte Carlo\n * permutation above those limits. This keeps imbalanced designs such as 1+24\n * exact without admitting expensive balanced designs merely because they have\n * the same total size. Throws on non-finite input and on `method:\n * 'asymptotic'` where an exact answer is available. Empty input yields `p = 1,\n * pFloor = 1` — no design, no attainable evidence.\n */\nexport function mannWhitneyU(\n a: number[],\n b: number[],\n opts: RankTestOptions = {},\n): MannWhitneyResult {\n assertFiniteSample('mannWhitneyU', 'a', a)\n assertFiniteSample('mannWhitneyU', 'b', b)\n\n const n1 = a.length\n const n2 = b.length\n if (n1 === 0 || n2 === 0) return { u: 0, uA: 0, p: 1, method: 'exact', pFloor: 1 }\n\n const total = n1 + n2\n const combined = [\n ...a.map((v) => ({ v, fromA: true })),\n ...b.map((v) => ({ v, fromA: false })),\n ].sort((x, y) => x.v - y.v)\n\n const { midranks, tieTerm } = midranksWithTieTerm(combined.map((entry) => entry.v))\n let rankSumA = 0\n for (let k = 0; k < total; k++) {\n if (combined[k]!.fromA) rankSumA += midranks[k]!\n }\n\n const uA = rankSumA - (n1 * (n1 + 1)) / 2\n const u = Math.min(uA, n1 * n2 - uA)\n // Midranks are integers or halves, so doubling makes the null convolution\n // integral. U is centred on n₁n₂/2, hence a doubled centre of n₁n₂.\n const doubled = midranks.map((rank) => Math.round(rank * 2))\n const doubledDeviation = Math.abs(2 * uA - n1 * n2)\n const selectedN = Math.min(n1, n2)\n const otherN = total - selectedN\n const exactCost = exactTwoSampleCost(doubled, selectedN)\n\n const designFloor = exactTwoSampleFloor(doubled, selectedN)\n const method = selectRankTestMethod(\n 'mannWhitneyU',\n opts.method ?? 'auto',\n `n1=${n1}, n2=${n2}`,\n exactCost.states <= MANN_WHITNEY_EXACT_MAX_STATES &&\n exactCost.work <= MANN_WHITNEY_EXACT_MAX_WORK,\n designFloor,\n `${MANN_WHITNEY_EXACT_MAX_STATES.toLocaleString('en-US')} states and ` +\n `${MANN_WHITNEY_EXACT_MAX_WORK.toLocaleString('en-US')} transitions`,\n )\n\n if (method === 'exact') {\n const { p, pFloor } = exactTwoSampleP(doubled, selectedN, otherN, doubledDeviation)\n return { u, uA, p, method, pFloor }\n }\n\n if (method === 'asymptotic') {\n return {\n u,\n uA,\n p: asymptoticTwoSidedP(doubledDeviation / 2, twoSampleSigma(n1, n2, total, tieTerm)),\n method,\n pFloor: designFloor,\n }\n }\n\n const permutations = resolvePermutations('mannWhitneyU', opts.permutations)\n const rng = opts.seed === undefined ? makeRng(symmetricTwoSampleSeed(a, b)) : makeRng(opts.seed)\n let atLeastAsExtreme = 0\n const pool = [...doubled]\n for (let iteration = 0; iteration < permutations; iteration++) {\n let doubledRankSum = 0\n for (let k = 0; k < selectedN; k++) {\n const pick = k + Math.floor(rng() * (total - k))\n const swapped = pool[pick]!\n pool[pick] = pool[k]!\n pool[k] = swapped\n doubledRankSum += swapped\n }\n if (\n Math.abs(doubledRankSum - selectedN * (selectedN + 1) - selectedN * otherN) >=\n doubledDeviation\n ) {\n atLeastAsExtreme++\n }\n }\n const pFloor = Math.max(1 / (permutations + 1), designFloor)\n return {\n u,\n uA,\n p: Math.max((1 + atLeastAsExtreme) / (permutations + 1), pFloor),\n method,\n pFloor,\n }\n}\n\nexport interface WilcoxonSignedRankResult {\n /** W⁺, the rank sum of the positive differences. (scipy reports\n * `min(W⁺, W⁻)`; compare statistics only after converting.) */\n w: number\n /** Two-sided p-value. */\n p: number\n /** How `p` was computed. */\n method: RankTestMethod\n /** Smallest two-sided p this design can produce. */\n pFloor: number\n /** Non-zero differences — zero differences are dropped and carry no rank. */\n nNonZero: number\n}\n\n/**\n * Wilcoxon signed-rank — paired, no distributional assumption on the deltas.\n *\n * Exact conditional (sign-flip) p by default at `n ≤\n * {@link WILCOXON_EXACT_MAX_N}` non-zero differences, seeded Monte Carlo\n * permutation above it. Throws on non-finite input and on `method:\n * 'asymptotic'` where an exact answer is available.\n *\n * `n` is the count of NON-ZERO differences: exact ties are dropped before\n * ranking, so a run of tied pairs shrinks the design and raises `pFloor`.\n * All-tied input yields `p = 1, pFloor = 1` — no attainable evidence, which\n * `pFloor` states rather than leaving `p = 1` to be read as a measured null.\n */\nexport function wilcoxonSignedRank(\n before: number[],\n after: number[],\n opts: RankTestOptions = {},\n): WilcoxonSignedRankResult {\n if (before.length !== after.length) {\n throw new ValidationError(\n `wilcoxonSignedRank: unequal sample sizes (${before.length} vs ${after.length})`,\n )\n }\n assertFiniteSample('wilcoxonSignedRank', 'before', before)\n assertFiniteSample('wilcoxonSignedRank', 'after', after)\n\n const diffs = before.map((b, i) => after[i]! - b).filter((d) => d !== 0)\n const n = diffs.length\n if (n === 0) return { w: 0, p: 1, method: 'exact', pFloor: 1, nNonZero: 0 }\n\n // When every non-zero difference has the same magnitude, the signed-rank\n // null reduces exactly to a binomial sign distribution. This is the common\n // pass/fail shape ({-1, 0, +1}); recognizing it avoids a 100k-draw\n // permutation for every repeated gate evaluation while preserving the exact\n // p-value and attainable floor. Explicit method requests still retain their\n // documented behavior.\n const abs = Math.abs(diffs[0]!)\n const allEqualAbs = diffs.every((d) => Math.abs(d) === abs)\n if ((opts.method === undefined || opts.method === 'auto') && allEqualAbs) {\n const positive = diffs.filter((d) => d > 0).length\n const negative = n - positive\n return {\n w: (positive * (n + 1)) / 2,\n p: binomialSignTwoSided(positive, negative),\n method: 'exact',\n pFloor: Math.min(1, 2 ** (1 - n)),\n nNonZero: n,\n }\n }\n\n const order = diffs.map((d, i) => ({ abs: Math.abs(d), i })).sort((x, y) => x.abs - y.abs)\n const { midranks, tieTerm } = midranksWithTieTerm(order.map((entry) => entry.abs))\n const ranks: number[] = new Array(n)\n for (let k = 0; k < n; k++) ranks[order[k]!.i] = midranks[k]!\n\n let wPlus = 0\n for (let k = 0; k < n; k++) if (diffs[k]! > 0) wPlus += ranks[k]!\n\n // Midranks are integers or halves; doubling makes the convolution integral.\n // Σ midranks = n(n+1)/2 whatever the tie pattern, so E[W⁺] = n(n+1)/4 and\n // the doubled centre is n(n+1)/2.\n const doubled = midranks.map((rank) => Math.round(rank * 2))\n const doubledDeviation = Math.abs(2 * wPlus - (n * (n + 1)) / 2)\n\n const designFloor = Math.min(1, 2 ** (1 - n))\n const method = selectRankTestMethod(\n 'wilcoxonSignedRank',\n opts.method ?? 'auto',\n `n=${n} non-zero differences`,\n n <= WILCOXON_EXACT_MAX_N,\n designFloor,\n `${WILCOXON_EXACT_MAX_N} non-zero differences`,\n )\n\n if (method === 'exact') {\n const { p, pFloor } = exactSignedRankP(doubled, doubledDeviation)\n return { w: wPlus, p, method, pFloor, nNonZero: n }\n }\n\n if (method === 'asymptotic') {\n const variance = (n * (n + 1) * (2 * n + 1)) / 24 - tieTerm / 48\n return {\n w: wPlus,\n p: asymptoticTwoSidedP(doubledDeviation / 2, Math.sqrt(variance)),\n method,\n pFloor: designFloor,\n nNonZero: n,\n }\n }\n\n const permutations = resolvePermutations('wilcoxonSignedRank', opts.permutations)\n const rng = makeRng(opts.seed, before, after)\n const doubledCentre = (n * (n + 1)) / 2\n let atLeastAsExtreme = 0\n for (let iteration = 0; iteration < permutations; iteration++) {\n let doubledWPlus = 0\n for (let k = 0; k < n; k++) if (rng() < 0.5) doubledWPlus += doubled[k]!\n if (Math.abs(doubledWPlus - doubledCentre) >= doubledDeviation) atLeastAsExtreme++\n }\n return {\n w: wPlus,\n p: (1 + atLeastAsExtreme) / (permutations + 1),\n method,\n pFloor: Math.max(1 / (permutations + 1), designFloor),\n nNonZero: n,\n }\n}\n\n/**\n * Average ranks over an ASCENDING-sorted array, plus `Σ(t³ − t)` over tie\n * groups of size `t` — the correction term both asymptotic rank-test variances\n * need.\n */\nfunction midranksWithTieTerm(sorted: readonly number[]): { midranks: number[]; tieTerm: number } {\n const midranks = new Array<number>(sorted.length)\n let tieTerm = 0\n let i = 0\n while (i < sorted.length) {\n let j = i\n while (j < sorted.length && sorted[j] === sorted[i]) j++\n const average = (i + 1 + j) / 2\n for (let k = i; k < j; k++) midranks[k] = average\n const groupSize = j - i\n if (groupSize > 1) tieTerm += groupSize ** 3 - groupSize\n i = j\n }\n return { midranks, tieTerm }\n}\n\nfunction selectRankTestMethod(\n fn: string,\n request: RankTestMethodRequest,\n design: string,\n exactFeasible: boolean,\n designFloor: number,\n threshold: string,\n): RankTestMethod {\n if (request === 'auto') return exactFeasible ? 'exact' : 'permutation'\n if (request === 'exact') {\n if (exactFeasible) return 'exact'\n throw new ValidationError(\n `${fn}: method 'exact' is out of range at ${design} — enumeration is bounded by ` +\n `${threshold}. Use 'auto' for the seeded Monte Carlo permutation, which converges ` +\n 'to the same answer.',\n )\n }\n if (exactFeasible) {\n throw new ValidationError(\n `${fn}: method 'asymptotic' is refused at ${design} — the exact p-grid at this design ` +\n `starts at ${formatProbability(designFloor)}, so an asymptotic p below it describes no ` +\n `attainable outcome. Use method 'exact' (the default) or add repetitions past ` +\n `${threshold}.`,\n )\n }\n return 'asymptotic'\n}\n\nfunction resolvePermutations(fn: string, permutations: number | undefined): number {\n if (permutations === undefined) return DEFAULT_PERMUTATIONS\n if (!Number.isInteger(permutations) || permutations < 1) {\n throw new ValidationError(`${fn}: permutations must be a positive integer, got ${permutations}`)\n }\n return permutations\n}\n\n/** Two-sided normal-approximation tail with the continuity correction. */\nfunction asymptoticTwoSidedP(deviation: number, sigma: number): number {\n if (!(sigma > 0)) return 1\n return Math.min(1, 2 * (1 - normalCdf(Math.max(0, deviation - 0.5) / sigma)))\n}\n\n/** SD of U under the permutation null, corrected for the realised ties. The\n * tie term reduces (N+1) and reaches it exactly when every value is tied, so\n * the variance floors at 0 rather than going negative. */\nfunction twoSampleSigma(n1: number, n2: number, total: number, tieTerm: number): number {\n if (total < 2) return 0\n const variance = ((n1 * n2) / 12) * (total + 1 - tieTerm / (total * (total - 1)))\n return Math.sqrt(Math.max(0, variance))\n}\n\nfunction logChoose(n: number, k: number): number {\n return lnGamma(n + 1) - lnGamma(k + 1) - lnGamma(n - k + 1)\n}\n\nfunction formatProbability(value: number): string {\n return value >= 1e-4 || value === 0 ? value.toFixed(4) : value.toExponential(3)\n}\n\n/**\n * Exact DP allocation and loop count for this observed rank vector.\n *\n * The smaller arm is sufficient because selecting its complement produces the\n * same two-sided U deviation while using fewer rows in the state table.\n */\nfunction exactTwoSampleCost(\n doubledRanks: readonly number[],\n selectedN: number,\n): { states: number; work: number } {\n const maxSum = doubledRanks.reduce((sum, rank) => sum + rank, 0)\n let work = 0\n for (let placed = 0; placed < doubledRanks.length; placed++) {\n work += Math.min(selectedN, placed + 1) * (maxSum - doubledRanks[placed]! + 1)\n }\n return {\n states: (selectedN + 1) * (maxSum + 1),\n work,\n }\n}\n\n/**\n * Smallest attainable two-sided p under the observed ties.\n *\n * Only subsets with the minimum or maximum rank sum can attain the largest\n * deviation. Their multiplicity is the number of ways to choose within the\n * tie group at each boundary, so this calculation is exact without allocating\n * the full null distribution.\n */\nfunction exactTwoSampleFloor(doubledRanks: readonly number[], selectedN: number): number {\n const total = doubledRanks.length\n const otherN = total - selectedN\n const minimumSum = doubledRanks.slice(0, selectedN).reduce((sum, rank) => sum + rank, 0)\n const maximumSum = doubledRanks.slice(total - selectedN).reduce((sum, rank) => sum + rank, 0)\n if (minimumSum === maximumSum) return 1\n\n const centre = selectedN * (selectedN + 1) + selectedN * otherN\n const minimumDeviation = Math.abs(minimumSum - centre)\n const maximumDeviation = Math.abs(maximumSum - centre)\n const totalLogWays = logChoose(total, selectedN)\n const minimumMass = Math.exp(\n logExtremeSubsetWays(doubledRanks, selectedN, 'minimum') - totalLogWays,\n )\n const maximumMass = Math.exp(\n logExtremeSubsetWays(doubledRanks, selectedN, 'maximum') - totalLogWays,\n )\n\n if (minimumDeviation > maximumDeviation) return minimumMass\n if (maximumDeviation > minimumDeviation) return maximumMass\n return Math.min(1, minimumMass + maximumMass)\n}\n\nfunction logExtremeSubsetWays(\n sortedRanks: readonly number[],\n selectedN: number,\n side: 'minimum' | 'maximum',\n): number {\n const boundaryIndex = side === 'minimum' ? selectedN - 1 : sortedRanks.length - selectedN\n const boundary = sortedRanks[boundaryIndex]!\n let first = boundaryIndex\n let afterLast = boundaryIndex + 1\n while (first > 0 && sortedRanks[first - 1] === boundary) first--\n while (afterLast < sortedRanks.length && sortedRanks[afterLast] === boundary) afterLast++\n\n const tieSize = afterLast - first\n const fixed = side === 'minimum' ? first : sortedRanks.length - afterLast\n return logChoose(tieSize, selectedN - fixed)\n}\n\n/**\n * Exact conditional two-sided p for the two-sample rank test.\n *\n * Convolves the observed doubled midranks into the null distribution of group\n * a's rank sum over every `C(n₁+n₂, n₁)` split — identical to enumerating the\n * splits, but `O(N·n₁·ΣR)` instead of `O(C(N,n₁)·n₁n₂)`. Conditioning on the\n * realised multiset makes the tie handling exact rather than a correction.\n *\n * The null is symmetric about `n₁n₂/2` (negating every value maps `U → n₁n₂ −\n * U` and permutes the split set onto itself), so the two-sided p is the mass\n * at least as far from the centre as the observation.\n */\nfunction exactTwoSampleP(\n doubledRanks: readonly number[],\n n1: number,\n n2: number,\n doubledDeviation: number,\n): { p: number; pFloor: number } {\n const maxSum = doubledRanks.reduce((sum, rank) => sum + rank, 0)\n const width = maxSum + 1\n // ways[k][s] = number of size-k subsets whose doubled rank sum is s.\n const ways: Float64Array[] = Array.from({ length: n1 + 1 }, () => new Float64Array(width))\n ways[0]![0] = 1\n let placed = 0\n for (const rank of doubledRanks) {\n for (let k = Math.min(n1, placed + 1); k >= 1; k--) {\n const from = ways[k - 1]!\n const into = ways[k]!\n for (let sum = maxSum - rank; sum >= 0; sum--) {\n const count = from[sum]!\n if (count !== 0) into[sum + rank]! += count\n }\n }\n placed++\n }\n\n // U = rankSum − n₁(n₁+1)/2, so doubled U = s − n₁(n₁+1), and the doubled\n // centre 2·(n₁n₂/2) is n₁n₂.\n const shift = n1 * (n1 + 1) + n1 * n2\n const chosen = ways[n1]!\n let totalWays = 0\n let extremeWays = 0\n let tailWays = 0\n let maxDeviation = -1\n for (let sum = 0; sum < width; sum++) {\n const count = chosen[sum]!\n if (count === 0) continue\n totalWays += count\n const deviation = Math.abs(sum - shift)\n if (deviation >= doubledDeviation) tailWays += count\n if (deviation > maxDeviation) {\n maxDeviation = deviation\n extremeWays = count\n } else if (deviation === maxDeviation) {\n extremeWays += count\n }\n }\n return { p: tailWays / totalWays, pFloor: extremeWays / totalWays }\n}\n\n/**\n * Exact conditional two-sided p for the paired signed-rank test.\n *\n * Convolves the observed doubled absolute midranks over all `2ⁿ` sign\n * assignments in `O(n·ΣR)`. Probabilities rather than counts keep `2ⁿ` off the\n * arithmetic. The null is symmetric about `n(n+1)/4`.\n */\nfunction exactSignedRankP(\n doubledRanks: readonly number[],\n doubledDeviation: number,\n): { p: number; pFloor: number } {\n const maxSum = doubledRanks.reduce((sum, rank) => sum + rank, 0)\n const width = maxSum + 1\n let mass = new Float64Array(width)\n mass[0] = 1\n for (const rank of doubledRanks) {\n const next = new Float64Array(width)\n for (let sum = 0; sum < width; sum++) {\n const probability = mass[sum]!\n if (probability === 0) continue\n next[sum]! += probability * 0.5\n next[sum + rank]! += probability * 0.5\n }\n mass = next\n }\n\n const centre = maxSum / 2\n let tail = 0\n let extreme = 0\n let maxDeviation = -1\n for (let sum = 0; sum < width; sum++) {\n const probability = mass[sum]!\n if (probability === 0) continue\n const deviation = Math.abs(sum - centre)\n if (deviation >= doubledDeviation) tail += probability\n if (deviation > maxDeviation) {\n maxDeviation = deviation\n extreme = probability\n } else if (deviation === maxDeviation) {\n extreme += probability\n }\n }\n return { p: Math.min(1, tail), pFloor: Math.min(1, extreme) }\n}\n","/**\n * Matched-pair arm comparison — \"did the treatment arm beat the baseline arm\n * on the SAME work items?\"\n *\n * An arm A/B over run records is only trustworthy when it is PAIRED: the same\n * task/scenario/seed evaluated under both arms, compared item-by-item, so\n * inter-item difficulty variance cancels instead of masquerading as an arm\n * effect. This module owns the two error-prone steps every consumer otherwise\n * hand-rolls:\n *\n * 1. Pairing — matching rows across arms by `pairKey` (and by `repKey`\n * within multi-rep items), with leftovers REPORTED rather than silently\n * dropped (a silently unbalanced pairing biases every paired statistic\n * downstream). Pairing never keys on outcome content: matching reps by\n * their outcomes deflates discordant-pair counts and makes McNemar\n * anti-conservative, so reps pair only by (`pairKey`, `repKey`) identity.\n * 2. Composition — feeding the matched pairs to the correct paired\n * estimators that already live in `statistics`: `mcnemar` +\n * `pairedRiskDifference` for pass/fail, `pairedBootstrap` +\n * `wilcoxonSignedRank` for continuous metrics. No statistic is\n * re-implemented here.\n *\n * The row shape is deliberately structural — callers project a `RunRecord`\n * (or any record) into `{ pairKey, arm, pass?, metrics? }`. Arm names are\n * caller-supplied parameters; the module ships no domain literal.\n */\n\nimport type { FindingTreatment } from './analyst/finding-composition'\nimport {\n type ArmAssignment,\n type ArmPopulationReading,\n prepareArmPopulations,\n} from './arm-populations'\nimport { ValidationError } from './errors'\nimport type { RunRecord } from './run-record'\nimport type { McNemarResult, PairedBootstrapOptions, PairedBootstrapResult } from './statistics'\nimport {\n mcnemar,\n pairedBootstrap,\n pairedRiskDifference,\n type RiskDifferenceResult,\n wilcoxonSignedRank,\n} from './statistics'\n\n/** One arm observation of one work item. Structural on purpose: callers\n * project their own record type (e.g. a `RunRecord`) into this shape. */\nexport interface PairedArmRow {\n /** Matching key — rows sharing a `pairKey` across both arms form pairs\n * (typically the task/scenario/seed identity). */\n pairKey: string\n /** Rep identity within a `pairKey` (e.g. a seed or rep number). Required on\n * every row of a `pairKey` that has more than one rep in either arm; reps\n * then pair only on exact (`pairKey`, `repKey`) match, never on outcome\n * content. Optional when each arm has at most one rep of the item. */\n repKey?: string\n /** Arm label this row was produced under. */\n arm: string\n /** Binary outcome; omit or null when no pass/fail outcome was observed. */\n pass?: boolean | null\n /** Actual formation verdict from the execution owner; absence/null stays unknown. */\n formation?: { formed: boolean | null; reason?: string }\n /** Recorded treatment provenance; assigned bundles live on the independent roster. */\n treatment?: FindingTreatment[]\n /** Named finite measurements; null/absent readings are unknown, not zero. */\n metrics?: Record<string, number | null>\n}\n\nexport interface PairArmsOptions {\n /** Arm treated as the control side of every pair. */\n baselineArm: string\n /** Arm treated as the treatment side of every pair. */\n treatmentArm: string\n}\n\n/** One matched (baseline, treatment) observation of the same work item. */\nexport interface MatchedPair {\n pairKey: string\n /** 0-based position of this pair within its `pairKey`, ordered by sorted\n * `repKey` (always 0 for a single-rep item). The rep identity itself is on\n * the rows (`baseline.repKey` / `treatment.repKey`). */\n repIndex: number\n baseline: PairedArmRow\n treatment: PairedArmRow\n}\n\nexport interface PairArmsResult {\n /** Matched pairs, ordered by (`pairKey`, `repIndex`). */\n pairs: MatchedPair[]\n /** Baseline rows left without a treatment counterpart — reported, never\n * silently dropped. */\n unpairedBaseline: PairedArmRow[]\n /** Treatment rows left without a baseline counterpart. */\n unpairedTreatment: PairedArmRow[]\n}\n\n/**\n * Match rows across two arms into (baseline, treatment) pairs by `pairKey`.\n *\n * A `pairKey` with at most one row per arm pairs directly, no `repKey`\n * needed. A `pairKey` with multiple reps in either arm requires `repKey` on\n * every one of its rows, and reps pair only on exact (`pairKey`, `repKey`)\n * match — pairing is keyed purely on row identity, never on outcome content\n * (outcome-keyed matching deflates discordant counts and biases McNemar), and\n * is therefore independent of input order. Reps whose `repKey` has no\n * counterpart in the other arm, and items present in only one arm, land in\n * the unpaired lists — reported, never truncated.\n *\n * Fail-loud: throws when either named arm has zero rows (an unknown arm\n * name would otherwise read as \"everything unpaired\"), when the two arm\n * names are equal, when a multi-rep `pairKey` has a row without `repKey`, or\n * when a (`pairKey`, arm) group repeats a `repKey` (the match would be\n * ambiguous).\n */\nexport function pairArms(rows: readonly PairedArmRow[], opts: PairArmsOptions): PairArmsResult {\n const { baselineArm, treatmentArm } = opts\n if (baselineArm === treatmentArm) {\n throw new ValidationError(\n `pairArms: baselineArm and treatmentArm are both '${baselineArm}' — an arm cannot be compared to itself`,\n )\n }\n\n // arm → pairKey → rows\n const byArm = new Map<string, Map<string, PairedArmRow[]>>()\n const armsSeen = new Set<string>()\n for (const row of rows) {\n armsSeen.add(row.arm)\n if (row.arm !== baselineArm && row.arm !== treatmentArm) continue\n const byKey = byArm.get(row.arm) ?? new Map<string, PairedArmRow[]>()\n const group = byKey.get(row.pairKey) ?? []\n group.push(row)\n byKey.set(row.pairKey, group)\n byArm.set(row.arm, byKey)\n }\n\n for (const arm of [baselineArm, treatmentArm]) {\n if (!byArm.has(arm)) {\n const seen = [...armsSeen].sort().join(', ') || '<none>'\n throw new ValidationError(`pairArms: no rows for arm '${arm}' (arms present: ${seen})`)\n }\n }\n\n const baselineByKey = byArm.get(baselineArm)!\n const treatmentByKey = byArm.get(treatmentArm)!\n\n const allKeys = [...new Set([...baselineByKey.keys(), ...treatmentByKey.keys()])].sort()\n const pairs: MatchedPair[] = []\n const unpairedBaseline: PairedArmRow[] = []\n const unpairedTreatment: PairedArmRow[] = []\n for (const pairKey of allKeys) {\n const b = baselineByKey.get(pairKey) ?? []\n const t = treatmentByKey.get(pairKey) ?? []\n\n if (b.length <= 1 && t.length <= 1) {\n if (b.length === 1 && t.length === 1) {\n const baseline = b[0]!\n const treatment = t[0]!\n if (baseline.repKey !== undefined || treatment.repKey !== undefined) {\n if (\n baseline.repKey === undefined ||\n treatment.repKey === undefined ||\n baseline.repKey !== treatment.repKey\n ) {\n unpairedBaseline.push(baseline)\n unpairedTreatment.push(treatment)\n continue\n }\n }\n pairs.push({ pairKey, repIndex: 0, baseline, treatment })\n } else {\n unpairedBaseline.push(...b)\n unpairedTreatment.push(...t)\n }\n continue\n }\n\n const bByRep = indexByRepKey(b, pairKey, baselineArm)\n const tByRep = indexByRepKey(t, pairKey, treatmentArm)\n const repKeys = [...new Set([...bByRep.keys(), ...tByRep.keys()])].sort()\n let repIndex = 0\n for (const repKey of repKeys) {\n const baseline = bByRep.get(repKey)\n const treatment = tByRep.get(repKey)\n if (baseline !== undefined && treatment !== undefined) {\n pairs.push({ pairKey, repIndex: repIndex++, baseline, treatment })\n } else if (baseline !== undefined) {\n unpairedBaseline.push(baseline)\n } else if (treatment !== undefined) {\n unpairedTreatment.push(treatment)\n }\n }\n }\n\n return { pairs, unpairedBaseline, unpairedTreatment }\n}\n\n/** Index a multi-rep (pairKey, arm) group by `repKey`, enforcing that every\n * row carries one and that no repKey repeats within the group. */\nfunction indexByRepKey(\n group: readonly PairedArmRow[],\n pairKey: string,\n arm: string,\n): Map<string, PairedArmRow> {\n const byRep = new Map<string, PairedArmRow>()\n for (const row of group) {\n if (row.repKey === undefined) {\n throw new ValidationError(\n `pairArms: pairKey '${pairKey}' has multiple reps in an arm, but a row in arm '${arm}' ` +\n `is missing repKey — multi-rep items require an explicit repKey on every row so reps ` +\n `pair by identity (pairing reps by outcome or by index would bias the paired statistics)`,\n )\n }\n if (byRep.has(row.repKey)) {\n throw new ValidationError(\n `pairArms: duplicate repKey '${row.repKey}' for pairKey '${pairKey}' in arm '${arm}' — ` +\n `(pairKey, repKey) must uniquely identify a rep within an arm`,\n )\n }\n byRep.set(row.repKey, row)\n }\n return byRep\n}\n\n/** Paired pass/fail comparison over the pairs where BOTH sides carry `pass`. */\nexport interface PairedCorrectness {\n /** Discordant pairs where the treatment passed and the baseline failed. */\n b10: number\n /** Discordant pairs where the baseline passed and the treatment failed. */\n b01: number\n /** Exact McNemar significance over the paired outcomes (`b === b10`, `c === b01`). */\n mcnemar: McNemarResult\n /** Paired effect size: p(treatment) − p(baseline) with a paired-variance CI. */\n riskDifference: RiskDifferenceResult\n}\n\n/** Paired delta summary for one named metric (delta = treatment − baseline). */\nexport interface PairedMetricDelta {\n name: string\n /** Pairs where BOTH sides carry a finite value for this metric. */\n n: number\n /** Pairs where at least one side does not carry the metric. */\n nMissing: number\n /** Median paired delta, or null when `n === 0`. */\n medianDelta: number | null\n /** Mean paired delta, or null when `n === 0`. */\n meanDelta: number | null\n /** Bootstrap CI on the paired delta (`pairedBootstrap`); null when\n * `n === 0` — a zero-width [0, 0] interval on no data would read as a\n * measured tight null. */\n bootstrapCi: PairedBootstrapResult | null\n /** Wilcoxon signed-rank test on the paired deltas; null when `n === 0`. */\n wilcoxon: { w: number; p: number } | null\n}\n\nexport interface ComparePairedArmsOptions extends PairArmsOptions {\n /** Supply all expected seeds to report as-assigned and as-formed populations. */\n assignments?: readonly ArmAssignment[]\n /** Metrics to compare. Default: every metric name observed on any matched\n * pair, sorted. A name that appears on no pair is still reported (with\n * `n = 0`) so a misspelled metric is visible instead of vanishing. */\n metricNames?: string[]\n /** Passed through to `pairedBootstrap` — set `seed` for reproducible CIs. */\n bootstrap?: PairedBootstrapOptions\n}\n\nexport interface PairedArmsComparison {\n /** Absent when the assignment population is unknown (no roster supplied). */\n armPopulations?: ArmPopulationReading[]\n nPairs: number\n nUnpairedBaseline: number\n nUnpairedTreatment: number\n /** null when no matched pair carries `pass` on both sides — a pass/fail\n * verdict over rows that never measured pass/fail would be fabricated. */\n correctness: PairedCorrectness | null\n metricDeltas: PairedMetricDelta[]\n}\n\n/**\n * Full matched-pair arm comparison: pair via {@link pairArms}, then compose\n * the paired estimators from `statistics` over the matched pairs.\n *\n * Correctness uses only the pairs where both sides carry `pass` (`mcnemar.n`\n * is that subset's size); each metric uses only the pairs where both sides\n * carry a finite value for it, with the remainder counted in `nMissing`.\n * Deltas are treatment − baseline throughout. With an assignment roster, pairing\n * covers declared seed identities; missing observations remain identity-only rows\n * and never contribute fabricated outcomes or metrics. Per-arm summaries report\n * every assignment and the explicitly formed subset separately.\n *\n * Fail-loud: inherits {@link pairArms}'s unknown-arm throw, and throws on a\n * non-finite metric value — silently treating corrupt telemetry as \"metric\n * absent\" would misreport it as missing coverage.\n */\nexport function comparePairedArms(\n rows: readonly PairedArmRow[],\n opts: ComparePairedArmsOptions,\n): PairedArmsComparison {\n const populations =\n opts.assignments === undefined ? undefined : prepareArmPopulations(rows, opts.assignments, opts)\n const { pairs, unpairedBaseline, unpairedTreatment } = pairArms(populations?.rows ?? rows, opts)\n\n let correctness: PairedCorrectness | null = null\n const baselinePass: number[] = []\n const treatmentPass: number[] = []\n for (const pair of pairs) {\n if (pair.baseline.pass == null || pair.treatment.pass == null) continue\n baselinePass.push(pair.baseline.pass ? 1 : 0)\n treatmentPass.push(pair.treatment.pass ? 1 : 0)\n }\n if (baselinePass.length > 0) {\n const mc = mcnemar(baselinePass, treatmentPass)\n correctness = {\n b10: mc.b,\n b01: mc.c,\n mcnemar: mc,\n riskDifference: pairedRiskDifference(baselinePass, treatmentPass),\n }\n }\n\n const metricNames =\n opts.metricNames ??\n [\n ...new Set(\n pairs.flatMap((p) => [\n ...Object.keys(p.baseline.metrics ?? {}),\n ...Object.keys(p.treatment.metrics ?? {}),\n ]),\n ),\n ].sort()\n\n const metricDeltas: PairedMetricDelta[] = metricNames.map((name) => {\n const before: number[] = []\n const after: number[] = []\n let nMissing = 0\n for (const pair of pairs) {\n const b = metricValue(pair.baseline, name)\n const t = metricValue(pair.treatment, name)\n if (b === undefined || t === undefined) {\n nMissing++\n continue\n }\n before.push(b)\n after.push(t)\n }\n const bootstrapCi = before.length === 0 ? null : pairedBootstrap(before, after, opts.bootstrap)\n return {\n name,\n n: before.length,\n nMissing,\n medianDelta: bootstrapCi?.median ?? null,\n meanDelta: bootstrapCi?.mean ?? null,\n bootstrapCi,\n wilcoxon: before.length === 0 ? null : wilcoxonSignedRank(before, after),\n }\n })\n\n return {\n ...(populations ? { armPopulations: populations.readings } : {}),\n nPairs: pairs.length,\n nUnpairedBaseline: unpairedBaseline.length,\n nUnpairedTreatment: unpairedTreatment.length,\n correctness,\n metricDeltas,\n }\n}\n\nexport interface MatchedRunRecordPair {\n pairKey: string\n repKey: string\n baseline: RunRecord\n treatment: RunRecord\n}\n\nexport interface PairRunRecordsResult {\n pairs: MatchedRunRecordPair[]\n unpairedBaseline: RunRecord[]\n unpairedTreatment: RunRecord[]\n}\n\ninterface RunRecordArmRow extends PairedArmRow {\n run: RunRecord\n repKey: string\n}\n\n/**\n * Pair two RunRecord arms by the identity of the evaluated work:\n * `(experimentId, scenarioId, seed)`.\n *\n * Falling back to array order, candidate id, or experiment id can compare\n * different tasks and fabricate lift. Duplicate identities throw.\n */\nexport function pairRunRecords(\n baselineRuns: readonly RunRecord[],\n treatmentRuns: readonly RunRecord[],\n): PairRunRecordsResult {\n const baselineRows = runRecordArmRows(baselineRuns, 'baseline')\n const treatmentRows = runRecordArmRows(treatmentRuns, 'treatment')\n validateRunRecordArmRows(baselineRows, 'baseline')\n validateRunRecordArmRows(treatmentRows, 'treatment')\n if (baselineRows.length === 0 || treatmentRows.length === 0) {\n return {\n pairs: [],\n unpairedBaseline: baselineRows.map((row) => row.run),\n unpairedTreatment: treatmentRows.map((row) => row.run),\n }\n }\n\n const result = pairArms([...baselineRows, ...treatmentRows], {\n baselineArm: 'baseline',\n treatmentArm: 'treatment',\n })\n return {\n pairs: result.pairs.map((pair) => {\n const baseline = pair.baseline as RunRecordArmRow\n const treatment = pair.treatment as RunRecordArmRow\n return {\n pairKey: pair.pairKey,\n repKey: baseline.repKey,\n baseline: baseline.run,\n treatment: treatment.run,\n }\n }),\n unpairedBaseline: result.unpairedBaseline.map((row) => (row as RunRecordArmRow).run),\n unpairedTreatment: result.unpairedTreatment.map((row) => (row as RunRecordArmRow).run),\n }\n}\n\nfunction runRecordArmRows(runs: readonly RunRecord[], arm: string): RunRecordArmRow[] {\n return runs.map((run) => {\n const scenarioId = run.scenarioId.trim()\n if (!scenarioId) {\n throw new ValidationError(\n `pairRunRecords: run '${run.runId}' is missing scenarioId; paired comparisons require explicit scenario identity`,\n )\n }\n return {\n pairKey: JSON.stringify([run.experimentId, scenarioId]),\n repKey: String(run.seed),\n arm,\n run,\n }\n })\n}\n\nfunction validateRunRecordArmRows(rows: readonly RunRecordArmRow[], arm: string): void {\n const byPairKey = new Map<string, RunRecordArmRow[]>()\n for (const row of rows) {\n const group = byPairKey.get(row.pairKey) ?? []\n group.push(row)\n byPairKey.set(row.pairKey, group)\n }\n for (const [pairKey, group] of byPairKey) {\n if (group.length > 1) indexByRepKey(group, pairKey, arm)\n }\n}\n\nfunction metricValue(row: PairedArmRow, name: string): number | undefined {\n const v = row.metrics?.[name]\n if (v == null) return undefined\n if (!Number.isFinite(v)) {\n throw new ValidationError(\n `comparePairedArms: non-finite value for metric '${name}' on pairKey '${row.pairKey}' (arm '${row.arm}'): ${v}`,\n )\n }\n return v\n}\n"],"mappings":";;;;;;AA6BA,MAAM,SAAS,QACb,KAAK,UAAU;CAAC,IAAI;CAAK,IAAI;CAAS,IAAI,UAAU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F,OAAO;AACT"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { m as regularizedIncompleteBeta, o as binomialSignTwoSided, u as zQuantile } from "./mean-DDFhslBt.js";
|
|
2
2
|
// src/statistics/paired-binary.ts
|
|
3
3
|
/**
|
|
4
4
|
* Wilson score interval for a binomial proportion. Correct at small n and near
|
|
@@ -369,4 +369,4 @@ function passAtK(n, c, k) {
|
|
|
369
369
|
}
|
|
370
370
|
export { pairedRiskDifferenceScore as a, pairedRiskDifferenceExact as i, pairedBinaryScale as n, passAtK as o, pairedRiskDifference as r, wilson as s, mcnemar as t };
|
|
371
371
|
|
|
372
|
-
//# sourceMappingURL=paired-binary-
|
|
372
|
+
//# sourceMappingURL=paired-binary-B477lksS.js.map
|