@tangle-network/agent-eval 1.0.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 +119 -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-DWkc5mzq.js → benchmark-command-BeDZB3BQ.js} +11 -11
- package/dist/{benchmark-command-DWkc5mzq.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 +7 -2
- 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,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { s as RedactionReport } from "./redact-jrT0APTU.js";
|
|
2
2
|
import { SpanKind } from "@tangle-network/agent-trace-contract";
|
|
3
3
|
type DiagnosisSpanStatus = 'OK' | 'ERROR' | 'UNSET';
|
|
4
4
|
interface DiagnosisSpan {
|
|
@@ -55,4 +55,4 @@ declare function ingestSpans(raw: readonly unknown[], options: {
|
|
|
55
55
|
*/
|
|
56
56
|
declare function epochMillis(value: unknown): number | null;
|
|
57
57
|
export { isContentAttribute as a, ingestSpans as i, IngestReport as n, epochMillis as r, DiagnosisSpan as t };
|
|
58
|
-
//# sourceMappingURL=spans-
|
|
58
|
+
//# sourceMappingURL=spans-CGjHouKM.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"spans-
|
|
1
|
+
{"version":3,"file":"spans-CGjHouKM.d.ts","names":[],"sources":["../src/diagnosis/spans.ts"],"mappings":";;KAuBY;UAEK;EACf;EACA;EACA;EACA;EACA,MAAM;EACN;EACA;EACA,QAAQ;EACR;EACA;EACA;;;;;;;EAOA;EACA,YAAY;;UAGG;EACf;EACA;;EAEA;;EAEA;;EAEA;EACA,SAAS;;EAET;;iBA0Bc,mBAAmB;;;;;;;iBAUnB,YACd,yBACA;EAAW;;EACR,OAAO;EAAiB,QAAQ;;;;;;;iBAgHrB,YAAY"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { r as pairedBootstrap } from "./paired-tests-
|
|
2
|
-
import { t as decidePairedPromotion } from "./paired-promotion-decision-
|
|
1
|
+
import { r as pairedBootstrap } from "./paired-tests-kASEKpc-.js";
|
|
2
|
+
import { t as decidePairedPromotion } from "./paired-promotion-decision-5Pl_qJLX.js";
|
|
3
3
|
// src/campaign/gates/statistical-heldout.ts
|
|
4
4
|
/**
|
|
5
5
|
* Held-out inference pairs execution cells and judge identities before taking
|
|
@@ -252,4 +252,4 @@ function dimensionRegressions(candidate, baseline, scenarioIds, criticalDimensio
|
|
|
252
252
|
}
|
|
253
253
|
export { heldoutSignificance as a, dimensionRegressions as i, aggregatePairedHoldout as n, pairHoldout as o, detectScale as r, TIE_WARN_FRACTION as t };
|
|
254
254
|
|
|
255
|
-
//# sourceMappingURL=statistical-heldout-
|
|
255
|
+
//# sourceMappingURL=statistical-heldout-DYF5f10K.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"statistical-heldout-C9hz_AF9.js","names":[],"sources":["../src/campaign/gates/statistical-heldout.ts"],"sourcesContent":["/**\n * Held-out inference pairs execution cells and judge identities before taking\n * means within registered independent units. Repetitions can improve a unit's\n * precision without increasing n. Ungrouped inference concerns independently\n * sampled execution cells conditional on a fixed scenario roster.\n *\n * The shared paired decision rule selects the estimator and statistical test.\n * Dimension reports retain missing coverage so required safety checks cannot\n * pass through absent evidence. Thresholds use the judge's native score scale.\n */\n\nimport {\n decidePairedPromotion,\n type PairedDecisionMethod,\n type PairedDecisionStatistic,\n type PairedMcNemarEvidence,\n type PairedPromotionDecision,\n} from '../../paired-promotion-decision'\nimport {\n DECISION_PAIRED_DELTA_STATISTIC,\n type PairedBootstrapResult,\n pairedBootstrap,\n} from '../../statistics'\nimport type { JudgeScore } from '../types'\n\n/** Tie fraction at/above which a gate annotates its verdict with the tie share.\n * Tie-domination of the median bites structurally at >= 0.5 (the median is then\n * 0 by construction); 0.4 is a softer warn threshold that flags a run APPROACHING\n * that regime, so an operator sees it before the median goes fully blind. */\nexport const TIE_WARN_FRACTION = 0.4\n\nexport interface PairedHoldout {\n /** Baseline scalar per paired cell (same order as `after`/`cellIds`). */\n before: number[]\n /** Candidate scalar per paired cell. */\n after: number[]\n /** The full cellIds (`scenario:rep`) that paired, in order. */\n cellIds: string[]\n}\n\n/** Campaign cell IDs append a numeric repetition after the scenario's full ID. */\nfunction scenarioIdFromCellId(cellId: string): string {\n const separator = cellId.lastIndexOf(':')\n const repetition = cellId.slice(separator + 1)\n if (\n separator < 1 ||\n cellId.trim() !== cellId ||\n !/^(0|[1-9]\\d*)$/.test(repetition) ||\n !Number.isSafeInteger(Number(repetition))\n ) {\n throw new Error(`pairHoldout: malformed cellId '${cellId}'; expected scenarioId:rep`)\n }\n return cellId.slice(0, separator)\n}\n\n/** Preserve cell pairing before taking equal-weight independent-unit means. */\nexport function aggregatePairedHoldout(\n paired: PairedHoldout,\n independentUnitByScenarioId?: ReadonlyMap<string, string>,\n): { before: number[]; after: number[]; unitIds: string[] } {\n if (\n paired.before.length !== paired.after.length ||\n paired.before.length !== paired.cellIds.length\n ) {\n throw new Error('aggregatePairedHoldout: scores and cellIds must have the same length')\n }\n if (new Set(paired.cellIds).size !== paired.cellIds.length) {\n throw new Error('aggregatePairedHoldout: duplicate cellIds cannot count as new observations')\n }\n if (\n paired.before.some((value) => !Number.isFinite(value)) ||\n paired.after.some((value) => !Number.isFinite(value))\n ) {\n throw new Error('aggregatePairedHoldout: paired scores must be finite')\n }\n if (independentUnitByScenarioId === undefined) {\n return { before: [...paired.before], after: [...paired.after], unitIds: [...paired.cellIds] }\n }\n const scenarioIds = paired.cellIds.map(scenarioIdFromCellId)\n const groups = new Map<string, { before: number; after: number; n: number }>()\n for (let i = 0; i < paired.cellIds.length; i++) {\n const scenarioId = scenarioIds[i]!\n const unitId = independentUnitByScenarioId.get(scenarioId)\n if (typeof unitId !== 'string' || unitId.length === 0 || unitId.trim() !== unitId) {\n throw new Error(\n `aggregatePairedHoldout: missing independent unit for scenario '${scenarioId}'`,\n )\n }\n const group = groups.get(unitId) ?? { before: 0, after: 0, n: 0 }\n group.before += paired.before[i]!\n group.after += paired.after[i]!\n group.n += 1\n groups.set(unitId, group)\n }\n const unitIds = [...groups.keys()].sort()\n return {\n before: unitIds.map((id) => groups.get(id)!.before / groups.get(id)!.n),\n after: unitIds.map((id) => groups.get(id)!.after / groups.get(id)!.n),\n unitIds,\n }\n}\n\n/**\n * Pair candidate vs baseline holdout observations by FULL cellId. `select`\n * pulls the scalar from a cell's judge reports (composite, or a named\n * dimension); a cell contributes the mean of `select` across its judges. Cells\n * whose scenario is not in `scenarioIds`, or where `select` is undefined for\n * every judge on both sides, are skipped. The selected judge IDs must agree\n * within each pair. Throws when the two maps disagree on holdout cell IDs — a\n * load-bearing invariant: the baseline + winner holdout campaigns run the same\n * scenarios with the same seed base, so their cellIds MUST align; a mismatch\n * means a silent pairing bug, not a soft fallback.\n */\nexport function pairHoldout(\n candidate: Map<string, Record<string, JudgeScore>>,\n baseline: Map<string, Record<string, JudgeScore>>,\n scenarioIds: Set<string>,\n select: (s: JudgeScore) => number | undefined,\n): PairedHoldout {\n const cellValues = (\n byCell: Map<string, Record<string, JudgeScore>>,\n cellId: string,\n ): Map<string, number> => {\n const scores = byCell.get(cellId)\n const values = new Map<string, number>()\n if (!scores) return values\n for (const [judgeId, s] of Object.entries(scores)) {\n if (s.failed === true) {\n throw new Error(`pairHoldout: cell '${cellId}' contains a failed judge score`)\n }\n const v = select(s)\n if (typeof v === 'number' && !Number.isFinite(v)) {\n throw new Error(`pairHoldout: cell '${cellId}' contains a non-finite selected score`)\n }\n if (typeof v === 'number') values.set(judgeId, v)\n }\n return values\n }\n\n const inScope = (cellId: string) => scenarioIds.has(scenarioIdFromCellId(cellId))\n const candCells = [...candidate.keys()].filter(inScope).sort()\n const baseCells = [...baseline.keys()].filter(inScope).sort()\n // Alignment invariant — the holdout campaigns share scenarios + seed, so the\n // cell sets must be identical. Differ ⇒ a real pairing bug; fail loud.\n if (candCells.length !== baseCells.length || candCells.some((c, i) => c !== baseCells[i])) {\n throw new Error(\n `pairHoldout: candidate/baseline holdout cells do not align — ` +\n `candidate=[${candCells.join(',')}] baseline=[${baseCells.join(',')}]. ` +\n `Both holdout campaigns must run the same scenarios with the same seed base.`,\n )\n }\n\n const before: number[] = []\n const after: number[] = []\n const cellIds: string[] = []\n for (const cellId of candCells) {\n const b = cellValues(baseline, cellId)\n const a = cellValues(candidate, cellId)\n // A scalar absent on both sides means that dimension was not scored. A\n // one-sided absence is asymmetric evidence loss, never a row to discard.\n if (b.size === 0 && a.size === 0) continue\n if (b.size === 0 || a.size === 0) {\n throw new Error(`pairHoldout: cell '${cellId}' has a selected score on only one arm`)\n }\n if (b.size !== a.size || [...b.keys()].some((id) => !a.has(id))) {\n throw new Error(`pairHoldout: cell '${cellId}' selected judge IDs do not align`)\n }\n const judgeIds = [...b.keys()].sort()\n before.push(meanSelectedScores(judgeIds.map((id) => b.get(id)!)))\n after.push(meanSelectedScores(judgeIds.map((id) => a.get(id)!)))\n cellIds.push(cellId)\n }\n return { before, after, cellIds }\n}\n\nfunction meanSelectedScores(values: number[]): number {\n const first = values[0]!\n // Summing identical fractional scores can round their mean outside the\n // declared binary support. An agreeing judge set preserves its exact value.\n return values.every((value) => value === first)\n ? first\n : values.reduce((sum, value) => sum + value, 0) / values.length\n}\n\nexport interface HeldoutSignificance {\n paired: PairedHoldout\n /**\n * The paired bootstrap on the requested statistic (MEAN by default — see the\n * tie note on `heldoutSignificance`).\n *\n * DIAGNOSTIC, not necessarily the interval the verdict keyed on. On a\n * two-point (pass/fail) outcome the decision routes to Tango's score interval\n * instead, because a percentile bootstrap of the mean over a three-atom\n * lattice is not a valid interval at a nonzero margin. Read\n * `decision.low`/`decision.high` for the interval that actually decided, and\n * `decisionStatistic` for which one it is.\n */\n bootstrap: PairedBootstrapResult\n /** The MEDIAN paired-delta bootstrap, reported as a diagnostic. When many\n * scenarios are tied (both sides solve them), the median is pinned near 0\n * regardless of the mean lift — comparing the two exposes tie-domination. */\n medianBootstrap: PairedBootstrapResult\n /**\n * The full promotion decision: which estimator the outcome's shape admits,\n * the interval it produced, McNemar's exact veto on the two-point path, and\n * whether the interval was zero-width (no evidence in either direction). The\n * single source of `significant`.\n */\n decision: PairedPromotionDecision\n /** Which paired estimator the verdict was decided on. */\n decisionStatistic: PairedDecisionStatistic\n /** McNemar's exact evidence on the two-point path; null otherwise. */\n mcnemar: PairedMcNemarEvidence | null\n /** Fraction of paired observations that are exact ties (|delta| < 1e-9). A\n * high tie fraction is WHY a median-based gate would have missed a real lift;\n * it is the observability the tie fix adds. */\n tieFraction: number\n /** Number of paired observation units, after configured aggregation. */\n n: number\n /** Original matched execution cells, before aggregation. */\n pairedCellN: number\n observationUnit: 'registered' | 'cell'\n /** Registered unit IDs, or cell IDs on the ungrouped path. */\n unitIds: string[]\n /** Effective minimum for the requested target and chosen estimator. */\n minimumRequired: number\n /** Statistical method that carried the decision. */\n decisionMethod: PairedDecisionMethod\n /** Exact one-sided p-value on the small-sample path; otherwise null. */\n pValue: number | null\n /** True iff n >= minimumRequired, the DECIDING interval has nonzero width,\n * its lower bound clears the threshold, and McNemar's exact test does not\n * veto at a non-negative threshold. */\n significant: boolean\n /** Set when n < minimumRequired — too little evidence to claim significance. */\n fewRuns: boolean\n}\n\nexport interface HeldoutSignificanceOptions {\n deltaThreshold?: number\n minProductiveRuns?: number\n confidence?: number\n resamples?: number\n /** Fixed by default for a deterministic, reproducible gate verdict. */\n seed?: number\n statistic?: 'mean' | 'median'\n /** Group full cell pairs into equal-weight independent units before inference. */\n independentUnitByScenarioId?: ReadonlyMap<string, string>\n}\n\n/**\n * Significance of the held-out composite lift: ship only when the lower bound\n * of the interval the outcome's shape ADMITS exceeds `deltaThreshold` (default\n * 0 ⇒ \"confidently positive\"). Interpret `deltaThreshold` in the judge's native\n * scale.\n *\n * The decision is delegated whole to {@link decidePairedPromotion}, the one\n * copy of the rule (`src/paired-promotion-decision.ts`), which `HeldOutGate`\n * also calls. That module's header carries the measurements; the short version\n * is three guards a bare `bootstrap.low > threshold` does not have:\n *\n * - a two-point (pass/fail) outcome decides on Tango's SCORE interval, the\n * only paired-binary construction that stays valid at a nonzero margin;\n * - McNemar's exact test VETOES at any non-negative threshold;\n * - a ZERO-WIDTH interval is refused rather than promoted, in either\n * direction — [0,0] clears every negative threshold and [g,g] clears every\n * threshold below g, and both are an absence of evidence, not a result.\n *\n * Measured on this function before those guards landed, at a nominal 5 %:\n * 14.60 % false promotion at n = 40 on a paired-binary noninferiority boundary,\n * and 88.50 % at n = 6 under a bounded asymmetric null whose true mean paired\n * delta is exactly 0.\n *\n * Continuous mean targets require bootstrap eligibility. Explicit median\n * targets can use the exact sign test at its confidence-dependent minimum.\n */\nexport function heldoutSignificance(\n paired: PairedHoldout,\n opts: HeldoutSignificanceOptions = {},\n): HeldoutSignificance {\n const deltaThreshold = opts.deltaThreshold ?? 0\n const confidence = opts.confidence ?? 0.95\n const resamples = opts.resamples ?? 2000\n const seed = opts.seed ?? 1337\n // DEFAULT to the MEAN paired delta, not the median. The median is destroyed by\n // TIES: whenever both baseline and candidate solve a holdout scenario (a common\n // case once the agent is decent — and INCREASINGLY common as you add holdout\n // scenarios for statistical power), that scenario contributes delta 0. When\n // >=50% of paired cells are ties the median is pinned at 0 regardless of a large,\n // consistent lift on the rest, and the gate holds a genuinely better candidate.\n // (Measured live, supervisor-lab run 6: 40 cells, 20 ties, MEAN +0.177, MEDIAN 0\n // → false hold. Doubling the holdout for \"power\" made it WORSE by adding ties.)\n // The mean equals the reported aggregate lift, ties correctly contribute 0\n // without dominating, and it is the textbook paired-comparison estimator; the\n // median is kept as a reported diagnostic. Callers wanting outlier-robustness at\n // the cost of tie-blindness can still pass `statistic: 'median'`.\n const statistic = opts.statistic ?? 'mean'\n const observations = aggregatePairedHoldout(paired, opts.independentUnitByScenarioId)\n const decision = decidePairedPromotion(observations.before, observations.after, {\n confidence,\n resamples,\n statistic,\n seed,\n threshold: deltaThreshold,\n minPairs: opts.minProductiveRuns,\n })\n // `decision.bootstrap` is null exactly when the score interval decided, so\n // the requested-statistic bootstrap is computed here for the diagnostic\n // field. Same two bootstraps as before on every path.\n const bootstrap =\n decision.bootstrap ??\n pairedBootstrap(observations.before, observations.after, {\n confidence,\n resamples,\n statistic,\n seed,\n })\n const medianBootstrap =\n statistic === 'median'\n ? bootstrap\n : pairedBootstrap(observations.before, observations.after, {\n confidence,\n resamples,\n statistic: 'median',\n seed,\n })\n const n = observations.before.length\n let ties = 0\n for (let i = 0; i < n; i += 1) {\n const after = observations.after[i]!\n const before = observations.before[i]!\n if (Math.abs(after - before) < 1e-9) ties += 1\n }\n const tieFraction = n === 0 ? 0 : ties / n\n return {\n paired,\n bootstrap,\n medianBootstrap,\n decision,\n decisionStatistic: decision.statistic,\n mcnemar: decision.mcnemar,\n tieFraction,\n n,\n pairedCellN: paired.cellIds.length,\n observationUnit: opts.independentUnitByScenarioId === undefined ? 'cell' : 'registered',\n unitIds: observations.unitIds,\n minimumRequired: decision.minimumPairs,\n decisionMethod: decision.method,\n pValue: decision.pValue,\n significant: decision.promote,\n fewRuns: !decision.sufficient,\n }\n}\n\nexport interface DimensionRegression {\n dimension: string\n /** Paired bootstrap on (candidate − baseline). DIAGNOSTIC on a pass/fail\n * dimension, where `ci` carries the interval that decided instead. */\n bootstrap: PairedBootstrapResult\n /** Which paired statistic `bootstrap.low` is the lower bound of. `'mean'`\n * unless the caller asked for the median. `bootstrap.median` still carries\n * the median point estimate either way. */\n bootstrapStatistic: 'median' | 'mean'\n /** The interval `regressed` was decided on, in the dimension's native units. */\n ci: { low: number; high: number }\n /** Which estimator produced `ci`. */\n decisionStatistic: PairedDecisionStatistic\n /** McNemar's exact evidence on a pass/fail dimension; null otherwise. */\n mcnemar: PairedMcNemarEvidence | null\n /** `ci` has zero width — no evidence in either direction. */\n indeterminate: boolean\n /** The bootstrap lower bound is below negative tolerance, or the shared\n * paired test supports a drop exceeding tolerance. Missing coverage and\n * insufficient observations are reported separately. */\n regressed: boolean\n tolerance: number\n n: number\n pairedCellN: number\n observationUnit: 'registered' | 'cell'\n /** Statistical minimum for the configured independent observation unit. */\n minimumRequired: number\n fewRuns: boolean\n /** Both arms lack this dimension on these otherwise matched execution cells. */\n missingCellIds: string[]\n /** Configured scenarios with no paired dimension measurement at all. */\n missingScenarioIds: string[]\n}\n\n/** Detect the native scale of a set of scores: 0-100 when any magnitude clears\n * 1.5, else [0,1]. Used to auto-scale the regression tolerance so a default\n * expressed for [0,1] is not silently a no-op on a 0-100 dimension. */\nexport function detectScale(values: number[]): 1 | 100 {\n return values.some((v) => Math.abs(v) > 1.5) ? 100 : 1\n}\n\n/**\n * Report required-dimension evidence after full pairing and optional unit means.\n * A bootstrap floor breach or a shared paired test supporting a drop marks\n * regression. These two criteria are distinct; `ci` records the shared\n * estimator and `bootstrap` records the floor interval. Missing observations\n * and insufficient n remain explicit for the caller's evidence policy.\n * The default tolerance is 0.05 on [0,1] and 5 on a detected 0-100 scale.\n */\nexport function dimensionRegressions(\n candidate: Map<string, Record<string, JudgeScore>>,\n baseline: Map<string, Record<string, JudgeScore>>,\n scenarioIds: Set<string>,\n criticalDimensions: string[],\n opts: {\n tolerance?: number\n confidence?: number\n resamples?: number\n seed?: number\n /** Paired statistic the CI is computed on. Default `'mean'` — see\n * {@link DECISION_PAIRED_DELTA_STATISTIC} for why the median is not. */\n statistic?: 'mean' | 'median'\n independentUnitByScenarioId?: ReadonlyMap<string, string>\n minProductiveRuns?: number\n } = {},\n): DimensionRegression[] {\n const out: DimensionRegression[] = []\n const expectedCellIds = [...baseline.keys()]\n .filter((cellId) => scenarioIds.has(scenarioIdFromCellId(cellId)))\n .sort()\n for (const dim of criticalDimensions) {\n const paired = pairHoldout(candidate, baseline, scenarioIds, (s) => s.dimensions[dim])\n if (paired.before.length === 0) continue // dimension not scored on this judge\n const observations = aggregatePairedHoldout(paired, opts.independentUnitByScenarioId)\n const measuredCells = new Set(paired.cellIds)\n const measuredScenarios = new Set(paired.cellIds.map(scenarioIdFromCellId))\n const tolerance = opts.tolerance ?? 0.05 * detectScale([...paired.before, ...paired.after])\n const bootstrapStatistic = opts.statistic ?? DECISION_PAIRED_DELTA_STATISTIC\n const shared = {\n confidence: opts.confidence ?? 0.95,\n resamples: opts.resamples ?? 2000,\n statistic: bootstrapStatistic,\n seed: opts.seed ?? 1337,\n minPairs: opts.minProductiveRuns,\n }\n const guard = decidePairedPromotion(observations.before, observations.after, shared)\n const regression = decidePairedPromotion(observations.after, observations.before, {\n ...shared,\n threshold: tolerance,\n })\n const bootstrap =\n guard.bootstrap ?? pairedBootstrap(observations.before, observations.after, shared)\n out.push({\n dimension: dim,\n bootstrap,\n bootstrapStatistic,\n ci: { low: guard.low, high: guard.high },\n decisionStatistic: guard.statistic,\n mcnemar: guard.mcnemar,\n indeterminate: guard.indeterminate,\n // Fires on EITHER burden of proof — see `floorBreached` in\n // `promotion-policy.ts` for the same rule and the reasoning. The CI arm\n // is the contract this interface and `default-production-gate`'s reason\n // string both state (\"CI.low < -tolerance\"), read off the DECIDING\n // interval; the exact-test arm adds the small-sample path where the\n // bootstrap interval is descriptive only.\n // The credible-worst-case arm stays on the BOOTSTRAP — see the same\n // decision in `floorBreached` (`promotion-policy.ts`). On a pass/fail\n // dimension the score interval is ±z²/(n+z²) even when every pair is\n // concordant, so reading the floor off it would flag an unchanged safety\n // dimension as regressed at any realistic n. The PROVEN-drop arm does use\n // the shared rule, which is what closes the fail-open hole that mattered:\n // a genuine pass/fail regression is now judged on an interval valid at\n // the nonzero `tolerance`, instead of a bootstrap that is pinned wherever\n // ties dominate.\n regressed: bootstrap.low < -tolerance || regression.promote,\n tolerance,\n n: observations.before.length,\n pairedCellN: paired.cellIds.length,\n observationUnit: opts.independentUnitByScenarioId === undefined ? 'cell' : 'registered',\n minimumRequired: guard.minimumPairs,\n fewRuns: !guard.sufficient,\n missingCellIds: expectedCellIds.filter((cellId) => !measuredCells.has(cellId)),\n missingScenarioIds: [...scenarioIds].filter((id) => !measuredScenarios.has(id)).sort(),\n })\n }\n return out\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA6BA,MAAa,oBAAoB;;AAYjC,SAAS,qBAAqB,QAAwB;CACpD,MAAM,YAAY,OAAO,YAAY,GAAG;CACxC,MAAM,aAAa,OAAO,MAAM,YAAY,CAAC;CAC7C,IACE,YAAY,KACZ,OAAO,KAAK,MAAM,UAClB,CAAC,iBAAiB,KAAK,UAAU,KACjC,CAAC,OAAO,cAAc,OAAO,UAAU,CAAC,GAExC,MAAM,IAAI,MAAM,kCAAkC,OAAO,2BAA2B;CAEtF,OAAO,OAAO,MAAM,GAAG,SAAS;AAClC;;AAGA,SAAgB,uBACd,QACA,6BAC0D;CAC1D,IACE,OAAO,OAAO,WAAW,OAAO,MAAM,UACtC,OAAO,OAAO,WAAW,OAAO,QAAQ,QAExC,MAAM,IAAI,MAAM,sEAAsE;CAExF,IAAI,IAAI,IAAI,OAAO,OAAO,CAAC,CAAC,SAAS,OAAO,QAAQ,QAClD,MAAM,IAAI,MAAM,4EAA4E;CAE9F,IACE,OAAO,OAAO,MAAM,UAAU,CAAC,OAAO,SAAS,KAAK,CAAC,KACrD,OAAO,MAAM,MAAM,UAAU,CAAC,OAAO,SAAS,KAAK,CAAC,GAEpD,MAAM,IAAI,MAAM,sDAAsD;CAExE,IAAI,gCAAgC,KAAA,GAClC,OAAO;EAAE,QAAQ,CAAC,GAAG,OAAO,MAAM;EAAG,OAAO,CAAC,GAAG,OAAO,KAA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EACb,CAAC;EACD,MAAM,YACJ,MAAM,aAAa,gBAAgB,aAAa,QAAQ,aAAa,OAAO,MAAM;EACpF,IAAI,KAAK;GACP,WAAW;GACX;GACA;GACA,IAAI;IAAE,KAAK,MAAM;IAAK,MAAM,MAAM;GAAK;GACvC,mBAAmB,MAAM;GACzB,SAAS,MAAM;GACf,eAAe,MAAM;GAgBrB,WAAW,UAAU,MAAM,CAAC,aAAa,WAAW;GACpD;GACA,GAAG,aAAa,OAAO;GACvB,aAAa,OAAO,QAAQ;GAC5B,iBAAiB,KAAK,gCAAgC,KAAA,IAAY,SAAS;GAC3E,iBAAiB,MAAM;GACvB,SAAS,CAAC,MAAM;GAChB,gBAAgB,gBAAgB,QAAQ,WAAW,CAAC,cAAc,IAAI,MAAM,CAAC;GAC7E,oBAAoB,CAAC,GAAG,WAAW,CAAC,CAAC,QAAQ,OAAO,CAAC,kBAAkB,IAAI,EAAE,CAAC,CAAC,CAAC,KAAK;EACvF,CAAC;CACH;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"statistical-heldout-DYF5f10K.js","names":[],"sources":["../src/campaign/gates/statistical-heldout.ts"],"sourcesContent":["/**\n * Held-out inference pairs execution cells and judge identities before taking\n * means within registered independent units. Repetitions can improve a unit's\n * precision without increasing n. Ungrouped inference concerns independently\n * sampled execution cells conditional on a fixed scenario roster.\n *\n * The shared paired decision rule selects the estimator and statistical test.\n * Dimension reports retain missing coverage so required safety checks cannot\n * pass through absent evidence. Thresholds use the judge's native score scale.\n */\n\nimport {\n decidePairedPromotion,\n type PairedDecisionMethod,\n type PairedDecisionStatistic,\n type PairedMcNemarEvidence,\n type PairedPromotionDecision,\n} from '../../paired-promotion-decision'\nimport {\n DECISION_PAIRED_DELTA_STATISTIC,\n type PairedBootstrapResult,\n pairedBootstrap,\n} from '../../statistics'\nimport type { JudgeScore } from '../types'\n\n/** Tie fraction at/above which a gate annotates its verdict with the tie share.\n * Tie-domination of the median bites structurally at >= 0.5 (the median is then\n * 0 by construction); 0.4 is a softer warn threshold that flags a run APPROACHING\n * that regime, so an operator sees it before the median goes fully blind. */\nexport const TIE_WARN_FRACTION = 0.4\n\nexport interface PairedHoldout {\n /** Baseline scalar per paired cell (same order as `after`/`cellIds`). */\n before: number[]\n /** Candidate scalar per paired cell. */\n after: number[]\n /** The full cellIds (`scenario:rep`) that paired, in order. */\n cellIds: string[]\n}\n\n/** Campaign cell IDs append a numeric repetition after the scenario's full ID. */\nfunction scenarioIdFromCellId(cellId: string): string {\n const separator = cellId.lastIndexOf(':')\n const repetition = cellId.slice(separator + 1)\n if (\n separator < 1 ||\n cellId.trim() !== cellId ||\n !/^(0|[1-9]\\d*)$/.test(repetition) ||\n !Number.isSafeInteger(Number(repetition))\n ) {\n throw new Error(`pairHoldout: malformed cellId '${cellId}'; expected scenarioId:rep`)\n }\n return cellId.slice(0, separator)\n}\n\n/** Preserve cell pairing before taking equal-weight independent-unit means. */\nexport function aggregatePairedHoldout(\n paired: PairedHoldout,\n independentUnitByScenarioId?: ReadonlyMap<string, string>,\n): { before: number[]; after: number[]; unitIds: string[] } {\n if (\n paired.before.length !== paired.after.length ||\n paired.before.length !== paired.cellIds.length\n ) {\n throw new Error('aggregatePairedHoldout: scores and cellIds must have the same length')\n }\n if (new Set(paired.cellIds).size !== paired.cellIds.length) {\n throw new Error('aggregatePairedHoldout: duplicate cellIds cannot count as new observations')\n }\n if (\n paired.before.some((value) => !Number.isFinite(value)) ||\n paired.after.some((value) => !Number.isFinite(value))\n ) {\n throw new Error('aggregatePairedHoldout: paired scores must be finite')\n }\n if (independentUnitByScenarioId === undefined) {\n return { before: [...paired.before], after: [...paired.after], unitIds: [...paired.cellIds] }\n }\n const scenarioIds = paired.cellIds.map(scenarioIdFromCellId)\n const groups = new Map<string, { before: number; after: number; n: number }>()\n for (let i = 0; i < paired.cellIds.length; i++) {\n const scenarioId = scenarioIds[i]!\n const unitId = independentUnitByScenarioId.get(scenarioId)\n if (typeof unitId !== 'string' || unitId.length === 0 || unitId.trim() !== unitId) {\n throw new Error(\n `aggregatePairedHoldout: missing independent unit for scenario '${scenarioId}'`,\n )\n }\n const group = groups.get(unitId) ?? { before: 0, after: 0, n: 0 }\n group.before += paired.before[i]!\n group.after += paired.after[i]!\n group.n += 1\n groups.set(unitId, group)\n }\n const unitIds = [...groups.keys()].sort()\n return {\n before: unitIds.map((id) => groups.get(id)!.before / groups.get(id)!.n),\n after: unitIds.map((id) => groups.get(id)!.after / groups.get(id)!.n),\n unitIds,\n }\n}\n\n/**\n * Pair candidate vs baseline holdout observations by FULL cellId. `select`\n * pulls the scalar from a cell's judge reports (composite, or a named\n * dimension); a cell contributes the mean of `select` across its judges. Cells\n * whose scenario is not in `scenarioIds`, or where `select` is undefined for\n * every judge on both sides, are skipped. The selected judge IDs must agree\n * within each pair. Throws when the two maps disagree on holdout cell IDs — a\n * load-bearing invariant: the baseline + winner holdout campaigns run the same\n * scenarios with the same seed base, so their cellIds MUST align; a mismatch\n * means a silent pairing bug, not a soft fallback.\n */\nexport function pairHoldout(\n candidate: Map<string, Record<string, JudgeScore>>,\n baseline: Map<string, Record<string, JudgeScore>>,\n scenarioIds: Set<string>,\n select: (s: JudgeScore) => number | undefined,\n): PairedHoldout {\n const cellValues = (\n byCell: Map<string, Record<string, JudgeScore>>,\n cellId: string,\n ): Map<string, number> => {\n const scores = byCell.get(cellId)\n const values = new Map<string, number>()\n if (!scores) return values\n for (const [judgeId, s] of Object.entries(scores)) {\n if (s.failed === true) {\n throw new Error(`pairHoldout: cell '${cellId}' contains a failed judge score`)\n }\n const v = select(s)\n if (typeof v === 'number' && !Number.isFinite(v)) {\n throw new Error(`pairHoldout: cell '${cellId}' contains a non-finite selected score`)\n }\n if (typeof v === 'number') values.set(judgeId, v)\n }\n return values\n }\n\n const inScope = (cellId: string) => scenarioIds.has(scenarioIdFromCellId(cellId))\n const candCells = [...candidate.keys()].filter(inScope).sort()\n const baseCells = [...baseline.keys()].filter(inScope).sort()\n // Alignment invariant — the holdout campaigns share scenarios + seed, so the\n // cell sets must be identical. Differ ⇒ a real pairing bug; fail loud.\n if (candCells.length !== baseCells.length || candCells.some((c, i) => c !== baseCells[i])) {\n throw new Error(\n `pairHoldout: candidate/baseline holdout cells do not align — ` +\n `candidate=[${candCells.join(',')}] baseline=[${baseCells.join(',')}]. ` +\n `Both holdout campaigns must run the same scenarios with the same seed base.`,\n )\n }\n\n const before: number[] = []\n const after: number[] = []\n const cellIds: string[] = []\n for (const cellId of candCells) {\n const b = cellValues(baseline, cellId)\n const a = cellValues(candidate, cellId)\n // A scalar absent on both sides means that dimension was not scored. A\n // one-sided absence is asymmetric evidence loss, never a row to discard.\n if (b.size === 0 && a.size === 0) continue\n if (b.size === 0 || a.size === 0) {\n throw new Error(`pairHoldout: cell '${cellId}' has a selected score on only one arm`)\n }\n if (b.size !== a.size || [...b.keys()].some((id) => !a.has(id))) {\n throw new Error(`pairHoldout: cell '${cellId}' selected judge IDs do not align`)\n }\n const judgeIds = [...b.keys()].sort()\n before.push(meanSelectedScores(judgeIds.map((id) => b.get(id)!)))\n after.push(meanSelectedScores(judgeIds.map((id) => a.get(id)!)))\n cellIds.push(cellId)\n }\n return { before, after, cellIds }\n}\n\nfunction meanSelectedScores(values: number[]): number {\n const first = values[0]!\n // Summing identical fractional scores can round their mean outside the\n // declared binary support. An agreeing judge set preserves its exact value.\n return values.every((value) => value === first)\n ? first\n : values.reduce((sum, value) => sum + value, 0) / values.length\n}\n\nexport interface HeldoutSignificance {\n paired: PairedHoldout\n /**\n * The paired bootstrap on the requested statistic (MEAN by default — see the\n * tie note on `heldoutSignificance`).\n *\n * DIAGNOSTIC, not necessarily the interval the verdict keyed on. On a\n * two-point (pass/fail) outcome the decision routes to Tango's score interval\n * instead, because a percentile bootstrap of the mean over a three-atom\n * lattice is not a valid interval at a nonzero margin. Read\n * `decision.low`/`decision.high` for the interval that actually decided, and\n * `decisionStatistic` for which one it is.\n */\n bootstrap: PairedBootstrapResult\n /** The MEDIAN paired-delta bootstrap, reported as a diagnostic. When many\n * scenarios are tied (both sides solve them), the median is pinned near 0\n * regardless of the mean lift — comparing the two exposes tie-domination. */\n medianBootstrap: PairedBootstrapResult\n /**\n * The full promotion decision: which estimator the outcome's shape admits,\n * the interval it produced, McNemar's exact veto on the two-point path, and\n * whether the interval was zero-width (no evidence in either direction). The\n * single source of `significant`.\n */\n decision: PairedPromotionDecision\n /** Which paired estimator the verdict was decided on. */\n decisionStatistic: PairedDecisionStatistic\n /** McNemar's exact evidence on the two-point path; null otherwise. */\n mcnemar: PairedMcNemarEvidence | null\n /** Fraction of paired observations that are exact ties (|delta| < 1e-9). A\n * high tie fraction is WHY a median-based gate would have missed a real lift;\n * it is the observability the tie fix adds. */\n tieFraction: number\n /** Number of paired observation units, after configured aggregation. */\n n: number\n /** Original matched execution cells, before aggregation. */\n pairedCellN: number\n observationUnit: 'registered' | 'cell'\n /** Registered unit IDs, or cell IDs on the ungrouped path. */\n unitIds: string[]\n /** Effective minimum for the requested target and chosen estimator. */\n minimumRequired: number\n /** Statistical method that carried the decision. */\n decisionMethod: PairedDecisionMethod\n /** Exact one-sided p-value on the small-sample path; otherwise null. */\n pValue: number | null\n /** True iff n >= minimumRequired, the DECIDING interval has nonzero width,\n * its lower bound clears the threshold, and McNemar's exact test does not\n * veto at a non-negative threshold. */\n significant: boolean\n /** Set when n < minimumRequired — too little evidence to claim significance. */\n fewRuns: boolean\n}\n\nexport interface HeldoutSignificanceOptions {\n deltaThreshold?: number\n minProductiveRuns?: number\n confidence?: number\n resamples?: number\n /** Fixed by default for a deterministic, reproducible gate verdict. */\n seed?: number\n statistic?: 'mean' | 'median'\n /** Group full cell pairs into equal-weight independent units before inference. */\n independentUnitByScenarioId?: ReadonlyMap<string, string>\n}\n\n/**\n * Significance of the held-out composite lift: ship only when the lower bound\n * of the interval the outcome's shape ADMITS exceeds `deltaThreshold` (default\n * 0 ⇒ \"confidently positive\"). Interpret `deltaThreshold` in the judge's native\n * scale.\n *\n * The decision is delegated whole to {@link decidePairedPromotion}, the one\n * copy of the rule (`src/paired-promotion-decision.ts`), which `HeldOutGate`\n * also calls. That module's header carries the measurements; the short version\n * is three guards a bare `bootstrap.low > threshold` does not have:\n *\n * - a two-point (pass/fail) outcome decides on Tango's SCORE interval, the\n * only paired-binary construction that stays valid at a nonzero margin;\n * - McNemar's exact test VETOES at any non-negative threshold;\n * - a ZERO-WIDTH interval is refused rather than promoted, in either\n * direction — [0,0] clears every negative threshold and [g,g] clears every\n * threshold below g, and both are an absence of evidence, not a result.\n *\n * Measured on this function before those guards landed, at a nominal 5 %:\n * 14.60 % false promotion at n = 40 on a paired-binary noninferiority boundary,\n * and 88.50 % at n = 6 under a bounded asymmetric null whose true mean paired\n * delta is exactly 0.\n *\n * Continuous mean targets require bootstrap eligibility. Explicit median\n * targets can use the exact sign test at its confidence-dependent minimum.\n */\nexport function heldoutSignificance(\n paired: PairedHoldout,\n opts: HeldoutSignificanceOptions = {},\n): HeldoutSignificance {\n const deltaThreshold = opts.deltaThreshold ?? 0\n const confidence = opts.confidence ?? 0.95\n const resamples = opts.resamples ?? 2000\n const seed = opts.seed ?? 1337\n // DEFAULT to the MEAN paired delta, not the median. The median is destroyed by\n // TIES: whenever both baseline and candidate solve a holdout scenario (a common\n // case once the agent is decent — and INCREASINGLY common as you add holdout\n // scenarios for statistical power), that scenario contributes delta 0. When\n // >=50% of paired cells are ties the median is pinned at 0 regardless of a large,\n // consistent lift on the rest, and the gate holds a genuinely better candidate.\n // (Measured live, supervisor-lab run 6: 40 cells, 20 ties, MEAN +0.177, MEDIAN 0\n // → false hold. Doubling the holdout for \"power\" made it WORSE by adding ties.)\n // The mean equals the reported aggregate lift, ties correctly contribute 0\n // without dominating, and it is the textbook paired-comparison estimator; the\n // median is kept as a reported diagnostic. Callers wanting outlier-robustness at\n // the cost of tie-blindness can still pass `statistic: 'median'`.\n const statistic = opts.statistic ?? 'mean'\n const observations = aggregatePairedHoldout(paired, opts.independentUnitByScenarioId)\n const decision = decidePairedPromotion(observations.before, observations.after, {\n confidence,\n resamples,\n statistic,\n seed,\n threshold: deltaThreshold,\n minPairs: opts.minProductiveRuns,\n })\n // `decision.bootstrap` is null exactly when the score interval decided, so\n // the requested-statistic bootstrap is computed here for the diagnostic\n // field. Same two bootstraps as before on every path.\n const bootstrap =\n decision.bootstrap ??\n pairedBootstrap(observations.before, observations.after, {\n confidence,\n resamples,\n statistic,\n seed,\n })\n const medianBootstrap =\n statistic === 'median'\n ? bootstrap\n : pairedBootstrap(observations.before, observations.after, {\n confidence,\n resamples,\n statistic: 'median',\n seed,\n })\n const n = observations.before.length\n let ties = 0\n for (let i = 0; i < n; i += 1) {\n const after = observations.after[i]!\n const before = observations.before[i]!\n if (Math.abs(after - before) < 1e-9) ties += 1\n }\n const tieFraction = n === 0 ? 0 : ties / n\n return {\n paired,\n bootstrap,\n medianBootstrap,\n decision,\n decisionStatistic: decision.statistic,\n mcnemar: decision.mcnemar,\n tieFraction,\n n,\n pairedCellN: paired.cellIds.length,\n observationUnit: opts.independentUnitByScenarioId === undefined ? 'cell' : 'registered',\n unitIds: observations.unitIds,\n minimumRequired: decision.minimumPairs,\n decisionMethod: decision.method,\n pValue: decision.pValue,\n significant: decision.promote,\n fewRuns: !decision.sufficient,\n }\n}\n\nexport interface DimensionRegression {\n dimension: string\n /** Paired bootstrap on (candidate − baseline). DIAGNOSTIC on a pass/fail\n * dimension, where `ci` carries the interval that decided instead. */\n bootstrap: PairedBootstrapResult\n /** Which paired statistic `bootstrap.low` is the lower bound of. `'mean'`\n * unless the caller asked for the median. `bootstrap.median` still carries\n * the median point estimate either way. */\n bootstrapStatistic: 'median' | 'mean'\n /** The interval `regressed` was decided on, in the dimension's native units. */\n ci: { low: number; high: number }\n /** Which estimator produced `ci`. */\n decisionStatistic: PairedDecisionStatistic\n /** McNemar's exact evidence on a pass/fail dimension; null otherwise. */\n mcnemar: PairedMcNemarEvidence | null\n /** `ci` has zero width — no evidence in either direction. */\n indeterminate: boolean\n /** The bootstrap lower bound is below negative tolerance, or the shared\n * paired test supports a drop exceeding tolerance. Missing coverage and\n * insufficient observations are reported separately. */\n regressed: boolean\n tolerance: number\n n: number\n pairedCellN: number\n observationUnit: 'registered' | 'cell'\n /** Statistical minimum for the configured independent observation unit. */\n minimumRequired: number\n fewRuns: boolean\n /** Both arms lack this dimension on these otherwise matched execution cells. */\n missingCellIds: string[]\n /** Configured scenarios with no paired dimension measurement at all. */\n missingScenarioIds: string[]\n}\n\n/** Detect the native scale of a set of scores: 0-100 when any magnitude clears\n * 1.5, else [0,1]. Used to auto-scale the regression tolerance so a default\n * expressed for [0,1] is not silently a no-op on a 0-100 dimension. */\nexport function detectScale(values: number[]): 1 | 100 {\n return values.some((v) => Math.abs(v) > 1.5) ? 100 : 1\n}\n\n/**\n * Report required-dimension evidence after full pairing and optional unit means.\n * A bootstrap floor breach or a shared paired test supporting a drop marks\n * regression. These two criteria are distinct; `ci` records the shared\n * estimator and `bootstrap` records the floor interval. Missing observations\n * and insufficient n remain explicit for the caller's evidence policy.\n * The default tolerance is 0.05 on [0,1] and 5 on a detected 0-100 scale.\n */\nexport function dimensionRegressions(\n candidate: Map<string, Record<string, JudgeScore>>,\n baseline: Map<string, Record<string, JudgeScore>>,\n scenarioIds: Set<string>,\n criticalDimensions: string[],\n opts: {\n tolerance?: number\n confidence?: number\n resamples?: number\n seed?: number\n /** Paired statistic the CI is computed on. Default `'mean'` — see\n * {@link DECISION_PAIRED_DELTA_STATISTIC} for why the median is not. */\n statistic?: 'mean' | 'median'\n independentUnitByScenarioId?: ReadonlyMap<string, string>\n minProductiveRuns?: number\n } = {},\n): DimensionRegression[] {\n const out: DimensionRegression[] = []\n const expectedCellIds = [...baseline.keys()]\n .filter((cellId) => scenarioIds.has(scenarioIdFromCellId(cellId)))\n .sort()\n for (const dim of criticalDimensions) {\n const paired = pairHoldout(candidate, baseline, scenarioIds, (s) => s.dimensions[dim])\n if (paired.before.length === 0) continue // dimension not scored on this judge\n const observations = aggregatePairedHoldout(paired, opts.independentUnitByScenarioId)\n const measuredCells = new Set(paired.cellIds)\n const measuredScenarios = new Set(paired.cellIds.map(scenarioIdFromCellId))\n const tolerance = opts.tolerance ?? 0.05 * detectScale([...paired.before, ...paired.after])\n const bootstrapStatistic = opts.statistic ?? DECISION_PAIRED_DELTA_STATISTIC\n const shared = {\n confidence: opts.confidence ?? 0.95,\n resamples: opts.resamples ?? 2000,\n statistic: bootstrapStatistic,\n seed: opts.seed ?? 1337,\n minPairs: opts.minProductiveRuns,\n }\n const guard = decidePairedPromotion(observations.before, observations.after, shared)\n const regression = decidePairedPromotion(observations.after, observations.before, {\n ...shared,\n threshold: tolerance,\n })\n const bootstrap =\n guard.bootstrap ?? pairedBootstrap(observations.before, observations.after, shared)\n out.push({\n dimension: dim,\n bootstrap,\n bootstrapStatistic,\n ci: { low: guard.low, high: guard.high },\n decisionStatistic: guard.statistic,\n mcnemar: guard.mcnemar,\n indeterminate: guard.indeterminate,\n // Fires on EITHER burden of proof — see `floorBreached` in\n // `promotion-policy.ts` for the same rule and the reasoning. The CI arm\n // is the contract this interface and `default-production-gate`'s reason\n // string both state (\"CI.low < -tolerance\"), read off the DECIDING\n // interval; the exact-test arm adds the small-sample path where the\n // bootstrap interval is descriptive only.\n // The credible-worst-case arm stays on the BOOTSTRAP — see the same\n // decision in `floorBreached` (`promotion-policy.ts`). On a pass/fail\n // dimension the score interval is ±z²/(n+z²) even when every pair is\n // concordant, so reading the floor off it would flag an unchanged safety\n // dimension as regressed at any realistic n. The PROVEN-drop arm does use\n // the shared rule, which is what closes the fail-open hole that mattered:\n // a genuine pass/fail regression is now judged on an interval valid at\n // the nonzero `tolerance`, instead of a bootstrap that is pinned wherever\n // ties dominate.\n regressed: bootstrap.low < -tolerance || regression.promote,\n tolerance,\n n: observations.before.length,\n pairedCellN: paired.cellIds.length,\n observationUnit: opts.independentUnitByScenarioId === undefined ? 'cell' : 'registered',\n minimumRequired: guard.minimumPairs,\n fewRuns: !guard.sufficient,\n missingCellIds: expectedCellIds.filter((cellId) => !measuredCells.has(cellId)),\n missingScenarioIds: [...scenarioIds].filter((id) => !measuredScenarios.has(id)).sort(),\n })\n }\n return out\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA6BA,MAAa,oBAAoB;;AAYjC,SAAS,qBAAqB,QAAwB;CACpD,MAAM,YAAY,OAAO,YAAY,GAAG;CACxC,MAAM,aAAa,OAAO,MAAM,YAAY,CAAC;CAC7C,IACE,YAAY,KACZ,OAAO,KAAK,MAAM,UAClB,CAAC,iBAAiB,KAAK,UAAU,KACjC,CAAC,OAAO,cAAc,OAAO,UAAU,CAAC,GAExC,MAAM,IAAI,MAAM,kCAAkC,OAAO,2BAA2B;CAEtF,OAAO,OAAO,MAAM,GAAG,SAAS;AAClC;;AAGA,SAAgB,uBACd,QACA,6BAC0D;CAC1D,IACE,OAAO,OAAO,WAAW,OAAO,MAAM,UACtC,OAAO,OAAO,WAAW,OAAO,QAAQ,QAExC,MAAM,IAAI,MAAM,sEAAsE;CAExF,IAAI,IAAI,IAAI,OAAO,OAAO,CAAC,CAAC,SAAS,OAAO,QAAQ,QAClD,MAAM,IAAI,MAAM,4EAA4E;CAE9F,IACE,OAAO,OAAO,MAAM,UAAU,CAAC,OAAO,SAAS,KAAK,CAAC,KACrD,OAAO,MAAM,MAAM,UAAU,CAAC,OAAO,SAAS,KAAK,CAAC,GAEpD,MAAM,IAAI,MAAM,sDAAsD;CAExE,IAAI,gCAAgC,KAAA,GAClC,OAAO;EAAE,QAAQ,CAAC,GAAG,OAAO,MAAM;EAAG,OAAO,CAAC,GAAG,OAAO,KAAK;EAAG,SAAS,CAAC,GAAG,OAAO,OAAO;CAAE;CAE9F,MAAM,cAAc,OAAO,QAAQ,IAAI,oBAAoB;CAC3D,MAAM,yBAAS,IAAI,IAA0D;CAC7E,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,QAAQ,KAAK;EAC9C,MAAM,aAAa,YAAY;EAC/B,MAAM,SAAS,4BAA4B,IAAI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MAAM,CAAC,aAAa,WAAW;GACpD;GACA,GAAG,aAAa,OAAO;GACvB,aAAa,OAAO,QAAQ;GAC5B,iBAAiB,KAAK,gCAAgC,KAAA,IAAY,SAAS;GAC3E,iBAAiB,MAAM;GACvB,SAAS,CAAC,MAAM;GAChB,gBAAgB,gBAAgB,QAAQ,WAAW,CAAC,cAAc,IAAI,MAAM,CAAC;GAC7E,oBAAoB,CAAC,GAAG,WAAW,CAAC,CAAC,QAAQ,OAAO,CAAC,kBAAkB,IAAI,EAAE,CAAC,CAAC,CAAC,KAAK;EACvF,CAAC;CACH;CACA,OAAO;AACT"}
|
|
@@ -2,7 +2,7 @@ import { a as RunRecord } from "./run-record-D2BFMPGl.js";
|
|
|
2
2
|
import { z as FindingTreatment } from "./types-DzCO-S1m.js";
|
|
3
3
|
import { a as PairedPromotionDecision, i as PairedMcNemarEvidence, l as PairedBootstrapOptions, r as PairedDecisionStatistic, t as PairedDecisionMethod, u as PairedBootstrapResult } from "./paired-promotion-decision-BDnqepZ1.js";
|
|
4
4
|
import { r as LedgerHash } from "./canonical-gLeHiqzd.js";
|
|
5
|
-
import { R as Scenario, a as CampaignResult, b as GenerationRecord, h as GateContext, j as MutableSurface, p as Gate, v as GateResult, w as JudgeScore } from "./types-
|
|
5
|
+
import { R as Scenario, a as CampaignResult, b as GenerationRecord, h as GateContext, j as MutableSurface, p as Gate, v as GateResult, w as JudgeScore } from "./types-BF-xQGQn.js";
|
|
6
6
|
import { z } from "zod";
|
|
7
7
|
/** A binomial proportion estimate with a confidence interval. */
|
|
8
8
|
interface ProportionInterval {
|
|
@@ -1273,4 +1273,4 @@ declare function dimensionRegressions(candidate: Map<string, Record<string, Judg
|
|
|
1273
1273
|
minProductiveRuns?: number;
|
|
1274
1274
|
}): DimensionRegression[];
|
|
1275
1275
|
export { paretoPolicy as $, PairRunRecordsResult as A, EProcess as At, ArmPopulationSummary as B, mcnemar as Bt, signManifest as C, FinalEvidenceError as Ct, MatchedRunRecordPair as D, FinalEvidenceRecord as Dt, MatchedPair as E, FinalEvidenceOutcome as Et, comparePairedArms as F, ExactRiskDifferenceResult as Ft, AxisVerdict as G, wilson as Gt, PowerPreflightOptions as H, pairedRiskDifferenceExact as Ht, pairArms as I, McNemarResult as It, ObjectiveSource as J, BuildEvidenceVectorOptions as K, pairRunRecords as L, ProportionInterval as Lt, PairedArmsComparison as M, EProcessState as Mt, PairedCorrectness as N, EProcessStep as Nt, PairArmsOptions as O, FinalEvidenceReservation as Ot, PairedMetricDelta as P, eProcess as Pt, buildEvidenceVector as Q, ArmAssignment as R, RiskDifferenceResult as Rt, manifestContentDigest as S, FinalEvidenceConflictError as St, ComparePairedArmsOptions as T, FinalEvidenceMeasurement as Tt, powerPreflight as U, pairedRiskDifferenceScore as Ut, PowerPreflight as V, pairedRiskDifference as Vt, AxisEvidence as W, passAtK as Wt, PromotionObjective as X, ParetoSignificanceGateOptions as Y, PromotionPolicy as Z, HypothesisManifest as _, AttestationProvenance as _t, dimensionRegressions as a, CampaignEvidenceContext as at, SignedManifestAlgo as b, attest as bt, SequentialDecideFn as c, EvidenceAuthority as ct, SequentialObservation as d, EvidenceReceipt as dt, paretoSignificanceGate as et, SequentialPairedGate as f, EvidenceReceiptVerification as ft, sequentialPairedGate as g, ATTESTATION_ALGORITHM as gt, sequentialDecide as h, verifyEvidenceReceipt as ht, PairedHoldout as i, paretoFrontier as it, PairedArmRow as j, EProcessOptions as jt, PairArmsResult as k, openFinalEvidenceLedger as kt, SequentialDecideOptions as l, EvidenceAuthorityKind as lt, SequentialStreamState as m, isIndependentEvidence as mt, HeldoutSignificance as n, ParetoResult as nt, heldoutSignificance as o, createCampaignEvidenceReceipt as ot, SequentialPairedGateOptions as p, createEvidenceReceipt as pt, EvidenceVector as q, HeldoutSignificanceOptions as r, dominates as rt, pairHoldout as s, CreateEvidenceReceiptInput as st, DimensionRegression as t, Objective as tt, SequentialGateDecision as u, EvidenceBinding as ut, HypothesisResult as v, AttestationVerification as vt, verifyManifest as w, FinalEvidenceLedger as wt, hashJson as x, verifyAttestation as xt, SignedManifest as y, AttestedReport as yt, ArmPopulationReading as z, ScoreRiskDifferenceResult as zt };
|
|
1276
|
-
//# sourceMappingURL=statistical-heldout-
|
|
1276
|
+
//# sourceMappingURL=statistical-heldout-bU7FBNjR.d.ts.map
|
package/dist/{statistical-heldout-Cei036nE.d.ts.map → statistical-heldout-bU7FBNjR.d.ts.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"statistical-heldout-
|
|
1
|
+
{"version":3,"file":"statistical-heldout-bU7FBNjR.d.ts","names":["_$__evidence_receipt0.EvidenceReceipt"],"sources":["../src/statistics/paired-binary.ts","../src/statistics/sequential-eprocess.ts","../src/experiment/final-evidence.ts","../src/attestation.ts","../src/experiment/evidence-receipt.ts","../src/experiment/campaign-evidence.ts","../src/pareto.ts","../src/campaign/gates/promotion-policy.ts","../src/campaign/gates/power-preflight.ts","../src/arm-populations.ts","../src/paired-arms.ts","../src/pre-registration.ts","../src/campaign/gates/sequential.ts","../src/campaign/gates/statistical-heldout.ts"],"mappings":";;;;;;;UAgBiB;;EAEf;;EAEA;;EAEA;;;;;;;;;;;;iBAac,OAAO,mBAAmB,WAAW,sBAAoB;;UA2DxD;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;;;;;;;;;;;;;iBAec,QACd,SAAS,6BACT,WAAW,8BACV;;UAmBc;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;;;;;;;;;;;;;;;;;iBAmBc,qBACd,SAAS,6BACT,WAAW,6BACX,sBACC;;;;UAkCc;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgCc,0BACd,SAAS,6BACT,WAAW,6BACX,sBACC;;;UAyEc;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;;;;;;;;;;;;;;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A;;EAEA,8BAA8B;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6BhB,oBACd,QAAQ,eACR,OAAM,6BACL;UA2Ec;EACf;;;EAGA,WAAW;;;;EAIX;;EAEA;IAAM;IAAa;;;EAEnB,mBAAmB;;EAEnB,SAAS;;EAET;;;;EAIA;EACA;EACA;EACA;EACA;;EAEA;EACA;;EAEA;;EAEA;;;;;;;;;;iBAkBc,qBACd,WAAW,YAAY,eAAe,cACtC,UAAU,YAAY,eAAe,cACrC,aAAa,aACb,8BACA;EACE;EACA;EACA;EACA;;;EAGA;EACA,8BAA8B;EAC9B;IAED"}
|
|
@@ -3,11 +3,12 @@ import { t as LEDGER_HASH_PATTERN } from "./canonical-CicJlINA.js";
|
|
|
3
3
|
import { n as runTraceAnalyst } from "./kind-factory-VKysp1ds.js";
|
|
4
4
|
import { OPENINFERENCE_SPAN_KIND, applyLlmSpanOtlpAttributes } from "./trace-attributes.js";
|
|
5
5
|
import { n as extractUsageFromSse, t as extractUsage } from "./extract-usage-ISFqhfDz.js";
|
|
6
|
-
import { a as providerFromBaseUrl, i as defaultProviderRedactor } from "./raw-provider-sink-
|
|
6
|
+
import { a as providerFromBaseUrl, i as defaultProviderRedactor } from "./raw-provider-sink-RbaEv2vB.js";
|
|
7
7
|
import { n as traceSpanKindToOpenInferenceKind, t as applyToolSpanOtlpAttributes } from "./otlp-attributes-Boeb7gtH.js";
|
|
8
8
|
import { r as OtlpFileTraceStore, t as BufferTraceStore } from "./store-otlp-DmLm65XW.js";
|
|
9
9
|
import { randomUUID } from "node:crypto";
|
|
10
|
-
import {
|
|
10
|
+
import { toW3CSpanId, toW3CTraceId } from "@tangle-network/agent-trace-contract";
|
|
11
|
+
import { msToUnixNano, otlpTraceExport, toOtlpAttributes } from "@tangle-network/agent-trace-contract/otlp";
|
|
11
12
|
// src/trace/capture-fetch.ts
|
|
12
13
|
/**
|
|
13
14
|
* Wrap a provider `fetch` and record request, response, and error events.
|
|
@@ -135,42 +136,6 @@ function captureFetchToRawSink(fetch, sink, ctx, opts = {}) {
|
|
|
135
136
|
return response;
|
|
136
137
|
};
|
|
137
138
|
}
|
|
138
|
-
// src/trace/otlp-encoding.ts
|
|
139
|
-
/** OTLP `KeyValue[]` for a flat attribute record. */
|
|
140
|
-
function toOtlpAttributes(record) {
|
|
141
|
-
return Object.entries(record).map(([key, value]) => ({
|
|
142
|
-
key,
|
|
143
|
-
value: typeof value === "number" ? Number.isInteger(value) ? { intValue: value.toString() } : { doubleValue: value } : typeof value === "boolean" ? { boolValue: value } : { stringValue: value }
|
|
144
|
-
}));
|
|
145
|
-
}
|
|
146
|
-
/** OTLP nanosecond timestamp, as the decimal string the protocol requires. */
|
|
147
|
-
function msToUnixNano(ms) {
|
|
148
|
-
return (BigInt(Math.floor(ms)) * 1000000n).toString();
|
|
149
|
-
}
|
|
150
|
-
// src/trace/wire-ids.ts
|
|
151
|
-
/**
|
|
152
|
-
* The ONE mapping from agent-eval's human-readable ids (run ids, span labels)
|
|
153
|
-
* to W3C/OTLP wire ids. Every exporter in this package MUST route through
|
|
154
|
-
* these two functions — two exporters with private paddings once produced
|
|
155
|
-
* DIFFERENT trace ids for the same run, and one emitted invalid hex embedding
|
|
156
|
-
* the raw run id in the wire id (tangle-network/agent-runtime#694).
|
|
157
|
-
*
|
|
158
|
-
* Semantics:
|
|
159
|
-
* - an id that is ALREADY a valid W3C id passes through unchanged, so a
|
|
160
|
-
* trace id received from an inbound `traceparent` survives the round-trip
|
|
161
|
-
* and cross-process correlation is preserved;
|
|
162
|
-
* - anything else is derived with the contract's `deriveHexId`, the only
|
|
163
|
-
* legal derivation — deterministic, so every process that derives from the
|
|
164
|
-
* same human id mints the SAME wire id.
|
|
165
|
-
*/
|
|
166
|
-
/** 32-hex W3C trace id for any id string. */
|
|
167
|
-
function traceIdForWire(id) {
|
|
168
|
-
return isW3CTraceId(id) ? id : deriveHexId(id, 16);
|
|
169
|
-
}
|
|
170
|
-
/** 16-hex W3C span id for any id string. */
|
|
171
|
-
function spanIdForWire(id) {
|
|
172
|
-
return isW3CSpanId(id) ? id : deriveHexId(id, 8);
|
|
173
|
-
}
|
|
174
139
|
// src/trace/otel.ts
|
|
175
140
|
/**
|
|
176
141
|
* OpenTelemetry JSON export — maps TraceSchema v1 to OTLP/JSON so
|
|
@@ -199,31 +164,26 @@ async function exportRunAsOtlp(store, runId, resourceAttrs = {}) {
|
|
|
199
164
|
arr.push(e);
|
|
200
165
|
eventsBySpan.set(e.spanId, arr);
|
|
201
166
|
}
|
|
202
|
-
const traceId =
|
|
167
|
+
const traceId = toW3CTraceId(run.runId);
|
|
203
168
|
const otlpSpans = spans.map((s) => spanToOtlp(s, traceId, eventsBySpan.get(s.spanId) ?? []));
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
scopeSpans: [{
|
|
216
|
-
scope: OTEL_AGENT_EVAL_SCOPE,
|
|
217
|
-
spans: otlpSpans
|
|
218
|
-
}]
|
|
219
|
-
}] };
|
|
169
|
+
const resource = toOtlpAttributes({
|
|
170
|
+
"service.name": "agent-eval",
|
|
171
|
+
"run.id": run.runId,
|
|
172
|
+
"run.scenario_id": run.scenarioId,
|
|
173
|
+
"run.variant_id": run.variantId ?? "",
|
|
174
|
+
"run.dataset_version": run.datasetVersion ?? "",
|
|
175
|
+
"run.code_sha": run.codeSha ?? "",
|
|
176
|
+
"run.model_fingerprint": run.modelFingerprint ?? "",
|
|
177
|
+
...resourceAttrs
|
|
178
|
+
});
|
|
179
|
+
return otlpTraceExport(resource, OTEL_AGENT_EVAL_SCOPE, otlpSpans);
|
|
220
180
|
}
|
|
221
181
|
function spanToOtlp(span, traceId, events) {
|
|
222
182
|
const endedAt = span.endedAt ?? span.startedAt;
|
|
223
183
|
return {
|
|
224
184
|
traceId,
|
|
225
|
-
spanId:
|
|
226
|
-
parentSpanId: span.parentSpanId ?
|
|
185
|
+
spanId: toW3CSpanId(span.spanId),
|
|
186
|
+
parentSpanId: span.parentSpanId ? toW3CSpanId(span.parentSpanId) : void 0,
|
|
227
187
|
name: span.name,
|
|
228
188
|
kind: 1,
|
|
229
189
|
startTimeUnixNano: msToUnixNano(span.startedAt),
|
|
@@ -270,9 +230,6 @@ function flattenPayload(payload) {
|
|
|
270
230
|
else out[k] = JSON.stringify(v);
|
|
271
231
|
return out;
|
|
272
232
|
}
|
|
273
|
-
function runToTraceId(run) {
|
|
274
|
-
return traceIdForWire(run.runId);
|
|
275
|
-
}
|
|
276
233
|
const TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION = "trace-analyst-research-v1-2026-07-30";
|
|
277
234
|
// src/trace-analyst/analyst.ts
|
|
278
235
|
/**
|
|
@@ -705,6 +662,6 @@ function toolSpanTimeIso(value, spanId, field) {
|
|
|
705
662
|
if (iso) return iso;
|
|
706
663
|
throw new CaptureIntegrityError(`toolSpansToTraceAnalysisStore: span '${spanId}' has invalid ${field}`);
|
|
707
664
|
}
|
|
708
|
-
export { exportRunAsOtlp as _, spanStatusToOtlp as a,
|
|
665
|
+
export { exportRunAsOtlp as _, spanStatusToOtlp as a, describeTraceInsightScope as c, isTraceInsightArtifact as d, isTraceInsightAttribution as f, analyzeTraces as g, tokenizeDomainWords as h, epochMillisToIso as i, domainEvidencePattern as l, scoreTraceInsightReadiness as m, toolSpansToTraceAnalysisStore as n, buildTraceInsightContext as o, isTraceInsightEvidence as p, createOtlpFlatLine as r, buildTraceInsightPrompt as s, ToolTraceMissingError as t, inferDomainKeywords as u, captureFetchToRawSink as v };
|
|
709
666
|
|
|
710
|
-
//# sourceMappingURL=store-tool-spans-
|
|
667
|
+
//# sourceMappingURL=store-tool-spans-GGaCijFy.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store-tool-spans-GGaCijFy.js","names":[],"sources":["../src/trace/capture-fetch.ts","../src/trace/otel.ts","../src/trace-analyst/prompts.ts","../src/trace-analyst/analyst.ts","../src/trace-analyst/insights.ts","../src/trace/otlp-flat.ts","../src/trace-analyst/store-tool-spans.ts"],"sourcesContent":["/**\n * Wrap a provider `fetch` and record request, response, and error events.\n *\n * The returned value is a plain `typeof fetch`. Capture is best-effort by\n * default; set `failClosed` when telemetry loss must stop the provider call.\n */\n\nimport {\n type ExtractedUsage,\n extractUsage,\n extractUsageFromSse,\n type SseUsageMode,\n} from './extract-usage'\nimport {\n defaultProviderRedactor,\n type ProviderRedactor,\n providerFromBaseUrl,\n type RawProviderDirection,\n type RawProviderEvent,\n type RawProviderSink,\n} from './raw-provider-sink'\n\nexport interface CaptureFetchContext {\n /** Logical run id stamped on every captured event. Required — without it\n * the raw events can't be paired with their parent `Run`. */\n runId: string\n /** Optional logical span id (enables span-level sink filtering). */\n spanId?: string\n /** Resolved base URL (normalised, no trailing slash). Used for the event's\n * `baseUrl` and for endpoint-path extraction. */\n baseUrl: string\n /** Model id the caller intends to invoke. Stamped on every event. */\n model: string\n /** Provider override. When omitted, `providerFromBaseUrl(baseUrl)`. */\n provider?: string\n}\n\nexport interface CaptureFetchOptions {\n /** Override the capture-time redactor. Default `defaultProviderRedactor`. */\n redactor?: ProviderRedactor\n /** Cap on captured response-body bytes; beyond it the body is truncated and\n * `body_truncated` is added to `redactedFields`. Default 2 MiB. */\n responseBodyByteCap?: number\n /** When true, a sink-write failure propagates to the caller. Default false\n * — capture is best-effort so a sink failure never kills the LLM call. */\n failClosed?: boolean\n /**\n * Invoked with the token usage parsed off each successful response (JSON or\n * SSE), keyed by the captured context. Lets a caller fold usage → cost without\n * re-cloning the response themselves. Not called when the response carries no\n * usage. Best-effort: a throw here is swallowed (it never kills the LLM call)\n * unless `failClosed` is set.\n */\n onUsage?: (usage: ExtractedUsage, ctx: CaptureFetchContext) => void\n /** How repeated SSE usage events should be reconciled. Default `cumulative`. */\n sseUsageMode?: SseUsageMode\n}\n\nconst DEFAULT_BODY_CAP = 2 * 1024 * 1024\n\nfunction headersToRecord(headers: Headers | undefined): Record<string, string> | undefined {\n if (!headers) return undefined\n const out: Record<string, string> = {}\n headers.forEach((value, key) => {\n out[key.toLowerCase()] = value\n })\n return Object.keys(out).length > 0 ? out : undefined\n}\n\nfunction parseMaybeJson(text: string): unknown {\n if (text.length === 0) return undefined\n try {\n return JSON.parse(text)\n } catch {\n return text\n }\n}\n\n/** Best-effort request-body read across the `fetch` input forms. */\nasync function readRequestBody(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n): Promise<unknown> {\n if (typeof init?.body === 'string') return parseMaybeJson(init.body)\n if (init?.body != null) return undefined // streams / FormData / Blob — not captured\n if (input instanceof Request) {\n try {\n return parseMaybeJson(await input.clone().text())\n } catch {\n return undefined\n }\n }\n return undefined\n}\n\nfunction endpointFromUrl(url: string, baseUrl: string): string {\n const normalisedBase = baseUrl.replace(/\\/+$/, '')\n if (url.startsWith(normalisedBase)) return url.slice(normalisedBase.length) || '/'\n try {\n return new URL(url).pathname\n } catch {\n return url\n }\n}\n\nexport function captureFetchToRawSink(\n fetch: typeof globalThis.fetch,\n sink: RawProviderSink,\n ctx: CaptureFetchContext,\n opts: CaptureFetchOptions = {},\n): typeof globalThis.fetch {\n const provider = ctx.provider ?? providerFromBaseUrl(ctx.baseUrl)\n const redactor = opts.redactor ?? defaultProviderRedactor\n const bodyCap = opts.responseBodyByteCap ?? DEFAULT_BODY_CAP\n let warned = false\n\n const baseEvent = (direction: RawProviderDirection, endpoint: string): RawProviderEvent => ({\n eventId: crypto.randomUUID(),\n runId: ctx.runId,\n spanId: ctx.spanId,\n provider,\n model: ctx.model,\n endpoint,\n baseUrl: ctx.baseUrl,\n attemptIndex: 0, // retries are re-invocations one layer up; documented in 0.x\n direction,\n timestamp: Date.now(),\n redactedFields: [],\n })\n\n const record = async (event: RawProviderEvent): Promise<void> => {\n try {\n await sink.record(redactor(event))\n } catch (err) {\n if (opts.failClosed) throw err\n if (!warned) {\n warned = true\n console.warn(\n `captureFetchToRawSink: sink.record failed (capture is best-effort) — ${\n err instanceof Error ? err.message : String(err)\n }`,\n )\n }\n }\n }\n\n return async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n const url =\n typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url\n const method = (init?.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase()\n const endpoint = endpointFromUrl(url, ctx.baseUrl)\n\n const reqHeaders = new Headers(\n init?.headers ?? (input instanceof Request ? input.headers : undefined),\n )\n await record({\n ...baseEvent('request', endpoint),\n requestHeaders: { ...headersToRecord(reqHeaders), 'x-http-method': method },\n requestBody: await readRequestBody(input, init),\n })\n\n const start = Date.now()\n let response: Response\n try {\n response = await fetch(input, init)\n } catch (err) {\n await record({\n ...baseEvent('error', endpoint),\n durationMs: Date.now() - start,\n errorMessage: err instanceof Error ? err.message : String(err),\n })\n throw err\n }\n\n // Read the body off a clone so the caller still consumes the original.\n let responseBody: unknown\n let rawText: string | undefined\n const redactedFields: string[] = []\n try {\n rawText = await response.clone().text()\n if (rawText.length > bodyCap) {\n responseBody = rawText.slice(0, bodyCap)\n redactedFields.push('body_truncated')\n } else {\n responseBody = parseMaybeJson(rawText)\n }\n } catch {\n responseBody = undefined\n }\n\n if (opts.onUsage && rawText !== undefined) {\n // Reuse the body already read for capture; no extra clone. JSON first,\n // then SSE accumulation. A throw in the consumer's callback is swallowed\n // (best-effort) unless failClosed is set — the LLM call must not die here.\n try {\n const parsedForUsage = parseMaybeJson(rawText)\n const usage =\n extractUsage(parsedForUsage) ??\n (typeof parsedForUsage === 'string'\n ? extractUsageFromSse(rawText, { mode: opts.sseUsageMode })\n : null)\n if (usage) opts.onUsage(usage, ctx)\n } catch (err) {\n if (opts.failClosed) throw err\n }\n }\n\n await record({\n ...baseEvent('response', endpoint),\n durationMs: Date.now() - start,\n statusCode: response.status,\n responseHeaders: headersToRecord(response.headers),\n responseBody,\n redactedFields,\n })\n\n return response\n }\n}\n","/**\n * OpenTelemetry JSON export — maps TraceSchema v1 to OTLP/JSON so\n * traces render natively in Jaeger / Honeycomb / Langfuse / Grafana.\n *\n * Wire format only. We do NOT depend on the @opentelemetry SDK — that\n * would drag in polyfills incompatible with Workers/Edge. Consumers\n * push the JSON to their collector of choice via HTTP.\n *\n * Reference: OTLP 1.3.2 (ResourceSpans / ScopeSpans / Span).\n */\n\nimport { toW3CSpanId, toW3CTraceId } from '@tangle-network/agent-trace-contract'\nimport {\n msToUnixNano,\n type OtlpSpan,\n type OtlpTraceExport,\n otlpTraceExport,\n toOtlpAttributes,\n} from '@tangle-network/agent-trace-contract/otlp'\nimport {\n applyLlmSpanOtlpAttributes,\n applyToolSpanOtlpAttributes,\n OPENINFERENCE_SPAN_KIND,\n traceSpanKindToOpenInferenceKind,\n} from './otlp-attributes'\nimport type { Span, TraceEvent } from './schema'\nimport type { TraceStore } from './store'\n\nconst OTEL_AGENT_EVAL_SCOPE = { name: '@tangle-network/agent-eval', version: '0.3.0' }\n\nexport type { OtlpResourceSpans, OtlpSpan } from '@tangle-network/agent-trace-contract/otlp'\nexport type OtlpExport = OtlpTraceExport\n\n/** Export a single run's spans + events in OTLP/JSON. */\nexport async function exportRunAsOtlp(\n store: TraceStore,\n runId: string,\n resourceAttrs: Record<string, string | number | boolean> = {},\n): Promise<OtlpExport> {\n const run = await store.getRun(runId)\n if (!run) throw new Error(`run ${runId} not found`)\n const spans = await store.spans({ runId })\n const events = await store.events({ runId })\n const eventsBySpan = new Map<string, TraceEvent[]>()\n for (const e of events) {\n if (!e.spanId) continue\n const arr = eventsBySpan.get(e.spanId) ?? []\n arr.push(e)\n eventsBySpan.set(e.spanId, arr)\n }\n const traceId = toW3CTraceId(run.runId)\n const otlpSpans: OtlpSpan[] = spans.map((s) =>\n spanToOtlp(s, traceId, eventsBySpan.get(s.spanId) ?? []),\n )\n const resource = toOtlpAttributes({\n 'service.name': 'agent-eval',\n 'run.id': run.runId,\n 'run.scenario_id': run.scenarioId,\n 'run.variant_id': run.variantId ?? '',\n 'run.dataset_version': run.datasetVersion ?? '',\n 'run.code_sha': run.codeSha ?? '',\n 'run.model_fingerprint': run.modelFingerprint ?? '',\n ...resourceAttrs,\n })\n return otlpTraceExport(resource, OTEL_AGENT_EVAL_SCOPE, otlpSpans)\n}\n\nfunction spanToOtlp(span: Span, traceId: string, events: TraceEvent[]): OtlpSpan {\n const endedAt = span.endedAt ?? span.startedAt\n return {\n traceId,\n spanId: toW3CSpanId(span.spanId),\n parentSpanId: span.parentSpanId ? toW3CSpanId(span.parentSpanId) : undefined,\n name: span.name,\n kind: 1, // SPAN_KIND_INTERNAL\n startTimeUnixNano: msToUnixNano(span.startedAt),\n endTimeUnixNano: msToUnixNano(endedAt),\n attributes: toOtlpAttributes(flattenSpanAttributes(span)),\n events: events.map((e) => ({\n timeUnixNano: msToUnixNano(e.timestamp),\n name: e.kind,\n attributes: toOtlpAttributes(flattenPayload(e.payload)),\n })),\n status: span.status === 'error' ? { code: 2, message: span.error } : { code: 1 },\n }\n}\n\nfunction flattenSpanAttributes(span: Span): Record<string, string | number | boolean> {\n const base: Record<string, string | number | boolean> = {}\n if (span.attributes) {\n for (const [k, v] of Object.entries(span.attributes)) {\n if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') base[k] = v\n }\n }\n base[OPENINFERENCE_SPAN_KIND] = traceSpanKindToOpenInferenceKind(span.kind)\n if (span.kind === 'llm') {\n applyLlmSpanOtlpAttributes(base, span)\n } else if (span.kind === 'tool') {\n applyToolSpanOtlpAttributes(base, span)\n } else if (span.kind === 'retrieval') {\n base['retrieval.query'] = span.query\n base['retrieval.hits'] = span.hits.length\n } else if (span.kind === 'judge') {\n base['judge.id'] = span.judgeId\n base['judge.dimension'] = span.dimension\n base['judge.score'] = span.score\n base['judge.target_span_id'] = span.targetSpanId\n } else if (span.kind === 'sandbox') {\n if (span.image) base['sandbox.image'] = span.image\n if (span.exitCode !== undefined) base['sandbox.exit_code'] = span.exitCode\n if (span.testsPassed !== undefined) base['sandbox.tests_passed'] = span.testsPassed\n if (span.testsTotal !== undefined) base['sandbox.tests_total'] = span.testsTotal\n }\n return base\n}\n\nfunction flattenPayload(\n payload: Record<string, unknown>,\n): Record<string, string | number | boolean> {\n const out: Record<string, string | number | boolean> = {}\n for (const [k, v] of Object.entries(payload)) {\n if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') out[k] = v\n else out[k] = JSON.stringify(v)\n }\n return out\n}\n","/** General policy for recursive, evidence-backed trace analysis. */\n\nexport const TRACE_ANALYST_ACTOR_DESCRIPTION = `Answer the question by inspecting the OTLP trace dataset with the available tools.\n\n1. Call getDatasetOverview first. Use its real trace ids and dataset size to plan the investigation.\n2. Narrow with queryTraces and countTraces before scanning large payloads.\n3. For a small trace, use viewTrace. For a large trace, use searchTrace and then viewSpans or searchSpan.\n4. Never invent a trace id, span id, tool result, error, frequency, or final outcome.\n5. When a search reports has_more, refine the query before drawing a conclusion.\n6. Use llm_query only over evidence already loaded. A recursive query cannot inspect traces itself.\n7. Cite exact evidence URIs returned by the tools. Include a short exact excerpt when it supports the claim.\n8. Return no finding when the available evidence cannot support one.\n\nThe prose answer must directly answer the question and state important uncertainty.\nThe findings array contains only actionable or decision-relevant claims supported by inspected evidence.`\n\nexport const TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION = 'trace-analyst-research-v1-2026-07-30'\n","import { randomUUID } from 'node:crypto'\nimport type {\n TraceAnalysisEngine,\n TraceAnalysisEngineResult,\n TraceAnalystLimits,\n} from '../analyst/engine'\nimport { runTraceAnalyst } from '../analyst/kind-factory'\nimport type { TraceToolGroupName } from '../analyst/tool-groups'\nimport type { AnalystFinding, AnalystUsageReceipt } from '../analyst/types'\nimport type { CostLedgerHandle } from '../cost-ledger'\nimport { TRACE_ANALYST_ACTOR_DESCRIPTION, TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION } from './prompts'\nimport type { TraceAnalysisStore } from './store'\nimport { OtlpFileTraceStore } from './store-otlp'\n\nexport interface AnalyzeTracesInput {\n question: string\n id?: string\n description?: string\n area?: string\n}\n\nexport type AnalyzeTracesResult = TraceAnalysisEngineResult\n\nexport interface AnalyzeTracesOptions {\n /** OTLP JSONL path or a caller-owned store. */\n source: string | TraceAnalysisStore\n /** Recursive research engine. */\n engine: TraceAnalysisEngine\n /** Override the general trace-research policy. */\n instructions?: string\n /** Smallest tool set that can answer the question. Default: all. */\n toolGroup?: TraceToolGroupName\n limits?: Partial<TraceAnalystLimits>\n runId?: string\n budgetUsd?: number\n costLedger?: CostLedgerHandle\n costPhase?: string\n priorFindings?: readonly AnalystFinding[]\n upstreamFindings?: readonly AnalystFinding[]\n recordUsage?: (receipt: AnalystUsageReceipt) => void\n tags?: Record<string, string>\n log?: (message: string, fields?: Record<string, unknown>) => void\n signal?: AbortSignal\n}\n\n/**\n * Answer one question by recursively inspecting a trace store.\n *\n * The returned answer, cited findings, engine steps, call counts, and runtime\n * identity are one audit record. A direct one-shot model call is not used.\n */\nexport async function analyzeTraces(\n input: AnalyzeTracesInput,\n options: AnalyzeTracesOptions,\n): Promise<AnalyzeTracesResult> {\n if (typeof input.question !== 'string' || !input.question.trim()) {\n throw new TypeError('analyzeTraces: input.question must be a non-empty string')\n }\n const id = input.id?.trim() || 'trace-analysis'\n const store =\n typeof options.source === 'string'\n ? new OtlpFileTraceStore({ path: options.source })\n : options.source\n if (store instanceof OtlpFileTraceStore) {\n await store.ensureIndexed(options.signal ? { signal: options.signal } : undefined)\n }\n\n return runTraceAnalyst({\n definition: {\n id,\n description:\n input.description?.trim() ||\n 'Answers a caller-defined question by recursively inspecting trace evidence.',\n area: input.area?.trim() || 'trace-analysis',\n version: TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION,\n question: input.question,\n instructions: options.instructions ?? TRACE_ANALYST_ACTOR_DESCRIPTION,\n toolGroup: options.toolGroup ?? 'all',\n limits: options.limits,\n },\n engine: options.engine,\n store,\n context: {\n runId: options.runId ?? id,\n correlationId: randomUUID(),\n budgetUsd: options.budgetUsd,\n costLedger: options.costLedger,\n costPhase: options.costPhase ?? 'trace-analysis',\n priorFindings: options.priorFindings,\n upstreamFindings: options.upstreamFindings,\n recordUsage: options.recordUsage,\n tags: options.tags,\n log: options.log,\n signal: options.signal,\n },\n })\n}\n","import type { SearchArtifactRef } from '../campaign/search-ledger-types'\nimport { LEDGER_HASH_PATTERN } from '../ledger-core/canonical'\n\nexport interface TraceInsightTask {\n id: string\n name: string\n prompt?: string\n difficulty?: string\n tags?: string[]\n outcome?: string\n score?: number\n gaps?: string[]\n}\n\nexport interface TraceInsightSuite {\n name: string\n collectionId?: string\n tasks: TraceInsightTask[]\n}\n\nexport interface TraceInsightFinding {\n kind: string\n severity?: string\n taskIds: string[]\n evidence?: string\n proposedFixClass?: string\n /** Narrative evidence remains a note; customer attribution uses byte-backed evidence only. */\n attribution?: TraceInsightAttribution\n}\n\n/** A byte-backed observation. Locators are not identities; every link carries a digest. */\nexport interface TraceInsightEvidence {\n subject: {\n verticalId: string\n taskId: string\n cellId: string | null\n attemptId: string | null\n company: string | null\n tool: string | null\n toolRevision: string | null\n }\n artifacts: Record<\n 'seed' | 'task' | 'cell' | 'request' | 'response' | 'document' | 'controls' | 'binding',\n SearchArtifactRef | null\n >\n spans: Array<{ traceId: string; spanId: string; artifact: SearchArtifactRef }>\n}\n\nexport type TraceInsightAttribution = TraceInsightEvidence &\n (\n | { outcome: 'unknown'; evidenceClass: 'unknown'; reasons: string[] }\n | {\n outcome: 'tool-failure'\n evidenceClass: 'validated-request-response'\n proof: SearchArtifactRef\n authority: SearchArtifactRef\n }\n | {\n outcome: 'documentation-failure'\n evidenceClass: 'authoritative-execution'\n documentation: 'stale' | 'contradictory'\n proof: SearchArtifactRef\n authority: SearchArtifactRef\n }\n | {\n outcome: 'documentation-failure'\n evidenceClass: 'paired-corrected-document'\n proof: SearchArtifactRef\n plan: SearchArtifactRef\n comparisonId: string\n correctedEvidence: SearchArtifactRef\n }\n )\n\nfunction evidenceRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction evidenceText(value: unknown): value is string {\n return typeof value === 'string' && value.trim().length > 0\n}\n\n/** Structural validation only. The producer must verify bytes and execute the evidence rule. */\nexport function isTraceInsightArtifact(value: unknown): value is SearchArtifactRef {\n if (\n !evidenceRecord(value) ||\n !evidenceText(value.role) ||\n !evidenceText(value.uri) ||\n typeof value.sha256 !== 'string' ||\n !LEDGER_HASH_PATTERN.test(value.sha256) ||\n !Number.isSafeInteger(value.byteLength) ||\n (value.byteLength as number) < 0\n )\n return false\n // Customer reports must not turn a locator into an executable link.\n try {\n const url = new URL(value.uri)\n return ['https:', 'file:'].includes(url.protocol) && !url.username && !url.password\n } catch {\n return /^artifacts\\/[a-f0-9]{64}$/.test(value.uri)\n }\n}\n\nexport function isTraceInsightEvidence(value: unknown): value is TraceInsightEvidence {\n if (\n !evidenceRecord(value) ||\n !evidenceRecord(value.subject) ||\n !evidenceRecord(value.artifacts) ||\n !Array.isArray(value.spans)\n )\n return false\n const subject = value.subject\n if (!evidenceText(subject.verticalId) || !evidenceText(subject.taskId)) return false\n for (const field of ['cellId', 'attemptId', 'company', 'tool', 'toolRevision']) {\n if (subject[field] !== null && !evidenceText(subject[field])) return false\n }\n for (const role of [\n 'seed',\n 'task',\n 'cell',\n 'request',\n 'response',\n 'document',\n 'controls',\n 'binding',\n ]) {\n const artifact = value.artifacts[role]\n if (artifact !== null && (!isTraceInsightArtifact(artifact) || artifact.role !== role))\n return false\n }\n return value.spans.every(\n (span) =>\n evidenceRecord(span) &&\n typeof span.traceId === 'string' &&\n /^[a-f0-9]{32}$/.test(span.traceId) &&\n !/^0+$/.test(span.traceId) &&\n typeof span.spanId === 'string' &&\n /^[a-f0-9]{16}$/.test(span.spanId) &&\n !/^0+$/.test(span.spanId) &&\n isTraceInsightArtifact(span.artifact) &&\n span.artifact.role === 'span',\n )\n}\n\nexport function isTraceInsightAttribution(value: unknown): value is TraceInsightAttribution {\n if (!isTraceInsightEvidence(value)) return false\n const attribution = value as TraceInsightEvidence & Record<string, unknown>\n if (attribution.outcome === 'unknown') {\n return (\n attribution.evidenceClass === 'unknown' &&\n Array.isArray(attribution.reasons) &&\n attribution.reasons.length > 0 &&\n attribution.reasons.every(evidenceText)\n )\n }\n if (\n Object.values(value.subject).some((entry) => entry === null) ||\n Object.values(value.artifacts).some((artifact) => artifact === null) ||\n value.spans.length === 0 ||\n !isTraceInsightArtifact(attribution.proof)\n )\n return false\n if (attribution.outcome === 'tool-failure') {\n return (\n attribution.evidenceClass === 'validated-request-response' &&\n attribution.proof.role === 'execution' &&\n isTraceInsightArtifact(attribution.authority) &&\n attribution.authority.role === 'authority'\n )\n }\n if (attribution.outcome !== 'documentation-failure') return false\n if (attribution.evidenceClass === 'authoritative-execution') {\n return (\n (attribution.documentation === 'stale' || attribution.documentation === 'contradictory') &&\n attribution.proof.role === 'execution' &&\n isTraceInsightArtifact(attribution.authority) &&\n attribution.authority.role === 'authority'\n )\n }\n return (\n attribution.evidenceClass === 'paired-corrected-document' &&\n attribution.proof.role === 'publication' &&\n isTraceInsightArtifact(attribution.plan) &&\n attribution.plan.role === 'plan' &&\n isTraceInsightArtifact(attribution.correctedEvidence) &&\n attribution.correctedEvidence.role === 'binding' &&\n evidenceText(attribution.comparisonId)\n )\n}\n\nexport interface TraceInsightQuestion {\n id: string\n question: string\n why: string\n}\n\nexport interface TraceInsightPanelRole {\n id: string\n name: string\n responsibility: string\n}\n\nexport interface TraceInsightPromptInput {\n suite: TraceInsightSuite\n findings?: TraceInsightFinding[]\n agent?: Record<string, unknown>\n totals?: Record<string, unknown>\n maxRepresentativeTraces?: number\n}\n\nexport interface TraceInsightContext {\n suite: TraceInsightSuite\n scope: string\n keywords: string[]\n questions: TraceInsightQuestion[]\n panel: TraceInsightPanelRole[]\n findings: TraceInsightFinding[]\n agent: Record<string, unknown> | null\n totals: Record<string, unknown> | null\n}\n\nexport interface TraceInsightQualityGate {\n id: string\n label: string\n passed: boolean\n severity: 'critical' | 'high' | 'medium' | 'low'\n detail: string\n}\n\nexport interface TraceInsightReadiness {\n score: number\n grade: 'external-ready' | 'internal-review' | 'raw-analysis'\n gates: TraceInsightQualityGate[]\n}\n\nconst DOMAIN_STOP_WORDS = new Set([\n 'and',\n 'advanced',\n 'app',\n 'build',\n 'create',\n 'easy',\n 'expert',\n 'extreme',\n 'for',\n 'from',\n 'hard',\n 'implementation',\n 'integrate',\n 'medium',\n 'project',\n 'task',\n 'the',\n 'this',\n 'with',\n 'workflow',\n])\n\nexport function tokenizeDomainWords(value: string): string[] {\n return [...value.matchAll(/[A-Za-z][A-Za-z0-9.+#-]{2,}/g)]\n .map((match) => match[0].toLowerCase())\n .filter((word) => !DOMAIN_STOP_WORDS.has(word))\n}\n\nexport function inferDomainKeywords(suite: TraceInsightSuite): string[] {\n const suiteWords = new Set(tokenizeDomainWords(`${suite.name} ${suite.collectionId ?? ''}`))\n const source = [\n suite.name,\n suite.collectionId ?? '',\n ...suite.tasks.flatMap((task) => [\n task.id,\n task.name,\n task.prompt ?? '',\n task.difficulty ?? '',\n ...(task.tags ?? []),\n ...(task.gaps ?? []),\n ]),\n ].join(' ')\n const counts = new Map<string, number>()\n for (const word of tokenizeDomainWords(source)) counts.set(word, (counts.get(word) ?? 0) + 1)\n return [...counts.entries()]\n .filter(([word, count]) => count >= 2 || suiteWords.has(word))\n .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n .map(([word]) => word)\n .slice(0, 18)\n}\n\nexport function domainEvidencePattern(keywords: string[]): RegExp {\n const escaped = keywords\n .filter((keyword) => keyword.length >= 3)\n .map((keyword) => keyword.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'))\n return escaped.length > 0\n ? new RegExp(`(?<![A-Za-z0-9])(?:${escaped.join('|')})(?![A-Za-z0-9])`, 'i')\n : /(?<![A-Za-z0-9])(?:sdk|api|css|dns|xml|provider|client|service|integration|webhook|transaction|auth|oauth|graphql|rest)(?![A-Za-z0-9])/i\n}\n\nexport function describeTraceInsightScope(suite: TraceInsightSuite): string {\n const taskLabel =\n suite.tasks.length === 1\n ? '1 implementation task'\n : `${suite.tasks.length} implementation tasks`\n const tags = new Map<string, number>()\n for (const task of suite.tasks) {\n for (const tag of task.tags ?? []) tags.set(tag, (tags.get(tag) ?? 0) + 1)\n }\n const topTags = [...tags.entries()]\n .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n .slice(0, 8)\n .map(([tag]) => tag)\n if (topTags.length > 0) return `${taskLabel} across ${topTags.join(', ')}.`\n const difficulties = [\n ...new Set(\n suite.tasks.map((task) => task.difficulty).filter((value): value is string => Boolean(value)),\n ),\n ].join(', ')\n return `${taskLabel} across ${difficulties || 'the selected benchmark scope'}.`\n}\n\nfunction planTraceInsightQuestions(input: TraceInsightPromptInput): TraceInsightQuestion[] {\n const hasFailures = input.suite.tasks.some((task) => task.outcome && task.outcome !== 'satisfied')\n const hasMultipleShots = input.suite.tasks.some((task) =>\n (task.gaps ?? []).some((gap) => /shot|review|retry|continue/i.test(gap)),\n )\n const questions: TraceInsightQuestion[] = [\n {\n id: 'execution-path',\n question: 'What did the worker actually do before the first meaningful implementation edit?',\n why: 'Separates grounded execution from polished but shallow output.',\n },\n {\n id: 'research-grounding',\n question:\n 'Did the worker inspect docs, source, examples, or package references before committing to an implementation path?',\n why: 'Identifies whether failures came from weak retrieval, weak examples, or premature coding.',\n },\n {\n id: 'domain-proof',\n question:\n 'Which tasks produced executable domain proof versus UI copy, placeholders, or inferred behavior?',\n why: 'Keeps product-quality claims tied to concrete evidence.',\n },\n {\n id: 'root-cause',\n question:\n 'For each major failure cluster, is the likely root cause prompt/scaffold, docs/examples, SDK/API ergonomics, evaluator, runtime, or model behavior?',\n why: 'Turns trace observations into actionable ownership.',\n },\n {\n id: 'evidence-quality',\n question:\n 'Which external-facing claims are directly supported by trace ids, span ids, verifier findings, reviewer notes, or generated code?',\n why: 'Prevents unsupported customer-report conclusions.',\n },\n ]\n if (hasMultipleShots) {\n questions.push({\n id: 'reviewer-lift',\n question: 'Where did reviewer feedback improve score, stall, or regress across shots?',\n why: 'Shows whether the driver loop is learning or merely repeating work.',\n })\n }\n if (hasFailures) {\n questions.push({\n id: 'optimization-targets',\n question:\n 'Which prompt, evaluator, scaffold, or workflow changes should feed the next GEPA/autoresearch optimization run?',\n why: 'Connects benchmark evidence to the optimization loop.',\n })\n }\n return questions\n}\n\nexport function buildTraceInsightContext(input: TraceInsightPromptInput): TraceInsightContext {\n return {\n suite: input.suite,\n scope: describeTraceInsightScope(input.suite),\n keywords: inferDomainKeywords(input.suite),\n questions: planTraceInsightQuestions(input),\n panel: defaultTraceInsightPanel(),\n findings: input.findings ?? [],\n agent: input.agent ?? null,\n totals: input.totals ?? null,\n }\n}\n\nexport function scoreTraceInsightReadiness(context: TraceInsightContext): TraceInsightReadiness {\n const failedTasks = context.suite.tasks.filter(\n (task) => task.outcome && task.outcome !== 'satisfied',\n )\n const findingTaskIds = new Set(context.findings.flatMap((finding) => finding.taskIds))\n const failedTasksWithFindings = failedTasks.filter((task) => findingTaskIds.has(task.id))\n const tasksWithGaps = context.suite.tasks.filter((task) => (task.gaps ?? []).length > 0)\n const gates: TraceInsightQualityGate[] = [\n {\n id: 'domain-context',\n label: 'Domain context inferred',\n passed: context.keywords.length > 0,\n severity: 'high',\n detail:\n context.keywords.length > 0\n ? `${context.keywords.length} domain terms inferred: ${context.keywords.slice(0, 8).join(', ')}`\n : 'No domain terms were inferred from suite, tasks, prompts, tags, or gaps.',\n },\n {\n id: 'panel-coverage',\n label: 'Analyst panel planned',\n passed: context.panel.length >= 4 && context.questions.length >= 5,\n severity: 'high',\n detail: `${context.panel.length} panel roles and ${context.questions.length} investigation questions planned.`,\n },\n {\n id: 'failure-coverage',\n label: 'Failures mapped to findings',\n passed:\n failedTasks.length === 0 || failedTasksWithFindings.length / failedTasks.length >= 0.5,\n severity: 'critical',\n detail:\n failedTasks.length === 0\n ? 'No failed tasks in suite.'\n : `${failedTasksWithFindings.length}/${failedTasks.length} failed tasks appear in finding clusters.`,\n },\n {\n id: 'gap-evidence',\n label: 'Task gaps captured',\n passed: failedTasks.length === 0 || tasksWithGaps.length / failedTasks.length >= 0.5,\n severity: 'medium',\n detail: `${tasksWithGaps.length} tasks include explicit evaluator or analyst gaps.`,\n },\n {\n id: 'attribution-evidence',\n label: 'Evidence-classed customer findings',\n passed:\n failedTasks.every((task) =>\n context.findings.some(\n (finding) =>\n finding.taskIds.includes(task.id) && finding.attribution?.subject.taskId === task.id,\n ),\n ) &&\n context.findings.every(\n (finding) =>\n isTraceInsightAttribution(finding.attribution) &&\n finding.taskIds.length === 1 &&\n finding.taskIds[0] === finding.attribution.subject.taskId,\n ),\n severity: 'critical',\n detail:\n 'Every finding needs an explicit evidence class and byte-backed links, or an explicit unknown; prose is not attribution evidence.',\n },\n ]\n const penalty = gates.reduce((sum, gate) => {\n if (gate.passed) return sum\n if (gate.severity === 'critical') return sum + 35\n if (gate.severity === 'high') return sum + 20\n if (gate.severity === 'medium') return sum + 10\n return sum + 5\n }, 0)\n const score = Math.max(0, Math.min(1, 1 - penalty / 100))\n return {\n score,\n grade: score >= 0.9 ? 'external-ready' : score >= 0.7 ? 'internal-review' : 'raw-analysis',\n gates,\n }\n}\n\nfunction defaultTraceInsightPanel(): TraceInsightPanelRole[] {\n return [\n {\n id: 'trace-forensics',\n name: 'Trace Forensics',\n responsibility:\n 'Reconstruct what the worker did in order, including research, edits, reviewer interventions, verifier feedback, and stop reason.',\n },\n {\n id: 'root-cause',\n name: 'Root Cause',\n responsibility:\n 'Map failures to prompt/scaffold, docs/examples, SDK/API/product ergonomics, evaluator, runtime, or model behavior.',\n },\n {\n id: 'optimization',\n name: 'Optimization',\n responsibility:\n 'Identify prompt, reviewer, evaluator, scaffold, and GEPA/autoresearch changes that should be tested next.',\n },\n {\n id: 'external-evidence',\n name: 'External Evidence',\n responsibility:\n 'Separate customer-safe claims from internal harness findings and reject conclusions without task, trace, span, code, reviewer, or verifier evidence.',\n },\n ]\n}\n\nexport function buildTraceInsightPrompt(input: TraceInsightPromptInput): string {\n const context = buildTraceInsightContext(input)\n const maxRepresentativeTraces = input.maxRepresentativeTraces ?? 6\n return `Analyze this benchmark run and produce evidence-backed trace intelligence.\n\nAudience:\n- internal AI/product leadership\n- possible customer-facing report for ${input.suite.name}\n\nInvestigation plan:\n${context.questions.map((item, index) => `${index + 1}. ${item.question} (${item.why})`).join('\\n')}\n\nAnalyst panel:\n${context.panel.map((role) => `- ${role.name}: ${role.responsibility}`).join('\\n')}\n\nIf the task branches are independent, use subagents for the panel roles above and aggregate their findings. Do not run a panel role unless its answer will change the final report.\n\nRequired output:\n1. Executive verdict: what this run proves and does not prove.\n2. The investigation questions you answered and the evidence used.\n3. Failure taxonomy: agent prompting, evaluator/harness, docs/examples, SDK/API/product integration, infra.\n4. Evidence-backed examples with trace ids/task ids and concrete verifier findings.\n5. Highest-ROI fixes for the benchmark harness, prompt/GEPA optimization, and customer-facing product/docs surface.\n6. What is safe for an external report versus what must stay internal.\n7. One rerun plan that would validate lift after optimization.\n\nBudget:\n- Inspect the dataset overview, the failure summary, and at most ${maxRepresentativeTraces} representative traces.\n- Prefer traces named in the failure summary over broad exploration.\n- Do not do exhaustive trace sweeps.\n- Return the final report as soon as the taxonomy and examples are supported.\n\nRun summary:\n${JSON.stringify(\n {\n suite: input.suite.name,\n scope: context.scope,\n inferredKeywords: context.keywords,\n agent: context.agent,\n totals: context.totals,\n findings: context.findings.map((finding) => ({\n kind: finding.kind,\n severity: finding.severity,\n taskCount: finding.taskIds.length,\n proposedFixClass: finding.proposedFixClass,\n attribution: finding.attribution,\n })),\n failures: input.suite.tasks\n .filter((task) => task.outcome && task.outcome !== 'satisfied')\n .map((task) => ({\n task: task.id,\n difficulty: task.difficulty,\n outcome: task.outcome,\n score: task.score,\n gaps: task.gaps ?? [],\n })),\n },\n null,\n 2,\n)}\n\nUse the trace tools. Do not invent facts. Cite task ids. Separate customer-facing claims from internal harness/model findings.\nCustomer attribution must preserve the supplied evidence class and artifact links. A narrative, regex label, observational rate, or document age is not causal evidence. Without validated request/response execution or a supported registered corrected-document comparison, report unknown; do not guess a failing company or tool.`\n}\n","/** Canonical flattened OTLP span shape shared by trace producers and readers. */\n\nimport type { SpanStatus } from './schema'\n\nexport type OtlpStatusCode = 'STATUS_CODE_OK' | 'STATUS_CODE_ERROR' | 'STATUS_CODE_UNSET'\n\nexport interface OtlpFlatLine {\n trace_id: string\n span_id: string\n parent_span_id: string | null\n name: string\n kind: string\n start_time: string\n end_time: string\n status: {\n code: OtlpStatusCode\n message?: string\n }\n resource: { attributes: Record<string, unknown> }\n attributes: Record<string, unknown>\n events?: Array<{ name: string; timeUnixNano?: string; attributes?: Record<string, unknown> }>\n}\n\ninterface CreateOtlpFlatLineInput {\n traceId: string\n spanId: string\n parentSpanId: string | null\n name: string\n kind: string\n startTime: string\n endTime: string\n statusCode: OtlpStatusCode\n statusMessage?: string\n resource: OtlpFlatLine['resource']\n attributes: Record<string, unknown>\n events?: OtlpFlatLine['events']\n}\n\nexport function createOtlpFlatLine(input: CreateOtlpFlatLineInput): OtlpFlatLine {\n return {\n trace_id: input.traceId,\n span_id: input.spanId,\n parent_span_id: input.parentSpanId,\n name: input.name,\n kind: input.kind,\n start_time: input.startTime,\n end_time: input.endTime,\n status: {\n code: input.statusCode,\n ...(input.statusMessage !== undefined ? { message: input.statusMessage } : {}),\n },\n resource: input.resource,\n attributes: input.attributes,\n ...(input.events && input.events.length > 0 ? { events: input.events } : {}),\n }\n}\n\n/** Map the canonical trace status while letting each caller choose its legacy default. */\nexport function spanStatusToOtlp(\n status: SpanStatus | undefined,\n error: string | undefined,\n defaultCode: OtlpStatusCode,\n): OtlpStatusCode {\n if (status === 'error' || error) return 'STATUS_CODE_ERROR'\n if (status === 'ok') return 'STATUS_CODE_OK'\n return defaultCode\n}\n\n/** Convert epoch milliseconds, returning `undefined` for invalid or out-of-range values. */\nexport function epochMillisToIso(value: number): string | undefined {\n if (!Number.isFinite(value)) return undefined\n try {\n return new Date(value).toISOString()\n } catch {\n return undefined\n }\n}\n","import { CaptureIntegrityError } from '../errors'\nimport { applyToolSpanOtlpAttributes, OPENINFERENCE_SPAN_KIND } from '../trace/otlp-attributes'\nimport { createOtlpFlatLine, epochMillisToIso, spanStatusToOtlp } from '../trace/otlp-flat'\nimport type { ToolSpan } from '../trace/schema'\nimport type { TraceAnalysisStore } from './store'\nimport { BufferTraceStore } from './store-otlp'\nimport type { ToolSpansToTraceAnalysisStoreOptions } from './store-otlp-buffered'\n\n/** Missing tool spans cannot distinguish a tool-free run from broken capture. */\nexport class ToolTraceMissingError extends CaptureIntegrityError {\n constructor() {\n super('toolSpansToTraceAnalysisStore: no tool spans supplied; trace evidence is missing')\n }\n}\n\n/**\n * Snapshot canonical tool spans into the read interface used by trace analysts.\n * One run becomes one trace while arguments, results, errors, and timing remain searchable.\n */\nexport function toolSpansToTraceAnalysisStore(\n spans: readonly ToolSpan[] | null | undefined,\n options: ToolSpansToTraceAnalysisStoreOptions = {},\n): TraceAnalysisStore {\n if (!spans || spans.length === 0) throw new ToolTraceMissingError()\n\n const seen = new Set<string>()\n const lines = spans.map((span, index) => {\n assertToolSpanIdentity(span, index)\n const identity = `${span.runId}\\u0000${span.spanId}`\n if (seen.has(identity)) {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: duplicate span '${span.spanId}' in run '${span.runId}'`,\n )\n }\n seen.add(identity)\n\n const attributes = { ...(span.attributes ?? {}) }\n applyToolSpanOtlpAttributes(attributes, span)\n attributes[OPENINFERENCE_SPAN_KIND] = 'TOOL'\n\n const endedAt = span.endedAt ?? span.startedAt + (span.latencyMs ?? 0)\n const line = createOtlpFlatLine({\n traceId: span.runId,\n spanId: span.spanId,\n parentSpanId: span.parentSpanId ?? null,\n name: span.name,\n kind: 'SPAN_KIND_INTERNAL',\n startTime: toolSpanTimeIso(span.startedAt, span.spanId, 'startedAt'),\n endTime: toolSpanTimeIso(endedAt, span.spanId, 'endedAt'),\n statusCode: spanStatusToOtlp(span.status, span.error, 'STATUS_CODE_UNSET'),\n statusMessage: span.error,\n resource: { attributes: {} },\n attributes,\n })\n try {\n return JSON.stringify(line)\n } catch (cause) {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span '${span.spanId}' in run '${span.runId}' is not JSON-serializable`,\n { cause },\n )\n }\n })\n\n return new BufferTraceStore(Buffer.from(`${lines.join('\\n')}\\n`, 'utf8'), options)\n}\n\nfunction assertToolSpanIdentity(span: ToolSpan, index: number): void {\n if (span.kind !== 'tool') {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span at index ${index} has kind '${String(span.kind)}', not 'tool'`,\n )\n }\n if (!span.runId || !span.spanId || !span.name || !span.toolName) {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span at index ${index} is missing runId, spanId, name, or toolName`,\n )\n }\n if (!Number.isFinite(span.startedAt)) {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span '${span.spanId}' has invalid startedAt`,\n )\n }\n if (span.endedAt !== undefined && !Number.isFinite(span.endedAt)) {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span '${span.spanId}' has invalid endedAt`,\n )\n }\n if (span.endedAt !== undefined && span.endedAt < span.startedAt) {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span '${span.spanId}' ends before it starts`,\n )\n }\n if (span.latencyMs !== undefined && (!Number.isFinite(span.latencyMs) || span.latencyMs < 0)) {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span '${span.spanId}' has invalid latencyMs`,\n )\n }\n}\n\nfunction toolSpanTimeIso(value: number, spanId: string, field: string): string {\n const iso = epochMillisToIso(value)\n if (iso) return iso\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span '${spanId}' has invalid ${field}`,\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA0DA,MAAM,mBAAmB;AAEzB,SAAS,gBAAgB,SAAkE;C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,YAAY,KAAA,KAAa,CAAC,OAAO,SAAS,KAAK,OAAO,GAC7D,MAAM,IAAI,sBACR,wCAAwC,KAAK,OAAO,sBACtD;CAEF,IAAI,KAAK,YAAY,KAAA,KAAa,KAAK,UAAU,KAAK,WACpD,MAAM,IAAI,sBACR,wCAAwC,KAAK,OAAO,wBACtD;CAEF,IAAI,KAAK,cAAc,KAAA,MAAc,CAAC,OAAO,SAAS,KAAK,SAAS,KAAK,KAAK,YAAY,IACxF,MAAM,IAAI,sBACR,wCAAwC,KAAK,OAAO,wBACtD;AAEJ;AAEA,SAAS,gBAAgB,OAAe,QAAgB,OAAuB;CAC7E,MAAM,MAAM,iBAAiB,KAAK;CAClC,IAAI,KAAK,OAAO;CAChB,MAAM,IAAI,sBACR,wCAAwC,OAAO,gBAAgB,OACjE;AACF"}
|
|
@@ -8,6 +8,7 @@ import { i as SearchArtifactRef } from "./search-ledger-types-qiYRUo_N.js";
|
|
|
8
8
|
import { s as TraceStore } from "./store-CMs5wGXP.js";
|
|
9
9
|
import { i as TraceAnalystLimits, r as TraceAnalysisEngineResult, t as TraceAnalysisEngine } from "./engine-CaHaCc3W.js";
|
|
10
10
|
import { t as TraceToolGroupName } from "./tool-groups-C3K-d3gd.js";
|
|
11
|
+
import { OtlpResourceSpans, OtlpSpan, OtlpTraceExport } from "@tangle-network/agent-trace-contract/otlp";
|
|
11
12
|
interface AnalyzeTracesInput {
|
|
12
13
|
question: string;
|
|
13
14
|
id?: string;
|
|
@@ -158,49 +159,7 @@ declare function describeTraceInsightScope(suite: TraceInsightSuite): string;
|
|
|
158
159
|
declare function buildTraceInsightContext(input: TraceInsightPromptInput): TraceInsightContext;
|
|
159
160
|
declare function scoreTraceInsightReadiness(context: TraceInsightContext): TraceInsightReadiness;
|
|
160
161
|
declare function buildTraceInsightPrompt(input: TraceInsightPromptInput): string;
|
|
161
|
-
|
|
162
|
-
name: string;
|
|
163
|
-
version: string;
|
|
164
|
-
};
|
|
165
|
-
interface OtlpSpan {
|
|
166
|
-
traceId: string;
|
|
167
|
-
spanId: string;
|
|
168
|
-
parentSpanId?: string;
|
|
169
|
-
name: string;
|
|
170
|
-
kind: number;
|
|
171
|
-
startTimeUnixNano: string;
|
|
172
|
-
endTimeUnixNano: string;
|
|
173
|
-
attributes: Array<{
|
|
174
|
-
key: string;
|
|
175
|
-
value: {
|
|
176
|
-
stringValue?: string;
|
|
177
|
-
intValue?: string;
|
|
178
|
-
doubleValue?: number;
|
|
179
|
-
boolValue?: boolean;
|
|
180
|
-
};
|
|
181
|
-
}>;
|
|
182
|
-
events?: Array<{
|
|
183
|
-
timeUnixNano: string;
|
|
184
|
-
name: string;
|
|
185
|
-
attributes?: OtlpSpan['attributes'];
|
|
186
|
-
}>;
|
|
187
|
-
status?: {
|
|
188
|
-
code: number;
|
|
189
|
-
message?: string;
|
|
190
|
-
};
|
|
191
|
-
}
|
|
192
|
-
interface OtlpResourceSpans {
|
|
193
|
-
resource: {
|
|
194
|
-
attributes: OtlpSpan['attributes'];
|
|
195
|
-
};
|
|
196
|
-
scopeSpans: Array<{
|
|
197
|
-
scope: typeof OTEL_AGENT_EVAL_SCOPE;
|
|
198
|
-
spans: OtlpSpan[];
|
|
199
|
-
}>;
|
|
200
|
-
}
|
|
201
|
-
interface OtlpExport {
|
|
202
|
-
resourceSpans: OtlpResourceSpans[];
|
|
203
|
-
}
|
|
162
|
+
type OtlpExport = OtlpTraceExport;
|
|
204
163
|
/** Export a single run's spans + events in OTLP/JSON. */
|
|
205
164
|
declare function exportRunAsOtlp(store: TraceStore, runId: string, resourceAttrs?: Record<string, string | number | boolean>): Promise<OtlpExport>;
|
|
206
165
|
interface ToolSpansToTraceAnalysisStoreOptions {
|
|
@@ -394,4 +353,4 @@ declare class ToolTraceMissingError extends CaptureIntegrityError {
|
|
|
394
353
|
*/
|
|
395
354
|
declare function toolSpansToTraceAnalysisStore(spans: readonly ToolSpan[] | null | undefined, options?: ToolSpansToTraceAnalysisStoreOptions): TraceAnalysisStore;
|
|
396
355
|
export { TraceInsightReadiness as A, isTraceInsightEvidence as B, TraceInsightContext as C, TraceInsightPromptInput as D, TraceInsightPanelRole as E, describeTraceInsightScope as F, AnalyzeTracesResult as G, tokenizeDomainWords as H, domainEvidencePattern as I, analyzeTraces as K, inferDomainKeywords as L, TraceInsightTask as M, buildTraceInsightContext as N, TraceInsightQualityGate as O, buildTraceInsightPrompt as P, isTraceInsightArtifact as R, TraceInsightAttribution as S, TraceInsightFinding as T, AnalyzeTracesInput as U, scoreTraceInsightReadiness as V, AnalyzeTracesOptions as W, ToolSpansToTraceAnalysisStoreOptions as _, captureFetchToRawSink as a, OtlpSpan as b, ExtractedUsage as c, extractUsageFromSse as d, OtlpFileTraceStore as f, spanRecordsToTraceAnalysisStore as g, otlpTextToTraceAnalysisStore as h, CaptureFetchOptions as i, TraceInsightSuite as j, TraceInsightQuestion as k, SseUsageMode as l, SpanRecordsToTraceAnalysisStoreOptions as m, toolSpansToTraceAnalysisStore as n, OtlpFlatLine as o, OtlpFileTraceStoreOptions as p, CaptureFetchContext as r, ExtractUsageFromSseOptions as s, ToolTraceMissingError as t, extractUsage as u, OtlpExport as v, TraceInsightEvidence as w, exportRunAsOtlp as x, OtlpResourceSpans as y, isTraceInsightAttribution as z };
|
|
397
|
-
//# sourceMappingURL=store-tool-spans-
|
|
356
|
+
//# sourceMappingURL=store-tool-spans-lWf6INTH.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store-tool-spans-lWf6INTH.d.ts","names":[],"sources":["../src/trace-analyst/analyst.ts","../src/trace-analyst/insights.ts","../src/trace/otel.ts","../src/trace-analyst/store-otlp-buffered.ts","../src/trace-analyst/store-otlp.ts","../src/trace/extract-usage.ts","../src/trace/otlp-flat.ts","../src/trace/capture-fetch.ts","../src/trace-analyst/store-tool-spans.ts"],"mappings":";;;;;;;;;;;UAciB;EACf;EACA;EACA;EACA;;KAGU,sBAAsB;UAEjB;;EAEf,iBAAiB;;EAEjB,QAA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f;;EAEA;;;EAGA;;EAEA;;EAEA;;UAGe;;EAEf,WAAW;;;EAGX;;;EAGA;;;;;;;;EAQA,WAAW,OAAO,gBAAgB,KAAK;;EAEvC,eAAe;;iBAkDD,sBACd,cAAc,WAAW,OACzB,MAAM,iBACN,KAAK,qBACL,OAAM,6BACE,WAAW;;cCrGR,8BAA8B;;;;;;;iBAU3B,8BACd,gBAAgB,+BAChB,UAAS,uCACR"}
|
|
@@ -3,13 +3,12 @@ import { l as hashJson } from "./agent-profile-cell-CT5JYueM.js";
|
|
|
3
3
|
import { r as observedSplitScore } from "./reward-P0VD_Aft.js";
|
|
4
4
|
import { n as renderResearchHtml } from "./reporting-html-DMXIjATy.js";
|
|
5
5
|
import { t as interpolatedQuantile } from "./quantile-CncXP-Ss.js";
|
|
6
|
-
import { a as wilcoxonSignedRank, r as pairRunRecords } from "./paired-arms-
|
|
7
|
-
import {
|
|
8
|
-
import { t as confidenceInterval } from "./descriptive-
|
|
6
|
+
import { a as wilcoxonSignedRank, r as pairRunRecords } from "./paired-arms-C0Vd9bGG.js";
|
|
7
|
+
import { s as makeRng, t as mean } from "./mean-DDFhslBt.js";
|
|
8
|
+
import { t as confidenceInterval } from "./descriptive-BTzLL-aj.js";
|
|
9
9
|
import { t as benjaminiHochberg } from "./multiplicity-DAd4xaDC.js";
|
|
10
|
-
import { r as pairedBootstrap } from "./paired-tests-
|
|
11
|
-
import { r as pairedMde } from "./power-and-mde-
|
|
12
|
-
import { t as mean } from "./mean-BPuUNznQ.js";
|
|
10
|
+
import { r as pairedBootstrap } from "./paired-tests-kASEKpc-.js";
|
|
11
|
+
import { r as pairedMde } from "./power-and-mde-CRxepy8y.js";
|
|
13
12
|
// src/research-report-render.ts
|
|
14
13
|
function renderResearchMarkdown(report) {
|
|
15
14
|
const lines = [];
|
|
@@ -841,4 +840,4 @@ async function researchReport(runs, opts = {}) {
|
|
|
841
840
|
}
|
|
842
841
|
export { cliffsDelta as a, pairedCohensDz as c, summaryTable as i, RESEARCH_REPORT_HARD_PAIR_FLOOR as l, gainHistogram as n, cohensD as o, paretoChart as r, interpretCliffs as s, researchReport as t };
|
|
843
842
|
|
|
844
|
-
//# sourceMappingURL=summary-report-
|
|
843
|
+
//# sourceMappingURL=summary-report-BstMpOfy.js.map
|