@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 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"descriptive-cPwITVfy.js","names":[],"sources":["../src/statistics/descriptive.ts"],"sourcesContent":["/**\n * Descriptive statistics: means, bootstrap spread, correlation, and the\n * weighted judge-dimension composite. Nothing here is a significance test.\n */\n\nimport { ValidationError } from '../errors'\nimport { assertFiniteSample, makeRng } from './internal'\n\n/** Weighted mean — falls back to uniform weights when omitted */\nexport function weightedMean(scores: { score: number; weight?: number }[]): number {\n if (scores.length === 0) return 0\n let totalWeight = 0\n let weightedSum = 0\n for (const { score, weight } of scores) {\n const w = weight ?? 1\n weightedSum += score * w\n totalWeight += w\n }\n return totalWeight > 0 ? weightedSum / totalWeight : 0\n}\n\n/**\n * Percentile bootstrap confidence interval on the mean of `scores`.\n *\n * Descriptive spread. It is not a significance test, and at small n its bounds\n * are anti-conservative in the same way {@link pairedBootstrap}'s are — see\n * {@link BOOTSTRAP_GATE_MIN_N}. With no `seed` the resampling is seeded from\n * the scores themselves, so the interval is reproducible either way.\n */\nexport function confidenceInterval(\n scores: number[],\n confidence = 0.95,\n opts: { seed?: number; resamples?: number } = {},\n): { mean: number; lower: number; upper: number } {\n if (scores.length === 0) return { mean: 0, lower: 0, upper: 0 }\n if (scores.length === 1) return { mean: scores[0]!, lower: scores[0]!, upper: scores[0]! }\n\n const n = scores.length\n const mean = scores.reduce((a, b) => a + b, 0) / n\n\n const B = opts.resamples ?? 1000\n const rng = makeRng(opts.seed, scores)\n const bootstrapMeans: number[] = []\n\n for (let i = 0; i < B; i++) {\n let sum = 0\n for (let j = 0; j < n; j++) {\n sum += scores[Math.floor(rng() * n)]!\n }\n bootstrapMeans.push(sum / n)\n }\n\n bootstrapMeans.sort((a, b) => a - b)\n\n const alpha = 1 - confidence\n const lowerIdx = Math.floor((alpha / 2) * B)\n const upperIdx = Math.floor((1 - alpha / 2) * B) - 1\n\n return {\n mean,\n lower: bootstrapMeans[lowerIdx]!,\n upper: bootstrapMeans[Math.min(upperIdx, B - 1)]!,\n }\n}\n\n/** Partial credit: returns 0-1 ratio of current toward target */\nexport function partialCredit(current: number, target: number): number {\n if (target <= 0) return 1\n return Math.min(1, Math.max(0, current / target))\n}\n\n/** Distribution summary of a number series: count, extremes, quantiles, sum. */\nexport interface SeriesDistribution {\n readonly n: number\n readonly min: number\n readonly p50: number\n readonly p90: number\n readonly max: number\n readonly sum: number\n readonly percentiles?: Readonly<Record<number, number>>\n readonly medianInterval?: {\n readonly method: 'normal-order-statistics'\n readonly criticalValue: number\n readonly sampleSize: number\n readonly lowRank: number\n readonly highRank: number\n readonly low: number\n readonly high: number\n }\n}\n\nexport interface SeriesDistributionOptions {\n /** Nearest-rank percentiles on a 0–100 scale, including fractional tails. */\n percentiles?: readonly number[]\n /** Descriptive median rank band, not a bootstrap interval or promotion test. */\n medianInterval?: { criticalValue: number }\n}\n\n/**\n * Fold a number series into its distribution summary. Quantiles use the\n * nearest-rank definition — the `ceil(q·n)`-th order statistic — so every\n * reported quantile is a value from the series. Returns `null` for an empty\n * series: an empty series has no distribution, and a zero-filled summary\n * would read as a measured all-zero series.\n */\nexport function summarizeNumberSeries(\n values: readonly number[],\n options?: SeriesDistributionOptions,\n): SeriesDistribution | null {\n const criticalValue = options?.medianInterval?.criticalValue\n if (options) {\n assertFiniteSample('summarizeNumberSeries', 'values', values)\n for (const percentile of options.percentiles ?? []) {\n if (!Number.isFinite(percentile) || percentile < 0 || percentile > 100) {\n throw new ValidationError(\n 'summarizeNumberSeries: percentiles must be finite and between 0 and 100',\n )\n }\n }\n if (\n options.medianInterval &&\n (criticalValue === undefined || !Number.isFinite(criticalValue) || criticalValue < 0)\n ) {\n throw new ValidationError(\n 'summarizeNumberSeries: median criticalValue must be finite and nonnegative',\n )\n }\n }\n if (values.length === 0) return null\n const sorted = [...values].sort((a, b) => a - b)\n const n = sorted.length\n const rank = (q: number): number =>\n sorted[Math.min(n - 1, Math.max(0, Math.ceil(q * n) - 1))] as number\n const sum = sorted.reduce((a, b) => a + b, 0)\n if (options && !Number.isFinite(sum)) {\n throw new ValidationError('summarizeNumberSeries: sample sum exceeded finite range')\n }\n const spread = criticalValue === undefined ? undefined : (criticalValue / 2) * Math.sqrt(n)\n const lowRank = spread === undefined ? 1 : Math.max(1, Math.floor(n / 2 - spread))\n const highRank = spread === undefined ? n : Math.min(n, Math.ceil(n / 2 + 1 + spread))\n return {\n n,\n min: sorted[0] as number,\n p50: rank(0.5),\n p90: rank(0.9),\n max: sorted[sorted.length - 1] as number,\n sum,\n ...(options?.percentiles === undefined\n ? {}\n : {\n percentiles: Object.fromEntries(\n options.percentiles.map((percentile) => [percentile, rank(percentile / 100)]),\n ),\n }),\n ...(criticalValue === undefined\n ? {}\n : {\n medianInterval: {\n method: 'normal-order-statistics' as const,\n criticalValue,\n sampleSize: n,\n lowRank,\n highRank,\n low: sorted[lowRank - 1] as number,\n high: sorted[highRank - 1] as number,\n },\n }),\n }\n}\n\n// ── Correlation (Pearson / Spearman) ─────────────────────────────────\n//\n// The single source for linear (Pearson) and rank (Spearman) correlation.\n// Edge-case contract is explicit so every caller agrees on what a\n// degenerate input means:\n// - length mismatch or n < 2 → NaN (correlation is undefined; not 0)\n// - both series constant → 1 (degenerate perfect agreement)\n// - exactly one series constant → 0 (no covariation to detect)\n// Returning NaN for n < 2 (rather than 0) keeps \"not enough data\" distinct\n// from \"measured zero correlation\", which a 0 would silently conflate.\n\n/**\n * Average-rank-with-ties transform (1-indexed). Tied values receive the mean\n * of the ranks they span, the standard correction for Spearman's ρ.\n */\nexport function ranks(xs: number[]): number[] {\n const indexed = xs.map((v, i) => ({ v, i })).sort((a, b) => a.v - b.v)\n const r = new Array<number>(xs.length)\n let i = 0\n while (i < indexed.length) {\n let j = i\n while (j + 1 < indexed.length && indexed[j + 1]!.v === indexed[i]!.v) j++\n const avg = (i + j) / 2 + 1\n for (let k = i; k <= j; k++) r[indexed[k]!.i] = avg\n i = j + 1\n }\n return r\n}\n\n/**\n * Pearson product-moment correlation coefficient r ∈ [-1, 1] between two\n * equal-length series. See the edge-case contract above: NaN for n < 2 or\n * unequal lengths, 1 when both series are constant, 0 when exactly one is.\n */\nexport function pearsonR(a: number[], b: number[]): number {\n if (a.length !== b.length || a.length < 2) return Number.NaN\n const n = a.length\n const meanA = a.reduce((s, v) => s + v, 0) / n\n const meanB = b.reduce((s, v) => s + v, 0) / n\n let num = 0\n let varA = 0\n let varB = 0\n for (let i = 0; i < n; i++) {\n const da = a[i]! - meanA\n const db = b[i]! - meanB\n num += da * db\n varA += da * da\n varB += db * db\n }\n if (varA === 0 || varB === 0) return varA === 0 && varB === 0 ? 1 : 0\n return num / Math.sqrt(varA * varB)\n}\n\n/**\n * Spearman's rank correlation ρ — Pearson over the average-rank-with-ties\n * transform of each series. Same edge-case contract as {@link pearsonR}.\n */\nexport function spearmanR(a: number[], b: number[]): number {\n if (a.length !== b.length || a.length < 2) return Number.NaN\n return pearsonR(ranks(a), ranks(b))\n}\n\nexport interface WeightedCompositeInput {\n /** Per-dimension scores (typically 0..1). */\n dims: Record<string, number>\n /** Weight per dimension. Every weighted dimension MUST be present in\n * `dims` — a weight for an absent dimension is a config error and throws,\n * because silently dropping it would renormalise the composite onto a\n * different denominator than intended. */\n weights: Record<string, number>\n /** Optional pass threshold; when set, the result reports `pass`. */\n threshold?: number\n}\n\nexport interface WeightedCompositeResult {\n composite: number\n pass?: boolean\n}\n\n/**\n * Weighted composite over judge dimensions: `Σ(score_d · w_d) / Σ(w_d)` across\n * the weighted dimensions. The canonical replacement for the per-consumer\n * hand-rolled composite math (tax/legal/creative/gtm each ship a copy).\n *\n * Fail-loud: throws if a weighted dimension is missing from `dims`, if any\n * weight is negative, or if the weights sum to 0 — none of which can produce\n * a meaningful composite.\n */\nexport function weightedComposite(input: WeightedCompositeInput): WeightedCompositeResult {\n const entries = Object.entries(input.weights)\n if (entries.length === 0) {\n throw new Error('weightedComposite: `weights` is empty — nothing to combine')\n }\n let weightedSum = 0\n let weightTotal = 0\n for (const [dim, weight] of entries) {\n if (weight < 0) {\n throw new Error(`weightedComposite: weight for '${dim}' is negative (${weight})`)\n }\n if (!(dim in input.dims)) {\n throw new Error(\n `weightedComposite: weighted dimension '${dim}' is absent from \\`dims\\` — ` +\n 'refusing to renormalise onto a different denominator',\n )\n }\n weightedSum += input.dims[dim]! * weight\n weightTotal += weight\n }\n if (weightTotal === 0) {\n throw new Error('weightedComposite: weights sum to 0 — composite is undefined')\n }\n const composite = weightedSum / weightTotal\n return input.threshold === undefined\n ? { composite }\n : { composite, pass: composite >= input.threshold }\n}\n"],"mappings":";;;;;;;;AASA,SAAgB,aAAa,QAAsD;CACjF,IAAI,OAAO,WAAW,GAAG,OAAO;CAChC,IAAI,cAAc;CAClB,IAAI,cAAc;CAClB,KAAK,MAAM,EAAE,OAAO,YAAY,QAAQ;EACtC,MAAM,IAAI,UAAU;EACpB,eAAe,QAAQ;EACvB,eAAe;CACjB;CACA,OAAO,cAAc,IAAI,cAAc,cAAc;AACvD;;;;;;;;;AAU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W,EAAE,UAAU,EAAE,SAAS,GAAG,OAAO;CAClD,OAAO,SAAS,MAAM,CAAC,GAAG,MAAM,CAAC,CAAC;AACpC;;;;;;;;;;AA4BA,SAAgB,kBAAkB,OAAwD;CACxF,MAAM,UAAU,OAAO,QAAQ,MAAM,OAAO;CAC5C,IAAI,QAAQ,WAAW,GACrB,MAAM,IAAI,MAAM,4DAA4D;CAE9E,IAAI,cAAc;CAClB,IAAI,cAAc;CAClB,KAAK,MAAM,CAAC,KAAK,WAAW,SAAS;EACnC,IAAI,SAAS,GACX,MAAM,IAAI,MAAM,kCAAkC,IAAI,iBAAiB,OAAO,EAAE;EAElF,IAAI,EAAE,OAAO,MAAM,OACjB,MAAM,IAAI,MACR,0CAA0C,IAAI,iFAEhD;EAEF,eAAe,MAAM,KAAK,OAAQ;EAClC,eAAe;CACjB;CACA,IAAI,gBAAgB,GAClB,MAAM,IAAI,MAAM,8DAA8D;CAEhF,MAAM,YAAY,cAAc;CAChC,OAAO,MAAM,cAAc,KAAA,IACvB,EAAE,UAAU,IACZ;EAAE;EAAW,MAAM,aAAa,MAAM;CAAU;AACtD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"evaluation-B8H3GYej.js","names":[],"sources":["../src/analyst/evaluation-context.ts","../src/evaluation.ts"],"sourcesContent":["import { CostLedger } from '../cost-ledger'\nimport type { EvaluationContext } from '../evaluation'\nimport type { AnalystContext } from './types'\n\n/** One deadline, spending authority and usage bridge for every evaluation-backed analyst. */\nexport function analystEvaluationContext(\n context: AnalystContext,\n actor: string,\n): {\n evaluation: EvaluationContext\n analystContext: AnalystContext & { signal: AbortSignal }\n} {\n const signals = context.signal ? [context.signal] : []\n if (context.deadlineMs !== undefined) {\n const remaining = context.deadlineMs - Date.now()\n if (!Number.isFinite(remaining)) throw new TypeError('Analyst deadline must be finite')\n if (remaining <= 0) throw new DOMException('Analyst deadline exceeded', 'TimeoutError')\n signals.push(AbortSignal.timeout(Math.ceil(remaining)))\n }\n const signal = AbortSignal.any(signals)\n signal.throwIfAborted()\n return {\n analystContext: { ...context, signal },\n evaluation: {\n signal,\n // No implicit account overrides an evaluator's configured spending authority.\n costLedger:\n context.costLedger ??\n (context.budgetUsd === undefined\n ? undefined\n : new CostLedger({ costCeilingUsd: context.budgetUsd })),\n actor,\n channel: 'analyst',\n costPhase: context.costPhase,\n costTags: { ...context.tags, runId: context.runId, correlationId: context.correlationId },\n onReceipt: (receipt) =>\n context.recordUsage?.({\n calls: 1,\n tokens: receipt.usageUnknown\n ? null\n : { input: receipt.inputTokens, output: receipt.outputTokens },\n cost: receipt.costUnknown\n ? { kind: 'uncaptured', usd: null }\n : {\n kind: receipt.actualCostUsd === undefined ? 'estimated' : 'observed',\n usd: receipt.costUsd,\n },\n }),\n },\n }\n}\n","import { analystEvaluationContext } from './analyst/evaluation-context'\nimport type { Analyst, AnalystContext, AnalystFinding } from './analyst/types'\nimport type { JudgeConfig, JudgeScore, Scenario } from './campaign/types'\nimport type {\n CostChannel,\n CostLedgerHandle,\n CostReceipt,\n CostReceiptInput,\n MaximumCharge,\n} from './cost-ledger'\nimport { CostLedger } from './cost-ledger'\n\nexport interface EvaluationResult<T> {\n value: T\n receipt: CostReceipt\n durationMs: number\n}\n\nexport interface EvaluationContext {\n /** Physical paid-call identity, forwarded through the existing ledger and transport.\n * Reusing it in one ledger conflicts; it is not an automatic result-replay policy. */\n callId?: string\n signal?: AbortSignal\n costLedger?: CostLedgerHandle\n actor?: string\n channel?: CostChannel\n costPhase?: string\n costTags?: Record<string, string>\n maximumCharge?: MaximumCharge\n /** Awaited after accounting and before validation or result delivery. */\n onReceipt?: (receipt: CostReceipt) => void | Promise<void>\n}\n\nexport type CostedEvaluator<I, O> = (\n input: I,\n context?: EvaluationContext,\n) => Promise<EvaluationResult<O>>\n\nexport interface EvaluatorOptions<I, O> {\n execute: (input: I, context: { signal: AbortSignal; idempotencyKey: string }) => Promise<O>\n receipt: (value: O) => CostReceiptInput\n receiptFromError?: (error: Error) => CostReceiptInput | undefined\n model?: string | ((input: I) => string)\n costLedger?: CostLedgerHandle\n maximumCharge?: MaximumCharge\n /** Awaited after accounting, so invalid output never erases paid work. */\n validate?: (value: O, input: I) => void | Promise<void>\n}\n\n/** A metered function, independent of providers, question formats, and application policy. */\nexport function createEvaluator<I, O>(options: EvaluatorOptions<I, O>): CostedEvaluator<I, O> {\n const defaults = { ...options }\n const ledger = defaults.costLedger ?? new CostLedger()\n return async (input, context = {}) => {\n context.signal?.throwIfAborted()\n const started = performance.now()\n const paid = await (context.costLedger ?? ledger).runPaidCall({\n callId: context.callId,\n actor: context.actor ?? 'evaluation',\n channel: context.channel ?? 'evaluation',\n phase: context.costPhase ?? 'evaluation',\n tags: context.costTags,\n model: typeof defaults.model === 'function' ? defaults.model(input) : defaults.model,\n signal: context.signal,\n maximumCharge: context.maximumCharge ?? defaults.maximumCharge,\n execute: (signal, idempotencyKey) => defaults.execute(input, { signal, idempotencyKey }),\n receipt: defaults.receipt,\n receiptFromError: defaults.receiptFromError,\n })\n if (paid.receipt) await context.onReceipt?.(paid.receipt)\n if (!paid.succeeded) throw paid.error\n // A transport can complete after cancellation. Keep its paid receipt, not a live decision.\n context.signal?.throwIfAborted()\n await defaults.validate?.(paid.value, input)\n context.signal?.throwIfAborted()\n return { value: paid.value, receipt: paid.receipt, durationMs: performance.now() - started }\n }\n}\n\nexport interface EvaluationJudgeOptions<A, S extends Scenario, O> {\n name: string\n version: string\n dimensions: JudgeConfig<A, S>['dimensions']\n evaluate: CostedEvaluator<{ artifact: A; scenario: S }, O>\n map: (value: O, input: { artifact: A; scenario: S }) => JudgeScore | Promise<JudgeScore>\n /** Persist the complete observation before reducing it to a verdict. */\n record?: (\n result: EvaluationResult<O>,\n input: { artifact: A; scenario: S },\n ) => void | Promise<void>\n appliesTo?: (scenario: S) => boolean\n}\n\n/** Return the existing contract. Mapping never performs another inference call. */\nexport function asJudge<A, S extends Scenario, O>(\n options: EvaluationJudgeOptions<A, S, O>,\n): JudgeConfig<A, S> {\n // The version describes these callbacks, not later mutations of the caller's options.\n const config = { ...options, dimensions: structuredClone(options.dimensions) }\n return {\n name: config.name,\n judgeVersion: config.version,\n dimensions: config.dimensions,\n appliesTo: config.appliesTo,\n async score({ artifact, scenario, signal, costLedger, costPhase, costTags }) {\n signal.throwIfAborted()\n const input = { artifact, scenario }\n const result = await config.evaluate(input, {\n signal,\n costLedger,\n actor: config.name,\n channel: 'judge',\n costPhase,\n costTags: { ...costTags, scenarioId: scenario.id },\n })\n await config.record?.(result, input)\n signal.throwIfAborted()\n const score = await config.map(result.value, input)\n signal.throwIfAborted()\n return score\n },\n }\n}\n\nexport interface EvaluationAnalystOptions<I, O> {\n id: string\n version: string\n description: string\n inputKind: Analyst<I>['inputKind']\n cost: Analyst<I>['cost']\n evaluate: (\n input: I,\n context: EvaluationContext,\n analystContext: AnalystContext,\n ) => Promise<EvaluationResult<O>>\n map: (value: O, input: I, context: AnalystContext) => AnalystFinding[] | Promise<AnalystFinding[]>\n record?: (result: EvaluationResult<O>, input: I, context: AnalystContext) => void | Promise<void>\n}\n\n/** Registry, graph, and trace consumers keep the same Analyst interface. */\nexport function asAnalyst<I, O>(options: EvaluationAnalystOptions<I, O>): Analyst<I> {\n const config = { ...options, cost: structuredClone(options.cost) }\n return {\n id: config.id,\n version: config.version,\n description: config.description,\n inputKind: config.inputKind,\n cost: config.cost,\n async analyze(input, context) {\n const { evaluation, analystContext } = analystEvaluationContext(context, config.id)\n const signal = analystContext.signal\n const result = await config.evaluate(input, evaluation, analystContext)\n await config.record?.(result, input, analystContext)\n signal.throwIfAborted()\n const findings = await config.map(result.value, input, analystContext)\n signal.throwIfAborted()\n return findings\n },\n }\n}\n"],"mappings":";;;AAKA,SAAgB,yBACd,SACA,OAIA;CACA,MAAM,UAAU,QAAQ,SAAS,CAAC,QAAQ,MAAM,IAAI,CAAC;CACrD,IAAI,QAAQ,eAAe,KAAA,GAAW;EACpC,MAAM,YAAY,QAAQ,aAAa,KAAK,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B,IACzB;IAAS,UAAU;IAAG,UAAU;eACtB;EACZ,aAAa,UAAU;;;iBAIT,QAAQ,GAAG,UAAU,UAAU,GAC7C,SAAS,uBAAuB,GAAG,GAAG,KACrC,YAAY,GAAG;UA4BD,yBAAyB,GAAG;EAC3C;EACA;EACA;EACA,WAAW,QAAQ;EACnB,MAAM,QAAQ;EACd,WACE,OAAO,GACP,SAAS,mBACT,gBAAgB,mBACb,QAAQ,iBAAiB;EAC9B,MAAM,OAAO,GAAG,OAAO,GAAG,SAAS,mBAAmB,mBAAmB,QAAQ;EACjF,UAAU,QAAQ,iBAAiB,IAAI,OAAO,GAAG,SAAS,0BAA0B;;;iBAItE,UAAU,GAAG,GAAG,SAAS,yBAAyB,GAAG,KAAK,QAAQ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"internal-v6XfOeJW.js","names":[],"sources":["../src/math/special-functions.ts","../src/statistics/internal.ts"],"sourcesContent":["/** Lanczos approximation to ln Gamma(z). */\nexport function lnGamma(z: number): number {\n const g = 7\n const coefficients = [\n 0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313,\n -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6,\n 1.5056327351493116e-7,\n ]\n if (z < 0.5) {\n return Math.log(Math.PI / Math.sin(Math.PI * z)) - lnGamma(1 - z)\n }\n z -= 1\n let x = coefficients[0]!\n for (let i = 1; i < g + 2; i++) x += coefficients[i]! / (z + i)\n const t = z + g + 0.5\n return 0.5 * Math.log(2 * Math.PI) + (z + 0.5) * Math.log(t) - t + Math.log(x)\n}\n\n/**\n * Regularized incomplete beta function I_x(a, b).\n *\n * The Lentz continued fraction converges only for `x < (a+1)/(a+b+2)`; outside\n * that domain it must be reached through the symmetry `I_x(a,b) = 1 −\n * I_{1−x}(b,a)`. `studentTCdf` drives `x → 1` as `|t| → 0`, so the mirrored\n * branch is the one every near-null t-statistic takes.\n */\nexport function regularizedIncompleteBeta(x: number, a: number, b: number): number {\n if (x <= 0) return 0\n if (x >= 1) return 1\n const logBeta = lnGamma(a) + lnGamma(b) - lnGamma(a + b)\n // x^a·(1−x)^b / B(a,b) — symmetric under (x,a,b) → (1−x,b,a), so the\n // mirrored branch reuses it unchanged.\n const front = Math.exp(Math.log(x) * a + Math.log(1 - x) * b - logBeta)\n if (x < (a + 1) / (a + b + 2)) {\n return (front * betaContinuedFraction(x, a, b)) / a\n }\n return 1 - (front * betaContinuedFraction(1 - x, b, a)) / b\n}\n\n/** Modified Lentz evaluation of the beta continued fraction at `x`. */\nfunction betaContinuedFraction(x: number, a: number, b: number): number {\n const maxIterations = 300\n const epsilon = 3e-15\n let c = 1\n let d = 1 - ((a + b) * x) / (a + 1)\n if (Math.abs(d) < 1e-30) d = 1e-30\n d = 1 / d\n let fraction = d\n for (let m = 1; m <= maxIterations; m++) {\n const m2 = 2 * m\n let numerator = (m * (b - m) * x) / ((a + m2 - 1) * (a + m2))\n d = 1 + numerator * d\n if (Math.abs(d) < 1e-30) d = 1e-30\n c = 1 + numerator / c\n if (Math.abs(c) < 1e-30) c = 1e-30\n d = 1 / d\n fraction *= d * c\n numerator = -((a + m) * (a + b + m) * x) / ((a + m2) * (a + m2 + 1))\n d = 1 + numerator * d\n if (Math.abs(d) < 1e-30) d = 1e-30\n c = 1 + numerator / c\n if (Math.abs(c) < 1e-30) c = 1e-30\n d = 1 / d\n const delta = d * c\n fraction *= delta\n if (Math.abs(delta - 1) < epsilon) break\n }\n return fraction\n}\n","/**\n * Shared internals for the statistics modules. Nothing here is part of the\n * public statistics surface — `./index` does not re-export this module.\n */\n\nimport { ValidationError } from '../errors'\nimport { interpolatedQuantile } from '../math/quantile'\nimport { lnGamma } from '../math/special-functions'\nimport { mulberry32 } from './random'\n\n/** Every rank test refuses non-finite input. Beyond the arithmetic being\n * undefined, the tie-grouping scan compares values with `===`, and\n * `NaN === NaN` is false, so a NaN would leave the group boundary unable to\n * advance and spin the loop forever. */\nexport function assertFiniteSample(fn: string, label: string, xs: readonly number[]): void {\n for (let i = 0; i < xs.length; i++) {\n if (!Number.isFinite(xs[i])) {\n throw new ValidationError(`${fn}: ${label}[${i}] must be finite, got ${xs[i]}`)\n }\n }\n}\n\n/**\n * Two-sided exact p-value for b successes out of (b + c) Bernoulli(0.5) trials —\n * the exact-binomial core of {@link mcnemar}. `min(1, 2·P(X ≤ min(b,c)))`. No\n * discordant pairs ⇒ no evidence ⇒ p = 1. Summed in log space (lnGamma) so it\n * stays exact at large discordant counts without overflow.\n */\nexport function binomialSignTwoSided(b: number, c: number): number {\n const nd = b + c\n if (nd === 0) return 1\n return Math.min(1, 2 * binomialHalfLowerTail(Math.min(b, c), nd))\n}\n\n/** P(X >= successes) for X ~ Binomial(n, 0.5). */\nexport function binomialHalfUpperTail(successes: number, n: number): number {\n if (successes <= 0) return 1\n if (successes > n) return 0\n\n // Use the smaller side of the distribution. For lower thresholds the\n // complement sums at most half the mass; for upper thresholds symmetry\n // maps the upper tail to a lower tail without subtraction.\n if (successes <= n / 2) {\n return Math.max(0, 1 - binomialHalfLowerTail(successes - 1, n))\n }\n return binomialHalfLowerTail(n - successes, n)\n}\n\n/** P(X <= maxSuccesses) for X ~ Binomial(n, 0.5), accumulated in log space. */\nfunction binomialHalfLowerTail(maxSuccesses: number, n: number): number {\n if (maxSuccesses < 0) return 0\n if (maxSuccesses >= n) return 1\n if (maxSuccesses === 0) return 2 ** -n\n\n const logHalfN = n * Math.log(0.5)\n let logTail = Number.NEGATIVE_INFINITY\n for (let i = 0; i <= maxSuccesses; i++) {\n const logChoose = lnGamma(n + 1) - lnGamma(i + 1) - lnGamma(n - i + 1)\n logTail = logAddExp(logTail, logChoose + logHalfN)\n }\n return Math.min(1, Math.exp(logTail))\n}\n\nfunction logAddExp(a: number, b: number): number {\n if (a === Number.NEGATIVE_INFINITY) return b\n if (b === Number.NEGATIVE_INFINITY) return a\n const max = Math.max(a, b)\n const min = Math.min(a, b)\n return max + Math.log1p(Math.exp(min - max))\n}\n\n/** Standard-normal inverse CDF (Acklam approximation). */\nexport function zQuantile(p: number): number {\n if (p <= 0 || p >= 1) {\n if (p === 0) return -Infinity\n if (p === 1) return Infinity\n return NaN\n }\n const a = [\n -3.969683028665376e1, 2.209460984245205e2, -2.759285104469687e2, 1.38357751867269e2,\n -3.066479806614716e1, 2.506628277459239,\n ]\n const b = [\n -5.447609879822406e1, 1.615858368580409e2, -1.556989798598866e2, 6.680131188771972e1,\n -1.328068155288572e1,\n ]\n const c = [\n -7.784894002430293e-3, -3.223964580411365e-1, -2.400758277161838, -2.549732539343734,\n 4.374664141464968, 2.938163982698783,\n ]\n const d = [7.784695709041462e-3, 3.224671290700398e-1, 2.445134137142996, 3.754408661907416]\n const pLow = 0.02425\n const pHigh = 1 - pLow\n let q: number\n let r: number\n if (p < pLow) {\n q = Math.sqrt(-2 * Math.log(p))\n return (\n (((((c[0]! * q + c[1]!) * q + c[2]!) * q + c[3]!) * q + c[4]!) * q + c[5]!) /\n ((((d[0]! * q + d[1]!) * q + d[2]!) * q + d[3]!) * q + 1)\n )\n }\n if (p <= pHigh) {\n q = p - 0.5\n r = q * q\n return (\n ((((((a[0]! * r + a[1]!) * r + a[2]!) * r + a[3]!) * r + a[4]!) * r + a[5]!) * q) /\n (((((b[0]! * r + b[1]!) * r + b[2]!) * r + b[3]!) * r + b[4]!) * r + 1)\n )\n }\n q = Math.sqrt(-2 * Math.log(1 - p))\n return (\n -(((((c[0]! * q + c[1]!) * q + c[2]!) * q + c[3]!) * q + c[4]!) * q + c[5]!) /\n ((((d[0]! * q + d[1]!) * q + d[2]!) * q + d[3]!) * q + 1)\n )\n}\n\nexport function medianInPlace(xs: number[]): number {\n if (xs.length === 0) return 0\n xs.sort((a, b) => a - b)\n return interpolatedQuantile(xs, 0.5)\n}\n\n/**\n * PRNG for every resampling path in this module.\n *\n * With no caller seed the seed is DERIVED FROM THE DATA rather than taken from\n * `Math.random`, so re-running the same input reproduces the same interval —\n * a gate verdict that cannot be re-derived is not evidence. Distinct data\n * still gets a distinct stream. Same pattern as `promotion-gate.ts`.\n */\nexport function makeRng(\n seed: number | undefined,\n ...series: readonly (readonly number[])[]\n): () => number {\n return mulberry32(seed ?? seedFromData(series))\n}\n\n/** FNV-1a over the IEEE-754 bytes of every observation. */\nfunction seedFromData(series: readonly (readonly number[])[]): number {\n const view = new DataView(new ArrayBuffer(8))\n // 32-bit FNV-1a over the IEEE-754 BYTES of each observation, not over a\n // string. Frozen: it seeds the unseeded bootstrap from the data itself, so a\n // change moves every interval this package has already published. The\n // string-input variants elsewhere cannot be substituted here.\n let hash = 0x811c9dc5\n for (const xs of series) {\n for (const x of xs) {\n view.setFloat64(0, x)\n for (let byte = 0; byte < 8; byte++) {\n hash = Math.imul(hash ^ view.getUint8(byte), 0x01000193)\n }\n }\n // Separator, so ([1],[2]) and ([1,2],[]) do not collide.\n hash = Math.imul(hash ^ 0xff, 0x01000193)\n }\n return hash | 0\n}\n\n/** Order-independent seed for a symmetric two-sample statistic. */\nexport function symmetricTwoSampleSeed(a: readonly number[], b: readonly number[]): number {\n const sortedA = [...a].sort((left, right) => left - right)\n const sortedB = [...b].sort((left, right) => left - right)\n const forward = seedFromData([sortedA, sortedB]) >>> 0\n const reversed = seedFromData([sortedB, sortedA]) >>> 0\n return Math.min(forward, reversed)\n}\n"],"mappings":";;;;;AACA,SAAgB,QAAQ,GAAmB;CACzC,MAAM,IAAI;CACV,MAAM,eAAe;EACnB;EAAqB;EAAmB;EAAqB;EAC7D;EAAqB;EAAoB;EAAsB;EAC/D;CACF;CACA,IAAI,IAAI,IACN,OAAO,KAAK,IAAI,KAAK,KAAK,KAAK,IAAI,KAAK,KAAK,CAAC,CAAC,IAAI,QAAQ,IAAI,CAAC;CAElE,KAAK;CACL,IAAI,IAAI,aAAa;CACrB,KAAK,IAAI,IAAI,GAAG,IAAI,GAAO,KAAK,KAAK,aAAa,MAAO,IAAI;CAC7D,MAAM,IAAI,IAAI,IAAI;CAClB,OAAO,KAAM,KAAK,IAAI,IAA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CAAC,SAAS,OAAO,CAAC,MAAM;CACtD,OAAO,KAAK,IAAI,SAAS,QAAQ;AACnC"}
|
package/dist/mean-BPuUNznQ.js
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
// src/statistics/mean.ts
|
|
2
|
-
/** Arithmetic mean. An empty input has no mean and returns NaN. */
|
|
3
|
-
function mean(values) {
|
|
4
|
-
return values.reduce((sum, value) => sum + value, 0) / values.length;
|
|
5
|
-
}
|
|
6
|
-
/** Arithmetic mean, or null for an empty input. */
|
|
7
|
-
function meanOrNull(values) {
|
|
8
|
-
return values.length === 0 ? null : mean(values);
|
|
9
|
-
}
|
|
10
|
-
/** Arithmetic mean, or 0 for an empty input. */
|
|
11
|
-
function meanOrZero(values) {
|
|
12
|
-
return values.length === 0 ? 0 : mean(values);
|
|
13
|
-
}
|
|
14
|
-
export { meanOrNull as n, meanOrZero as r, mean as t };
|
|
15
|
-
|
|
16
|
-
//# sourceMappingURL=mean-BPuUNznQ.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"mean-BPuUNznQ.js","names":[],"sources":["../src/statistics/mean.ts"],"sourcesContent":["/** Arithmetic mean. An empty input has no mean and returns NaN. */\nexport function mean(values: readonly number[]): number {\n return values.reduce((sum, value) => sum + value, 0) / values.length\n}\n\n/** Arithmetic mean, or null for an empty input. */\nexport function meanOrNull(values: readonly number[]): number | null {\n return values.length === 0 ? null : mean(values)\n}\n\n/** Arithmetic mean, or 0 for an empty input. */\nexport function meanOrZero(values: readonly number[]): number {\n return values.length === 0 ? 0 : mean(values)\n}\n"],"mappings":";;AACA,SAAgB,KAAK,QAAmC;CACtD,OAAO,OAAO,QAAQ,KAAK,UAAU,MAAM,OAAO,CAAC,IAAI,OAAO;AAChE;;AAGA,SAAgB,WAAW,QAA0C;CACnE,OAAO,OAAO,WAAW,IAAI,OAAO,KAAK,MAAM;AACjD;;AAGA,SAAgB,WAAW,QAAmC;CAC5D,OAAO,OAAO,WAAW,IAAI,IAAI,KAAK,MAAM;AAC9C"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"paired-tests-C2zUqgUW.js","names":[],"sources":["../src/math/student-t.ts","../src/statistics/paired-tests.ts"],"sourcesContent":["import { regularizedIncompleteBeta } from './special-functions'\n\n/**\n * Student-t CDF via the regularized incomplete beta function.\n */\nexport function studentTCdf(t: number, degreesOfFreedom: number): number {\n if (degreesOfFreedom <= 0) return 0.5\n\n const x = degreesOfFreedom / (degreesOfFreedom + t * t)\n const beta = regularizedIncompleteBeta(x, degreesOfFreedom / 2, 0.5)\n return t >= 0 ? 1 - 0.5 * beta : 0.5 * beta\n}\n\n/**\n * Inverse Student-t CDF, solved against {@link studentTCdf}.\n *\n * The CDF is monotone, so bracket expansion followed by bisection is stable\n * across fractional degrees of freedom and does not need a separate\n * approximation with a different error profile.\n */\nexport function studentTQuantile(probability: number, degreesOfFreedom: number): number {\n if (!Number.isFinite(probability) || probability < 0 || probability > 1) {\n throw new RangeError(`studentTQuantile: probability must be in [0,1], got ${probability}`)\n }\n if (!Number.isFinite(degreesOfFreedom) || degreesOfFreedom <= 0) {\n throw new RangeError(\n `studentTQuantile: degreesOfFreedom must be positive and finite, got ${degreesOfFreedom}`,\n )\n }\n if (probability === 0) return Number.NEGATIVE_INFINITY\n if (probability === 1) return Number.POSITIVE_INFINITY\n if (probability === 0.5) return 0\n if (probability < 0.5) return -studentTQuantile(1 - probability, degreesOfFreedom)\n\n let low = 0\n let high = 1\n while (studentTCdf(high, degreesOfFreedom) < probability) high *= 2\n for (let iteration = 0; iteration < 64; iteration++) {\n const middle = (low + high) / 2\n if (studentTCdf(middle, degreesOfFreedom) < probability) low = middle\n else high = middle\n }\n return (low + high) / 2\n}\n","/**\n * Paired significance tests on continuous scores: the paired t-test, the\n * promotion-gate paired bootstrap, the exact sign test, and the package-wide\n * paired-delta decision statistic.\n */\n\nimport { ValidationError } from '../errors'\nimport { studentTCdf } from '../math/student-t'\nimport { assertFiniteSample, binomialHalfUpperTail, makeRng, medianInPlace } from './internal'\n\nexport interface PairedTTestResult {\n /** Null when the statistic is undefined — see {@link pairedTTest}. */\n t: number | null\n df: number\n /** Null exactly when `t` is null. */\n p: number | null\n}\n\n/**\n * Paired t-test — before/after measurements on the SAME items.\n * Pairing removes inter-item variance, giving tighter significance than\n * an unpaired test when comparing prompt v1 vs prompt v2 on identical\n * scenarios.\n *\n * Returns `t = p = null` where the statistic is undefined: fewer than two\n * pairs, or a non-zero constant delta whose observed variance is zero. A\n * constant shift carries no information about the variance it would have to\n * be compared against, so the honest answer is \"undefined\", not `p = 0` —\n * three observations cannot buy absolute certainty. This is the same contract\n * {@link pairedCohensDz} states for the same condition. An all-zero delta is\n * different: it is a measured null, and returns `t = 0, p = 1`.\n */\nexport function pairedTTest(before: number[], after: number[]): PairedTTestResult {\n if (before.length !== after.length) {\n throw new ValidationError(\n `pairedTTest: unequal sample sizes (${before.length} vs ${after.length})`,\n )\n }\n assertFiniteSample('pairedTTest', 'before', before)\n assertFiniteSample('pairedTTest', 'after', after)\n const n = before.length\n if (n < 2) return { t: null, df: 0, p: null }\n\n const diffs = before.map((b, i) => after[i]! - b)\n const mean = diffs.reduce((a, b) => a + b, 0) / n\n const variance = diffs.reduce((acc, d) => acc + (d - mean) ** 2, 0) / (n - 1)\n const se = Math.sqrt(variance / n)\n if (se === 0) {\n return mean === 0 ? { t: 0, df: n - 1, p: 1 } : { t: null, df: n - 1, p: null }\n }\n\n const t = mean / se\n const df = n - 1\n const p = 2 * (1 - studentTCdf(Math.abs(t), df))\n return { t, df, p }\n}\n\n// ── Paired bootstrap (promotion-gate effect size) ────────────────────\n\nexport interface PairedBootstrapResult {\n /** Number of paired observations. */\n n: number\n /** Median of paired deltas (after − before). */\n median: number\n /** Mean of paired deltas. */\n mean: number\n /** Lower bound of the bootstrap CI on the chosen statistic. */\n low: number\n /** Upper bound of the bootstrap CI on the chosen statistic. */\n high: number\n /** Confidence level used (e.g. 0.95). */\n confidence: number\n /** Number of bootstrap resamples used. */\n resamples: number\n /** False below {@link BOOTSTRAP_GATE_MIN_N}. See {@link pairedBootstrap}. */\n gateEligible: boolean\n}\n\n/**\n * Pairs below which a percentile bootstrap interval is descriptive spread only.\n *\n * `P(low > 0)` under a true null, against a nominal 2.5 %, measured over 4000\n * seeded trials: 13.53 % at n = 3, 3.52 % at n = 10, 3.10 % at n = 20 on the\n * median; 13.85 %, 4.90 %, 3.80 % on the mean. This is intrinsic to resampling\n * three points, not an implementation error — scipy's BCa gives 16.0 % on the\n * same n = 3 data — so no change to the estimator moves it. Below this floor\n * the decision belongs to the exact sign test or exact signed-rank test.\n */\nexport const BOOTSTRAP_GATE_MIN_N = 20\n\nexport interface PairedBootstrapOptions {\n /** Confidence level. Default 0.95. */\n confidence?: number\n /** Bootstrap resample count. Default 2000. */\n resamples?: number\n /** Statistic to bootstrap. Default 'median'. */\n statistic?: 'median' | 'mean'\n /** Deterministic seed. If omitted, derived from the deltas so the interval\n * is reproducible regardless. */\n seed?: number\n}\n\n/**\n * Paired bootstrap on (after − before) deltas. Returns a CI on the chosen\n * statistic (median by default); pairs are resampled with replacement. Throws\n * on unequal sample sizes.\n *\n * `low > threshold` carries the stated confidence ONLY at `n ≥\n * {@link BOOTSTRAP_GATE_MIN_N}`, which `gateEligible` reports. Below it the\n * check fires under a true null several times more often than nominal, so the\n * interval is descriptive spread and a promotion must not turn on it.\n */\nexport function pairedBootstrap(\n before: number[],\n after: number[],\n opts: PairedBootstrapOptions = {},\n): PairedBootstrapResult {\n if (before.length !== after.length) {\n throw new Error(`pairedBootstrap: unequal sample sizes (${before.length} vs ${after.length})`)\n }\n const confidence = opts.confidence ?? 0.95\n const resamples = opts.resamples ?? 2000\n const statistic = opts.statistic ?? 'median'\n if (confidence <= 0 || confidence >= 1) {\n throw new Error(`pairedBootstrap: confidence must be in (0,1), got ${confidence}`)\n }\n\n const n = before.length\n const deltas = before.map((b, i) => after[i]! - b)\n const gateEligible = n >= BOOTSTRAP_GATE_MIN_N\n if (n === 0) {\n return { n: 0, median: 0, mean: 0, low: 0, high: 0, confidence, resamples, gateEligible }\n }\n if (n === 1) {\n const d = deltas[0]!\n return { n: 1, median: d, mean: d, low: d, high: d, confidence, resamples, gateEligible }\n }\n\n const rng = makeRng(opts.seed, deltas)\n const samples = new Array<number>(resamples)\n for (let b = 0; b < resamples; b++) {\n if (statistic === 'mean') {\n let sum = 0\n for (let k = 0; k < n; k++) {\n sum += deltas[Math.floor(rng() * n)]!\n }\n samples[b] = sum / n\n } else {\n const acc = new Array<number>(n)\n for (let k = 0; k < n; k++) {\n acc[k] = deltas[Math.floor(rng() * n)]!\n }\n samples[b] = medianInPlace(acc)\n }\n }\n samples.sort((a, b) => a - b)\n\n const alpha = 1 - confidence\n const lowIdx = Math.floor((alpha / 2) * resamples)\n const highIdx = Math.min(resamples - 1, Math.ceil((1 - alpha / 2) * resamples) - 1)\n\n return {\n n,\n median: medianInPlace([...deltas]),\n mean: deltas.reduce((s, x) => s + x, 0) / n,\n low: samples[lowIdx]!,\n high: samples[Math.max(highIdx, lowIdx)]!,\n confidence,\n resamples,\n gateEligible,\n }\n}\n\n/** Pre-registered direction for a one-sided paired sign test. */\nexport type SignTestAlternative = 'greater' | 'less'\n\n/** Exact one-sided sign-test result for paired numeric differences. */\nexport interface PairedSignTestResult {\n /** Total supplied differences, including zero ties. */\n n: number\n /** Strictly positive differences. */\n positive: number\n /** Strictly negative differences. */\n negative: number\n /** Zero differences excluded from the binomial test. */\n ties: number\n /** Non-zero differences used by the binomial test. */\n nNonTies: number\n /** Direction of the pre-registered alternative hypothesis. */\n alternative: SignTestAlternative\n /** Exact one-sided p-value under P(positive) = P(negative) = 0.5. */\n pValue: number\n}\n\n/**\n * Exact one-sided sign test over paired differences.\n *\n * Pass `after[i] - before[i]` for each matched item. `alternative = 'greater'`\n * tests whether positive signs are more likely than negative signs and returns\n * `P(Binomial(nNonTies, 0.5) >= positive)`. `alternative = 'less'` treats\n * negative signs as successes instead. With a continuous difference\n * distribution this is the usual directional median test. Exact zero\n * differences are ties and do not enter the binomial denominator. All-tie and\n * empty inputs return p = 1. Every input difference must be finite, and the\n * direction must be chosen explicitly so a caller cannot select it after\n * seeing the signs.\n */\nexport function pairedSignTest(\n differences: readonly number[],\n alternative: SignTestAlternative,\n): PairedSignTestResult {\n if (alternative !== 'greater' && alternative !== 'less') {\n throw new ValidationError(\n `pairedSignTest: alternative must be 'greater' or 'less', got ${alternative}`,\n )\n }\n\n let positive = 0\n let negative = 0\n let ties = 0\n for (let i = 0; i < differences.length; i++) {\n const difference = differences[i]!\n if (!Number.isFinite(difference)) {\n throw new ValidationError(\n `pairedSignTest: difference at index ${i} must be finite, got ${difference}`,\n )\n }\n if (difference > 0) positive++\n else if (difference < 0) negative++\n else ties++\n }\n\n const nNonTies = positive + negative\n const successes = alternative === 'greater' ? positive : negative\n return {\n n: differences.length,\n positive,\n negative,\n ties,\n nNonTies,\n alternative,\n pValue: binomialHalfUpperTail(successes, nNonTies),\n }\n}\n\n/** Fraction of paired observations whose delta is an exact tie (|after − before|\n * < 1e-9). Throws on unequal sample sizes; 0 pairs ⇒ 0. */\nexport function pairedDeltaTieFraction(\n before: ArrayLike<number>,\n after: ArrayLike<number>,\n): number {\n if (before.length !== after.length) {\n throw new Error(\n `pairedDeltaTieFraction: unequal sample sizes (${before.length} vs ${after.length})`,\n )\n }\n const n = before.length\n if (n === 0) return 0\n let ties = 0\n for (let i = 0; i < n; i++) {\n if (Math.abs(after[i]! - before[i]!) < 1e-9) ties++\n }\n return ties / n\n}\n\n/**\n * The paired-delta statistic a DECISION is computed on, package-wide.\n *\n * The mean paired delta is the estimator that answers the question a promotion\n * gate asks — \"by how much did the candidate move the score\" — in the caller's\n * own units, and it equals the aggregate lift everyone quotes. The MEDIAN\n * answers a different question and loses the answer to this one in every regime\n * eval data actually lands in:\n * - TWO-POINT (pass/fail) outcomes on any encoding: the delta vector lives in\n * {−s, 0, +s} dominated by zeros, so the median and its whole bootstrap CI\n * are pinned at exactly 0 however large the shift. (Decide these on\n * {@link pairedRiskDifferenceExact} instead — same estimand, exact interval.)\n * - TIE-DOMINATED outcomes: at half the pairs tied the sample median is 0 by\n * construction, and `ci.low > threshold` then answers \"no\" forever at a\n * non-negative threshold and \"yes\" forever at a negative one.\n * - LOW-CARDINALITY outcomes, even well below half ties: judge dimensions on\n * integer 0-100, and block scores like {⅔, 1} from averaging pass/fail\n * leaves, put the median on a coarse lattice whose bootstrap percentiles\n * land on atoms. Measured: 26 blocks of 3 pass/fail leaves carrying a real\n * +12.8pp lift, only 23% of pairs tied, gives a median CI of [0, 0.333] —\n * lower bound exactly 0, so a gate at threshold 0 refuses a real lift.\n * That last case is why there is no tie-fraction threshold here: any cutoff on\n * ties leaves the lattice case open on the other side of it.\n *\n * `heldoutSignificance` has defaulted to the mean since #316 for the same\n * reason. The median remains available per call site for callers who\n * specifically want outlier robustness and accept the blindness.\n */\nexport const DECISION_PAIRED_DELTA_STATISTIC: 'mean' = 'mean'\n"],"mappings":";;;;;;AAKA,SAAgB,YAAY,GAAW,kBAAkC;CACvE,IAAI,oBAAoB,GAAG,OAAO;CAElC,MAAM,IAAI,oBAAoB,mBAAmB,IAAI;CACrD,MAAM,OAAO,0BAA0B,GAAG,mBAAmB,GAAG,EAAG;CACnE,OAAO,KAAK,IAAI,IAAI,KAAM,OAAO,KAAM;AACzC;;;;;;;;AASA,SAAgB,iBAAiB,aAAqB,kBAAkC;CACtF,IAAI,CAAC,OAAO,SAAS,WAAW,KAAK,cAAc,KAAK,cAAc,GACpE,MAAM,IAAI,WAAW,uDAAuD,aAAa;CAE3F,IAAI,CAAC,OAAO,SAAS,gBAAgB,KAAK,oBAAoB,GAC5D,MAAM,IAAI,WACR,uEAAuE,kBACzE;CAEF,IAAI,gBAAgB,GAAG,OAAO,OAAO;CACrC,IAAI,gBAAgB,GAAG,OAAO,OAAO;CACrC,IAAI,gBAAgB,IAAK,OAAO;CAChC,IAAI,cAAc,IAAK,OAAO,CAAC,iBAAi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;AA8BA,MAAa,kCAA0C"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"redact-C_wzC4c_.d.ts","names":[],"sources":["../src/trace/redact.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KA8CY;;KAKA;;;;;;cAOC;UAEI;;EAEf;EACA,UAAU;EACV;EACA;;UAGe;EACf;EACA,SAAS;;EAET;EACA,YAAY;EACZ;EACA,UAAU;;UAGK;;EAEf,UAAU;;EAEV;;;;;;;;;EASA;;EAEA,SAAS;;UAGM;;EAEf,UAAU;;EAEV;;KAGU;UAEK;EACf,UAAU;EACV;EACA;EACA;;EAEA;;UAGe;EACf,QAAQ;EACR,SAAS;EACT,UAAU;;EAEV;;;iBAkVc,qBAAqB,UAAS,mBAA+B;;;;;;iBAkC7D,OAAO,GACrB,OAAO,GACP,UAAS;EACN,OAAO;EAAG,QAAQ;;;;;;iBAUP,WAAW,cAAc,UAAS;;;;;;;iBAgKlC,kBAAkB,gBAAgB,UAAS,gBAAqB;;;;;iBAoBhE,gBACd,SAAS,kBACT,mBAAmB,sBACnB,iCACC;;iBAsCa,aAAa,SAAS;;;;;;iBAStB,eAAe,GAC7B,OAAO,GACP,UAAS;EACN,OAAO;EAAG,QAAQ;EAAiB,SAAS"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"redact-D6APJS1d.js","names":[],"sources":["../src/trace/redaction/detectors.ts","../src/trace/redact.ts"],"sourcesContent":["import type { SafetyCategory } from '../redact'\n\n// ── Key classifier ───────────────────────────────────────────────────────\n\n/**\n * Canonical snake_case form of a field name, so camelCase, kebab-case, dotted\n * and snake_case spellings match one list: `userPassword`, `user-password` and\n * `user.password` all become `user_password`.\n */\nexport function normalizeKey(key: string): string {\n return key\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '_')\n .replace(/^_+|_+$/g, '')\n}\n\n/** Counts, limits and model vocabulary that contain the word \"token\" but are not credentials. */\nconst NON_CREDENTIAL_TOKEN_KEYS: ReadonlySet<string> = new Set([\n 'tokens',\n 'max_tokens',\n 'min_tokens',\n 'ls_max_tokens',\n 'token_count',\n 'token_limit',\n 'token_budget',\n 'input_tokens',\n 'output_tokens',\n 'total_tokens',\n 'cached_tokens',\n 'prompt_tokens',\n 'completion_tokens',\n 'reasoning_tokens',\n 'bos_token',\n 'eos_token',\n 'pad_token',\n 'unk_token',\n 'sep_token',\n 'cls_token',\n 'mask_token',\n 'stop_token',\n // Pagination cursors are opaque but not credentials.\n 'page_token',\n 'next_page_token',\n 'prev_page_token',\n 'next_token',\n 'continuation_token',\n 'cursor_token',\n 'sync_token',\n])\n\nconst CREDENTIAL_KEYS = [\n 'authorization',\n 'auth',\n 'cookie',\n 'api_key',\n 'apikey',\n 'api_token',\n 'access_key',\n 'secret_key',\n 'private_key',\n 'signing_key',\n 'encryption_key',\n 'master_key',\n 'session_key',\n 'client_secret',\n 'secret',\n 'password',\n 'passwd',\n 'passphrase',\n 'credential',\n 'credentials',\n 'bearer',\n 'dsn',\n 'database_url',\n 'connection_string',\n 'pat',\n] as const\n\n/** Email fields are personal data in every profile. */\nconst EMAIL_KEYS = ['email', 'email_address'] as const\n\n/** Personal-data fields removed by the share and strict profiles. */\nconst SHARE_PERSONAL_KEYS = [\n 'phone',\n 'phone_number',\n 'mobile',\n 'ip',\n 'ip_address',\n 'remote_addr',\n 'street_address',\n 'postal_address',\n 'home_address',\n 'billing_address',\n 'shipping_address',\n 'mailing_address',\n 'date_of_birth',\n 'dob',\n 'ssn',\n] as const\n\n/** Identifiers pseudonymized by the share and strict profiles. */\nconst IDENTIFIER_KEYS = [\n 'user_id',\n 'user_uuid',\n 'account_id',\n 'account_uuid',\n 'customer_id',\n 'tenant_id',\n 'org_id',\n 'organization_id',\n 'organisation_id',\n 'team_id',\n 'enduser_id',\n 'actor_id',\n 'principal_id',\n 'member_id',\n 'session_id',\n 'request_id',\n 'correlation_id',\n 'device_id',\n 'installation_id',\n] as const\n\n/** Fields that carry prompts, model output, tool payloads or other free text. Removed by `strict`. */\nconst RAW_CONTENT_KEYS = [\n 'prompt',\n 'prompts',\n 'system_prompt',\n 'completion',\n 'input',\n 'output',\n 'message',\n 'messages',\n 'content',\n 'text',\n 'thinking',\n 'reasoning',\n 'transcript',\n 'context',\n 'document',\n 'documents',\n 'chunk',\n 'chunks',\n 'retrieval',\n 'query',\n 'args',\n 'arguments',\n 'result',\n 'body',\n 'command',\n 'full_command',\n 'input_value',\n 'output_value',\n 'instructions',\n 'system_instructions',\n 'stdout',\n 'stderr',\n 'stacktrace',\n 'status_description',\n 'input_preview',\n 'output_preview',\n 'current_task',\n 'user_input',\n 'request_text',\n] as const\n\n/**\n * A key matches a list entry exactly or as a suffix (`openai_api_key`,\n * `db_password`, `tool_output`). Prefix compounds (`secret_name`,\n * `password_min_length`, `auth_type`, `content_type`) do not match: they name\n * or describe a value rather than hold it, and flagging them would make the\n * share verdict refuse ordinary traces. Value detectors still catch a\n * credential-shaped value under any key.\n */\nfunction matchesKeyList(normalized: string, keys: readonly string[]): boolean {\n for (const key of keys) {\n if (normalized === key || normalized.endsWith(`_${key}`)) return true\n }\n return false\n}\n\nfunction isTokenCredentialKey(normalized: string): boolean {\n if (NON_CREDENTIAL_TOKEN_KEYS.has(normalized)) return false\n if (normalized === 'token') return true\n // access_token and refreshToken are credentials; max_tokens and input_tokens are counts.\n if (normalized.endsWith('tokens')) return false\n return normalized.endsWith('token')\n}\n\ntype KeyClass = 'credential' | 'email' | 'share-personal' | 'identifier' | 'raw-content'\n\n/** Trace keys repeat on every span, so classifications are cached. */\nconst keyClassCache = new Map<string, KeyClass | null>()\n\nexport function classifyKeyName(key: string): KeyClass | undefined {\n const cached = keyClassCache.get(key)\n if (cached !== undefined) return cached ?? undefined\n const kind = classifyNormalizedKey(normalizeKey(key))\n if (keyClassCache.size >= 10_000) keyClassCache.clear()\n keyClassCache.set(key, kind ?? null)\n return kind\n}\n\nfunction classifyNormalizedKey(normalized: string): KeyClass | undefined {\n if (!normalized || NON_CREDENTIAL_TOKEN_KEYS.has(normalized)) return undefined\n if (isTokenCredentialKey(normalized)) return 'credential'\n if (matchesKeyList(normalized, CREDENTIAL_KEYS)) return 'credential'\n if (matchesKeyList(normalized, EMAIL_KEYS)) return 'email'\n if (matchesKeyList(normalized, SHARE_PERSONAL_KEYS)) return 'share-personal'\n if (matchesKeyList(normalized, IDENTIFIER_KEYS)) return 'identifier'\n if (matchesKeyList(normalized, RAW_CONTENT_KEYS)) return 'raw-content'\n return undefined\n}\n\n/**\n * The safety category a field name puts its value in, or undefined for an\n * ordinary field. Token counts and model limits (`inputTokens`, `max_tokens`,\n * `token_count`) and names such as `author` are not credentials.\n */\nexport function classifyKey(key: string): SafetyCategory | undefined {\n const kind = classifyKeyName(key)\n if (kind === undefined) return undefined\n if (kind === 'credential') return 'credential'\n if (kind === 'identifier') return 'identifier'\n if (kind === 'raw-content') return 'raw-content'\n return 'personal-data'\n}\n\n// ── Value detectors ──────────────────────────────────────────────────────\n\ninterface ValueDetector {\n id: string\n pattern: RegExp\n}\n\n/**\n * High-confidence credential shapes. A hit replaces the whole string. Each\n * pattern is written without the `g` flag so `test` stays stateless.\n *\n * The provider-branded prefixes below (`sk-ant-`, `AIza`, `ghp_`, `xoxb-`,\n * `AKIA`, `hubcap_`, `eyJ`…) have no leading `\\b`. A `\\b` word-boundary\n * assertion does not fire between two word characters, so it silently passed\n * a real token when something else glued a word character directly in front\n * of it — a compound identifier like `env.GITHUB_TOKEN_ghp_<token>` (a `_`\n * before `ghp_`) or `BACKUP_AKIA<key>` (a `_` before `AKIA`). These prefixes\n * are distinctive enough on their own, so scanning without that boundary\n * catches the same real credential wherever it is glued, at the cost of no\n * meaningful new false positives (`scripts/redaction-corpus.json` covers\n * both).\n */\nconst CREDENTIAL_DETECTORS: readonly ValueDetector[] = [\n { id: 'private-key', pattern: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/ },\n { id: 'jwt', pattern: /eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}/ },\n { id: 'bearer', pattern: /\\bbearer\\s+[A-Za-z0-9._~+/=-]{12,}/i },\n {\n id: 'authorization-header',\n pattern: /^\\s*(?:basic|digest|apikey)\\s+[A-Za-z0-9._~+/=:-]{8,}\\s*$/i,\n },\n { id: 'anthropic-key', pattern: /sk-ant-[A-Za-z0-9_-]{16,}/ },\n { id: 'provider-key', pattern: /sk-(?:proj-|tan-)?[A-Za-z0-9_-]{16,}/ },\n { id: 'stripe-key', pattern: /(?:sk|rk)_(?:live|test)_[A-Za-z0-9_]{10,}/ },\n { id: 'google-api-key', pattern: /AIza[0-9A-Za-z_-]{20,}/ },\n { id: 'github-token', pattern: /(?:gh[pousr]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,})/ },\n { id: 'slack-token', pattern: /xox[abeoprs]-[A-Za-z0-9-]{10,}/ },\n { id: 'aws-access-key', pattern: /(?:AKIA|ASIA)[A-Z0-9]{16}\\b/ },\n { id: 'tangle-capability', pattern: /(?:hubcap_|hct_)[A-Za-z0-9_=-]{8,}/ },\n {\n // Scheme, userinfo user and password each bounded (32/512/512 chars): the\n // unbounded `*`/`+` here made `detectCredential` catastrophically slow on\n // adversarial text with no `://` at all — 256 KiB of `\"a.\"` took ~59s,\n // measured before this fix (scratchpad/rv/before.ts). A real URL's scheme\n // and userinfo are always far under these bounds.\n id: 'url-credentials',\n pattern: /\\b[a-z][a-z0-9+.-]{0,31}:\\/\\/[^\\s/:@]{1,512}:[^\\s/@]{1,512}@/i,\n },\n {\n id: 'url-secret-param',\n pattern:\n /[?&](?:access_token|api_key|apikey|auth|token|secret|password|sig|signature|x-amz-signature|x-goog-signature)=[^&\\s\"'#)]{8,}/i,\n },\n {\n // `GH_TOKEN=…`, `--api-key=…`, `\"client_secret\": \"…\"`, `password: …` in free\n // text. The value must mix letters and digits and be at least 12\n // characters, so prose (`token: string`), variable references (`$TOKEN`)\n // and dotenvx ciphertext (`encrypted:…`) pass. The pattern starts at the\n // key word itself, with no identifier prefix, so it scans in linear time.\n // The two mixed-content lookaheads and the value itself are bounded to\n // 512 chars: unbounded, `'token='` repeated took ~20s at 256 KiB and\n // `'password:x'` repeated took ~12s at 256 KiB (measured before this fix,\n // scratchpad/rv/before.ts). A real credential value is always far under\n // 512 chars.\n id: 'secret-assignment',\n pattern:\n /(?:api[_-]?key|apikey|access[_-]?key|secret[_-]?key|private[_-]?key|secret|token|password|passwd|passphrase|credentials?)[\"']?[ \\t]*[:=][ \\t]*[\"']?(?!encrypted:)(?![$`<[{(%])(?=[^\\s\"'`,;&|]{0,512}[0-9])(?=[^\\s\"'`,;&|]{0,512}[A-Za-z])[^\\s\"'`,;&|]{12,512}/i,\n },\n {\n // `{\"password\": \"hunter2\"}` or `'client_secret': '…'` inside serialized\n // JSON, YAML or a log line. A quoted credential field name followed by a\n // quoted value holds a secret whatever the value's shape or length. Bare\n // `\"token\"` is left out: model logprob output uses it for text tokens.\n // Placeholders (`[REDACTED…]`, `$VAR`, `{env:VAR}`, `***`, `<value>`) and\n // prose with two or more spaces (a field description) do not match.\n id: 'json-secret',\n pattern:\n /[\"'][A-Za-z0-9_.-]{0,40}?(?:api[_-]?key|apikey|access[_-]?key|secret[_-]?key|private[_-]?key|client[_-]?secret|secret|password|passwd|passphrase|credentials?|(?:access|refresh|id|auth|session|bearer|api|github|gh|slack|npm)[_-]?token)[\"'][ \\t]*:[ \\t]*[\"'](?!\\[REDACTED|[$*{<])(?![^\"'\\r\\n]* [^\"'\\r\\n]* )[^\"'\\r\\n]{3,}[\"']/i,\n },\n {\n // `DB_PASSWORD=CorrectHorseBatteryStaple`, `PGPASSWORD=postgres`: unlike\n // `secret-assignment` above, the all-upper-case env-var name ending in a\n // credential word is itself the signal, so a letters-only or short real\n // password still matches (no digit-mixing or 12-char minimum). Requires\n // the name to be immediately followed by `=`, so `MAX_TOKENS=16` and\n // `TOKEN_EXPIRY=…` (the word isn't the end of the name) do not match.\n id: 'env-secret-assignment',\n pattern:\n /\\b[A-Z][A-Z0-9_]*?(?:PASSWORD|PASSWD|SECRET|PASSPHRASE|APIKEY|API_KEY|TOKEN|CREDENTIALS?)[ \\t]*=[ \\t]*(?!\\$|<|\\*|\\{|%|encrypted:)[^\\s\"'`,;&|]{4,}/,\n },\n // Bare-key shapes not covered above. Each requires a distinctive prefix so\n // it does not fire on ordinary identifiers — same reasoning as the\n // provider-branded block above, and the same leading-`\\b` bug: a token\n // glued to preceding text by a digit or underscore (`1ghp_…`, `_sk_live_…`)\n // is invisible to an anchored detector.\n { id: 'huggingface-token', pattern: /hf_[A-Za-z0-9]{20,}/ },\n { id: 'npm-token', pattern: /npm_[A-Za-z0-9]{20,}/ },\n { id: 'gitlab-token', pattern: /glpat-[A-Za-z0-9_-]{16,}/ },\n { id: 'groq-key', pattern: /gsk_[A-Za-z0-9]{20,}/ },\n { id: 'xai-key', pattern: /xai-[A-Za-z0-9]{16,}/ },\n // ElevenLabs and similar bare `sk_<hex>` shapes — underscore, unlike the\n // hyphenated `sk-…` `provider-key` pattern above, so the two never overlap.\n { id: 'bare-sk-key', pattern: /sk_[A-Za-z0-9]{32,}\\b/ },\n {\n // `Cookie: sessionid=…; csrftoken=…` in free text or a captured header.\n id: 'cookie-header',\n pattern: /\\bcookie\\s*:\\s*[A-Za-z0-9_-]+=[^;\\r\\n]{3,}(?:;\\s*[A-Za-z0-9_-]+=[^;\\r\\n]{3,})*/i,\n },\n]\n\n/** Personal-data shapes, replaced in place so the surrounding text survives. */\nexport const PERSONAL_DATA_DETECTORS: readonly (ValueDetector & {\n /** A substring the text must contain before the pattern runs. */\n requires?: string\n accept?: (match: string) => boolean\n})[] = [\n {\n id: 'email',\n requires: '@',\n pattern: /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/g,\n accept: isEmailAddress,\n },\n {\n // Card numbers: a card-network prefix and a valid Luhn digit, written\n // unbroken (13-19 digits) or in printed groups (4-4-4-4, 4-4-4-4-3, Amex\n // 4-6-5). A word character or hyphen on either side rejects the match, so\n // digits inside UUIDs, dated file names and hyphenated ids never match.\n id: 'card-number',\n pattern:\n /(?<![\\w-])(?:\\d{13,19}|\\d{4}([ -])\\d{4}\\1\\d{4}\\1\\d{4}(?:\\1\\d{3})?|\\d{4}([ -])\\d{6}\\2\\d{5})(?![\\w-])/g,\n accept: (match) => {\n const digits = match.replace(/[ -]/g, '')\n return CARD_PREFIX.test(digits) && luhnValid(digits)\n },\n },\n { id: 'ssn', pattern: /\\b\\d{3}-\\d{2}-\\d{4}\\b/g },\n {\n // Separators are required: a bare ten-digit run is usually an epoch second or an id.\n id: 'phone',\n pattern: /(?:\\+1[-.\\s]?)?(?:\\(\\d{3}\\)\\s?|\\b\\d{3}[-.\\s])\\d{3}[-.\\s]\\d{4}\\b/g,\n },\n]\n\n/** Visa, Mastercard, Amex, Diners, JCB, Discover and UnionPay issuer prefixes. */\nconst CARD_PREFIX = /^(?:4|5[1-5]|2[2-7]|3[04-9]|6(?:011|4[4-9]|5|2))/\n\n/**\n * Top-level domains that are file extensions: `icon@2x.png`, `worker@3.service`\n * and `notes@AGENTS.md` are not addresses.\n */\nconst NON_EMAIL_TLDS: ReadonlySet<string> = new Set([\n 'md',\n 'mdx',\n 'txt',\n 'json',\n 'jsonl',\n 'yaml',\n 'yml',\n 'toml',\n 'lock',\n 'ts',\n 'tsx',\n 'js',\n 'jsx',\n 'mjs',\n 'cjs',\n 'py',\n 'rs',\n 'go',\n 'sh',\n 'css',\n 'html',\n 'svg',\n 'png',\n 'jpg',\n 'jpeg',\n 'gif',\n 'webp',\n 'service',\n 'socket',\n 'timer',\n 'mount',\n 'target',\n])\n\nfunction isEmailAddress(match: string): boolean {\n // `git@github.com:org/repo` is an SSH remote, not a person.\n if (match.toLowerCase().startsWith('git@')) return false\n const tld = match.slice(match.lastIndexOf('.') + 1).toLowerCase()\n return !NON_EMAIL_TLDS.has(tld)\n}\n\nfunction luhnValid(digits: string): boolean {\n if (/^(\\d)\\1+$/.test(digits)) return false\n let sum = 0\n let double = false\n for (let index = digits.length - 1; index >= 0; index -= 1) {\n let digit = digits.charCodeAt(index) - 48\n if (double) {\n digit *= 2\n if (digit > 9) digit -= 9\n }\n sum += digit\n double = !double\n }\n return sum % 10 === 0\n}\n\n/** The first credential detector that matches, or undefined. */\nexport function detectCredential(text: string): string | undefined {\n for (const detector of CREDENTIAL_DETECTORS) {\n if (detector.pattern.test(text)) return detector.id\n }\n return undefined\n}\n\n/** Personal-data detector ids that match somewhere in `text`. */\nexport function detectPersonalData(text: string): string[] {\n const hits: string[] = []\n for (const detector of PERSONAL_DATA_DETECTORS) {\n if (detector.requires && !text.includes(detector.requires)) continue\n detector.pattern.lastIndex = 0\n for (const match of text.matchAll(detector.pattern)) {\n if (!detector.accept || detector.accept(match[0])) {\n hits.push(detector.id)\n break\n }\n }\n }\n return hits\n}\n\n/**\n * Every form in which a known secret can appear in a trace: as written,\n * base64, base64url and URL-encoded. Values shorter than 4 characters are\n * ignored; they would match ordinary text.\n */\nexport function knownSecretForms(values: readonly string[] | undefined): string[] {\n const forms = new Set<string>()\n for (const value of values ?? []) {\n if (value.length < 4) continue\n const bytes = Buffer.from(value, 'utf8')\n forms.add(value)\n forms.add(bytes.toString('base64'))\n forms.add(bytes.toString('base64url'))\n forms.add(encodeURIComponent(value))\n }\n // Longest first, so a secret that contains another is reported as itself.\n return [...forms].sort((left, right) => right.length - left.length)\n}\n\nconst BASE64_TEXT = /^[A-Za-z0-9+/_-]+={0,2}$/\n\n// A base64 blob embedded in larger text — `Authorization: Basic <base64>` is\n// the common case — can hold a known secret without the WHOLE string being\n// base64. Bounded to 4096 chars per candidate: this scans in linear time (the\n// sum of candidate lengths is at most `text.length`), so no ReDoS risk.\nconst EMBEDDED_BASE64 = /[A-Za-z0-9+/]{16,4096}={0,2}/g\n\nfunction containsKnownSecret(text: string, forms: readonly string[]): boolean {\n if (forms.length === 0) return false\n if (forms.some((form) => text.includes(form))) return true\n // A whole-string base64 payload can hold a secret at any byte offset.\n if (text.length >= 8 && BASE64_TEXT.test(text)) {\n const decoded = Buffer.from(\n text,\n text.includes('-') || text.includes('_') ? 'base64url' : 'base64',\n ).toString('utf8')\n if (forms.some((form) => decoded.includes(form))) return true\n }\n // `Basic <base64(user:key)>` jointly encodes the userinfo, so the secret's\n // OWN base64 form (added to `forms` above) is generally not a substring of\n // it — 3-byte base64 group alignment shifts with whatever precedes the\n // secret in the original bytes. Decode any embedded base64-looking run and\n // check its plaintext directly instead of relying on aligned forms.\n for (const match of text.matchAll(EMBEDDED_BASE64)) {\n if (match[0] === text) continue // already checked above\n try {\n const decoded = Buffer.from(match[0], 'base64').toString('utf8')\n if (forms.some((form) => decoded.includes(form))) return true\n } catch {\n // Not valid base64 (e.g. wrong padding) — not a candidate.\n }\n }\n return false\n}\n\n/** The detector that marks `text` as a credential: a known secret first, then the value shapes. */\nexport function credentialIn(text: string, knownSecrets: readonly string[]): string | undefined {\n return containsKnownSecret(text, knownSecrets) ? 'known-secret' : detectCredential(text)\n}\n","/**\n * The redaction core: the one place that decides what must not leave a\n * process or a machine. Every trace writer, exporter, uploader and share path\n * calls it.\n *\n * Three profiles, each a superset of the one before:\n * - `default` removes credentials, found by key name and by value shape, and\n * personal data (email addresses, card numbers, SSNs, phone numbers).\n * Content is kept. Strings are capped at 1 MiB.\n * - `share` also removes phone, IP and postal-address fields, replaces\n * account, user, tenant, session and request identifiers with pseudonyms\n * that stay consistent within one call, and caps strings at 64 KiB.\n * - `strict` also removes prompt, completion, message, tool payload and other\n * raw-content fields and embedded media, and caps strings at 4 KiB.\n *\n * A string that holds a credential is replaced whole with\n * `[REDACTED:<detector>]`. Replacing only the matched span can leave part of a\n * secret behind when a pattern's boundary is wrong. Personal data inside prose\n * is replaced in place, so the rest of the text stays readable.\n *\n * `assessShareSafety` reads a value without changing it and returns SAFE,\n * SAFE_WITH_WARNINGS, UNSAFE or UNKNOWN. UNKNOWN means the scanner could not\n * read part of the value (a cycle, binary data, nesting past the depth limit);\n * it is never reported as safe. `redactForShare` redacts and then assesses the\n * redacted output, so a detector gap shows up as UNSAFE instead of a leak.\n *\n * Reports and findings carry paths, categories and detector ids, never the\n * values they matched.\n *\n * The key classifier and the credential detector list are adapted from\n * agent-inspect (MIT, commit 3c3cbeda). `scripts/redaction-corpus.json` holds\n * the must-flag and must-not-flag cases, including the copied agent-inspect\n * safety corpus with its MIT notice; `pnpm redaction:corpus` runs this module\n * over every case.\n */\n\nimport { createHmac, randomBytes } from 'node:crypto'\nimport {\n classifyKey,\n classifyKeyName,\n credentialIn,\n detectPersonalData,\n knownSecretForms,\n PERSONAL_DATA_DETECTORS,\n} from './redaction/detectors'\n\nexport type RedactionProfile = 'default' | 'share' | 'strict'\n\nexport const REDACTION_PROFILES: readonly RedactionProfile[] = ['default', 'share', 'strict']\n\n/** What a finding is about. `media` is embedded binary content (a `data:` URI) no text detector can read. */\nexport type SafetyCategory = 'credential' | 'personal-data' | 'identifier' | 'raw-content' | 'media'\n\n/**\n * Version of the detector set and profile rules. Stored work that depends on\n * redaction behavior (saved optimizer inputs, per-span redaction stamps) keys\n * on it, so bump it whenever a detector, key list, cap or marker changes.\n */\nexport const REDACTION_VERSION = '2.4.0'\n\nexport interface RedactionFinding {\n /** JSON Pointer (RFC 6901) to the value or key that was changed. */\n path: string\n category: SafetyCategory\n detector: string\n action: 'redacted' | 'pseudonymized' | 'truncated'\n}\n\nexport interface RedactionReport {\n version: string\n profile: RedactionProfile\n /** Values and keys replaced, pseudonymized or truncated. */\n redactionCount: number\n byDetector: Record<string, number>\n truncatedCount: number\n findings: RedactionFinding[]\n}\n\nexport interface RedactOptions {\n /** Default `default`. */\n profile?: RedactionProfile\n /** Lower the profile's per-string cap. A value above the profile cap is ignored. */\n maxStringBytes?: number\n /**\n * Exact values the caller knows are secret (an API key the run was given, a\n * password from the environment), whatever shape they have. Each occurrence\n * in a string, as written or base64, base64url or URL-encoded, becomes\n * `[REDACTED:known-secret]` and the text around it is kept. A key that\n * contains one, and a whole-string base64 payload that holds one at any byte\n * offset, is replaced whole.\n */\n knownSecrets?: readonly string[]\n /** Add this call's findings to an existing report instead of a new one. */\n report?: RedactionReport\n}\n\nexport interface AssessOptions {\n /** Default `default`. */\n profile?: RedactionProfile\n /** As in `RedactOptions`: any surviving occurrence makes the verdict UNSAFE. */\n knownSecrets?: readonly string[]\n}\n\nexport type ShareSafetyStatus = 'SAFE' | 'SAFE_WITH_WARNINGS' | 'UNSAFE' | 'UNKNOWN'\n\nexport interface ShareSafetyFinding {\n category: SafetyCategory\n detector: string\n severity: 'error' | 'warning'\n count: number\n /** Up to five JSON Pointers where the detector fired. */\n paths: string[]\n}\n\nexport interface ShareSafetyVerdict {\n status: ShareSafetyStatus\n profile: RedactionProfile\n findings: ShareSafetyFinding[]\n /** Parts the scanner could not read, as `<path>: <reason>`. Any entry makes the status UNKNOWN. */\n unreadable: string[]\n}\n\n// ── Profiles ─────────────────────────────────────────────────────────────\n\ninterface ProfileRules {\n maxStringBytes: number\n /** Key categories whose values are removed or pseudonymized. */\n redactKeys: ReadonlySet<'share-personal' | 'identifier' | 'raw-content'>\n redactMedia: boolean\n severity: Record<SafetyCategory, 'error' | 'warning' | undefined>\n}\n\nconst KIB = 1024\n\nconst PROFILE_RULES: Record<RedactionProfile, ProfileRules> = {\n default: {\n maxStringBytes: 1024 * KIB,\n redactKeys: new Set(),\n redactMedia: false,\n severity: {\n credential: 'error',\n 'personal-data': 'warning',\n identifier: undefined,\n 'raw-content': 'warning',\n media: 'warning',\n },\n },\n share: {\n maxStringBytes: 64 * KIB,\n redactKeys: new Set(['share-personal', 'identifier']),\n redactMedia: false,\n severity: {\n credential: 'error',\n 'personal-data': 'error',\n identifier: 'warning',\n 'raw-content': 'warning',\n media: 'warning',\n },\n },\n strict: {\n maxStringBytes: 4 * KIB,\n redactKeys: new Set(['share-personal', 'identifier', 'raw-content']),\n redactMedia: true,\n severity: {\n credential: 'error',\n 'personal-data': 'error',\n identifier: 'warning',\n 'raw-content': 'error',\n media: 'error',\n },\n },\n}\n\nconst MARKER_PREFIX = '[REDACTED:'\n\nfunction marker(detector: string): string {\n return `${MARKER_PREFIX}${detector}]`\n}\n\n/**\n * Placeholders other tools write for a removed value. A credential field that\n * holds one of these is already redacted and is not flagged again.\n */\nconst REDACTED_PLACEHOLDER =\n /^(?:\\[(?:REDACTED|redacted)(?::[^\\]]*)?\\]|\\[ID:[0-9a-f]{12}\\]|\\*{3,}|<redacted>|«redacted»|\\[HASH:[0-9a-f]{8,}\\])$/\n\nfunction isPlaceholder(value: string): boolean {\n return value === '' || REDACTED_PLACEHOLDER.test(value)\n}\n\n// The whole string must be the data URI — `$` at the end, not just a `^`\n// prefix check. A prefix-only check let `data:text/plain;base64,…\\n` PLUS\n// arbitrary trailing text through as unread \"media\", when the trailing text\n// (or, for text/json mimes, the payload itself once decoded) is exactly the\n// kind of prose a credential or personal-data detector should see.\nconst DATA_URI = /^data:([\\w.+-]+\\/[\\w.+-]+)(?:;[\\w.+-]+=[\\w.+-]+)*;base64,([A-Za-z0-9+/=\\s]*)$/i\n\n/** A data: URI's mime type and base64 payload, only when the whole string is the URI. */\nfunction matchDataUri(text: string): { mime: string; payload: string } | undefined {\n const m = DATA_URI.exec(text)\n if (!m) return undefined\n return { mime: (m[1] ?? '').toLowerCase(), payload: m[2] ?? '' }\n}\n\n/** Decodes a data: URI's base64 payload to text, or undefined if it is not valid base64. */\nfunction decodeDataUriPayload(payload: string): string | undefined {\n const cleaned = payload.replace(/\\s+/g, '')\n if (cleaned.length === 0) return ''\n if (!/^[A-Za-z0-9+/]*={0,2}$/.test(cleaned) || cleaned.length % 4 !== 0) return undefined\n try {\n return Buffer.from(cleaned, 'base64').toString('utf8')\n } catch {\n return undefined\n }\n}\n\nconst READABLE_IMAGE_MIME = /^image\\//\n\n/** Mimes whose payload is text a detector can read once decoded. */\nconst DECODABLE_TEXT_MIME = /^text\\/|^application\\/json$/\n\n/** Whether a decoded data: URI payload holds a credential or personal data,\n * by key name (for application/json) or by value shape (for any text). */\nfunction decodedPayloadIsUnsafe(\n decoded: string,\n mime: string,\n knownSecrets: readonly string[],\n): boolean {\n if (mime === 'application/json') {\n try {\n return jsonValueIsUnsafe(JSON.parse(decoded), knownSecrets)\n } catch {\n // Not actually valid JSON despite the mime type — fall through to plain text.\n }\n }\n if (credentialIn(decoded, knownSecrets)) return true\n return detectPersonalData(decoded).length > 0\n}\n\nfunction jsonValueIsUnsafe(value: unknown, knownSecrets: readonly string[]): boolean {\n if (value === null || value === undefined) return false\n if (typeof value === 'string')\n return credentialIn(value, knownSecrets) !== undefined || detectPersonalData(value).length > 0\n if (typeof value !== 'object') return false\n if (Array.isArray(value)) return value.some((item) => jsonValueIsUnsafe(item, knownSecrets))\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\n const category = classifyKey(key)\n if (category === 'credential') return true\n if (category === 'personal-data' && (typeof item === 'string' || typeof item === 'number'))\n return true\n if (jsonValueIsUnsafe(item, knownSecrets)) return true\n }\n return false\n}\n\n// ── Redaction ────────────────────────────────────────────────────────────\n\nconst MAX_DEPTH = 64\n\ninterface WalkState {\n rules: ProfileRules\n maxStringBytes: number\n knownSecrets: string[]\n report: RedactionReport\n /** Created on first use: most calls pseudonymize nothing. */\n pseudonymKey?: Buffer\n seen: WeakSet<object>\n}\n\nfunction record(\n state: WalkState,\n path: string,\n category: SafetyCategory,\n detector: string,\n action: RedactionFinding['action'],\n): void {\n const report = state.report\n if (action === 'truncated') report.truncatedCount += 1\n report.redactionCount += 1\n report.byDetector[detector] = (report.byDetector[detector] ?? 0) + 1\n report.findings.push({ path, category, detector, action })\n}\n\nfunction pointer(parent: string, key: string | number): string {\n return `${parent}/${String(key).replace(/~/g, '~0').replace(/\\//g, '~1')}`\n}\n\nfunction truncateUtf8(text: string, maxBytes: number): string | undefined {\n if (text.length <= maxBytes / 4) return undefined\n const bytes = Buffer.from(text, 'utf8')\n if (bytes.length <= maxBytes) return undefined\n // Step back to the first byte of a UTF-8 sequence so no character is split.\n let cut = maxBytes\n while (cut > 0 && ((bytes[cut] ?? 0) & 0xc0) === 0x80) cut -= 1\n return `${bytes.subarray(0, cut).toString('utf8')}…[truncated ${bytes.length - cut} bytes]`\n}\n\nfunction redactStringAt(text: string, path: string, state: WalkState): string {\n if (isPlaceholder(text)) return text\n // A known secret is an exact value, so it is cut out where it stands and the\n // text around it survives: an error message keeps its diagnosis.\n let output = text\n for (const form of state.knownSecrets) {\n if (!output.includes(form)) continue\n output = output.split(form).join(marker('known-secret'))\n record(state, path, 'credential', 'known-secret', 'redacted')\n }\n const dataUri = matchDataUri(output)\n if (dataUri) {\n if (DECODABLE_TEXT_MIME.test(dataUri.mime)) {\n const decoded = decodeDataUriPayload(dataUri.payload)\n if (decoded === undefined) {\n // Can't verify what an undecodable payload holds — fail closed rather\n // than pass it through as if it were opaque, harmless media.\n record(state, path, 'credential', 'data-uri-payload', 'redacted')\n return marker('data-uri-payload')\n }\n if (decodedPayloadIsUnsafe(decoded, dataUri.mime, state.knownSecrets)) {\n record(state, path, 'credential', 'data-uri-payload', 'redacted')\n return marker('data-uri-payload')\n }\n // Decoded clean: still opaque bytes to a downstream reader once\n // embedded, so it's subject to the ordinary media rule below, same as\n // any other data URI.\n }\n if (!state.rules.redactMedia) return output\n record(state, path, 'media', 'media', 'redacted')\n return marker('media')\n }\n // A value shape, or a whole-string base64 payload that holds a known secret\n // at any byte offset, replaces the whole string. The detectors themselves\n // only ever see a bounded prefix (`boundForScan`): a credential that lives\n // entirely beyond `maxStringBytes` would be truncated out of the output\n // below anyway, so scanning past the bound costs time without changing\n // what can leak. The untouched tail is reattached after the personal-data\n // pass so later truncation still sees (and cuts) the full length.\n const boundLen = Math.min(output.length, state.maxStringBytes)\n let scanTarget = output.slice(0, boundLen)\n const tail = output.slice(boundLen)\n const credential = credentialIn(scanTarget, state.knownSecrets)\n if (credential) {\n record(state, path, 'credential', credential, 'redacted')\n return marker(credential)\n }\n for (const detector of PERSONAL_DATA_DETECTORS) {\n if (detector.requires && !scanTarget.includes(detector.requires)) continue\n scanTarget = scanTarget.replace(detector.pattern, (match) => {\n if (detector.accept && !detector.accept(match)) return match\n record(state, path, 'personal-data', detector.id, 'redacted')\n return marker(detector.id)\n })\n }\n output = scanTarget + tail\n const truncated = truncateUtf8(output, state.maxStringBytes)\n if (truncated === undefined) return output\n record(state, path, 'raw-content', 'size-cap', 'truncated')\n return truncated\n}\n\nfunction pseudonym(value: string | number, state: WalkState): string {\n state.pseudonymKey ??= randomBytes(32)\n const digest = createHmac('sha256', state.pseudonymKey).update(String(value)).digest('hex')\n return `[ID:${digest.slice(0, 12)}]`\n}\n\nfunction redactKeyed(\n key: string,\n value: unknown,\n path: string,\n depth: number,\n state: WalkState,\n): unknown {\n const kind = classifyKeyName(key)\n if (value === null || value === undefined || typeof value === 'boolean') {\n return value\n }\n if (typeof value === 'string' && isPlaceholder(value)) return value\n // Numbers under a credential name are limits and counts (`password_max_age`), not secrets.\n if (kind === 'credential' && typeof value !== 'number') {\n record(state, path, 'credential', 'credential-key', 'redacted')\n return marker('credential-key')\n }\n if (\n kind === 'email' ||\n (kind === 'share-personal' && state.rules.redactKeys.has('share-personal'))\n ) {\n if (typeof value === 'string' || typeof value === 'number') {\n record(state, path, 'personal-data', 'personal-data-key', 'redacted')\n return marker('personal-data-key')\n }\n }\n if (kind === 'identifier' && state.rules.redactKeys.has('identifier')) {\n if (typeof value === 'string' || typeof value === 'number') {\n record(state, path, 'identifier', 'identifier-key', 'pseudonymized')\n return pseudonym(value, state)\n }\n }\n if (\n kind === 'raw-content' &&\n state.rules.redactKeys.has('raw-content') &&\n typeof value !== 'number'\n ) {\n record(state, path, 'raw-content', 'raw-content-key', 'redacted')\n return marker('raw-content-key')\n }\n return walk(value, path, depth + 1, state)\n}\n\nfunction walk(value: unknown, path: string, depth: number, state: WalkState): unknown {\n if (typeof value === 'string') return redactStringAt(value, path, state)\n if (value === null || typeof value !== 'object') return value\n if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {\n record(state, path, 'media', 'binary', 'redacted')\n return marker('binary')\n }\n if (value instanceof Date) return value\n if (depth > MAX_DEPTH) {\n record(state, path, 'raw-content', 'depth-limit', 'truncated')\n return marker('depth-limit')\n }\n if (state.seen.has(value)) {\n record(state, path, 'raw-content', 'circular', 'redacted')\n return marker('circular')\n }\n state.seen.add(value)\n try {\n if (Array.isArray(value)) {\n return value.map((item, index) => walk(item, pointer(path, index), depth + 1, state))\n }\n const out: Record<string, unknown> = {}\n let renamed = 0\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\n let outKey = key\n const keyCredential = credentialIn(key, state.knownSecrets)\n // A personal-data value used AS a key (an email or card number mapping\n // to something) is just as reachable as one in a value — walk() only\n // ever inspects keys for a credential shape, so `{'alice@x.com': 3}`\n // passed through unchanged with verdict SAFE.\n const keyPersonalData = keyCredential ? undefined : detectPersonalData(key)[0]\n if (keyCredential) {\n renamed += 1\n outKey = `${marker(keyCredential)}#${renamed}`\n record(state, pointer(path, outKey), 'credential', keyCredential, 'redacted')\n } else if (keyPersonalData) {\n renamed += 1\n outKey = `${marker(keyPersonalData)}#${renamed}`\n record(state, pointer(path, outKey), 'personal-data', keyPersonalData, 'redacted')\n }\n out[outKey] = redactKeyed(key, item, pointer(path, outKey), depth, state)\n }\n return out\n } finally {\n state.seen.delete(value)\n }\n}\n\n/** An empty report to accumulate `redactText` calls into. */\nexport function emptyRedactionReport(profile: RedactionProfile = 'default'): RedactionReport {\n return {\n version: REDACTION_VERSION,\n profile,\n redactionCount: 0,\n byDetector: {},\n truncatedCount: 0,\n findings: [],\n }\n}\n\nfunction newState(options: RedactOptions, report?: RedactionReport): WalkState {\n const profile = options.profile ?? 'default'\n const rules = PROFILE_RULES[profile]\n if (!rules) throw new Error(`unknown redaction profile: ${String(profile)}`)\n const requested = options.maxStringBytes\n const maxStringBytes =\n typeof requested === 'number' && Number.isFinite(requested) && requested >= 0\n ? Math.min(Math.floor(requested), rules.maxStringBytes)\n : rules.maxStringBytes\n return {\n rules,\n maxStringBytes,\n knownSecrets: knownSecretForms(options.knownSecrets),\n report: report ?? emptyRedactionReport(profile),\n seen: new WeakSet(),\n }\n}\n\n/**\n * Return a redacted deep copy of `value` and a report of what changed. Pure:\n * the input is not mutated. Never throws on the value's shape; cycles, binary\n * data and nesting past 64 levels are replaced with markers.\n */\nexport function redact<T>(\n value: T,\n options: RedactOptions = {},\n): { value: T; report: RedactionReport } {\n const state = newState(options, options.report)\n const out = walk(value, '', 0, state) as T\n return { value: out, report: state.report }\n}\n\n/**\n * Redact one free-text string with the value detectors (no field name is\n * known). Pass `report` to accumulate counts across calls.\n */\nexport function redactText(text: string, options: RedactOptions = {}): string {\n const state = newState(options, options.report)\n return redactStringAt(text, '', state)\n}\n\n// ── Share-safety assessment ──────────────────────────────────────────────\n\ninterface ScanState {\n profile: RedactionProfile\n rules: ProfileRules\n knownSecrets: string[]\n findings: Map<string, ShareSafetyFinding>\n unreadable: string[]\n seen: WeakSet<object>\n}\n\nfunction flag(state: ScanState, path: string, category: SafetyCategory, detector: string): void {\n const severity = state.rules.severity[category]\n if (!severity) return\n const id = `${category}\\u0000${detector}`\n const existing = state.findings.get(id)\n if (existing) {\n existing.count += 1\n if (existing.paths.length < 5) existing.paths.push(path)\n return\n }\n state.findings.set(id, { category, detector, severity, count: 1, paths: [path] })\n}\n\nfunction scanString(text: string, path: string, state: ScanState): void {\n if (isPlaceholder(text)) return\n const dataUri = matchDataUri(text)\n if (dataUri) {\n scanDataUri(dataUri, path, state)\n return\n }\n const credential = credentialIn(text, state.knownSecrets)\n if (credential) {\n flag(state, path, 'credential', credential)\n return\n }\n for (const detector of detectPersonalData(text)) flag(state, path, 'personal-data', detector)\n}\n\nfunction scanDataUri(\n dataUri: { mime: string; payload: string },\n path: string,\n state: ScanState,\n): void {\n if (READABLE_IMAGE_MIME.test(dataUri.mime)) {\n flag(state, path, 'media', 'media')\n return\n }\n if (DECODABLE_TEXT_MIME.test(dataUri.mime)) {\n const decoded = decodeDataUriPayload(dataUri.payload)\n if (decoded === undefined) {\n state.unreadable.push(`${path || '/'}: data URI payload is not valid base64`)\n return\n }\n if (dataUri.mime === 'application/json') {\n try {\n scan(JSON.parse(decoded), path, 0, state)\n return\n } catch {\n // Not actually valid JSON despite the mime type — fall through to plain text.\n }\n }\n scanString(decoded, path, state)\n return\n }\n // audio/video/octet-stream/etc: bytes no text detector can read. A warning\n // under `default` (matches the existing image rule); under `share` and\n // `strict` — the profiles that actually gate whether something may be sent\n // off the machine — treat it as unreadable so the verdict is UNKNOWN\n // instead of silently allowing it through.\n if (state.profile === 'default') {\n flag(state, path, 'media', 'media')\n } else {\n state.unreadable.push(`${path || '/'}: ${dataUri.mime} data URI cannot be read`)\n }\n}\n\nfunction scanKeyed(\n key: string,\n value: unknown,\n path: string,\n depth: number,\n state: ScanState,\n): void {\n if (value === null || value === undefined || typeof value === 'boolean') return\n if (typeof value === 'string' && isPlaceholder(value)) return\n const category = classifyKey(key)\n if (category === 'credential' && typeof value !== 'number') {\n flag(state, path, 'credential', 'credential-key')\n return\n }\n const scalar = typeof value === 'string' || typeof value === 'number'\n if (category === 'personal-data' && scalar) {\n const kind = classifyKeyName(key)\n // Phone, IP and address fields are flagged from the share profile up; email always.\n if (kind === 'email' || state.profile !== 'default') {\n flag(state, path, 'personal-data', 'personal-data-key')\n return\n }\n }\n if (category === 'identifier' && scalar) flag(state, path, 'identifier', 'identifier-key')\n if (category === 'raw-content' && typeof value !== 'number')\n flag(state, path, 'raw-content', 'raw-content-key')\n scan(value, path, depth + 1, state)\n}\n\nfunction scan(value: unknown, path: string, depth: number, state: ScanState): void {\n if (typeof value === 'string') {\n scanString(value, path, state)\n return\n }\n if (value === null || typeof value !== 'object') return\n if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {\n state.unreadable.push(`${path || '/'}: binary data`)\n return\n }\n if (value instanceof Date) return\n if (depth > MAX_DEPTH) {\n state.unreadable.push(`${path || '/'}: nested deeper than ${MAX_DEPTH} levels`)\n return\n }\n if (state.seen.has(value)) {\n state.unreadable.push(`${path || '/'}: circular reference`)\n return\n }\n state.seen.add(value)\n try {\n if (Array.isArray(value)) {\n for (const [index, item] of value.entries())\n scan(item, pointer(path, index), depth + 1, state)\n return\n }\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\n // A credential or personal-data value used as a key must not reach the\n // finding paths.\n const keyCredential = credentialIn(key, state.knownSecrets)\n const keyPersonalData = keyCredential ? undefined : detectPersonalData(key)[0]\n const keyDetector = keyCredential ?? keyPersonalData\n const segment = keyDetector ? marker(keyDetector) : key\n if (keyCredential) flag(state, pointer(path, segment), 'credential', keyCredential)\n else if (keyPersonalData)\n flag(state, pointer(path, segment), 'personal-data', keyPersonalData)\n scanKeyed(key, item, pointer(path, segment), depth, state)\n }\n } finally {\n state.seen.delete(value)\n }\n}\n\n/**\n * Read `value` without changing it and say whether it is safe to share under\n * `profile`. UNKNOWN when any part could not be read; UNSAFE when any\n * error-severity finding remains; SAFE_WITH_WARNINGS when only warnings\n * remain (raw content, embedded media, identifiers under `share`).\n */\nexport function assessShareSafety(value: unknown, options: AssessOptions = {}): ShareSafetyVerdict {\n const profile = options.profile ?? 'default'\n const rules = PROFILE_RULES[profile]\n if (!rules) throw new Error(`unknown redaction profile: ${String(profile)}`)\n const state: ScanState = {\n profile,\n rules,\n knownSecrets: knownSecretForms(options.knownSecrets),\n findings: new Map(),\n unreadable: [],\n seen: new WeakSet(),\n }\n scan(value, '', 0, state)\n return verdictFrom(profile, [...state.findings.values()], state.unreadable)\n}\n\n/**\n * One verdict over several parts (files in a directory, spans in a bundle).\n * Callers prefix each part's paths with its source before combining.\n */\nexport function combineVerdicts(\n profile: RedactionProfile,\n verdicts: readonly ShareSafetyVerdict[],\n unreadable: readonly string[] = [],\n): ShareSafetyVerdict {\n const findings = new Map<string, ShareSafetyFinding>()\n for (const verdict of verdicts) {\n for (const finding of verdict.findings) {\n const id = `${finding.category}\\u0000${finding.detector}`\n const existing = findings.get(id)\n if (!existing) {\n findings.set(id, { ...finding, paths: [...finding.paths] })\n continue\n }\n existing.count += finding.count\n for (const path of finding.paths) if (existing.paths.length < 5) existing.paths.push(path)\n }\n }\n return verdictFrom(\n profile,\n [...findings.values()],\n [...verdicts.flatMap((verdict) => verdict.unreadable), ...unreadable],\n )\n}\n\nfunction verdictFrom(\n profile: RedactionProfile,\n findings: readonly ShareSafetyFinding[],\n unreadable: readonly string[],\n): ShareSafetyVerdict {\n const status: ShareSafetyStatus =\n unreadable.length > 0\n ? 'UNKNOWN'\n : findings.some((finding) => finding.severity === 'error')\n ? 'UNSAFE'\n : findings.length > 0\n ? 'SAFE_WITH_WARNINGS'\n : 'SAFE'\n return { status, profile, findings: [...findings], unreadable: [...unreadable] }\n}\n\n/** Whether a verdict allows sharing: SAFE or SAFE_WITH_WARNINGS. UNSAFE and UNKNOWN refuse. */\nexport function shareAllowed(verdict: ShareSafetyVerdict): boolean {\n return verdict.status === 'SAFE' || verdict.status === 'SAFE_WITH_WARNINGS'\n}\n\n/**\n * Redact `value` under `profile`, then assess the redacted output. The\n * verdict describes what would actually be shared: a detector that failed to\n * remove something shows up as UNSAFE here.\n */\nexport function redactForShare<T>(\n value: T,\n options: RedactOptions = {},\n): { value: T; report: RedactionReport; verdict: ShareSafetyVerdict } {\n const redacted = redact(value, options)\n const verdict = assessShareSafety(redacted.value, {\n profile: options.profile,\n knownSecrets: options.knownSecrets,\n })\n return { value: redacted.value, report: redacted.report, verdict }\n}\n"],"mappings":";;;;;;;AASA,SAAgB,aAAa,KAAqB;CAChD,OAAO,IACJ,QAAQ,sBAAsB,OAAO,CAAC,CACtC,YAAY,CAAC,CACb,QAAQ,eAAe,GAAG,CAAC,CAC3B,QAAQ,YAAY,EAAE;AAC3B;;AAGA,MAAM,4CAAiD,IAAI,IAAI;CAC7D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,kBAAkB;CACtB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAM,aAAa,CAAC,SAAS,eAAe;;AAG5C,MAAM,sBAAsB;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAM,kBAAkB;CACtB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAM,mBAAmB;CACvB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;AAUA,SAAS,eAAe,YAAoB,MAAkC;CAC5E,KAAK,MAAM,OAAO,MAChB,IAAI,eAAe,OAAO,WAAW,SAAS,IAAI,KAAK,GAAG,OAAO;CAEnE,OAAO;AACT;AAEA,SAAS,qBAAqB,YAA6B;CACzD,IAAI,0BAA0B,IAAI,UAAU,GAAG,OAAO;CACtD,IAAI,eAAe,SAAS,OAAO;CAEnC,IAAI,WAAW,SAAS,QAAQ,GAAG,OAAO;CAC1C,OAAO,WAAW,SAAS,OAAO;AACpC;;AAKA,MAAM,gCAAgB,IAAI,IAA6B;AAEvD,SAAgB,gBAAgB,KAAmC;CACjE,MAAM,SAAS,cAAc,IAAI,GAAG;CACpC,IAAI,WAAW,KAAA,GAAW,OAAO,UAAU,KAAA;CAC3C,MAAM,OAAO,sBAAsB,aAAa,GAAG,CAAC;CACpD,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C,IAAI,CAAC,UAAU;GACb,SAAS,IAAI,IAAI;IAAE,GAAG;IAAS,OAAO,CAAC,GAAG,QAAQ,KAAK;GAAE,CAAC;GAC1D;EACF;EACA,SAAS,SAAS,QAAQ;EAC1B,KAAK,MAAM,QAAQ,QAAQ,OAAO,IAAI,SAAS,MAAM,SAAS,GAAG,SAAS,MAAM,KAAK,IAAI;CAC3F;CAEF,OAAO,YACL,SACA,CAAC,GAAG,SAAS,OAAO,CAAC,GACrB,CAAC,GAAG,SAAS,SAAS,YAAY,QAAQ,UAAU,GAAG,GAAG,UAAU,CACtE;AACF;AAEA,SAAS,YACP,SACA,UACA,YACoB;CASpB,OAAO;EAAE,QAPP,WAAW,SAAS,IAChB,YACA,SAAS,MAAM,YAAY,QAAQ,aAAa,OAAO,IACrD,WACA,SAAS,SAAS,IAChB,uBACA;EACO;EAAS,UAAU,CAAC,GAAG,QAAQ;EAAG,YAAY,CAAC,GAAG,UAAU;CAAE;AACjF;;AAGA,SAAgB,aAAa,SAAsC;CACjE,OAAO,QAAQ,WAAW,UAAU,QAAQ,WAAW;AACzD;;;;;;AAOA,SAAgB,eACd,OACA,UAAyB,CAAC,GAC0C;CACpE,MAAM,WAAW,OAAO,OAAO,OAAO;CACtC,MAAM,UAAU,kBAAkB,SAAS,OAAO;EAChD,SAAS,QAAQ;EACjB,cAAc,QAAQ;CACxB,CAAC;CACD,OAAO;EAAE,OAAO,SAAS;EAAO,QAAQ,SAAS;EAAQ;CAAQ;AACnE"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"schema-DkFJr3Y8.d.ts","names":[],"sources":["../src/statistics/descriptive.ts","../src/rollout/license.ts","../src/rollout/schema.ts"],"mappings":";;;;;iBASgB,aAAa;EAAU;EAAe;;;;;;;;;;iBAoBtC,mBACd,kBACA,qBACA;EAAQ;EAAe;;EACpB;EAAc;EAAe;;;iBAiClB,cAAc,iBAAiB;;UAM9B;WACN;WACA;WACA;WACA;WACA;WACA;WACA,c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;IAAW;IAAkB;IAAgB;IAAgB;;;EAE7D,WAAW;;EAEX,8BAA8B;;EAE9B;;;;;;;EAOA;;;;;;;EAOA,iBAAiB;;UAGF;EACf,eAAe;EACf;;;EAGA;EACA;;EAEA;;EAEA;;EAEA;;EAEA;EACA,MAAM;EACN,MAAM;EACN,QAAQ;;EAER,UAAU;EACV,WAAW;;EAEX,QAAQ;EACR,SAAS;EACT,MAAM;EACN,WAAW;EACX,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA0GE,iBAAiB,MAAM,cAAc;iBAgXrC,oBAAoB;iBAmBpB,kBACd,gBACA,2BACS,SAAS;iBAOJ,cAAc,iBAAiB,SAAS;;;;;;cAa1C;;;;;;UAOG,6BAA6B;EAC5C;;;;;;;;;;;;;;;;;;;;;;KAuBU,oBAAoB,KAAK;YACzB;EACV,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAsCK,aAAa,gBAAgB,mBAA2B;;iBAiBxD,kBACd,4BACA,mBACC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"store-tool-spans-B3i3fl0A.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,QAAQ;;EAER;;EAEA,YAAY;EACZ,SAAS,QAAQ;EACjB;EACA;EACA,aAAa;EACb;EACA,yBAAyB;EACzB,4BAA4B;EAC5B,eAAe,SAAS;EACxB,OAAO;EACP,OAAO,iBAAiB,SAAS;EACjC,SAAS;;;;;;;;iBASW,cACpB,OAAO,oBACP,SAAS,uBACR,QAAQ;UCn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UCEpD;;;EAGf;;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"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"store-tool-spans-C2g8UYm-.js","names":[],"sources":["../src/trace/capture-fetch.ts","../src/trace/otlp-encoding.ts","../src/trace/wire-ids.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 * The ONE encoding from this package's span values to OTLP wire values.\n *\n * Both exporters emit the same `OtlpSpan` shape, so an attribute typed as a\n * double by one and a string by the other would make the same run read\n * differently depending on which exporter produced it.\n */\n\n/** One OTLP `KeyValue`: the value is tagged with the protocol's type slot. */\ninterface OtlpAttribute {\n key: string\n value: { stringValue?: string; intValue?: string; doubleValue?: number; boolValue?: boolean }\n}\n\n/** OTLP `KeyValue[]` for a flat attribute record. */\nexport function toOtlpAttributes(\n record: Record<string, string | number | boolean>,\n): OtlpAttribute[] {\n return Object.entries(record).map(([key, value]) => ({\n key,\n value:\n typeof value === 'number'\n ? Number.isInteger(value)\n ? { intValue: value.toString() }\n : { doubleValue: value }\n : typeof value === 'boolean'\n ? { boolValue: value }\n : { stringValue: value },\n }))\n}\n\n/** OTLP nanosecond timestamp, as the decimal string the protocol requires. */\nexport function msToUnixNano(ms: number): string {\n return (BigInt(Math.floor(ms)) * 1_000_000n).toString()\n}\n","/**\n * The ONE mapping from agent-eval's human-readable ids (run ids, span labels)\n * to W3C/OTLP wire ids. Every exporter in this package MUST route through\n * these two functions — two exporters with private paddings once produced\n * DIFFERENT trace ids for the same run, and one emitted invalid hex embedding\n * the raw run id in the wire id (tangle-network/agent-runtime#694).\n *\n * Semantics:\n * - an id that is ALREADY a valid W3C id passes through unchanged, so a\n * trace id received from an inbound `traceparent` survives the round-trip\n * and cross-process correlation is preserved;\n * - anything else is derived with the contract's `deriveHexId`, the only\n * legal derivation — deterministic, so every process that derives from the\n * same human id mints the SAME wire id.\n */\n\nimport { deriveHexId, isW3CSpanId, isW3CTraceId } from '@tangle-network/agent-trace-contract'\n\n/** 32-hex W3C trace id for any id string. */\nexport function traceIdForWire(id: string): string {\n return isW3CTraceId(id) ? id : deriveHexId(id, 16)\n}\n\n/** 16-hex W3C span id for any id string. */\nexport function spanIdForWire(id: string): string {\n return isW3CSpanId(id) ? id : deriveHexId(id, 8)\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 {\n applyLlmSpanOtlpAttributes,\n applyToolSpanOtlpAttributes,\n OPENINFERENCE_SPAN_KIND,\n traceSpanKindToOpenInferenceKind,\n} from './otlp-attributes'\nimport { msToUnixNano, toOtlpAttributes } from './otlp-encoding'\nimport type { Run, Span, TraceEvent } from './schema'\nimport type { TraceStore } from './store'\nimport { spanIdForWire, traceIdForWire } from './wire-ids'\n\nconst OTEL_AGENT_EVAL_SCOPE = { name: '@tangle-network/agent-eval', version: '0.3.0' }\n\nexport interface OtlpSpan {\n traceId: string\n spanId: string\n parentSpanId?: string\n name: string\n kind: number\n startTimeUnixNano: string\n endTimeUnixNano: string\n attributes: Array<{\n key: string\n value: { stringValue?: string; intValue?: string; doubleValue?: number; boolValue?: boolean }\n }>\n events?: Array<{ timeUnixNano: string; name: string; attributes?: OtlpSpan['attributes'] }>\n status?: { code: number; message?: string }\n}\n\nexport interface OtlpResourceSpans {\n resource: { attributes: OtlpSpan['attributes'] }\n scopeSpans: Array<{ scope: typeof OTEL_AGENT_EVAL_SCOPE; spans: OtlpSpan[] }>\n}\n\nexport interface OtlpExport {\n resourceSpans: OtlpResourceSpans[]\n}\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 = runToTraceId(run)\n const otlpSpans: OtlpSpan[] = spans.map((s) =>\n spanToOtlp(s, traceId, eventsBySpan.get(s.spanId) ?? []),\n )\n return {\n resourceSpans: [\n {\n resource: {\n attributes: 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 },\n scopeSpans: [{ scope: OTEL_AGENT_EVAL_SCOPE, spans: otlpSpans }],\n },\n ],\n }\n}\n\nfunction spanToOtlp(span: Span, traceId: string, events: TraceEvent[]): OtlpSpan {\n const endedAt = span.endedAt ?? span.startedAt\n return {\n traceId,\n spanId: spanIdForWire(span.spanId),\n parentSpanId: span.parentSpanId ? spanIdForWire(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\nfunction runToTraceId(run: Run): string {\n return traceIdForWire(run.runId)\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;CACzF,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,MAAM,MAA8B,CAAC;CACrC,QAAQ,SAAS,OAAO,QAAQ;EAC9B,IAAI,IAAI,YAAY,KAAK;CAC3B,CAAC;CACD,OAAO,OAAO,KAAK,GAAG,CAAC,CAAC,SAAS,IAAI,MAAM,KAAA;AAC7C;AAEA,SAAS,eAAe,MAAuB;CAC7C,IAAI,KAAK,WAAW,GAAG,OAAO,KAAA;CAC9B,IAAI;EACF,OAAO,KAAK,MAAM,IAAI;CACxB,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,eAAe,gBACb,OACA,MACkB;CAClB,IAAI,OAAO,MAAM,SAAS,UAAU,OAAO,eAAe,KAAK,IAAI;CACnE,IAAI,MAAM,QAAQ,MAAM,OAAO,KAAA;CAC/B,IAAI,i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S,CAAC,KAAK,UAAU,CAAC,KAAK,QAAQ,CAAC,KAAK,UACrD,MAAM,IAAI,sBACR,gDAAgD,MAAM,6CACxD;CAEF,IAAI,CAAC,OAAO,SAAS,KAAK,SAAS,GACjC,MAAM,IAAI,sBACR,wCAAwC,KAAK,OAAO,wBACtD;CAEF,IAAI,KAAK,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"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"systemone-Cw2txK5m.d.ts","names":["_$__meta_eval0.calibrationFromPairs"],"sources":["../src/analyst/findings-store.ts","../src/analyst/findings-ledger.ts","../src/decision-point-records.ts","../src/decision-point.ts","../src/systemone-domain-match.ts","../src/systemone.ts"],"mappings":";;;;;;;;;;;;;;UA8BiB,yBAAyB;EACxC;;cAGW;WAGiB;mBAFX;EAEW,YAAA;EAItB,OAAO,eAAe,UAAU,mBAAmB;;EAQzD,WAAW;;EAkBX,QAAQ,gBAAgB;;UAOT;;EAEf,UAAU;;EAEV,aAAa;;EAEb,WAAW;;;;;EAKX,SAAS;IAAQ,UAAU;IAAkB,SAAS;;;UAGvC;;;;;;;;EAQf,cAAc,UAAU,gBAAgB,SAAS;;;;;;iBAkBnC,aACd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