@tangle-network/agent-eval 1.0.19 → 1.0.20
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 +15 -21
- package/dist/adapters/http.d.ts +2 -2
- package/dist/{agent-profile-CPv4tENR.d.ts → agent-profile-BO8ruI6R.d.ts} +3 -3
- package/dist/{agent-profile-CPv4tENR.d.ts.map → agent-profile-BO8ruI6R.d.ts.map} +1 -1
- package/dist/analyst/index.d.ts +14 -14
- package/dist/analyst/index.js +11 -12
- package/dist/analyst/index.js.map +1 -1
- package/dist/{analyze-runs-pJ4fhnYg.d.ts → analyze-runs-DicleUI_.d.ts} +4 -4
- package/dist/{analyze-runs-pJ4fhnYg.d.ts.map → analyze-runs-DicleUI_.d.ts.map} +1 -1
- package/dist/{analyze-runs-C7vWBDhl.js → analyze-runs-e9vfXY--.js} +6 -110
- package/dist/analyze-runs-e9vfXY--.js.map +1 -0
- package/dist/app-grade/index.d.ts +4 -4
- package/dist/app-grade/index.js +3 -3
- package/dist/{benchmark-command-DSJQeYom.js → benchmark-command-BGZD77Un.js} +13 -14
- package/dist/benchmark-command-BGZD77Un.js.map +1 -0
- package/dist/benchmarks/index.d.ts +4 -4
- package/dist/benchmarks/index.js +4 -5
- package/dist/benchmarks/index.js.map +1 -1
- package/dist/builder-eval/index.js +1 -1
- package/dist/{calibration-CbZPApIO.js → calibration-Ze7SjhT9.js} +2 -2
- package/dist/{calibration-CbZPApIO.js.map → calibration-Ze7SjhT9.js.map} +1 -1
- package/dist/campaign/index.d.ts +7 -7
- package/dist/campaign/index.js +10 -10
- package/dist/{campaign-BABipFel.js → campaign-BfDMncQN.js} +14 -15
- package/dist/{campaign-BABipFel.js.map → campaign-BfDMncQN.js.map} +1 -1
- package/dist/{campaign-evidence-DONEWvVY.js → campaign-evidence-BuKlRzSA.js} +3 -3
- package/dist/{campaign-evidence-DONEWvVY.js.map → campaign-evidence-BuKlRzSA.js.map} +1 -1
- package/dist/{chat-client-D0me8iwq.js → chat-client-Zz97O3NB.js} +2 -2
- package/dist/{chat-client-D0me8iwq.js.map → chat-client-Zz97O3NB.js.map} +1 -1
- package/dist/{chat-json-call-C473CwTt.js → chat-json-call-Dgi7-RH-.js} +2 -2
- package/dist/{chat-json-call-C473CwTt.js.map → chat-json-call-Dgi7-RH-.js.map} +1 -1
- package/dist/cli.js +7 -7
- package/dist/{types-0KglnQ9o.d.ts → cluster-Cd0MRbr9.d.ts} +44 -2
- package/dist/cluster-Cd0MRbr9.d.ts.map +1 -0
- package/dist/cluster-bootstrap-BYIW7QJ4.js +24 -0
- package/dist/cluster-bootstrap-BYIW7QJ4.js.map +1 -0
- package/dist/{completion-verifier-7KEfroqx.d.ts → completion-verifier-BEpsr3N4.d.ts} +2 -2
- package/dist/{completion-verifier-7KEfroqx.d.ts.map → completion-verifier-BEpsr3N4.d.ts.map} +1 -1
- package/dist/{completion-verifier-ClmJV_Yc.js → completion-verifier-DFyYFezn.js} +3 -3
- package/dist/{completion-verifier-ClmJV_Yc.js.map → completion-verifier-DFyYFezn.js.map} +1 -1
- package/dist/contract/index.d.ts +10 -10
- package/dist/contract/index.js +14 -15
- package/dist/contract/index.js.map +1 -1
- package/dist/{cost-ledger-CS8R3IZj.js → cost-ledger-DfhStGcZ.js} +2 -2
- package/dist/{cost-ledger-CS8R3IZj.js.map → cost-ledger-DfhStGcZ.js.map} +1 -1
- package/dist/{decision-point-CNyoKOkz.js → decision-point-DJWievVw.js} +4 -4
- package/dist/{decision-point-CNyoKOkz.js.map → decision-point-DJWievVw.js.map} +1 -1
- package/dist/{default-registry-BbXr18AT.d.ts → default-registry-BpGFsSpZ.d.ts} +7 -7
- package/dist/{default-registry-BbXr18AT.d.ts.map → default-registry-BpGFsSpZ.d.ts.map} +1 -1
- package/dist/{default-registry-BB9_jzyH.js → default-registry-CdMtoY-s.js} +5 -5
- package/dist/{default-registry-BB9_jzyH.js.map → default-registry-CdMtoY-s.js.map} +1 -1
- package/dist/{define-agent-eval-D_DQMH04.d.ts → define-agent-eval-DcK8mg63.d.ts} +7 -7
- package/dist/{define-agent-eval-D_DQMH04.d.ts.map → define-agent-eval-DcK8mg63.d.ts.map} +1 -1
- package/dist/{define-agent-eval-Q4FdXGj7.js → define-agent-eval-DuQNZajG.js} +6 -6
- package/dist/{define-agent-eval-Q4FdXGj7.js.map → define-agent-eval-DuQNZajG.js.map} +1 -1
- package/dist/diagnosis/index.d.ts +2 -2
- package/dist/diagnosis/index.js +1 -1
- package/dist/{dspy-rlm-engine-CqQc0R2l.js → dspy-rlm-engine-cWyn8G1a.js} +4 -4
- package/dist/{dspy-rlm-engine-CqQc0R2l.js.map → dspy-rlm-engine-cWyn8G1a.js.map} +1 -1
- package/dist/{engine-rfV8Ff8V.d.ts → engine-BF8naBn7.d.ts} +2 -2
- package/dist/{engine-rfV8Ff8V.d.ts.map → engine-BF8naBn7.d.ts.map} +1 -1
- package/dist/{eval-campaign-CZSCjxVb.js → eval-campaign-LmpC_5fm.js} +2 -2
- package/dist/{eval-campaign-CZSCjxVb.js.map → eval-campaign-LmpC_5fm.js.map} +1 -1
- package/dist/{evaluation-SDXKL6Fx.d.ts → evaluation-BCejQgkV.d.ts} +4 -4
- package/dist/{evaluation-SDXKL6Fx.d.ts.map → evaluation-BCejQgkV.d.ts.map} +1 -1
- package/dist/{evaluation-BBI37mRe.js → evaluation-bU_bhlv-.js} +2 -2
- package/dist/{evaluation-BBI37mRe.js.map → evaluation-bU_bhlv-.js.map} +1 -1
- package/dist/evaluation.d.ts +1 -1
- package/dist/evaluation.js +1 -1
- package/dist/{exact-types-CaLLU1Pz.d.ts → exact-types-VAFjtOQN.d.ts} +2 -2
- package/dist/{exact-types-CaLLU1Pz.d.ts.map → exact-types-VAFjtOQN.d.ts.map} +1 -1
- package/dist/experiment/index.d.ts +3 -5
- package/dist/experiment/index.d.ts.map +1 -1
- package/dist/experiment/index.js +7 -12
- package/dist/experiment/index.js.map +1 -1
- package/dist/{exporters-BYBG9b1n.d.ts → exporters-dQKYD_Zo.d.ts} +2 -2
- package/dist/{exporters-BYBG9b1n.d.ts.map → exporters-dQKYD_Zo.d.ts.map} +1 -1
- package/dist/{external-optimizer-process-CfrY-nJT.js → external-optimizer-process-2ImGH_LR.js} +2 -2
- package/dist/{external-optimizer-process-CfrY-nJT.js.map → external-optimizer-process-2ImGH_LR.js.map} +1 -1
- package/dist/{external-optimizer-subprocess-BtJk8UcU.js → external-optimizer-subprocess-_C_2yriN.js} +3 -3
- package/dist/{external-optimizer-subprocess-BtJk8UcU.js.map → external-optimizer-subprocess-_C_2yriN.js.map} +1 -1
- package/dist/{feedback-trajectory-P37ju-gW.d.ts → feedback-trajectory-DTj8eVTR.d.ts} +3 -3
- package/dist/{feedback-trajectory-P37ju-gW.d.ts.map → feedback-trajectory-DTj8eVTR.d.ts.map} +1 -1
- package/dist/{findings-store-BnYN57-h.js → findings-store-BSuaV3dN.js} +7 -24
- package/dist/findings-store-BSuaV3dN.js.map +1 -0
- package/dist/fuzz.js +2 -2
- package/dist/{index-BPmj-_ta.d.ts → index-Bc8BZfzb.d.ts} +10 -9
- package/dist/index-Bc8BZfzb.d.ts.map +1 -0
- package/dist/index-BdLmBInV.d.ts +1099 -0
- package/dist/index-BdLmBInV.d.ts.map +1 -0
- package/dist/{index-D4lT7aFu.d.ts → index-CeYLLnfi.d.ts} +28 -128
- package/dist/index-CeYLLnfi.d.ts.map +1 -0
- package/dist/{index-C3t17kHu.d.ts → index-CzfdjM6o.d.ts} +7 -100
- package/dist/index-CzfdjM6o.d.ts.map +1 -0
- package/dist/{index-HuSMvqR2.d.ts → index-DYNHOTTB.d.ts} +5 -5
- package/dist/{index-HuSMvqR2.d.ts.map → index-DYNHOTTB.d.ts.map} +1 -1
- package/dist/{index-AmfM3usI.d.ts → index-D_eAFB3T.d.ts} +8 -8
- package/dist/{index-AmfM3usI.d.ts.map → index-D_eAFB3T.d.ts.map} +1 -1
- package/dist/{index-DLVbfss9.d.ts → index-gSu9DUiw.d.ts} +8 -8
- package/dist/{index-DLVbfss9.d.ts.map → index-gSu9DUiw.d.ts.map} +1 -1
- package/dist/index.d.ts +29 -31
- package/dist/index.js +28 -164
- package/dist/index.js.map +1 -1
- package/dist/{integrity-BAdVzT8u.d.ts → integrity-CrmnGB2T.d.ts} +2 -2
- package/dist/{integrity-BAdVzT8u.d.ts.map → integrity-CrmnGB2T.d.ts.map} +1 -1
- package/dist/{judge-gate-CIlBrn6q.js → judge-gate-BliY81A0.js} +3 -3
- package/dist/{judge-gate-CIlBrn6q.js.map → judge-gate-BliY81A0.js.map} +1 -1
- package/dist/{kind-factory-Cfz8DUCc.js → kind-factory-CV0FNCMM.js} +2 -2
- package/dist/{kind-factory-Cfz8DUCc.js.map → kind-factory-CV0FNCMM.js.map} +1 -1
- package/dist/{llm-client-BdSiZ4qz.js → llm-client-DMMSg-Ro.js} +2 -2
- package/dist/{llm-client-BdSiZ4qz.js.map → llm-client-DMMSg-Ro.js.map} +1 -1
- package/dist/{llm-judge-VD_MI6kd.js → llm-judge-Bnxuwjxl.js} +13 -14
- package/dist/{llm-judge-VD_MI6kd.js.map → llm-judge-Bnxuwjxl.js.map} +1 -1
- package/dist/{matrix-Yg1lHIGI.d.ts → matrix-D6zEwLvE.d.ts} +2 -2
- package/dist/{matrix-Yg1lHIGI.d.ts.map → matrix-D6zEwLvE.d.ts.map} +1 -1
- package/dist/meta-eval/index.d.ts +2 -2
- package/dist/meta-eval/index.js +7 -7
- package/dist/{metrics-DNCAUtuB.js → metrics-zALlR17s.js} +16 -17
- package/dist/metrics-zALlR17s.js.map +1 -0
- package/dist/multishot/golden/index.d.ts +1 -1
- package/dist/multishot/index.d.ts +2 -2
- package/dist/multishot/index.js +1 -1
- package/dist/openapi.json +1 -1
- package/dist/{outcome-observations-DZu5hLYF.js → outcome-observations-BpicIVQi.js} +2 -3
- package/dist/{outcome-observations-DZu5hLYF.js.map → outcome-observations-BpicIVQi.js.map} +1 -1
- package/dist/paired-arms-Dep5tbsw.js +338 -0
- package/dist/paired-arms-Dep5tbsw.js.map +1 -0
- package/dist/{paired-promotion-decision-BDnqepZ1.d.ts → paired-promotion-decision-BNzPfXDw.d.ts} +3 -113
- package/dist/paired-promotion-decision-BNzPfXDw.d.ts.map +1 -0
- package/dist/{paired-promotion-decision-CiueaTTj.js → paired-promotion-decision-Nt4CkkOT.js} +2 -3
- package/dist/{paired-promotion-decision-CiueaTTj.js.map → paired-promotion-decision-Nt4CkkOT.js.map} +1 -1
- package/dist/{pareto-a3EOmjfe.js → pareto-C445lnEH.js} +3 -6
- package/dist/{pareto-a3EOmjfe.js.map → pareto-C445lnEH.js.map} +1 -1
- package/dist/pipelines/index.js +1 -1
- package/dist/{prime-protocol-DKRk4l4U.d.ts → prime-protocol-D1NkJRuD.d.ts} +2 -2
- package/dist/{prime-protocol-DKRk4l4U.d.ts.map → prime-protocol-D1NkJRuD.d.ts.map} +1 -1
- package/dist/{promotion-gate-DOkgJcLW.d.ts → promotion-gate-DjAsmBSZ.d.ts} +3 -67
- package/dist/promotion-gate-DjAsmBSZ.d.ts.map +1 -0
- package/dist/{promotion-policy-DLPcEnCf.js → promotion-policy-CUWOv01m.js} +4 -4
- package/dist/{promotion-policy-DLPcEnCf.js.map → promotion-policy-CUWOv01m.js.map} +1 -1
- package/dist/{proposal-findings-BfzzZ_lN.js → proposal-findings-DWs94yT8.js} +2 -2
- package/dist/{proposal-findings-BfzzZ_lN.js.map → proposal-findings-DWs94yT8.js.map} +1 -1
- package/dist/{registry-Ck7w-rr5.d.ts → registry-BAcEbzKm.d.ts} +4 -4
- package/dist/{registry-Ck7w-rr5.d.ts.map → registry-BAcEbzKm.d.ts.map} +1 -1
- package/dist/{release-confidence-nfQNh3eb.js → release-confidence-DDrkmWxT.js} +2 -2
- package/dist/{release-confidence-nfQNh3eb.js.map → release-confidence-DDrkmWxT.js.map} +1 -1
- package/dist/reporting.d.ts +4 -5
- package/dist/reporting.d.ts.map +1 -1
- package/dist/reporting.js +5 -7
- package/dist/reporting.js.map +1 -1
- package/dist/{researcher-CLnNJ7Or.d.ts → researcher-D35yo0B8.d.ts} +4 -4
- package/dist/{researcher-CLnNJ7Or.d.ts.map → researcher-D35yo0B8.d.ts.map} +1 -1
- package/dist/{reward-hacking-B88f-Kh7.js → reward-hacking-DRb8K6N1.js} +2 -3
- package/dist/{reward-hacking-B88f-Kh7.js.map → reward-hacking-DRb8K6N1.js.map} +1 -1
- package/dist/rl.d.ts +9 -8
- package/dist/rl.d.ts.map +1 -1
- package/dist/rl.js +8 -10
- package/dist/rl.js.map +1 -1
- package/dist/rollout/index.d.ts +4 -4
- package/dist/rollout/index.js +1 -1
- package/dist/{rollout-Cu7kHGIe.js → rollout-DKa54qer.js} +2 -2
- package/dist/{rollout-Cu7kHGIe.js.map → rollout-DKa54qer.js.map} +1 -1
- package/dist/{rubric-predictive-validity-D_6ZPTNR.js → rubric-predictive-validity-BMS7SUyh.js} +2 -2
- package/dist/{rubric-predictive-validity-D_6ZPTNR.js.map → rubric-predictive-validity-BMS7SUyh.js.map} +1 -1
- package/dist/{run-record-CbUi2adH.js → run-record-CIflWk6i.js} +2 -2
- package/dist/{run-record-CbUi2adH.js.map → run-record-CIflWk6i.js.map} +1 -1
- package/dist/{runtime-rollouts-kGn1K5ut.js → runtime-rollouts-CfRyjk60.js} +2 -2
- package/dist/{runtime-rollouts-kGn1K5ut.js.map → runtime-rollouts-CfRyjk60.js.map} +1 -1
- package/dist/{schema-CfoA9U_U.d.ts → schema-PDKQ_iNE.d.ts} +2 -131
- package/dist/schema-PDKQ_iNE.d.ts.map +1 -0
- package/dist/search/index.d.ts +2 -2
- package/dist/search/index.js +2 -2
- package/dist/{search-kernel-DjqaPJqL.d.ts → search-kernel-Ds2zILpY.d.ts} +3 -3
- package/dist/{search-kernel-DjqaPJqL.d.ts.map → search-kernel-Ds2zILpY.d.ts.map} +1 -1
- package/dist/{search-summary-RJ5zXjHN.js → search-summary-BSftVrGY.js} +4 -4
- package/dist/{search-summary-RJ5zXjHN.js.map → search-summary-BSftVrGY.js.map} +1 -1
- package/dist/{sequential-Bb_pdTqG.d.ts → sequential-B9p6uoV8.d.ts} +9 -2
- package/dist/{sequential-Bb_pdTqG.d.ts.map → sequential-B9p6uoV8.d.ts.map} +1 -1
- package/dist/{sequential-Bjs5roiK.js → sequential-CAksw6EU.js} +32 -2
- package/dist/{sequential-Bjs5roiK.js.map → sequential-CAksw6EU.js.map} +1 -1
- package/dist/{sequential-BPbvgzfe.js → sequential-CqG6aLWS.js} +3 -3
- package/dist/{sequential-BPbvgzfe.js.map → sequential-CqG6aLWS.js.map} +1 -1
- package/dist/{server-CPKyf3bz.js → server-DFVwfoZq.js} +3 -3
- package/dist/{server-CPKyf3bz.js.map → server-DFVwfoZq.js.map} +1 -1
- package/dist/{skillopt-optimization-method-D9Hlmhjg.js → skillopt-optimization-method-DYwEndON.js} +9 -9
- package/dist/{skillopt-optimization-method-D9Hlmhjg.js.map → skillopt-optimization-method-DYwEndON.js.map} +1 -1
- package/dist/{statistical-heldout-C-tgpUuu.d.ts → statistical-heldout--0b1lgx4.d.ts} +6 -282
- package/dist/statistical-heldout--0b1lgx4.d.ts.map +1 -0
- package/dist/{statistical-heldout-NBxC7jGo.js → statistical-heldout-D6i58CJ5.js} +3 -3
- package/dist/{statistical-heldout-NBxC7jGo.js.map → statistical-heldout-D6i58CJ5.js.map} +1 -1
- package/dist/statistics-DCZIC-qT.js +2627 -0
- package/dist/statistics-DCZIC-qT.js.map +1 -0
- package/dist/statistics.d.ts +3 -0
- package/dist/statistics.js +3 -0
- package/dist/{store-otlp-BfPRa2p8.js → store-otlp-C-jyj3WX.js} +2 -2
- package/dist/{store-otlp-BfPRa2p8.js.map → store-otlp-C-jyj3WX.js.map} +1 -1
- package/dist/{store-tool-spans-BgwVHXma.d.ts → store-tool-spans-B3z_Qb5u.d.ts} +5 -5
- package/dist/{store-tool-spans-BgwVHXma.d.ts.map → store-tool-spans-B3z_Qb5u.d.ts.map} +1 -1
- package/dist/{store-tool-spans-BrSWHB9O.js → store-tool-spans-DalWlKY8.js} +3 -3
- package/dist/{store-tool-spans-BrSWHB9O.js.map → store-tool-spans-DalWlKY8.js.map} +1 -1
- package/dist/{summary-report-0La5vejY.d.ts → summary-report-Cv1AC-iv.d.ts} +2 -2
- package/dist/{summary-report-0La5vejY.d.ts.map → summary-report-Cv1AC-iv.d.ts.map} +1 -1
- package/dist/{summary-report-C3IJvp0i.js → summary-report-D_uussI3.js} +4 -52
- package/dist/summary-report-D_uussI3.js.map +1 -0
- package/dist/supervisor-run/index.d.ts +2 -2
- package/dist/supervisor-run/index.js +1 -1
- package/dist/{systemone-CpDppX8s.d.ts → systemone-C3xyEKvG.d.ts} +7 -7
- package/dist/{systemone-CpDppX8s.d.ts.map → systemone-C3xyEKvG.d.ts.map} +1 -1
- package/dist/{systemone-review-nbuMxxmi.d.ts → systemone-review-CToBl1oa.d.ts} +2 -2
- package/dist/{systemone-review-nbuMxxmi.d.ts.map → systemone-review-CToBl1oa.d.ts.map} +1 -1
- package/dist/systemone.d.ts +3 -3
- package/dist/systemone.js +2 -2
- package/dist/{tool-groups-BQsjZD9F.d.ts → tool-groups-R5RO9OHn.d.ts} +3 -3
- package/dist/tool-groups-R5RO9OHn.d.ts.map +1 -0
- package/dist/{tool-waste-Czt3aWID.js → tool-waste-DEhKfiIE.js} +2 -3
- package/dist/{tool-waste-Czt3aWID.js.map → tool-waste-DEhKfiIE.js.map} +1 -1
- package/dist/{trace-questions-CpTrtEcm.d.ts → trace-questions-BY6taxnl.d.ts} +3 -3
- package/dist/{trace-questions-CpTrtEcm.d.ts.map → trace-questions-BY6taxnl.d.ts.map} +1 -1
- package/dist/trace-repair/index.d.ts +1 -1
- package/dist/trace-repair/index.js +1 -2
- package/dist/trace-repair/index.js.map +1 -1
- package/dist/traces.d.ts +5 -5
- package/dist/traces.js +3 -3
- package/dist/{tree-DIHp6UQ0.js → tree-B2y1UR8o.js} +4 -6
- package/dist/{tree-DIHp6UQ0.js.map → tree-B2y1UR8o.js.map} +1 -1
- package/dist/{types-DNB9hIXa.d.ts → types-BAJ2Hb-d.d.ts} +3 -2
- package/dist/types-BAJ2Hb-d.d.ts.map +1 -0
- package/dist/{types-DsuOcYsE.d.ts → types-BwF--ZRz.d.ts} +2 -2
- package/dist/{types-DsuOcYsE.d.ts.map → types-BwF--ZRz.d.ts.map} +1 -1
- package/dist/{types-wDBk14lj.d.ts → types-CeMZYsNF.d.ts} +5 -4
- package/dist/types-CeMZYsNF.d.ts.map +1 -0
- package/dist/{types-B9s9Xo5_.d.ts → types-kBMNdo1X.d.ts} +3 -9
- package/dist/types-kBMNdo1X.d.ts.map +1 -0
- package/dist/wire/index.d.ts +6 -6
- package/dist/wire/index.js +1 -1
- package/docs/design/statistics-decisions.md +38 -364
- package/docs/design.md +1 -1
- package/docs/research-report-methodology.md +1 -1
- package/package.json +6 -1
- package/dist/agreement-irr-DXcXEt4I.js +0 -182
- package/dist/agreement-irr-DXcXEt4I.js.map +0 -1
- package/dist/analyze-runs-C7vWBDhl.js.map +0 -1
- package/dist/benchmark-command-DSJQeYom.js.map +0 -1
- package/dist/cluster-bootstrap-BteuR1hg.js +0 -65
- package/dist/cluster-bootstrap-BteuR1hg.js.map +0 -1
- package/dist/descriptive-B3Eb7tX0.js +0 -229
- package/dist/descriptive-B3Eb7tX0.js.map +0 -1
- package/dist/findings-store-BnYN57-h.js.map +0 -1
- package/dist/index-BPmj-_ta.d.ts.map +0 -1
- package/dist/index-C3t17kHu.d.ts.map +0 -1
- package/dist/index-D4lT7aFu.d.ts.map +0 -1
- package/dist/judge-calibration-DKR6Xi-w.js +0 -319
- package/dist/judge-calibration-DKR6Xi-w.js.map +0 -1
- package/dist/judge-calibration-DnrbQaXI.d.ts +0 -144
- package/dist/judge-calibration-DnrbQaXI.d.ts.map +0 -1
- package/dist/mean-D1d6gedE.js +0 -284
- package/dist/mean-D1d6gedE.js.map +0 -1
- package/dist/metrics-DNCAUtuB.js.map +0 -1
- package/dist/multiplicity-DAd4xaDC.js +0 -100
- package/dist/multiplicity-DAd4xaDC.js.map +0 -1
- package/dist/multiplicity-D_SEsc5j.d.ts +0 -41
- package/dist/multiplicity-D_SEsc5j.d.ts.map +0 -1
- package/dist/paired-arms-3-tsXvvC.js +0 -740
- package/dist/paired-arms-3-tsXvvC.js.map +0 -1
- package/dist/paired-binary-CMzmSSd5.js +0 -372
- package/dist/paired-binary-CMzmSSd5.js.map +0 -1
- package/dist/paired-promotion-decision-BDnqepZ1.d.ts.map +0 -1
- package/dist/paired-tests-Buh6feJ4.js +0 -211
- package/dist/paired-tests-Buh6feJ4.js.map +0 -1
- package/dist/power-and-mde-g3vOn0XK.js +0 -99
- package/dist/power-and-mde-g3vOn0XK.js.map +0 -1
- package/dist/promotion-gate-DOkgJcLW.d.ts.map +0 -1
- package/dist/random-BN150Q_X.d.ts +0 -79
- package/dist/random-BN150Q_X.d.ts.map +0 -1
- package/dist/schema-CfoA9U_U.d.ts.map +0 -1
- package/dist/sequential-eprocess-C1YLwFaz.js +0 -129
- package/dist/sequential-eprocess-C1YLwFaz.js.map +0 -1
- package/dist/statistical-heldout-C-tgpUuu.d.ts.map +0 -1
- package/dist/summary-report-C3IJvp0i.js.map +0 -1
- package/dist/tool-groups-BQsjZD9F.d.ts.map +0 -1
- package/dist/types-0KglnQ9o.d.ts.map +0 -1
- package/dist/types-B9s9Xo5_.d.ts.map +0 -1
- package/dist/types-DNB9hIXa.d.ts.map +0 -1
- package/dist/types-wDBk14lj.d.ts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["identity"],"sources":["../../src/analyst/benchmark-behavioral-calibration.ts","../../src/analyst/bind.ts","../../src/analyst/define.ts","../../src/analyst/domain-taxonomy.ts","../../src/analyst/failure-modes.ts","../../src/analyst/findings-ledger.ts","../../src/analyst/kinds/skill-usage.ts","../../src/analyst/promote.ts","../../src/analyst/rollup.ts","../../src/analyst/team-shape.ts","../../src/analyst/trace-questions.ts"],"sourcesContent":["import { z } from 'zod'\nimport { DECISION_POINT_AUC_BAR, DECISION_POINT_MIN_KAPPA } from '../decision-point'\nimport { validDecisionIdentity } from '../decision-point-records'\nimport { type NominalAgreementOptions, nominalAgreement } from '../statistics/agreement-irr'\nimport { rocAuc } from '../statistics/comparison-effects'\nimport { type BootstrapInterval, clusterBootstrap } from '../statistics/internal'\nimport {\n BEHAVIORAL_TRACE_QUESTIONS,\n type BehavioralQuestionCalibration,\n type BehavioralTraceAnswer,\n type BehavioralTraceLayer,\n type BehavioralTraceQuestionId,\n type BehavioralTraceSupport,\n type BehavioralWindowPolicy,\n behavioralTraceQuestionDigest,\n} from './behavioral-trace-questions'\nimport { behavioralTraceSupportSchema } from './behavioral-trace-support'\nimport { validBehavioralCalibration } from './behavioral-trace-validation'\nimport type { ExactExecutionComponentIdentity } from './exact-types'\nimport type { CalibrationInterval } from './finding-scope'\nimport type { AnalystFinding, EvidenceRef } from './types'\n\n/** Independently acquired labels. Null and unsure are exclusions, never negative labels. */\nexport interface BehavioralTraceGold {\n questionId: BehavioralTraceQuestionId\n windowId: string\n label: BehavioralTraceAnswer | null\n source: 'human' | 'agentrx'\n}\n/** One-vs-rest reading of a class: precision and recall from hard answers; the AUC of its probability\n * (null without a scored member of each class) with a seeded cluster bootstrap; the AUC bar line. */\nexport interface ClassCalibration {\n precision: number | null\n recall: number | null\n auc: number | null\n ci: CalibrationInterval | null\n eligibleAuc: boolean\n}\nexport interface BehavioralTraceCalibrationRow extends ClassCalibration {\n questionId: BehavioralTraceQuestionId\n layer: BehavioralTraceLayer\n method: 'computed' | 'judged'\n gold_n: number\n missingLabels: number\n unsureLabels: number\n missingPredictions: number\n abstentions: number\n sourceCounts: { human: number; agentrx: number }\n agreement: number | null\n kappa: number | null\n kappaCi: BootstrapInterval | null\n confusion: Record<'yes' | 'no', Record<'yes' | 'no' | 'unsure' | 'missing', number>>\n /** Wrong/unsure/missing semantic answers retain the selected event and complete scoped map.\n * Cross-map nominal agreement is separate from exact-definition decision reliability. */\n disagreements: Array<{\n windowId: string\n expected: 'yes' | 'no'\n predicted: BehavioralTraceAnswer | null\n support: BehavioralTraceSupport | null\n }>\n eligible: boolean\n /** Finite measured evidence, even if it misses the activation bar. */\n calibration: BehavioralQuestionCalibration | null\n}\nexport interface ChoiceGold {\n id: string\n label: string | null\n}\nexport interface ChoicePrediction {\n id: string\n cluster?: string\n choice: string | null\n probabilities: Record<string, number> | null\n}\n/** `gold_n` is the gold items labeled with this option, `predicted` the labeled items that chose it. */\nexport interface ChoiceOptionCalibration extends ClassCalibration {\n option: string\n gold_n: number\n predicted: number\n}\nexport interface ChoiceCalibration {\n options: string[]\n gold_n: number\n missingLabels: number\n missingPredictions: number\n abstentions: number\n agreement: number | null\n /** Multi-class Cohen's κ over the hard choices, with its cluster bootstrap. */\n kappa: number | null\n kappaCi: BootstrapInterval | null\n rows: ChoiceOptionCalibration[]\n}\nconst identity = z.string().refine(validDecisionIdentity)\nconst questionId = z.enum(\n Object.keys(BEHAVIORAL_TRACE_QUESTIONS) as [\n BehavioralTraceQuestionId,\n ...BehavioralTraceQuestionId[],\n ],\n)\nconst answer = z.enum(['yes', 'no', 'unsure'])\nconst goldSchema = z\n .object({\n questionId,\n windowId: identity,\n label: answer.nullable(),\n source: z.enum(['human', 'agentrx']),\n })\n .strict()\nconst predictionSchema = z\n .object({\n questionId,\n windowId: identity,\n traceId: identity.optional(),\n answer: answer.nullable(),\n probabilities: z.record(z.string(), z.number().finite()).nullable().optional(),\n questionDigest: z.string().nullable(),\n requestedModel: identity.nullable(),\n servedModel: identity.nullable(),\n support: behavioralTraceSupportSchema.optional(),\n })\n .passthrough()\nconst finite = (value: number) => (Number.isFinite(value) ? value : null)\nconst { auc: minAuc, ciLow, gold_n: minGold } = DECISION_POINT_AUC_BAR\n\n/** Same nominalAgreement owner as the existing AgentRx/failure-mode calibration path. */\nexport function calibrateBehavioralTraceQuestions(input: {\n layer: BehavioralTraceLayer\n windowPolicy: BehavioralWindowPolicy\n model: string\n servedModel: string\n evaluatorIdentity: ExactExecutionComponentIdentity\n gold: readonly BehavioralTraceGold[]\n findings: readonly AnalystFinding[]\n evidenceRefs: EvidenceRef[]\n resamples?: number\n seed?: number\n}): BehavioralTraceCalibrationRow[] {\n const predictions = new Map<string, z.infer<typeof predictionSchema> & { cluster: string }>()\n const gold = input.gold.map((row) => goldSchema.parse(row))\n const seen = new Set<string>()\n for (const row of gold) {\n const key = JSON.stringify([row.questionId, row.windowId])\n if (seen.has(key)) throw new TypeError('Duplicate behavioral gold label')\n seen.add(key)\n }\n for (const finding of input.findings) {\n if (finding.area !== 'behavioral-trace-question' || finding.layer !== input.layer) continue\n const row = predictionSchema.parse(finding.metadata?.behavioral_trace_question)\n if (\n row.support &&\n (row.support.map.windowId !== row.windowId ||\n row.support.method !== (row.questionId === 'identical-tool-repeat' ? 'computed' : 'judged'))\n )\n throw new TypeError('Behavioral support does not match its prediction')\n const key = JSON.stringify([row.questionId, row.windowId])\n if (predictions.has(key)) throw new TypeError('Duplicate behavioral prediction')\n // Windows of one agent are resampled together; a finding without a subject clusters by trace.\n predictions.set(key, { ...row, cluster: finding.subject ?? row.traceId ?? row.windowId })\n }\n const bootstrap = { resamples: input.resamples, seed: input.seed, options: ['yes', 'no'] }\n return (Object.keys(BEHAVIORAL_TRACE_QUESTIONS) as BehavioralTraceQuestionId[]).map((id) => {\n const computed = id === 'identical-tool-repeat'\n const digest = behavioralTraceQuestionDigest({\n questionId: id,\n ...input,\n servedModel: computed ? null : input.servedModel,\n })\n const counts = { missingLabels: 0, unsureLabels: 0, sourceCounts: { human: 0, agentrx: 0 } }\n const confusion = {\n yes: { yes: 0, no: 0, unsure: 0, missing: 0 },\n no: { yes: 0, no: 0, unsure: 0, missing: 0 },\n }\n const disagreements: BehavioralTraceCalibrationRow['disagreements'] = []\n const labels: ChoiceGold[] = []\n const answers: ChoicePrediction[] = []\n for (const item of gold.filter((item) => item.questionId === id)) {\n if (item.label === null) {\n counts.missingLabels++\n continue\n }\n if (item.label === 'unsure') {\n counts.unsureLabels++\n continue\n }\n counts.sourceCounts[item.source]++\n const prediction = predictions.get(JSON.stringify([id, item.windowId]))\n const matches =\n prediction?.questionDigest === digest &&\n prediction.requestedModel === (computed ? null : input.model) &&\n prediction.servedModel === (computed ? null : input.servedModel)\n const value = matches ? prediction.answer : null\n confusion[item.label][value ?? 'missing']++\n if (value !== item.label) {\n const support = matches ? (prediction.support ?? null) : null\n if (support && support.map.windowId !== item.windowId)\n throw new TypeError('Behavioral support map is outside the prediction window')\n disagreements.push({\n windowId: item.windowId,\n expected: item.label,\n predicted: value,\n support: support ? structuredClone(support) : null,\n })\n }\n // Missing predictions remain disagreements in the denominator.\n labels.push({ id: item.windowId, label: item.label })\n if (matches)\n answers.push({\n id: item.windowId,\n cluster: prediction.cluster,\n choice: prediction.answer,\n probabilities: prediction.probabilities ?? null,\n })\n }\n const result = calibrateChoiceQuestion(labels, answers, bootstrap)\n const { option: _option, gold_n: positives, predicted: _predicted, ...yes } = result.rows[0]!\n const bothClasses = positives > 0 && positives < result.gold_n\n // A one-class sample or a missing prediction must never supply a certificate that can authorize actions.\n const certified = bothClasses && result.missingPredictions === 0 && result.kappa !== null\n const row: BehavioralTraceCalibrationRow = {\n questionId: id,\n layer: input.layer,\n method: computed ? 'computed' : 'judged',\n ...counts,\n gold_n: result.gold_n,\n missingPredictions: result.missingPredictions,\n abstentions: result.abstentions,\n agreement: result.agreement,\n kappa: result.kappa,\n kappaCi: result.kappaCi,\n ...yes,\n ci: yes.ci && { ...yes.ci, cluster: 'subject' },\n confusion,\n disagreements,\n eligible: certified && result.kappa! >= DECISION_POINT_MIN_KAPPA,\n calibration: null,\n }\n if (certified) {\n row.calibration = {\n gold_n: row.gold_n,\n agreement: row.agreement!,\n kappa: row.kappa!,\n auc: row.auc,\n ci: row.ci,\n questionDigest: digest,\n servedModel: computed ? null : input.servedModel,\n evidenceRefs: structuredClone(input.evidenceRefs),\n }\n validBehavioralCalibration(row.calibration)\n }\n return row\n })\n}\n\n/** A Choice question over any option set: a one-vs-rest row per option plus the multi-class κ. A null\n * or out-of-set gold label is an exclusion; an out-of-set choice an abstention, a null choice missing. */\nexport function calibrateChoiceQuestion(\n gold: readonly ChoiceGold[],\n findings: readonly ChoicePrediction[],\n options: NominalAgreementOptions & { options?: readonly string[] } = {},\n): ChoiceCalibration {\n const predictions = new Map(findings.map((finding) => [finding.id, finding]))\n if (predictions.size !== findings.length) throw new TypeError('Duplicate choice prediction')\n const names = [\n ...(options.options ?? new Set(findings.flatMap((f) => Object.keys(f.probabilities ?? {})))),\n ]\n const labeled = gold.filter((item) => item.label !== null && names.includes(item.label))\n if (new Set(labeled.map((item) => item.id)).size !== labeled.length)\n throw new TypeError('Duplicate choice gold label')\n const joined = labeled.map((item) => ({ ...item, prediction: predictions.get(item.id) }))\n const cluster = (item: (typeof joined)[number]) => item.prediction?.cluster ?? item.id\n const agreement = nominalAgreement(\n joined.map((item) => [item.label!, item.prediction?.choice ?? '(missing prediction)'] as const),\n { ...options, clusters: joined.map(cluster) },\n )\n return {\n options: names,\n gold_n: agreement.n,\n missingLabels: gold.length - labeled.length,\n missingPredictions: joined.filter((item) => item.prediction?.choice == null).length,\n abstentions: joined.filter(\n (item) => item.prediction?.choice != null && !names.includes(item.prediction.choice),\n ).length,\n agreement: finite(agreement.agreement),\n kappa: finite(agreement.kappa),\n kappaCi: Number.isFinite(agreement.kappaCi.low) ? agreement.kappaCi : null,\n rows: names.map((option) => {\n const items = joined.map((item) => ({\n cluster: cluster(item),\n gold: item.label === option,\n chosen: item.prediction?.choice === option,\n score: item.prediction?.probabilities?.[option] ?? null,\n }))\n const chosen = items.filter((item) => item.chosen)\n const hits = chosen.filter((item) => item.gold).length\n const gold_n = items.filter((item) => item.gold).length\n // Precision and recall read every labeled item; the AUC and its interval read scored items only.\n const scored = items.filter((item) => item.score !== null)\n const area = (sample: typeof items) =>\n rocAuc(\n sample.map((i) => i.score!),\n sample.map((i) => Number(i.gold)),\n ) ?? Number.NaN\n const auc = finite(scored.length ? area(scored) : Number.NaN)\n const boot = auc !== null && clusterBootstrap(scored, (i) => i.cluster, area, options)\n const ci = boot && Number.isFinite(boot.low) ? { ...boot, cluster: 'cluster' } : null\n return {\n option,\n gold_n,\n predicted: chosen.length,\n precision: chosen.length ? hits / chosen.length : null,\n recall: gold_n ? hits / gold_n : null,\n auc,\n ci,\n eligibleAuc: ci !== null && auc! >= minAuc && ci.low >= ciLow && gold_n >= minGold,\n }\n }),\n }\n}\n","/**\n * bindAnalyst — compile an `AnalystDefinition` into a runnable arm.\n *\n * The definition declares protocol (question, task text, reply grammar,\n * evidence projection, budget, repair turns); the transport binding supplies\n * execution (a bridge endpoint, or the caller-owned model path). Each\n * projection mode dispatches to the same strategy its arm's entry point runs,\n * so a compiled definition and the historical creator send byte-identical\n * requests — the definition parity suite asserts this per arm.\n *\n * A projection × transport pair with no strategy fails loud with\n * `AnalystExpressivenessError` naming the pair: an arm shape this layer cannot\n * express must be reported, never approximated.\n */\n\nimport type { CustomTokenPricing } from '../cost-ledger'\nimport type { AnalystBenchmarkRunner } from './benchmark'\nimport { runChunkedAnalystDefinition } from './benchmark-public-chunked'\nimport { runReplVariableAnalystDefinition } from './benchmark-public-rlm'\nimport type { PublicAnalystBenchmarkModelConfig } from './benchmark-public-types'\nimport { runInlineAnalystDefinition } from './benchmark-runner-prime'\nimport { type AnalystDefinition, AnalystExpressivenessError } from './definition'\nimport type { PrimeBridgeTransport } from './prime-bridge-transport'\nimport type { AnalystRunInputs } from './types'\n\n/** Execution half of a binding: who actually reaches the model. */\nexport type AnalystTransportBinding =\n | {\n /** An OpenAI-compatible cli-bridge endpoint (inline projections). */\n readonly kind: 'prime-bridge'\n readonly baseUrl: string\n readonly model: string\n readonly transport?: PrimeBridgeTransport\n readonly pricing?: CustomTokenPricing\n }\n | {\n /** The caller-owned model path (chunked and repl-variable projections). */\n readonly kind: 'model-owner'\n readonly config: PublicAnalystBenchmarkModelConfig\n }\n\n/**\n * Compile a definition plus a transport binding into a runnable arm. Dispatch\n * is total over the expressible pairs; everything else is a loud refusal.\n */\nexport function bindAnalyst<TRow, TAssignment, TBlock>(\n definition: AnalystDefinition<TRow, TAssignment, TBlock>,\n transports: AnalystTransportBinding,\n): AnalystBenchmarkRunner<AnalystRunInputs> {\n const mode = definition.projection.mode\n if (mode === 'inline' && transports.kind === 'prime-bridge') {\n return runInlineAnalystDefinition(definition, {\n baseUrl: transports.baseUrl,\n model: transports.model,\n ...(transports.transport ? { transport: transports.transport } : {}),\n ...(transports.pricing ? { pricing: transports.pricing } : {}),\n })\n }\n if (mode === 'chunked' && transports.kind === 'model-owner') {\n return runChunkedAnalystDefinition(definition, transports.config)\n }\n if (mode === 'repl-variable' && transports.kind === 'model-owner') {\n return runReplVariableAnalystDefinition(\n // The repl-variable strategy is written against the engine's raw-finding\n // row type; the definition's own row declaration carries it.\n definition as Parameters<typeof runReplVariableAnalystDefinition>[0],\n transports.config,\n )\n }\n throw new AnalystExpressivenessError(\n `no strategy compiles a '${mode}' projection over a '${transports.kind}' transport; ` +\n `definition '${definition.id}' cannot be expressed by this layer yet`,\n )\n}\n","import type { TraceAnalysisStore } from '../trace-analyst/store'\nimport type { ExactCapableAnalyst } from './exact-types'\nimport type { TraceAnalystDefinition } from './kind-factory'\nimport type { Analyst, AnalystCost } from './types'\n\n/**\n * Define a reusable trace-research question.\n *\n * The returned value contains no model, credentials, or execution state. Bind\n * it to any TraceAnalysisEngine with `runTraceAnalyst` or\n * `createTraceAnalyst`.\n */\nexport function defineTraceAnalyst(definition: TraceAnalystDefinition): TraceAnalystDefinition {\n for (const [name, value] of [\n ['id', definition.id],\n ['description', definition.description],\n ['area', definition.area],\n ['version', definition.version],\n ['instructions', definition.instructions],\n ] as const) {\n if (typeof value !== 'string' || !value.trim()) {\n throw new TypeError(`defineTraceAnalyst: ${name} must be a non-empty string`)\n }\n }\n return {\n ...definition,\n limits: definition.limits ? { ...definition.limits } : undefined,\n }\n}\n\nexport interface DefineCustomAnalystOptions {\n id: string\n description: string\n version?: string\n cost: AnalystCost\n analyze: Analyst<TraceAnalysisStore>['analyze']\n}\n\nexport interface DefineExactCustomAnalystOptions extends DefineCustomAnalystOptions {\n /** Canonical JSON for behavior knobs not already bound by `version`. */\n executionConfig: Readonly<Record<string, unknown>>\n}\n\n/** Construct a registrable analyst from a hand-written analyze function. */\nexport function defineCustomAnalyst(\n options: DefineExactCustomAnalystOptions,\n): ExactCapableAnalyst<TraceAnalysisStore>\nexport function defineCustomAnalyst(\n options: DefineCustomAnalystOptions,\n): Analyst<TraceAnalysisStore>\nexport function defineCustomAnalyst(\n options: DefineCustomAnalystOptions | DefineExactCustomAnalystOptions,\n): Analyst<TraceAnalysisStore> | ExactCapableAnalyst<TraceAnalysisStore> {\n if (!options.id.trim()) throw new TypeError('defineCustomAnalyst: id must not be empty')\n if (!options.description.trim()) {\n throw new TypeError('defineCustomAnalyst: description must not be empty')\n }\n if (options.cost === undefined) {\n throw new TypeError('defineCustomAnalyst: cost must be declared')\n }\n if (\n 'executionConfig' in options &&\n (!options.executionConfig ||\n typeof options.executionConfig !== 'object' ||\n Array.isArray(options.executionConfig))\n ) {\n throw new TypeError('defineCustomAnalyst: executionConfig must be an object')\n }\n return {\n id: options.id,\n description: options.description,\n version: options.version ?? '1.0.0',\n inputKind: 'trace-store',\n cost: options.cost,\n analyze: options.analyze,\n ...('executionConfig' in options ? { executionConfig: options.executionConfig } : {}),\n }\n}\n","/**\n * Domain taxonomy — one versioned tree that both the layer ladder and the\n * domain hierarchy live in.\n *\n * Domain nodes nest to any depth (\"building systems\" → \"cryptographic\" →\n * \"zk proving\" → \"binary fields\"). Problems attach to one primary domain path\n * plus free tags, plays attach to a problem, and runs attach to a play. Every\n * node hangs under the implicit `lab` root, so one parent map answers both\n * \"which play holds this run\" and \"which domain holds this problem\", and\n * `promote` walks a single ladder: run → play → problem → domain path → lab.\n *\n * Plain data in, plain data out: every function returns a new value or a\n * typed failure, and nothing here reads a file or the network.\n */\n\nconst DOMAIN_TAXONOMY_SCHEMA = 'agent-eval.domain-taxonomy.v1'\n\n/** Id of the implicit root every top-level domain hangs under. */\nexport const LAB_NODE_ID = 'lab'\n\n/** Layers a taxonomy node can sit at, lowest first. */\nconst TAXONOMY_NODE_LAYERS = ['run', 'play', 'problem', 'domain'] as const\n\nexport type TaxonomyNodeLayer = (typeof TAXONOMY_NODE_LAYERS)[number]\n\nexport interface TaxonomyNode {\n id: string\n label: string\n layer: TaxonomyNodeLayer\n /** Null only for a top-level domain, whose parent is the implicit lab root. */\n parent: string | null\n /** Secondary classifications; they never change the node's place in the tree. */\n tags?: string[]\n}\n\nexport interface DomainTaxonomy {\n schema: typeof DOMAIN_TAXONOMY_SCHEMA\n /** Caller-chosen version; promoted findings record the version they were lifted under. */\n version: string\n nodes: TaxonomyNode[]\n}\n\nexport type TaxonomyOutcome<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; error: { message: string } }\n\n/** The layer a node of each kind must hang under. */\nconst PARENT_LAYER: Record<TaxonomyNodeLayer, TaxonomyNodeLayer | null> = {\n run: 'play',\n play: 'problem',\n problem: 'domain',\n domain: 'domain',\n}\n\nfunction fail<T>(message: string): TaxonomyOutcome<T> {\n return { succeeded: false, error: { message } }\n}\n\n/**\n * Validate a taxonomy: unique ids, known parents, each node under a parent of\n * the right layer, no cycles. `lab` is reserved for the implicit root.\n */\nexport function defineDomainTaxonomy(input: {\n version: string\n nodes: ReadonlyArray<TaxonomyNode>\n}): TaxonomyOutcome<DomainTaxonomy> {\n if (typeof input.version !== 'string' || !input.version.trim()) {\n return fail('taxonomy version must be a non-empty string')\n }\n const nodes = input.nodes.map((node) => ({\n id: node.id,\n label: node.label,\n layer: node.layer,\n parent: node.parent,\n ...(node.tags === undefined ? {} : { tags: [...node.tags] }),\n }))\n const byId = new Map<string, TaxonomyNode>()\n for (const node of nodes) {\n if (typeof node.id !== 'string' || !node.id.trim()) return fail('node ids must be non-empty')\n if (node.id === LAB_NODE_ID) return fail(`'${LAB_NODE_ID}' is the implicit root id`)\n if (byId.has(node.id)) return fail(`node '${node.id}' appears twice`)\n if (!(TAXONOMY_NODE_LAYERS as readonly string[]).includes(node.layer)) {\n return fail(`node '${node.id}' has unknown layer '${String(node.layer)}'`)\n }\n if (typeof node.label !== 'string' || !node.label.trim()) {\n return fail(`node '${node.id}' needs a label`)\n }\n byId.set(node.id, node)\n }\n for (const node of nodes) {\n if (node.parent === null) {\n if (node.layer !== 'domain') return fail(`${node.layer} '${node.id}' needs a parent`)\n continue\n }\n const parent = byId.get(node.parent)\n if (!parent) return fail(`node '${node.id}' names unknown parent '${node.parent}'`)\n if (parent.layer !== PARENT_LAYER[node.layer]) {\n return fail(\n `${node.layer} '${node.id}' must hang under a ${PARENT_LAYER[node.layer]}, not ${parent.layer} '${parent.id}'`,\n )\n }\n }\n for (const node of nodes) {\n const seen = new Set<string>()\n let current: TaxonomyNode | undefined = node\n while (current) {\n if (seen.has(current.id)) return fail(`node '${node.id}' sits on a parent cycle`)\n seen.add(current.id)\n current = current.parent === null ? undefined : byId.get(current.parent)\n }\n }\n return {\n succeeded: true,\n value: { schema: DOMAIN_TAXONOMY_SCHEMA, version: input.version, nodes },\n }\n}\n\nexport interface TaxonomyAttachment {\n id: string\n label: string\n layer: Exclude<TaxonomyNodeLayer, 'domain'>\n /**\n * For a problem: its primary domain path, broadest first. It must be a\n * chain of domain nodes from the top level down. Ignored for plays and runs.\n */\n path?: readonly string[]\n /** For a play or run: the problem or play it belongs to. */\n parent?: string\n tags?: readonly string[]\n}\n\n/** Attach a problem to one primary domain path, a play to a problem, or a run to a play. */\nexport function attachToTaxonomy(\n taxonomy: DomainTaxonomy,\n attachment: TaxonomyAttachment,\n): TaxonomyOutcome<DomainTaxonomy> {\n let parent: string\n if (attachment.layer === 'problem') {\n if (!attachment.path || attachment.path.length === 0) {\n return fail(`problem '${attachment.id}' needs a primary domain path`)\n }\n const resolved = resolveDomainPath(taxonomy, attachment.path)\n if (!resolved.succeeded) return resolved\n parent = attachment.path[attachment.path.length - 1]!\n } else {\n if (!attachment.parent) return fail(`${attachment.layer} '${attachment.id}' needs a parent`)\n parent = attachment.parent\n }\n return defineDomainTaxonomy({\n version: taxonomy.version,\n nodes: [\n ...taxonomy.nodes,\n {\n id: attachment.id,\n label: attachment.label,\n layer: attachment.layer,\n parent,\n ...(attachment.tags === undefined ? {} : { tags: [...attachment.tags] }),\n },\n ],\n })\n}\n\n/** Check that a path is a top-down chain of domain nodes. */\nexport function resolveDomainPath(\n taxonomy: DomainTaxonomy,\n path: readonly string[],\n): TaxonomyOutcome<readonly TaxonomyNode[]> {\n const byId = nodeIndex(taxonomy)\n const chain: TaxonomyNode[] = []\n let expectedParent: string | null = null\n for (const id of path) {\n const node = byId.get(id)\n if (node?.layer !== 'domain') return fail(`'${id}' is not a domain node`)\n if (node.parent !== expectedParent) {\n return fail(`domain path breaks at '${id}': its parent is '${node.parent ?? LAB_NODE_ID}'`)\n }\n chain.push(node)\n expectedParent = id\n }\n return { succeeded: true, value: chain }\n}\n\n/** Layer of a node id, with `lab` for the implicit root; undefined when unknown. */\nexport function taxonomyLayerOf(\n taxonomy: DomainTaxonomy,\n id: string,\n): TaxonomyNodeLayer | 'lab' | undefined {\n if (id === LAB_NODE_ID) return 'lab'\n return nodeIndex(taxonomy).get(id)?.layer\n}\n\n/** Parent id, with `lab` above every top-level domain and null above `lab`. */\nexport function taxonomyParentOf(taxonomy: DomainTaxonomy, id: string): string | null | undefined {\n if (id === LAB_NODE_ID) return null\n const node = nodeIndex(taxonomy).get(id)\n if (!node) return undefined\n return node.parent ?? LAB_NODE_ID\n}\n\n/** The node and its ancestors, nearest first, ending at `lab`. Empty for an unknown id. */\nexport function taxonomyAncestry(taxonomy: DomainTaxonomy, id: string): string[] {\n const byId = nodeIndex(taxonomy)\n const chain: string[] = []\n let current: string | null = id\n while (current !== null) {\n if (current === LAB_NODE_ID) {\n chain.push(current)\n break\n }\n const node = byId.get(current)\n if (!node) return []\n chain.push(current)\n current = node.parent ?? LAB_NODE_ID\n }\n return chain\n}\n\n/** Domain path of a node, broadest first: the domain ids above it, and itself when a domain. */\nexport function domainPathOf(taxonomy: DomainTaxonomy, id: string): string[] {\n const byId = nodeIndex(taxonomy)\n return taxonomyAncestry(taxonomy, id)\n .filter((ancestor) => byId.get(ancestor)?.layer === 'domain')\n .reverse()\n}\n\n/**\n * Deepest node that is an ancestor of (or equal to) every id, or undefined\n * when an id is unknown. `lab` is the answer when they share nothing else.\n */\nexport function lowestCommonAncestor(\n taxonomy: DomainTaxonomy,\n ids: readonly string[],\n): string | undefined {\n if (ids.length === 0) return undefined\n const chains = ids.map((id) => taxonomyAncestry(taxonomy, id))\n if (chains.some((chain) => chain.length === 0)) return undefined\n const others = chains.slice(1).map((chain) => new Set(chain))\n return chains[0]!.find((id) => others.every((chain) => chain.has(id)))\n}\n\nfunction nodeIndex(taxonomy: DomainTaxonomy): Map<string, TaxonomyNode> {\n return new Map(taxonomy.nodes.map((node) => [node.id, node]))\n}\n","/**\n * failure-modes — a judged analyst with fixed-choice labels, gated on its own\n * calibration.\n *\n * Labels are adapted from the MAST multi-agent failure taxonomy (Cemri et al.,\n * \"Why Do Multi-Agent LLM Systems Fail?\", 2025): its fourteen modes in three\n * groups, plus four single-agent modes so the public AgentRx set maps onto the\n * same labels, plus `none`. Two more fixed questions cover delegation-brief\n * completeness and steer handling.\n *\n * The judge runs through the System One decision path (`systemOneAnalyst`).\n * Construction requires a calibration — gold labels compared with the judge's\n * labels on the same items — and refuses to build an analyst whose Cohen's κ\n * is below `FAILURE_MODES_MIN_KAPPA`. A rubric that does not agree with its\n * gold set has nothing to report, so it reports nothing.\n */\n\nimport { readFile } from 'node:fs/promises'\nimport { nominalAgreement } from '../statistics/agreement-irr'\nimport { type SystemOneEvaluatorOptions, systemOneAnalyst } from '../systemone'\nimport type { SystemOneQuestions, SystemOneState } from '../systemone-protocol'\nimport { normalizeAgentRxCategory } from './benchmark-dataset-agentrx'\nimport type { AgentRxRow } from './benchmark-dataset-types'\nimport { externalId, positiveStep } from './benchmark-dataset-utils'\nimport { loadPublicBenchmarkRows } from './benchmark-public-data'\nimport type { FindingCalibration, FindingScope } from './finding-scope'\nimport { type Analyst, type AnalystContext, type AnalystFinding, makeFinding } from './types'\n\nexport const FAILURE_MODES_ANALYST_ID = 'failure-modes'\nexport const FAILURE_MODES_VERSION = '2'\n\n/** κ below this refuses the rubric. */\nexport const FAILURE_MODES_MIN_KAPPA = 0.6\n\nexport const FAILURE_MODE_LABELS = {\n // MAST 1 — specification and system design\n 'disobey-task-specification': 'Ignored or violated the stated task requirements or constraints.',\n 'disobey-role-specification': 'Acted outside its assigned role or took over another role.',\n 'step-repetition': 'Repeated a step already completed without new reason.',\n 'loss-of-conversation-history': 'Lost earlier context and acted as if it was never given.',\n 'unaware-of-termination-conditions': 'Did not recognize when the task was done or must stop.',\n // MAST 2 — inter-agent misalignment\n 'conversation-reset': 'Restarted the exchange and discarded progress.',\n 'fail-to-ask-for-clarification': 'Proceeded on an ambiguous instruction without asking.',\n 'task-derailment': 'Drifted from the task toward a different goal.',\n 'information-withholding': 'Kept back information another agent needed.',\n 'ignored-other-agent-input': \"Disregarded another agent's input or recommendation.\",\n 'reasoning-action-mismatch': 'Acted against its own stated reasoning or plan.',\n // MAST 3 — task verification and termination\n 'premature-termination': 'Stopped before the goal of the task was met.',\n 'no-or-incomplete-verification': 'Delivered without verifying, or verified only part.',\n 'incorrect-verification': 'Verified, but the check was wrong or passed bad output.',\n // Single-agent modes, so AgentRx labels map onto this set.\n 'invented-information': 'Stated facts, results or tool output that do not exist.',\n 'invalid-tool-invocation': 'Called a tool with an invalid name, argument or format.',\n 'misread-tool-output': 'Misinterpreted what a tool or handoff returned.',\n 'system-failure': 'Failed because of infrastructure, not the agent.',\n none: 'No failure mode applies.',\n} as const\n\nexport type FailureModeLabel = keyof typeof FAILURE_MODE_LABELS\n\n/**\n * AgentRx root-cause category → failure-mode label. `null` categories have no\n * counterpart here and are left out of the gold set, counted as unmapped.\n */\nconst AGENT_RX_FAILURE_MODE_MAP: Readonly<Record<string, FailureModeLabel | null>> = {\n 'instruction-plan-adherence-failure': 'disobey-task-specification',\n 'invention-of-new-information': 'invented-information',\n 'invalid-invocation': 'invalid-tool-invocation',\n 'misinterpretation-of-tool-output-handoff-failure': 'misread-tool-output',\n 'intent-plan-misalignment': 'task-derailment',\n // An underspecified user request is not evidence that an agent failed to clarify it.\n 'underspecified-user-intent': null,\n 'intent-not-supported': null,\n 'guardrails-triggered': null,\n 'system-failure': 'system-failure',\n inconclusive: null,\n}\n\n/** Agent roles in the pinned public AgentRx datasets; unfamiliar actors stay unknown. */\nconst AGENT_RX_AGENT_ACTORS = new Set(['assistant', 'orchestrator', 'websurfer', 'filesurfer'])\n\nexport const FAILURE_MODES_QUESTIONS = {\n failure_mode: {\n type: 'choice',\n instructions:\n 'Which agent or team root-cause failure best explains the observed shortfall? Identify the causal error rather than a downstream symptom; a corrected earlier mistake need not be the root cause. Use only the provided task, policy, actions, tool results and outcome evidence. Do not invent missing outcomes or infrastructure errors. Choose none when the evidence establishes that no failure occurred.',\n criteria: FAILURE_MODE_LABELS,\n },\n delegation_brief: {\n type: 'choice',\n instructions:\n 'When this agent delegated work, did the brief state the goal, the constraints, the expected output, and how the result would be checked?',\n criteria: {\n complete: 'Every delegated brief stated goal, constraints, output and check.',\n partial: 'Some brief left out one or more of goal, constraints, output or check.',\n missing: 'Work was delegated with no usable brief.',\n 'no-delegation': 'Nothing was delegated.',\n },\n },\n steer_handling: {\n type: 'choice',\n instructions: 'When a steer or correction arrived mid-task, what did the agent do with it?',\n criteria: {\n applied: 'Changed course as the steer asked.',\n ignored: 'Continued as before, or acknowledged without acting.',\n 'no-steer': 'No steer arrived.',\n },\n },\n} as const satisfies SystemOneQuestions\n\nexport interface FailureModeLabelItem {\n id: string\n label: FailureModeLabel\n}\n\nexport interface FailureModesCalibration extends FindingCalibration {\n /** Gold items with no judge label; each counts as a disagreement. */\n missingPredictions: number\n}\n\nexport type FailureModesOutcome<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; error: { kind: 'invalid' | 'uncalibrated'; message: string } }\n\nfunction isLabel(value: unknown): value is FailureModeLabel {\n return typeof value === 'string' && Object.hasOwn(FAILURE_MODE_LABELS, value)\n}\n\n/** Gold labels from AgentRx rows: each trajectory's root-cause category, mapped onto this set. */\nfunction failureModeGoldFromAgentRx(\n rows: readonly AgentRxRow[],\n): Pick<FailureModeGold, 'gold' | 'unmapped'> {\n const gold: FailureModeLabelItem[] = []\n const unmapped: FailureModeGold['unmapped'] = []\n const ids = new Set<string>()\n for (const row of rows) {\n const id = `agentrx:${externalId(row.trajectory_id, 'AgentRx trajectory id')}`\n if (ids.has(id)) throw new TypeError(`AgentRx trajectory '${row.trajectory_id}' repeats`)\n ids.add(id)\n const rootId = externalId(\n row.root_cause_failure_id ?? row.root_cause?.failure_id,\n `AgentRx trajectory '${row.trajectory_id}' root-cause failure id`,\n )\n const root = row.failures.find((failure) => String(failure.failure_id) === String(rootId))\n if (!root)\n throw new TypeError(`AgentRx trajectory '${row.trajectory_id}' has no root-cause failure`)\n const step = positiveStep(\n root.step_number,\n `AgentRx trajectory '${row.trajectory_id}' root step`,\n )\n const category = normalizeAgentRxCategory(root.failure_category)\n if (!Object.hasOwn(AGENT_RX_FAILURE_MODE_MAP, category)) {\n throw new RangeError(\n `AgentRx category '${root.failure_category}' is outside the AgentRx taxonomy`,\n )\n }\n const label = AGENT_RX_FAILURE_MODE_MAP[category]\n const actor = typeof root.failed_agent === 'string' ? root.failed_agent.trim() || null : null\n const reason =\n actor === null\n ? 'unknown-root-actor'\n : !AGENT_RX_AGENT_ACTORS.has(actor.toLowerCase())\n ? 'unsupported-root-actor'\n : label === null || label === undefined\n ? 'category-without-counterpart'\n : null\n if (reason !== null) {\n unmapped.push({\n id,\n category,\n reason,\n root: { failureId: rootId, step, actor },\n })\n } else if (label !== null && label !== undefined) {\n gold.push({ id, label })\n }\n }\n return { gold, unmapped }\n}\n\n/** Validate caller gold with unique, whitespace-unambiguous ids and known labels. */\nfunction parseFailureModeGold(raw: unknown): FailureModesOutcome<FailureModeLabelItem[]> {\n if (!Array.isArray(raw)) {\n return { succeeded: false, error: { kind: 'invalid', message: 'gold must be a JSON array' } }\n }\n const seen = new Set<string>()\n const items: FailureModeLabelItem[] = []\n for (const [index, row] of raw.entries()) {\n const id = (row as { id?: unknown } | null)?.id\n const label = (row as { label?: unknown } | null)?.label\n if (typeof id !== 'string' || !id.trim() || !isLabel(label)) {\n return {\n succeeded: false,\n error: {\n kind: 'invalid',\n message: `gold row ${index} needs a string id and a known label`,\n },\n }\n }\n if (id !== id.trim()) {\n return {\n succeeded: false,\n error: {\n kind: 'invalid',\n message: `gold row ${index} id must not have surrounding whitespace`,\n },\n }\n }\n if (seen.has(id)) {\n return { succeeded: false, error: { kind: 'invalid', message: `gold id '${id}' repeats` } }\n }\n seen.add(id)\n items.push({ id, label })\n }\n return { succeeded: true, value: items }\n}\n\nexport interface FailureModeGoldSources {\n /** The public AgentRx label file, the same file `analyst-benchmark --dataset agentrx --labels` reads. */\n agentRxLabelsPath?: string\n /** The caller's gold file: a JSON array of `{ id, label }`. */\n goldPath?: string\n}\n\nexport interface FailureModeGold {\n gold: FailureModeLabelItem[]\n /** Parsed sources with no eligible labels are unknown, never a successful calibration. */\n eligibility: 'eligible' | 'unknown'\n /** AgentRx rows read from `agentRxLabelsPath`; every one is either in `gold` or in `unmapped`. */\n agentRxRows: number\n /** Record this rule beside a new calibration; null when no AgentRx source was supplied. */\n agentRxMapping: { version: string; target: 'agent-or-team-root-cause' } | null\n unmapped: Array<{\n id: string\n category: string\n reason: 'unknown-root-actor' | 'unsupported-root-actor' | 'category-without-counterpart'\n root: { failureId: string; step: number; actor: string | null }\n }>\n}\n\n/**\n * Load the calibration gold set from the public AgentRx labels and the\n * caller's gold file, through the analyst module's public-dataset loader.\n * Caller gold ids must be disjoint from all AgentRx ids, including exclusions.\n * No source or an empty source is invalid. A parsed AgentRx source whose rows are all excluded returns\n * unknown eligibility with its reasons; it supplies no labels to calibrate.\n */\nexport async function loadFailureModeGold(\n sources: FailureModeGoldSources,\n): Promise<FailureModesOutcome<FailureModeGold>> {\n const invalid = (message: string) =>\n ({ succeeded: false, error: { kind: 'invalid', message } }) as const\n const gold: FailureModeLabelItem[] = []\n let agentRxRows = 0\n let agentRxMapping: FailureModeGold['agentRxMapping'] = null\n let unmapped: FailureModeGold['unmapped'] = []\n try {\n if (sources.agentRxLabelsPath !== undefined) {\n const rows = await loadPublicBenchmarkRows(sources.agentRxLabelsPath)\n agentRxRows = rows.length\n const mapped = failureModeGoldFromAgentRx(rows as unknown as AgentRxRow[])\n agentRxMapping = { version: '2', target: 'agent-or-team-root-cause' }\n gold.push(...mapped.gold)\n unmapped = mapped.unmapped\n }\n if (sources.goldPath !== undefined) {\n const parsed = parseFailureModeGold(JSON.parse(await readFile(sources.goldPath, 'utf8')))\n if (!parsed.succeeded) return parsed\n gold.push(...parsed.value)\n }\n } catch (error) {\n return invalid(error instanceof Error ? error.message : String(error))\n }\n if (gold.length === 0 && unmapped.length === 0)\n return invalid('failure-modes calibration needs at least one gold item')\n const ids = new Set(unmapped.map((item) => item.id))\n for (const item of gold) {\n if (ids.has(item.id)) return invalid(`gold id '${item.id}' repeats across sources`)\n ids.add(item.id)\n }\n return {\n succeeded: true,\n value: {\n gold,\n eligibility: gold.length > 0 ? 'eligible' : 'unknown',\n agentRxRows,\n agentRxMapping,\n unmapped,\n },\n }\n}\n\n/**\n * Score the judge's labels against gold labels for the same items, usually\n * the set `loadFailureModeGold` returns.\n */\nexport function calibrateFailureModes(\n gold: readonly FailureModeLabelItem[],\n predictions: readonly FailureModeLabelItem[],\n): FailureModesCalibration {\n const predicted = new Map<string, FailureModeLabel>()\n for (const prediction of predictions) {\n if (predicted.has(prediction.id))\n throw new TypeError(`prediction id '${prediction.id}' repeats`)\n predicted.set(prediction.id, prediction.label)\n }\n const ids = new Set<string>()\n let missingPredictions = 0\n const pairs: Array<readonly [string, string]> = []\n for (const item of gold) {\n if (ids.has(item.id)) throw new TypeError(`gold id '${item.id}' repeats`)\n ids.add(item.id)\n const label = predicted.get(item.id)\n if (label === undefined) missingPredictions += 1\n // A missing prediction is its own label: it can never match gold.\n pairs.push([item.label, label ?? '(no prediction)'])\n }\n const agreement = nominalAgreement(pairs)\n return {\n gold_n: agreement.n,\n agreement: agreement.agreement,\n kappa: agreement.kappa,\n missingPredictions,\n }\n}\n\nexport interface FailureModesAnalystOptions<I> extends SystemOneEvaluatorOptions {\n model: string\n /** The layer the judged subject sits at. */\n layer: 'agent' | 'team' | 'run'\n calibration: FindingCalibration\n renderState: (input: I, context: AnalystContext) => SystemOneState | Promise<SystemOneState>\n /** The judged population: the agent, team or run the state describes. */\n scope: (input: I, context: AnalystContext) => FindingScope\n subject?: (input: I, context: AnalystContext) => string\n}\n\n/**\n * Build the failure-modes analyst, or refuse when its calibration does not\n * clear `FAILURE_MODES_MIN_KAPPA`. An undefined κ (no gold, or one label\n * everywhere) is refused the same way.\n */\nexport function createFailureModesAnalyst<I>(\n options: FailureModesAnalystOptions<I>,\n): FailureModesOutcome<Analyst<I>> {\n const { calibration, layer, model, renderState, scope, subject, ...transport } = options\n if (!(calibration.gold_n > 0) || !(calibration.kappa >= FAILURE_MODES_MIN_KAPPA)) {\n return {\n succeeded: false,\n error: {\n kind: 'uncalibrated',\n message: `failure-modes rubric has kappa ${Number.isNaN(calibration.kappa) ? 'undefined' : calibration.kappa.toFixed(3)} over ${calibration.gold_n} gold items; reporting requires kappa >= ${FAILURE_MODES_MIN_KAPPA}`,\n },\n }\n }\n const method = {\n kind: 'judged' as const,\n name: FAILURE_MODES_ANALYST_ID,\n version: FAILURE_MODES_VERSION,\n calibration: {\n gold_n: calibration.gold_n,\n agreement: calibration.agreement,\n kappa: calibration.kappa,\n },\n }\n const analyst = systemOneAnalyst({\n ...transport,\n model,\n renderState,\n id: FAILURE_MODES_ANALYST_ID,\n description: 'Labels agent, team and run failures with a calibrated fixed-choice rubric.',\n inputKind: 'custom',\n version: FAILURE_MODES_VERSION,\n questions: FAILURE_MODES_QUESTIONS,\n findings: (value, input, context) => {\n const judgedSubject = subject?.(input, context)\n const base = {\n analyst_id: FAILURE_MODES_ANALYST_ID,\n derived_from_judge: true,\n layer,\n scope: scope(input, context),\n method,\n evidence_refs: [{ kind: 'artifact' as const, uri: `run://${context.runId}` }],\n ...(judgedSubject === undefined ? {} : { subject: judgedSubject }),\n }\n const out: AnalystFinding[] = []\n const mode = value.answers.failure_mode\n if (mode.choice !== 'none') {\n out.push(\n makeFinding({\n ...base,\n area: 'failure-mode',\n severity: 'medium',\n confidence: mode.confidence,\n claim: `Failure mode: ${mode.choice}`,\n claim_id: `failure-mode:${mode.choice}`,\n rationale: FAILURE_MODE_LABELS[mode.choice],\n }),\n )\n }\n const brief = value.answers.delegation_brief\n if (brief.choice === 'partial' || brief.choice === 'missing') {\n out.push(\n makeFinding({\n ...base,\n area: 'delegation-brief',\n severity: brief.choice === 'missing' ? 'high' : 'medium',\n confidence: brief.confidence,\n claim: `Delegation brief ${brief.choice}`,\n claim_id: `delegation-brief:${brief.choice}`,\n }),\n )\n }\n const steer = value.answers.steer_handling\n if (steer.choice === 'ignored') {\n out.push(\n makeFinding({\n ...base,\n area: 'steer-handling',\n severity: 'high',\n confidence: steer.confidence,\n claim: 'Steer ignored',\n claim_id: 'steer-handling:ignored',\n }),\n )\n }\n return out\n },\n })\n return { succeeded: true, value: analyst }\n}\n","/**\n * Findings ledger — analyst findings in the shared ledger-core journal.\n *\n * Each appended finding is one hash-chained, canonical JSON entry, fsynced and\n * pinned to a trusted head, so a later reader can prove nothing was rewritten\n * or cut from the end. A row is validated by `AnalystFindingSchema` before it\n * is written and again when it is read, so a 1.1.0 finding whose declared\n * population disagrees with its evidence never enters the record.\n *\n * Appends are idempotent per (run, finding): replaying a run's findings is a\n * no-op, and the same finding id with different content is a conflict.\n * `FindingsStore` remains the unchained JSONL store for existing consumers.\n */\n\nimport { z } from 'zod'\nimport type { LedgerHash } from '../ledger-core/canonical'\nimport { FileLedgerJournal, type LedgerJournalCodec } from '../ledger-core/journal'\nimport { merkleRoot } from '../ledger-core/merkle'\nimport { AnalystFindingSchema, type FindingLayer } from './finding-scope'\nimport {\n type DiffPolicy,\n diffFindings,\n type FindingsDiff,\n type PersistedFinding,\n} from './findings-store'\nimport type { AnalystFinding } from './types'\n\nconst schema = 'agent-eval.findings-ledger.v1' as const\nconst digest = z.string().regex(/^sha256:[a-f0-9]{64}$/)\nconst identity = z\n .string()\n .min(1)\n .refine((value) => value.trim() === value, { message: 'must not carry surrounding space' })\n\nconst eventSchema = z\n .object({\n kind: z.literal('finding'),\n eventId: identity,\n run_id: identity,\n finding: AnalystFindingSchema,\n })\n .strict()\n\ntype Event = z.infer<typeof eventSchema>\n\nconst entrySchema = z\n .object({\n schema: z.literal(schema),\n sequence: z.number().int().nonnegative(),\n previousHash: digest.nullable(),\n event: eventSchema,\n entryHash: digest,\n })\n .strict()\n\n/** One finding as the ledger holds it. */\nexport interface LedgerFinding extends PersistedFinding {\n /** Position in the journal; later entries were appended later. */\n sequence: number\n entryHash: LedgerHash\n}\n\nexport interface FindingsLedgerRead {\n findings: LedgerFinding[]\n /** RFC 9162 Merkle root over every entry hash, in journal order. */\n merkleRoot: LedgerHash\n}\n\nexport type FindingsLedgerOutcome<T> =\n | { succeeded: true; value: T }\n | {\n succeeded: false\n error: { kind: 'invalid' | 'conflict' | 'unavailable'; message: string }\n }\n\nexport interface FindingsLedger {\n readonly path: string\n append(\n runId: string,\n findings: readonly AnalystFinding[],\n ): Promise<FindingsLedgerOutcome<{ appended: number; replayed: number }>>\n read(): Promise<FindingsLedgerOutcome<FindingsLedgerRead>>\n}\n\nclass FindingsLedgerConflictError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'FindingsLedgerConflictError'\n }\n}\n\nclass FindingsLedgerInvalidError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'FindingsLedgerInvalidError'\n }\n}\n\nfunction codec(): LedgerJournalCodec<{ schema: typeof schema }, Event, LedgerFinding[]> {\n return {\n subject: 'findings ledger',\n header: { schema },\n integrityError: (message, options) => new Error(message, options),\n conflictError: (message) => new FindingsLedgerConflictError(message),\n parseEntry: (raw, context) => {\n const decoded = entrySchema.safeParse(raw)\n if (!decoded.success) {\n const issue = decoded.error.issues[0]\n throw new FindingsLedgerInvalidError(\n `findings ledger ${context.path}:${context.line} is invalid at ${(issue?.path ?? []).join('.')}: ${issue?.message}`,\n )\n }\n return {\n ...decoded.data,\n event: decoded.data.event as Event,\n previousHash: decoded.data.previousHash as LedgerHash | null,\n entryHash: decoded.data.entryHash as LedgerHash,\n }\n },\n checkEntryHeader: (entry) => {\n if (entry.schema !== schema) throw new FindingsLedgerInvalidError('unsupported ledger schema')\n },\n createProjector: () => {\n const rows: LedgerFinding[] = []\n return {\n apply: (entry) => {\n const { event } = entry\n if (event.eventId !== eventIdFor(event.run_id, event.finding.finding_id)) {\n throw new FindingsLedgerInvalidError(\n `event id ${event.eventId} does not name its finding`,\n )\n }\n rows.push({\n ...(event.finding as AnalystFinding),\n run_id: event.run_id,\n sequence: entry.sequence,\n entryHash: entry.entryHash,\n })\n },\n snapshot: () => [...rows],\n }\n },\n }\n}\n\nfunction eventIdFor(runId: string, findingId: string): string {\n return `finding:${runId}:${findingId}`\n}\n\nasync function outcome<T>(operation: () => Promise<T>): Promise<FindingsLedgerOutcome<T>> {\n try {\n return { succeeded: true, value: await operation() }\n } catch (error) {\n return {\n succeeded: false,\n error: {\n kind:\n error instanceof FindingsLedgerConflictError\n ? 'conflict'\n : error instanceof FindingsLedgerInvalidError || error instanceof z.ZodError\n ? 'invalid'\n : 'unavailable',\n message: error instanceof Error ? error.message : String(error),\n },\n }\n }\n}\n\n/** Open (or create on first append) the findings journal at `path`; every reopen requires its pin. */\nexport function openFindingsLedger(options: { path: string }): FindingsLedger {\n if (!options.path.trim()) throw new TypeError('findings ledger: path is empty')\n const journal = new FileLedgerJournal(options.path, codec(), { requireTrustedHead: true })\n return {\n path: journal.path,\n append: (runId, findings) =>\n outcome(async () => {\n identity.parse(runId)\n let appended = 0\n let replayed = 0\n for (const finding of findings) {\n const parsed = AnalystFindingSchema.safeParse(finding)\n if (!parsed.success) {\n const issue = parsed.error.issues[0]\n throw new FindingsLedgerInvalidError(\n `finding ${finding.finding_id} is invalid at ${(issue?.path ?? []).join('.')}: ${issue?.message}`,\n )\n }\n const result = await journal.append(\n {\n kind: 'finding',\n eventId: eventIdFor(runId, finding.finding_id),\n run_id: runId,\n finding: parsed.data,\n },\n { pinHead: true },\n )\n if (result.appended) appended += 1\n else replayed += 1\n }\n return { appended, replayed }\n }),\n read: () =>\n outcome(async () => {\n const findings = await journal.replay()\n return { findings, merkleRoot: merkleRoot(findings.map((row) => row.entryHash)) }\n }),\n }\n}\n\n// ── Queries ──────────────────────────────────────────────────────────\n\nexport interface FindingsQuery {\n layer?: FindingLayer | readonly FindingLayer[]\n subject?: string\n analystId?: string\n runId?: string\n claimId?: string\n /**\n * Findings whose `scope.domain_path` starts with this path. A finding with no\n * domain path never matches, so a path query cannot return unscoped findings.\n */\n domainPath?: readonly string[]\n}\n\n/** Filter ledger rows. Every set criterion must hold; 1.0.0 rows have no layer and never match one. */\nexport function queryFindings<T extends AnalystFinding & { run_id?: string }>(\n rows: readonly T[],\n query: FindingsQuery,\n): T[] {\n const layers =\n query.layer === undefined\n ? null\n : new Set(typeof query.layer === 'string' ? [query.layer] : query.layer)\n return rows.filter((row) => {\n if (layers && (row.layer === undefined || !layers.has(row.layer))) return false\n if (query.subject !== undefined && row.subject !== query.subject) return false\n if (query.analystId !== undefined && row.analyst_id !== query.analystId) return false\n if (query.runId !== undefined && row.run_id !== query.runId) return false\n if (query.claimId !== undefined && row.claim_id !== query.claimId) return false\n if (query.domainPath !== undefined) {\n const path = row.scope?.domain_path\n if (!path || path.length < query.domainPath.length) return false\n if (query.domainPath.some((id, index) => path[index] !== id)) return false\n }\n return true\n })\n}\n\nexport interface FindingsTimeStep {\n previous_run_id: string\n run_id: string\n diff: FindingsDiff\n}\n\n/**\n * Diff each run against the run before it, in the order runs first entered\n * the ledger. Uses `diffFindings`, so `appeared`, `disappeared`, `persisted`\n * and `changed` mean exactly what they mean for two runs.\n */\nexport function diffFindingsOverTime(\n rows: readonly LedgerFinding[],\n policy: DiffPolicy = {},\n): FindingsTimeStep[] {\n const runs: string[] = []\n const byRun = new Map<string, PersistedFinding[]>()\n for (const row of [...rows].sort((a, b) => a.sequence - b.sequence)) {\n const list = byRun.get(row.run_id)\n if (list) list.push(row)\n else {\n runs.push(row.run_id)\n byRun.set(row.run_id, [row])\n }\n }\n return runs.slice(1).map((runId, index) => ({\n previous_run_id: runs[index]!,\n run_id: runId,\n diff: diffFindings(byRun.get(runs[index]!)!, byRun.get(runId)!, policy),\n }))\n}\n","/**\n * Skill-usage analyst — a DETERMINISTIC `Analyst` over a Claude/Codex skill\n * library + its trace corpus. Unlike the trace-store kinds (failure-mode,\n * improvement, ...) this kind calls no LLM: it mines real usage and skill\n * structure and emits findings by rule.\n *\n * It exists because the naive \"Skill-tool invocation count\" lies low — it\n * misses orchestrated sub-dispatch (a leaf skill run BY /pursue or /governor\n * logs under the parent), slash-command entry, local-script bypass, and\n * on-disk artifacts. The 2026-05-30 skill audit found 39/53 skills at zero\n * direct invocations, yet only one was a genuine cut: the rest were\n * measurement-invisible or discovery-limited. This analyst encodes that\n * lesson as a multi-signal usage model so a cheap repeatable pass can keep\n * the library honest, and so the expensive audit workflow's verdicts can\n * GEPA-distill it toward agreement (see `gold/skill-verdicts.gold.jsonl`).\n *\n * Report-building (`buildSkillUsageReport`, an fs scan) is separated from\n * finding emission (`SkillUsageAnalyst.analyze`, pure) so the slow scan runs\n * once at the registry boundary and the rule logic stays unit-testable.\n */\n\nimport { type Dirent, existsSync, readdirSync, readFileSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\n\n\n\n\n// ── Input model ──────────────────────────────────────────────────────\n\ntype SkillKind = 'public' | 'private'\n\n/** One skill's multi-signal usage + structure. All counts are deterministic. */\nexport interface SkillUsageRecord {\n name: string\n kind: SkillKind\n /** Absolute path to the skill's SKILL.md. */\n path: string\n lines: number\n /** `\"skill\":\"<name>\"` Skill-tool invocations across the trace corpus. */\n directInvocations: number\n /** `<command-name>/<name>` slash invocations across the trace corpus. */\n slashInvocations: number\n /** Sibling skills whose SKILL.md dispatches to this one (`/<name>`). Proxy\n * for orchestrated sub-dispatch the per-skill counter cannot see. */\n inboundRefs: number\n /** On-disk artifacts attributable to the skill (e.g. `.evolve/<name>/**`). */\n artifactCount: number\n /** Tangle-private reference count in the body (leak signal for public skills). */\n tanglePrivateRefs: number\n hasReferencesDir: boolean\n hasEvalsDir: boolean\n /** Body mentions `skill-runs.jsonl` (visible to /reflect + /governor). */\n logsRuns: boolean\n /** Description carries an explicit `Triggers:` clause / trigger phrases. */\n hasTriggerPhrases: boolean\n}\n\nexport interface SkillUsageReport {\n generatedFromTraces: number\n records: SkillUsageRecord[]\n}\n\nexport interface SkillUsageScanConfig {\n /** Dirs holding `*.jsonl` transcripts (Claude `~/.claude/projects`, Codex sessions). */\n transcriptDirs: string[]\n /** Skill roots to scan; each dir directly under `root` with a `SKILL.md` is a skill. */\n skillRoots: { root: string; kind: SkillKind }[]\n /** Roots scanned for `<root>/.evolve/<skill>` artifact dirs. */\n artifactRoots?: string[]\n /** Token-prefixed mappings: skill name → extra artifact subpaths under an artifactRoot\n * (e.g. reflect → `.evolve/reflections`). Catches non-eponymous artifact dirs. */\n artifactAliases?: Record<string, string[]>\n /** Cap files read per transcript dir (bounds a huge corpus); 0 = unbounded. */\n maxTranscriptsPerDir?: number\n}\n\n// ── Deterministic thresholds ─────────────────────────────────────────\n\n\n\nconst TANGLE_PRIVATE_RE =\n /\\b(cli-bridge|tangletools|ops-board|drew-gtr-pro|@tangle-network\\/|~\\/company|tangle\\.tools|gtm-agent)\\b|\\bkimi\\b|\\btcloud\\b/gi\nconst TRIGGER_RE = /triggers?\\s*[:-]/i\n\n// ── Report builder (fs scan — slow, runs once at the registry boundary) ──\n\nfunction listSkillDirs(root: string): { name: string; path: string }[] {\n if (!existsSync(root)) return []\n const out: { name: string; path: string }[] = []\n for (const entry of readdirSync(root, { withFileTypes: true })) {\n if (!entry.isDirectory() && !entry.isSymbolicLink()) continue\n const skillMd = join(root, entry.name, 'SKILL.md')\n if (existsSync(skillMd)) out.push({ name: entry.name, path: skillMd })\n }\n return out\n}\n\nfunction walkJsonl(dir: string, cap: number): string[] {\n if (!existsSync(dir)) return []\n const files: string[] = []\n const stack = [dir]\n while (stack.length) {\n const cur = stack.pop()!\n let entries: Dirent[]\n try {\n entries = readdirSync(cur, { withFileTypes: true })\n } catch {\n continue\n }\n for (const e of entries) {\n const full = join(cur, e.name)\n if (e.isDirectory()) stack.push(full)\n else if (e.name.endsWith('.jsonl')) {\n files.push(full)\n if (cap > 0 && files.length >= cap) return files\n }\n }\n }\n return files\n}\n\nfunction frontmatterDescription(body: string): string {\n const fm = /^---\\n([\\s\\S]*?)\\n---/.exec(body)\n const block = fm?.[1] ?? ''\n const m = /description:\\s*(.+)/i.exec(block)\n return m?.[1] ?? ''\n}\n\nfunction countArtifacts(roots: string[], name: string, aliases: string[]): number {\n let n = 0\n for (const root of roots) {\n const candidates = [join(root, '.evolve', name), ...aliases.map((a) => join(root, a))]\n for (const dir of candidates) {\n if (!existsSync(dir)) continue\n try {\n if (statSync(dir).isDirectory()) n += readdirSync(dir).length\n else n += 1\n } catch {\n /* unreadable — skip */\n }\n }\n }\n return n\n}\n\n/** Scan the corpus + skill roots into a {@link SkillUsageReport}. Deterministic. */\nexport function buildSkillUsageReport(config: SkillUsageScanConfig): SkillUsageReport {\n const skills = config.skillRoots.flatMap(({ root, kind }) =>\n listSkillDirs(root).map((s) => ({ ...s, kind })),\n )\n const names = skills.map((s) => s.name)\n\n // One pass over the corpus accumulating direct + slash counts per skill.\n const direct = new Map<string, number>(names.map((n) => [n, 0]))\n const slash = new Map<string, number>(names.map((n) => [n, 0]))\n const skillRe = /\"skill\"\\s*:\\s*\"([a-z0-9_:-]+)\"/g\n const cmdRe = /<command-name>\\/?([a-z0-9_:-]+)<\\/command-name>/g\n let transcripts = 0\n for (const dir of config.transcriptDirs) {\n for (const file of walkJsonl(dir, config.maxTranscriptsPerDir ?? 0)) {\n transcripts += 1\n let data: string\n try {\n data = readFileSync(file, 'utf8')\n } catch {\n continue\n }\n for (const m of data.matchAll(skillRe)) {\n const g = m[1]\n if (!g) continue\n const n = g.split(':').pop() ?? g\n const prev = direct.get(n)\n if (prev !== undefined) direct.set(n, prev + 1)\n }\n for (const m of data.matchAll(cmdRe)) {\n const g = m[1]\n if (g === undefined) continue\n const prev = slash.get(g)\n if (prev !== undefined) slash.set(g, prev + 1)\n }\n }\n }\n\n // Read each skill body once; compute structure + inbound refs across siblings.\n const bodies = new Map<string, string>()\n for (const s of skills) {\n try {\n bodies.set(s.name, readFileSync(s.path, 'utf8'))\n } catch {\n bodies.set(s.name, '')\n }\n }\n const inbound = new Map<string, number>(names.map((n) => [n, 0]))\n for (const target of names) {\n const ref = new RegExp(`/${target}\\\\b|\\\\[\\\\[${target}\\\\]\\\\]`)\n for (const s of skills) {\n if (s.name === target) continue\n if (ref.test(bodies.get(s.name) ?? '')) inbound.set(target, inbound.get(target)! + 1)\n }\n }\n\n const records: SkillUsageRecord[] = skills.map((s) => {\n const body = bodies.get(s.name) ?? ''\n const dir = s.path.replace(/\\/SKILL\\.md$/, '')\n return {\n name: s.name,\n kind: s.kind,\n path: s.path,\n lines: body ? body.split('\\n').length : 0,\n directInvocations: direct.get(s.name) ?? 0,\n slashInvocations: slash.get(s.name) ?? 0,\n inboundRefs: inbound.get(s.name) ?? 0,\n artifactCount: countArtifacts(\n config.artifactRoots ?? [],\n s.name,\n config.artifactAliases?.[s.name] ?? [],\n ),\n tanglePrivateRefs: (body.match(TANGLE_PRIVATE_RE) ?? []).length,\n hasReferencesDir: existsSync(join(dir, 'references')),\n hasEvalsDir: existsSync(join(dir, 'evals')),\n logsRuns: body.includes('skill-runs.jsonl'),\n hasTriggerPhrases: TRIGGER_RE.test(frontmatterDescription(body) || body.slice(0, 600)),\n }\n })\n return { generatedFromTraces: transcripts, records }\n}\n\n// ── Finding emission (pure — unit-testable, no LLM, no fs) ────────────\n\n\n\n\n\n\n\n// ── The Analyst ──────────────────────────────────────────────────────\n\n\n\n\n","import {\n assertConsistentFindingConditions,\n findingCompositionKey,\n mergeFindingComposition,\n} from './finding-composition'\n/**\n * Promotion — the only way a claim moves above the layer it was measured at.\n *\n * A claim is restated at a parent node only when at least `k` independent\n * children carry the same `claim_id` with intervals that agree. Otherwise it\n * stays where it is, reported as untested above. The rule is the same on every\n * rung of the ladder: run → play → problem → each domain node up the path →\n * lab.\n *\n * The rule, exactly:\n * - A finding sits at the node that is the lowest common ancestor of its\n * `scope.population` in the taxonomy, and that node's layer must equal the\n * finding's `layer`. Four runs of one play place a claim at that play; the\n * same claim stored at `domain` or `lab` is refused as exceeding its\n * evidence.\n * - Only children with `measure.interval` vote. Voters must name the same\n * measure and unit, and their intervals must share a common point.\n * - Children are counted by lineage, not by node: two children whose evidence\n * units share a lineage root (run 2 built on run 1's code) count once, and\n * a child with no recorded lineage shares one root with every other such\n * child.\n * - Promoted findings cite every voting child by `finding://<finding_id>`.\n *\n * Event, turn, agent, team and meta findings sit outside the ladder and never\n * promote.\n */\n\nimport {\n type DomainTaxonomy,\n domainPathOf,\n LAB_NODE_ID,\n lowestCommonAncestor,\n taxonomyAncestry,\n taxonomyLayerOf,\n taxonomyParentOf,\n} from './domain-taxonomy'\nimport {\n type FindingLayer,\n type FindingMeasure,\n lineageRoots,\n mergeEvidenceUnits,\n mostSevere,\n spanningWindow,\n UNKNOWN_LINEAGE,\n} from './finding-scope'\nimport { type AnalystFinding, makeFinding } from './types'\n\n/** Bump when the promotion rule changes, so promoted findings name the rule that lifted them. */\nconst PROMOTE_VERSION = '1'\n\n/** The analyst id a promoted finding carries when its children came from different analysts. */\nconst PROMOTE_ANALYST_ID = 'promote'\n\nexport interface PromoteOptions {\n /** Independent agreeing children required to lift a claim. Default 2, minimum 2. */\n k?: number\n /** Timestamp stamped on promoted findings; defaults to now. */\n produced_at?: string\n}\n\n/** A finding promote did not lift, with the reason in words. */\nexport interface PromotionHold {\n finding_id: string\n claim_id: string | null\n /** The node the finding sits at, or null when it could not be placed. */\n node: string | null\n reason: string\n}\n\nexport interface PromotionResult {\n /** The input findings followed by every promoted finding. */\n findings: AnalystFinding[]\n promoted: AnalystFinding[]\n /** Placed findings whose claim was not lifted; they stay true at their own node. */\n untestedAbove: PromotionHold[]\n /** Findings promote cannot place on the ladder, and why. */\n unplaced: PromotionHold[]\n}\n\ninterface Placement {\n finding: AnalystFinding\n claimId: string\n node: string\n}\n\nconst LADDER: readonly FindingLayer[] = ['run', 'play', 'problem', 'domain', 'lab']\n\nexport function promote(\n findings: readonly AnalystFinding[],\n taxonomy: DomainTaxonomy,\n options: PromoteOptions = {},\n): PromotionResult {\n assertConsistentFindingConditions(findings)\n const k = options.k ?? 2\n if (!Number.isInteger(k) || k < 2) {\n throw new RangeError(`promote: k must be an integer of at least 2, got ${k}`)\n }\n const unplaced: PromotionHold[] = []\n const buckets = new Map<number, Placement[]>()\n const addPlacement = (placement: Placement): void => {\n const depth = taxonomyAncestry(taxonomy, placement.node).length\n const bucket = buckets.get(depth) ?? []\n bucket.push(placement)\n buckets.set(depth, bucket)\n }\n for (const finding of findings) {\n const placed = place(finding, taxonomy)\n if ('reason' in placed) unplaced.push(placed)\n else addPlacement(placed)\n }\n\n const roots = lineageRoots(\n mergeEvidenceUnits(findings.flatMap((finding) => finding.evidence_units ?? [])),\n )\n const promoted: AnalystFinding[] = []\n const untestedAbove: PromotionHold[] = []\n const hold = (placement: Placement, reason: string): void => {\n untestedAbove.push({\n finding_id: placement.finding.finding_id,\n claim_id: placement.claimId,\n node: placement.node,\n reason,\n })\n }\n\n // Deepest nodes first: a parent's bucket is complete, native findings and\n // lifted ones alike, before it is itself grouped for the next rung.\n for (let depth = Math.max(0, ...buckets.keys()); depth > 1; depth -= 1) {\n const groups = new Map<string, { parent: string; members: Placement[] }>()\n for (const placement of buckets.get(depth) ?? []) {\n const parent = taxonomyParentOf(taxonomy, placement.node)\n if (parent === null || parent === undefined) continue\n const key = JSON.stringify([\n placement.claimId,\n parent,\n findingCompositionKey(placement.finding),\n ])\n const group = groups.get(key) ?? { parent, members: [] }\n group.members.push(placement)\n groups.set(key, group)\n }\n for (const { parent, members } of groups.values()) {\n const verdict = judgeGroup(members, k, roots)\n if (!verdict.lift) {\n for (const member of members) hold(member, verdict.reason)\n continue\n }\n const lifted = liftedFinding(verdict.voters, parent, taxonomy, options.produced_at)\n promoted.push(lifted)\n addPlacement({ finding: lifted, claimId: members[0]!.claimId, node: parent })\n for (const member of members) {\n if (!verdict.voters.includes(member)) {\n hold(member, 'no interval, so it could not vote; the claim was lifted by its siblings')\n }\n }\n }\n }\n return { findings: [...findings, ...promoted], promoted, untestedAbove, unplaced }\n}\n\nfunction place(finding: AnalystFinding, taxonomy: DomainTaxonomy): Placement | PromotionHold {\n const unplaced = (reason: string, node: string | null = null): PromotionHold => ({\n finding_id: finding.finding_id,\n claim_id: finding.claim_id ?? null,\n node,\n reason,\n })\n if (finding.schema_version !== '1.1.0' || !finding.layer || !finding.scope) {\n return unplaced('no layer or scope (schema 1.0.0)')\n }\n if (finding.layer === 'meta')\n return unplaced('meta findings describe the instrument and never promote')\n if (!LADDER.includes(finding.layer)) {\n return unplaced(`${finding.layer} findings sit below the run → lab ladder`)\n }\n if (!finding.claim_id) return unplaced('no claim_id to match siblings by')\n const population = finding.scope.population\n if (population.length === 0) return unplaced('population names no units')\n const node = lowestCommonAncestor(taxonomy, population)\n if (node === undefined) return unplaced('population names ids outside the taxonomy')\n const nodeLayer = taxonomyLayerOf(taxonomy, node)\n if (nodeLayer !== finding.layer) {\n return unplaced(\n LADDER.indexOf(finding.layer) > LADDER.indexOf(nodeLayer as FindingLayer)\n ? `stated at ${finding.layer} but its population sits within ${nodeLayer} '${node}'`\n : `stated at ${finding.layer} but its population spans ${nodeLayer} '${node}'`,\n node,\n )\n }\n const path = finding.scope.domain_path\n if (path) {\n const expected = domainPathOf(taxonomy, node)\n if (path.length !== expected.length || path.some((id, index) => id !== expected[index])) {\n return unplaced(`domain_path ${JSON.stringify(path)} disagrees with the taxonomy`, node)\n }\n }\n return { finding, claimId: finding.claim_id, node }\n}\n\ntype GroupVerdict = { lift: true; voters: Placement[] } | { lift: false; reason: string }\n\nfunction judgeGroup(\n members: readonly Placement[],\n k: number,\n roots: ReadonlyMap<string, string>,\n): GroupVerdict {\n const voters = members.filter((member) => member.finding.measure?.interval !== undefined)\n if (voters.length === 0) return { lift: false, reason: 'no child carries an interval' }\n const first = voters[0]!.finding.measure!\n if (\n voters.some(\n ({ finding }) => finding.measure!.name !== first.name || finding.measure!.unit !== first.unit,\n )\n ) {\n return { lift: false, reason: 'children measure different quantities' }\n }\n const lo = Math.max(...voters.map(({ finding }) => finding.measure!.interval![0]))\n const hi = Math.min(...voters.map(({ finding }) => finding.measure!.interval![1]))\n if (lo > hi) return { lift: false, reason: 'child intervals do not agree' }\n\n const independent = independentChildren(voters, roots)\n if (independent < k) {\n const children = new Set(voters.map((voter) => voter.node)).size\n return {\n lift: false,\n reason:\n children > independent\n ? `${children} children agree but share lineage, leaving ${independent} independent of ${k} required`\n : `${independent} independent agreeing child${independent === 1 ? '' : 'ren'} of ${k} required`,\n }\n }\n return { lift: true, voters }\n}\n\n/**\n * Children joined when they share a lineage root, counted as components. A\n * child's roots are those of all its voters' evidence units; a voter with no\n * units has unknown lineage.\n */\nfunction independentChildren(\n voters: readonly Placement[],\n roots: ReadonlyMap<string, string>,\n): number {\n const rootsByNode = new Map<string, Set<string>>()\n for (const voter of voters) {\n const set = rootsByNode.get(voter.node) ?? new Set<string>()\n const units = voter.finding.evidence_units\n if (!units) set.add(UNKNOWN_LINEAGE)\n else for (const unit of units) set.add(roots.get(unit.id) ?? UNKNOWN_LINEAGE)\n rootsByNode.set(voter.node, set)\n }\n const parent = new Map<string, string>()\n const find = (id: string): string => {\n let current = id\n while (parent.get(current) !== current) current = parent.get(current)!\n return current\n }\n const owner = new Map<string, string>()\n for (const [node, nodeRoots] of rootsByNode) {\n parent.set(node, node)\n for (const root of nodeRoots) {\n const other = owner.get(root)\n if (other === undefined) owner.set(root, node)\n else parent.set(find(node), find(other))\n }\n }\n return new Set([...rootsByNode.keys()].map(find)).size\n}\n\nfunction liftedFinding(\n voters: readonly Placement[],\n parent: string,\n taxonomy: DomainTaxonomy,\n producedAt: string | undefined,\n): AnalystFinding {\n const findings = voters.map((voter) => voter.finding)\n const first = findings[0]!\n const measures = findings.map((finding) => finding.measure!) as FindingMeasure[]\n const levels = new Set(measures.map((measure) => measure.level))\n const level = levels.size === 1 ? measures[0]!.level : undefined\n const population = [...new Set(findings.flatMap((finding) => finding.scope!.population))].sort()\n const allUnits = findings.every((finding) => finding.evidence_units !== undefined)\n ? mergeEvidenceUnits(findings.flatMap((finding) => finding.evidence_units!))\n : undefined\n const confounders = [...new Set(findings.flatMap((finding) => finding.confounders ?? []))].sort()\n const analysts = new Set(findings.map((finding) => finding.analyst_id))\n const domainPath = domainPathOf(taxonomy, parent)\n const parentLayer = taxonomyLayerOf(taxonomy, parent) as FindingLayer\n return makeFinding({\n analyst_id: analysts.size === 1 ? first.analyst_id : PROMOTE_ANALYST_ID,\n area: first.area,\n claim: first.claim,\n claim_id: first.claim_id!,\n id_basis: `${first.claim_id}@${parent}`,\n ...mergeFindingComposition(findings),\n subject: parent,\n severity: mostSevere(findings),\n confidence: Math.min(...findings.map((finding) => finding.confidence)),\n evidence_refs: findings.map((finding) => ({\n kind: 'finding' as const,\n uri: `finding://${finding.finding_id}`,\n })),\n layer: parentLayer,\n scope: {\n population,\n n: population.length,\n window: spanningWindow(findings),\n ...(domainPath.length > 0 && parent !== LAB_NODE_ID ? { domain_path: domainPath } : {}),\n },\n method: { kind: 'computed', name: 'promote', version: PROMOTE_VERSION },\n measure: {\n name: measures[0]!.name,\n unit: measures[0]!.unit,\n value: measures.reduce((sum, measure) => sum + measure.value, 0) / measures.length,\n interval: [\n Math.max(...measures.map((measure) => measure.interval![0])),\n Math.min(...measures.map((measure) => measure.interval![1])),\n ],\n ...(level === undefined ? {} : { level }),\n },\n ...(confounders.length > 0 ? { confounders } : {}),\n ...(allUnits ? { evidence_units: allUnits } : {}),\n rationale: `Lifted to ${parentLayer} '${parent}': ${new Set(voters.map((voter) => voter.node)).size} children carry claim '${first.claim_id}' with intervals that share [${Math.max(...measures.map((m) => m.interval![0]))}, ${Math.min(...measures.map((m) => m.interval![1]))}].`,\n metadata: {\n taxonomy_version: taxonomy.version,\n promoted_from: [...new Set(voters.map((voter) => voter.node))].sort(),\n },\n ...(producedAt === undefined ? {} : { produced_at: producedAt }),\n })\n}\n","import {\n assertConsistentFindingConditions,\n findingCompositionKey,\n mergeFindingComposition,\n} from './finding-composition'\n/**\n * rollup — run findings aggregated up the ladder, with bootstrap intervals and\n * denominators, lifted only where `promote` allows.\n *\n * Run-layer findings that share a `claim_id` and a measure are pooled per play\n * into one play-layer finding. Its interval is a cluster bootstrap where each\n * cluster is a lineage root, so runs that built on each other move together\n * and four runs of one lineage yield one cluster and no interval. Those play\n * findings then go through `promote`; each finding it lifts to a problem,\n * domain node or the lab gets the pooled bootstrap over every run underneath\n * it, with its observation and cluster counts.\n */\n\nimport { clusterBootstrapMean } from '../meta-eval/cluster-bootstrap'\nimport {\n type DomainTaxonomy,\n domainPathOf,\n lowestCommonAncestor,\n taxonomyLayerOf,\n taxonomyParentOf,\n} from './domain-taxonomy'\nimport {\n lineageRoots,\n mergeEvidenceUnits,\n mostSevere,\n spanningWindow,\n UNKNOWN_LINEAGE,\n} from './finding-scope'\nimport { type PromotionHold, promote } from './promote'\nimport { type AnalystFinding, makeFinding } from './types'\n\nconst ROLLUP_ANALYST_ID = 'rollup'\nconst ROLLUP_VERSION = '1'\n\nexport interface RollupOptions {\n /** Independent agreeing children `promote` requires. Default 2. */\n k?: number\n /** Bootstrap seed; absent, the seed derives from the values, so reruns match. */\n seed?: number\n resamples?: number\n /** Interval confidence. Default 0.95. */\n confidence?: number\n produced_at?: string\n}\n\nexport interface RollupResult {\n /** Play aggregates followed by every finding promote lifted from them. */\n findings: AnalystFinding[]\n untestedAbove: PromotionHold[]\n /** Input findings rollup could not use, and why. */\n skipped: PromotionHold[]\n}\n\ninterface Observation {\n finding: AnalystFinding\n claimId: string\n run: string\n value: number\n cluster: string\n}\n\nexport function rollupFindings(\n findings: readonly AnalystFinding[],\n taxonomy: DomainTaxonomy,\n options: RollupOptions = {},\n): RollupResult {\n assertConsistentFindingConditions(findings)\n const confidence = options.confidence ?? 0.95\n const skipped: PromotionHold[] = []\n const skip = (finding: AnalystFinding, reason: string): void => {\n skipped.push({\n finding_id: finding.finding_id,\n claim_id: finding.claim_id ?? null,\n node: null,\n reason,\n })\n }\n const roots = lineageRoots(findings.flatMap((finding) => finding.evidence_units ?? []))\n const observations: Observation[] = []\n for (const finding of findings) {\n if (finding.layer !== 'run' || !finding.scope) continue\n if (!finding.claim_id) {\n skip(finding, 'no claim_id')\n continue\n }\n if (!finding.measure) {\n skip(finding, 'no measure to aggregate')\n continue\n }\n const run = lowestCommonAncestor(taxonomy, finding.scope.population)\n if (run === undefined || taxonomyLayerOf(taxonomy, run) !== 'run') {\n skip(finding, 'population is not one run in the taxonomy')\n continue\n }\n const units = finding.evidence_units\n const runRoots = new Set(\n units ? units.map((unit) => roots.get(unit.id) ?? UNKNOWN_LINEAGE) : [UNKNOWN_LINEAGE],\n )\n observations.push({\n finding,\n claimId: finding.claim_id,\n run,\n value: finding.measure.value,\n // A run whose units reach several roots is clustered on the first; one\n // run is one observation either way.\n cluster: [...runRoots].sort()[0]!,\n })\n }\n\n const groups = new Map<string, { play: string; members: Observation[] }>()\n for (const observation of observations) {\n const play = taxonomyParentOf(taxonomy, observation.run)!\n const key = JSON.stringify([\n observation.claimId,\n play,\n findingCompositionKey(observation.finding),\n ])\n const group = groups.get(key) ?? { play, members: [] }\n group.members.push(observation)\n groups.set(key, group)\n }\n const aggregates: AnalystFinding[] = []\n for (const { play, members } of groups.values()) {\n const measure = members[0]!.finding.measure!\n if (\n members.some(\n ({ finding }) =>\n finding.measure!.name !== measure.name || finding.measure!.unit !== measure.unit,\n )\n ) {\n for (const member of members)\n skip(member.finding, `runs of play '${play}' measure different quantities`)\n continue\n }\n const pooled = pool(members, options, confidence)\n const findingsInGroup = members.map((member) => member.finding)\n const population = [...new Set(members.map((member) => member.run))].sort()\n const units = findingsInGroup.every((finding) => finding.evidence_units !== undefined)\n ? mergeEvidenceUnits(findingsInGroup.flatMap((finding) => finding.evidence_units!))\n : undefined\n const domainPath = domainPathOf(taxonomy, play)\n const first = findingsInGroup[0]!\n aggregates.push(\n makeFinding({\n analyst_id: ROLLUP_ANALYST_ID,\n area: first.area,\n claim: first.claim,\n claim_id: first.claim_id!,\n id_basis: `${first.claim_id}@${play}`,\n ...mergeFindingComposition(findingsInGroup),\n subject: play,\n severity: mostSevere(findingsInGroup),\n confidence: Math.min(...findingsInGroup.map((finding) => finding.confidence)),\n evidence_refs: findingsInGroup.map((finding) => ({\n kind: 'finding' as const,\n uri: `finding://${finding.finding_id}`,\n })),\n layer: 'play',\n scope: {\n population,\n n: population.length,\n window: spanningWindow(findingsInGroup),\n ...(domainPath.length > 0 ? { domain_path: domainPath } : {}),\n },\n method: { kind: 'computed', name: ROLLUP_ANALYST_ID, version: ROLLUP_VERSION },\n measure: { name: measure.name, unit: measure.unit, ...pooled.measure },\n ...(units ? { evidence_units: units } : {}),\n metadata: { denominators: pooled.denominators },\n ...(options.produced_at === undefined ? {} : { produced_at: options.produced_at }),\n }),\n )\n }\n\n const promotion = promote(aggregates, taxonomy, {\n ...(options.k === undefined ? {} : { k: options.k }),\n ...(options.produced_at === undefined ? {} : { produced_at: options.produced_at }),\n })\n const promoted = promotion.promoted.map((finding) => {\n const covered = new Set(finding.scope!.population)\n const members = observations.filter(\n (observation) =>\n observation.claimId === finding.claim_id &&\n covered.has(observation.run) &&\n findingCompositionKey(observation.finding) === findingCompositionKey(finding),\n )\n const pooled = pool(members, options, confidence)\n return {\n ...finding,\n measure: { name: finding.measure!.name, unit: finding.measure!.unit, ...pooled.measure },\n metadata: { ...finding.metadata, denominators: pooled.denominators },\n }\n })\n return {\n findings: [...aggregates, ...promoted],\n untestedAbove: promotion.untestedAbove,\n skipped: [...skipped, ...promotion.unplaced],\n }\n}\n\n/**\n * Cluster bootstrap of the run values. With one cluster there is no spread\n * between independent sources, so the measure carries no interval and cannot\n * vote in `promote`.\n */\nfunction pool(members: readonly Observation[], options: RollupOptions, confidence: number) {\n const result = clusterBootstrapMean(\n members.map((member) => ({ cluster: member.cluster, value: member.value })),\n {\n confidence,\n ...(options.seed === undefined ? {} : { seed: options.seed }),\n ...(options.resamples === undefined ? {} : { resamples: options.resamples }),\n },\n )\n return {\n measure:\n result.clusters >= 2\n ? {\n value: result.mean,\n interval: [result.low, result.high] as [number, number],\n level: confidence,\n }\n : { value: result.mean },\n denominators: { observations: result.n, independent_clusters: result.clusters },\n }\n}\n\nexport interface RollupInput {\n findings: readonly AnalystFinding[]\n taxonomy: DomainTaxonomy\n options?: RollupOptions\n}\n","/**\n * team-shape — classify how a supervision tree was organized, from a Runtime\n * spawn journal and its coordination log.\n *\n * Input rows come in either of two shapes, read by the same parser:\n * - Runtime envelopes, as `readRuntimeSupervisorRun` returns them in\n * `SupervisorRunSources.journal` and `.coordinationLog`\n * (`teamShapeInputFromSources`);\n * - the structure-only reduction under `tests/fixtures/team-shape`\n * (`extract.py`): spawn rows `{ kind, journal, id, at }`, coordination\n * rows `{ at, type, owner, toWorker?, from?, by?, delivered? }`.\n *\n * Three edge sets over the agents:\n * - E, command, parent → child. The parent is the child id minus its last\n * `:sN` segment (`R:s1:s0` is child `s0` of `R:s1`); the spawn journal has\n * no parent field. An id outside that path is an unplaced agent: its E\n * edge is not observable, and it is never read as depth 1.\n * - G, governance, receiver → child: the agent whose journal holds the\n * child's `settled` row, plus the sender of each `steer`.\n * - C, communication, sender → receiver: coordination rows that name a\n * receiver (`toWorker`). The sender is `from`/`by` when the row names an\n * agent, else the log owner's digest, which no record joins to an agent.\n * `instruction` and `delivery-attempt` rows are the queue and transport\n * stages of the steer row that follows them, so they are not counted.\n *\n * Classes, version 1, checked in order; the first the record shows wins:\n * 1. single — one agent.\n * 2. governed-swarm — E runs between peers, or a team's governor\n * changes over the run.\n * 3. fleet — one dispatcher, and governance from a non-parent\n * agent inside the team or lateral C ≥ 20%.\n * 4. partition — two or more lead subtrees with no C or G between\n * them, and no lead settles to the root.\n * 5. hive — depth ≥ 2 and at least half the root's children\n * delegate (`hive depth N`).\n * 6. star-with-sub-leads — depth ≥ 2, fewer than half delegate.\n * 7. flat-star — depth 1; qualified by root integration share.\n * The thresholds are provisional and travel in `method.version`. A check the\n * record cannot decide (an owner digest is not an agent id, so lateral C and\n * steer governance often are not) reads `not observable from this record`,\n * never `no`, and the classification moves on to the next class.\n */\n\nimport type { SupervisorRunSources } from '../supervisor-run/types'\nimport type { Analyst } from './types'\nimport { makeFinding } from './types'\n\nexport const TEAM_SHAPE_ANALYST_ID = 'team-shape'\n\nconst TEAM_SHAPE_THRESHOLDS = {\n /** Share of the root's children that delegate at or above which depth ≥ 2 is a hive. */\n hiveDelegatingShare: 0.5,\n /** Lateral share of C edges at or above which a one-dispatcher team is a fleet. */\n fleetLateralCShare: 0.2,\n /** Root share of integrating commits at or above which a flat star reads `root integrates`. */\n rootIntegrationShare: 0.5,\n} as const\n\n/** Version 1, provisional, with the thresholds it was decided at. */\nexport const TEAM_SHAPE_VERSION = `1-provisional;hive-delegating=${TEAM_SHAPE_THRESHOLDS.hiveDelegatingShare};fleet-lateral-c=${TEAM_SHAPE_THRESHOLDS.fleetLateralCShare};root-integration=${TEAM_SHAPE_THRESHOLDS.rootIntegrationShare}`\n\nexport const TEAM_SHAPE_CLASSES = [\n 'single',\n 'governed-swarm',\n 'fleet',\n 'partition',\n 'hive',\n 'star-with-sub-leads',\n 'flat-star',\n] as const\n\nexport type TeamShapeClass = (typeof TEAM_SHAPE_CLASSES)[number]\n\nexport const NOT_OBSERVABLE = 'not observable from this record'\nexport type NotObservable = typeof NOT_OBSERVABLE\nexport type TeamShapeObserved<T> = T | NotObservable\n\nexport interface TeamIntegration {\n commit: string\n /** Agent id, in the record's id space, that authored the integrating commit. */\n by: string\n}\n\nexport interface TeamShapeInput {\n /** The run the record came from, cited as the finding's evidence. */\n runRef: string\n /** Spawn journal JSONL. */\n spawnJournal: string\n /** Coordination log JSONL; null or absent when the run kept none. */\n coordinationLog?: string | null\n /** The release's integrating commits; disco derives them from commit trailers. */\n integrations?: readonly TeamIntegration[]\n}\n\nexport interface TeamShapeEdge {\n from: string\n to: string\n count: number\n}\n\nexport interface TeamShapeFeatures {\n agents: number\n /** Agents other than the root. */\n tasks: number\n /** Agents whose id is outside the root's `:sN` path; their E edge is not observable. */\n unplacedAgents: number\n depth: number\n fanOut: { root: number; max: number }\n /** Root's children that delegate ÷ root's children; null when the root has none. */\n delegatingShare: number | null\n /** Spawns after the first settlement. */\n reHires: number\n settlementsByReceiver: Record<string, number>\n steers: { sent: number; delivered: number }\n /** Coordination messages per task; null with no tasks or no coordination log. */\n messagesPerTask: number | null\n /** Lateral C edges ÷ C edges. */\n lateralCShare: TeamShapeObserved<number>\n /** G edges from a non-parent agent ÷ G edges. */\n nonParentGShare: TeamShapeObserved<number>\n /** Root-authored integrating commits ÷ integrating commits. */\n rootIntegrationShare: TeamShapeObserved<number>\n}\n\nexport interface TeamShapeCheck {\n result: 'yes' | 'no' | NotObservable\n reason: string\n}\n\nexport interface TeamShape {\n class: TeamShapeClass\n depth: number\n /** Only a flat star carries one: `root integrates`, `root does not integrate` or `integration unknown`. */\n qualifier: string | null\n /** Class in words: `hive depth 2`, `flat-star (integration unknown)`. */\n label: string\n rootId: string\n features: TeamShapeFeatures\n /** Every class's rule against this record, in check order. */\n checks: Record<TeamShapeClass, TeamShapeCheck>\n graph: { command: TeamShapeEdge[]; governance: TeamShapeEdge[]; communication: TeamShapeEdge[] }\n invalidRows: { spawn: number; coordination: number }\n window: { from: string; to: string } | null\n}\n\nexport type TeamShapeOutcome =\n | { succeeded: true; value: TeamShape }\n | { succeeded: false; error: { message: string } }\n\ninterface SpawnRow {\n kind: 'spawned' | 'settled'\n /** Agent whose journal holds the row: the last segment of the journal key. */\n owner: string\n /** The whole journal key, to find the root marker. */\n journal: string\n id: string\n at: number\n}\n\ninterface CoordinationRow {\n at: number | null\n type: string\n owner: string | null\n toWorker?: string\n from?: string\n by?: string\n delivered?: boolean\n}\n\n/** Team-shape input for a run read through a supervisor-run reader. */\nexport function teamShapeInputFromSources(\n sources: SupervisorRunSources,\n integrations?: readonly TeamIntegration[],\n): { succeeded: true; value: TeamShapeInput } | { succeeded: false; error: { message: string } } {\n if (sources.journal === null) {\n return {\n succeeded: false,\n error: { message: sources.journalMissingReason ?? `no spawn journal for ${sources.runRef}` },\n }\n }\n return {\n succeeded: true,\n value: {\n runRef: sources.runRef,\n spawnJournal: sources.journal,\n coordinationLog: sources.coordinationLog ?? null,\n ...(integrations === undefined ? {} : { integrations }),\n },\n }\n}\n\nexport function classifyTeamShape(input: TeamShapeInput): TeamShapeOutcome {\n const spawnLog = parseSpawnRows(input.spawnJournal)\n const coordination =\n typeof input.coordinationLog === 'string' ? parseCoordinationRows(input.coordinationLog) : null\n const spawnedAt = new Map<string, number>()\n for (const row of spawnLog.rows) {\n if (row.kind !== 'spawned') continue\n spawnedAt.set(row.id, Math.min(row.at, spawnedAt.get(row.id) ?? Number.POSITIVE_INFINITY))\n }\n const rootIds = [\n ...new Set(\n spawnLog.rows\n .filter((row) => row.kind === 'spawned' && row.journal === row.id)\n .map((r) => r.id),\n ),\n ]\n if (rootIds.length !== 1) {\n return {\n succeeded: false,\n error: {\n message: `spawn journal for ${input.runRef} has ${rootIds.length} root markers; team-shape needs exactly one`,\n },\n }\n }\n const rootId = rootIds[0]!\n const agents = new Set(spawnedAt.keys())\n\n // E: the id path. A parent outside the record leaves the agent unplaced.\n const parentOf = new Map<string, string>()\n let unplacedAgents = 0\n for (const id of agents) {\n if (id === rootId) continue\n const parent = pathParent(id)\n if (parent !== null && agents.has(parent) && id.startsWith(`${rootId}:`)) {\n parentOf.set(id, parent)\n } else unplacedAgents += 1\n }\n const children = new Map<string, string[]>()\n const command = new Map<string, TeamShapeEdge>()\n for (const [child, parent] of parentOf) {\n children.set(parent, [...(children.get(parent) ?? []), child])\n addEdge(command, parent, child)\n }\n const depthOf = (id: string): number => {\n let hops = 0\n for (let at = parentOf.get(id); at !== undefined; at = parentOf.get(at)) hops += 1\n return hops\n }\n const depth = Math.max(0, ...[...parentOf.keys()].map(depthOf))\n const rootChildren = children.get(rootId) ?? []\n const leads = rootChildren.filter((child) => (children.get(child)?.length ?? 0) > 0)\n const delegatingShare = rootChildren.length === 0 ? null : leads.length / rootChildren.length\n const subtreeOf = (id: string): string | null => {\n let at: string | undefined = id\n while (at !== undefined && parentOf.get(at) !== rootId) at = parentOf.get(at)\n return at ?? null\n }\n\n // A spawn row in a journal that belongs to neither the parent nor the child itself.\n let peerSpawns = 0\n for (const row of spawnLog.rows) {\n if (row.kind !== 'spawned' || row.id === rootId) continue\n if (row.owner !== row.id && row.owner !== parentOf.get(row.id)) peerSpawns += 1\n }\n\n // G: settlements, receiver → child.\n const governance = new Map<string, TeamShapeEdge>()\n const settlementsByReceiver: Record<string, number> = {}\n const governorsByParent = new Map<string, { agents: Set<string>; digests: Set<string> }>()\n const governorsOf = (child: string) => {\n const parent = parentOf.get(child) ?? `unplaced:${child}`\n const entry = governorsByParent.get(parent) ?? { agents: new Set(), digests: new Set() }\n governorsByParent.set(parent, entry)\n return entry\n }\n let gResolved = 0\n let gUnresolved = 0\n let gNonParent = 0\n let firstSettlement = Number.POSITIVE_INFINITY\n for (const row of spawnLog.rows) {\n if (row.kind !== 'settled' || row.owner === row.id) continue\n firstSettlement = Math.min(firstSettlement, row.at)\n settlementsByReceiver[row.owner] = (settlementsByReceiver[row.owner] ?? 0) + 1\n addEdge(governance, row.owner, row.id)\n governorsOf(row.id).agents.add(row.owner)\n gResolved += 1\n if (parentOf.get(row.id) !== row.owner) gNonParent += 1\n }\n const reHires = [...spawnedAt.entries()].filter(\n ([id, at]) => id !== rootId && at > firstSettlement,\n ).length\n\n // C, and G from steers.\n const communication = new Map<string, TeamShapeEdge>()\n let messages = 0\n let cResolved = 0\n let cUnresolved = 0\n let cLateral = 0\n let cCrossSubtree = 0\n let gCrossSubtree = 0\n const steers = { sent: 0, delivered: 0 }\n const isAgent = (value: string | undefined): value is string =>\n value !== undefined && agents.has(value)\n for (const row of coordination?.rows ?? []) {\n if (row.type === 'instruction' || row.type === 'delivery-attempt') continue\n if (row.toWorker === undefined && row.from === undefined && row.by === undefined) continue\n messages += 1\n if (row.type === 'steer') {\n steers.sent += 1\n if (row.delivered === true) steers.delivered += 1\n }\n // A refused steer reached nobody: it is counted as sent, not as an edge.\n if (!isAgent(row.toWorker) || row.delivered === false) continue\n const receiver = row.toWorker\n const agentSender = [row.from, row.by].find(isAgent)\n const sender = agentSender ?? (row.owner === null ? null : `owner:${row.owner}`)\n if (sender === null) continue\n addEdge(communication, sender, receiver)\n if (agentSender === undefined) cUnresolved += 1\n else {\n cResolved += 1\n const parent = parentOf.get(receiver)\n if (parent !== undefined && parent === parentOf.get(agentSender)) cLateral += 1\n if (crosses(subtreeOf(agentSender), subtreeOf(receiver))) cCrossSubtree += 1\n }\n if (row.type === 'steer') {\n addEdge(governance, sender, receiver)\n if (agentSender === undefined) {\n gUnresolved += 1\n governorsOf(receiver).digests.add(sender)\n } else {\n gResolved += 1\n governorsOf(receiver).agents.add(agentSender)\n if (parentOf.get(receiver) !== agentSender) gNonParent += 1\n if (crosses(subtreeOf(agentSender), subtreeOf(receiver))) gCrossSubtree += 1\n }\n }\n }\n for (const [child, receiver] of spawnLog.rows\n .filter((row) => row.kind === 'settled' && row.owner !== row.id)\n .map((row) => [row.id, row.owner] as const)) {\n if (crosses(subtreeOf(receiver), subtreeOf(child))) gCrossSubtree += 1\n }\n\n const cTotal = cResolved + cUnresolved\n const gTotal = gResolved + gUnresolved\n const lateralCShare: TeamShapeObserved<number> =\n coordination === null || cTotal === 0 || cUnresolved > 0 ? NOT_OBSERVABLE : cLateral / cTotal\n const nonParentGShare: TeamShapeObserved<number> =\n gTotal === 0 || gUnresolved > 0 ? NOT_OBSERVABLE : gNonParent / gTotal\n const integrations = input.integrations ?? []\n const rootIntegrationShare: TeamShapeObserved<number> =\n integrations.length === 0\n ? NOT_OBSERVABLE\n : integrations.filter((row) => row.by === rootId).length / integrations.length\n\n const features: TeamShapeFeatures = {\n agents: agents.size,\n tasks: agents.size - 1,\n unplacedAgents,\n depth,\n fanOut: {\n root: rootChildren.length,\n max: Math.max(0, ...[...children.values()].map((c) => c.length)),\n },\n delegatingShare,\n reHires,\n settlementsByReceiver,\n steers,\n messagesPerTask: coordination === null || agents.size < 2 ? null : messages / (agents.size - 1),\n lateralCShare,\n nonParentGShare,\n rootIntegrationShare,\n }\n\n const checks = {} as Record<TeamShapeClass, TeamShapeCheck>\n checks.single = verdict(agents.size === 1, `${agents.size} agents`)\n\n const rotating = [...governorsByParent.entries()].find(([, g]) => g.agents.size > 1)\n const digestTeams = [...governorsByParent.values()].filter((g) => g.digests.size > 1).length\n checks['governed-swarm'] =\n peerSpawns > 0\n ? { result: 'yes', reason: `${peerSpawns} spawns recorded by a peer, not the parent` }\n : rotating !== undefined\n ? {\n result: 'yes',\n reason: `children of ${rotating[0]} are governed by ${[...rotating[1].agents].join(', ')}`,\n }\n : digestTeams > 0\n ? {\n result: NOT_OBSERVABLE,\n reason: `${digestTeams} teams were steered by more than one owner digest; a digest is not an agent id, so a rotating governor cannot be told from the operator`,\n }\n : {\n result: 'no',\n reason: 'every E edge runs parent to child and no team changed governor',\n }\n\n const dispatchers = [...children.keys()]\n if (dispatchers.length !== 1 || unplacedAgents > 0) {\n checks.fleet = {\n result: unplacedAgents > 0 && dispatchers.length <= 1 ? NOT_OBSERVABLE : 'no',\n reason:\n unplacedAgents > 0 && dispatchers.length <= 1\n ? `${unplacedAgents} unplaced agents hide who dispatched their work`\n : `${dispatchers.length} agents dispatch work`,\n }\n } else if (gNonParent > 0) {\n checks.fleet = { result: 'yes', reason: `${gNonParent} G edges come from a non-parent agent` }\n } else if (cLateral / Math.max(cTotal, 1) >= TEAM_SHAPE_THRESHOLDS.fleetLateralCShare) {\n checks.fleet = { result: 'yes', reason: `lateral C ${cLateral} of ${cTotal}` }\n } else if (gUnresolved > 0 || lateralCShare === NOT_OBSERVABLE) {\n checks.fleet = {\n result: NOT_OBSERVABLE,\n reason: `one dispatcher; ${gUnresolved} steer G and ${cUnresolved} C edges are sent from owner digests that no record joins to an agent${coordination === null ? ', and the run has no coordination log' : ''}`,\n }\n } else {\n checks.fleet = verdict(\n false,\n `one dispatcher, no non-parent G, lateral C ${cLateral} of ${cTotal}`,\n )\n }\n\n const rootSettledByLeads = spawnLog.rows.filter(\n (row) => row.kind === 'settled' && row.owner === rootId && leads.includes(row.id),\n ).length\n if (leads.length < 2 || rootSettledByLeads > 0 || gCrossSubtree > 0 || cCrossSubtree > 0) {\n checks.partition = verdict(\n false,\n `${leads.length} lead subtrees, ${rootSettledByLeads} lead settlements to the root, ${gCrossSubtree + cCrossSubtree} edges between subtrees`,\n )\n } else if (gUnresolved > 0 || cUnresolved > 0 || coordination === null) {\n checks.partition = {\n result: NOT_OBSERVABLE,\n reason: `${leads.length} lead subtrees and no lead settles to the root, but edges sent from owner digests cannot be placed in a subtree`,\n }\n } else {\n checks.partition = verdict(true, `${leads.length} lead subtrees with no C or G between them`)\n }\n\n const delegating = `${leads.length} of ${rootChildren.length} root children delegate`\n const hive = depth >= 2 && (delegatingShare ?? 0) >= TEAM_SHAPE_THRESHOLDS.hiveDelegatingShare\n checks.hive = verdict(hive, `depth ${depth}; ${delegating}`)\n checks['star-with-sub-leads'] = verdict(depth >= 2 && !hive, `depth ${depth}; ${delegating}`)\n checks['flat-star'] = verdict(depth === 1, `depth ${depth}`)\n\n const shapeClass = TEAM_SHAPE_CLASSES.find((name) => checks[name].result === 'yes')\n if (shapeClass === undefined) {\n return {\n succeeded: false,\n error: { message: `no team-shape class matches ${input.runRef} (depth ${depth})` },\n }\n }\n const qualifier =\n shapeClass !== 'flat-star'\n ? null\n : rootIntegrationShare === NOT_OBSERVABLE\n ? 'integration unknown'\n : rootIntegrationShare >= TEAM_SHAPE_THRESHOLDS.rootIntegrationShare\n ? 'root integrates'\n : 'root does not integrate'\n const label =\n shapeClass === 'hive'\n ? `hive depth ${depth}`\n : qualifier === null\n ? shapeClass\n : `${shapeClass} (${qualifier})`\n\n const times = [\n ...spawnLog.rows.map((row) => row.at),\n ...(coordination?.rows ?? []).flatMap((row) => (row.at === null ? [] : [row.at])),\n ]\n return {\n succeeded: true,\n value: {\n class: shapeClass,\n depth,\n qualifier,\n label,\n rootId,\n features,\n checks,\n graph: {\n command: [...command.values()],\n governance: [...governance.values()],\n communication: [...communication.values()],\n },\n invalidRows: { spawn: spawnLog.invalid, coordination: coordination?.invalid ?? 0 },\n window:\n times.length === 0\n ? null\n : {\n from: new Date(Math.min(...times)).toISOString(),\n to: new Date(Math.max(...times)).toISOString(),\n },\n },\n }\n}\n\nfunction verdict(holds: boolean, reason: string): TeamShapeCheck {\n return { result: holds ? 'yes' : 'no', reason }\n}\n\nfunction crosses(a: string | null, b: string | null): boolean {\n return a !== null && b !== null && a !== b\n}\n\nfunction pathParent(id: string): string | null {\n const match = /^(.+):s\\d+$/.exec(id)\n return match ? match[1]! : null\n}\n\nfunction addEdge(edges: Map<string, TeamShapeEdge>, from: string, to: string): void {\n const key = JSON.stringify([from, to])\n const edge = edges.get(key)\n if (edge) edge.count += 1\n else edges.set(key, { from, to, count: 1 })\n}\n\nfunction jsonLines(text: string): Array<Record<string, unknown> | null> {\n return text\n .split('\\n')\n .filter((line) => line.trim())\n .map((line) => {\n try {\n const value: unknown = JSON.parse(line)\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null\n } catch {\n return null\n }\n })\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null\n}\n\nfunction epochMs(value: unknown): number | null {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string') {\n const ms = Date.parse(value)\n return Number.isNaN(ms) ? null : ms\n }\n return null\n}\n\n/**\n * Spawned and settled rows from a Runtime envelope (`{ root, event }`) or a\n * reduced row (`{ kind, journal, id, at }`). Other Runtime event kinds are\n * read and skipped; a spawned or settled row without an id, journal or time\n * is invalid.\n */\nfunction parseSpawnRows(text: string): { rows: SpawnRow[]; invalid: number } {\n const rows: SpawnRow[] = []\n let invalid = 0\n for (const line of jsonLines(text)) {\n if (line === null) {\n invalid += 1\n continue\n }\n const event = asRecord(line.event) ?? line\n const journal = event === line ? line.journal : line.root\n const { kind, id } = event\n if (kind !== 'spawned' && kind !== 'settled') continue\n const at = epochMs(event.at)\n if (typeof id !== 'string' || typeof journal !== 'string' || at === null) {\n invalid += 1\n continue\n }\n rows.push({ kind, journal, owner: journal.slice(journal.lastIndexOf('/') + 1), id, at })\n }\n return { rows, invalid }\n}\n\n/**\n * Coordination rows from a Runtime record (`{ at, ownerId, event: { type,\n * <body> } }`, endpoints inside the event's one object-valued field) or a\n * reduced row (`{ at, type, owner, ... }`).\n */\nfunction parseCoordinationRows(text: string): { rows: CoordinationRow[]; invalid: number } {\n const rows: CoordinationRow[] = []\n let invalid = 0\n for (const line of jsonLines(text)) {\n const event = line === null ? null : (asRecord(line.event) ?? line)\n if (line === null || event === null || typeof event.type !== 'string') {\n invalid += 1\n continue\n }\n const body =\n event === line\n ? line\n : (Object.entries(event)\n .filter(([key]) => key !== 'type')\n .map(([, value]) => asRecord(value))\n .find((value) => value !== null) ?? {})\n const owner = typeof line.owner === 'string' ? line.owner : line.ownerId\n const row: CoordinationRow = {\n at: epochMs(line.at),\n type: event.type,\n owner: typeof owner === 'string' && owner ? owner : null,\n }\n for (const key of ['toWorker', 'from', 'by'] as const) {\n const value = body[key]\n if (typeof value === 'string') row[key] = value\n }\n const delivered = body.delivered ?? line.delivered\n if (typeof delivered === 'boolean') row.delivered = delivered\n rows.push(row)\n }\n return { rows, invalid }\n}\n\n/**\n * The team-shape analyst: one `team`-layer finding per run naming its class,\n * with the features and every class check in metadata. A record with no\n * timestamps fails the analyst instead of emitting a shape it did not measure.\n */\nexport function teamShapeAnalyst(): Analyst<TeamShapeInput> {\n return {\n id: TEAM_SHAPE_ANALYST_ID,\n description:\n 'Classifies a supervision tree as single, governed swarm, fleet, partition, hive, star with sub-leads or flat star.',\n inputKind: 'custom',\n cost: { kind: 'deterministic' },\n version: TEAM_SHAPE_VERSION,\n async analyze(input) {\n const outcome = classifyTeamShape(input)\n if (!outcome.succeeded) throw new Error(`team-shape: ${outcome.error.message}`)\n const shape = outcome.value\n if (shape.window === null) {\n throw new Error(`team-shape: record for ${input.runRef} carries no event timestamps`)\n }\n return [\n makeFinding({\n analyst_id: TEAM_SHAPE_ANALYST_ID,\n area: 'team-shape',\n severity: 'info',\n confidence: 1,\n subject: shape.rootId,\n claim: `Team shape is ${shape.label}`,\n claim_id: `team-shape:${shape.class}`,\n evidence_refs: [{ kind: 'artifact', uri: input.runRef }],\n layer: 'team',\n scope: { population: [input.runRef], n: 1, window: shape.window },\n method: { kind: 'computed', name: TEAM_SHAPE_ANALYST_ID, version: TEAM_SHAPE_VERSION },\n metadata: {\n class: shape.class,\n depth: shape.depth,\n qualifier: shape.qualifier,\n features: shape.features,\n checks: shape.checks,\n edges: {\n command: shape.graph.command.length,\n governance: shape.graph.governance.length,\n communication: shape.graph.communication.length,\n },\n invalid_rows: shape.invalidRows,\n },\n }),\n ]\n },\n }\n}\n","/**\n * Many questions over one trace store, concurrently, under one cost ledger, with an independent\n * verifier for every finding.\n *\n * `traces ask` answered questions this way for people. A continuation panel (agent-runtime,\n * discovery `docs/38-one-loop-and-continuation.md`, section 5) asks dozens to hundreds of atomic\n * questions of a director's own trace every time the outside check fails, so the runner lives here,\n * beside `runTraceAnalyst`, where both callers reach one implementation.\n *\n * Each question is one `runTraceAnalyst` call, which already refuses a finding with fewer distinct\n * citations than required or with a citation the store cannot resolve. What this module adds:\n *\n * - a worker pool: at most `concurrency` investigations at once, and one failed question never\n * stops the others; its failure is its answer;\n * - one shared `CostLedger`, so a single ceiling bounds every question and every verifier;\n * - an independent verifier per admitted finding, shown only the spans the finding cites. Analysts\n * misattribute often: the best method in Who&When found the failing step 14.2% of the time. A\n * finding a verifier reading only its own evidence does not support never reaches a caller as\n * verified.\n */\n\nimport type { CostLedgerHandle } from '../cost-ledger'\nimport type { TraceAnalysisStore } from '../trace-analyst/store'\nimport { defineTraceAnalyst } from './define'\nimport type { TraceAnalysisEngine, TraceAnalystLimits } from './engine'\nimport { parseTraceSpanEvidenceUri, type RawAnalystFinding } from './finding-signature'\nimport { runTraceAnalyst } from './kind-factory'\n\n/** One question to ask of the store. */\nexport interface TraceQuestionSpec {\n /** Stable id: letters, digits, dot, underscore, hyphen. */\n readonly id: string\n readonly question: string\n /** Guidance for this question only, after the shared rules. */\n readonly instructions?: string\n}\n\nexport interface AskTraceQuestionsOptions {\n readonly questions: readonly TraceQuestionSpec[]\n readonly store: TraceAnalysisStore\n readonly engine: TraceAnalysisEngine\n /** Every question and verifier charges this ledger; its ceiling bounds the whole call. */\n readonly costLedger: CostLedgerHandle\n /** Stable id for cost attribution and logs. */\n readonly runId: string\n /** Material every question receives before its first model call, such as the check's verdict. */\n readonly context?: string\n /** Investigations running at once. Default 4. */\n readonly concurrency?: number\n /** Distinct citations a finding needs. Default 2. */\n readonly minimumEvidenceCitations?: number\n /** Run the independent verifier on every admitted finding. Default true. */\n readonly verify?: boolean\n readonly limits?: Partial<TraceAnalystLimits>\n readonly signal?: AbortSignal\n readonly log?: (message: string, fields?: Record<string, unknown>) => void\n}\n\n/** A finding and what the verifier, shown only its cited spans, concluded. */\nexport interface VerifiedTraceFinding {\n readonly finding: RawAnalystFinding\n /** The finding's trace citations, as `trace://` URIs. */\n readonly citations: readonly string[]\n /** `true` supported, `false` not supported, `null` when verification was off or failed. */\n readonly verified: boolean | null\n /** The verifier's own words, when it answered. */\n readonly verifierAnswer?: string\n}\n\nexport interface TraceQuestionOutcome {\n readonly id: string\n readonly question: string\n readonly status: 'answered' | 'failed'\n readonly failure?: string\n /** The engine's prose answer, verbatim; `null` when it returned none. */\n readonly answer: string | null\n readonly findings: readonly VerifiedTraceFinding[]\n /** `null` when the engine failed before reporting. */\n readonly modelCalls: number | null\n readonly toolCalls: number | null\n}\n\nconst QUESTION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u\nconst DEFINITION_VERSION = '1.0.0'\n\nconst QUESTION_RULES = [\n 'Answer QUESTION only from trace tool results retrieved in this run.',\n 'Cite each fact as trace://<trace_id>/span/<span_id>, and quote the span in the excerpt.',\n 'If the trace does not record a fact, say \"not in trace\". Never infer a trace fact from the question.',\n].join('\\n')\n\nconst VERIFIER_RULES = [\n 'You check one CLAIM against the spans it cites, and nothing else.',\n 'Read each cited span with viewSpans. No other trace is readable.',\n 'First line: SUPPORTED if the spans themselves establish the claim, otherwise NOT SUPPORTED.',\n 'Second line: one sentence naming the span that decides it.',\n 'Return no findings.',\n].join('\\n')\n\n/**\n * Ask every question, then verify every admitted finding. Never throws for a failed question or\n * verifier: each failure is recorded on its outcome. Throws before any model call for a malformed\n * question list or options.\n */\nexport async function askTraceQuestions(\n opts: AskTraceQuestionsOptions,\n): Promise<TraceQuestionOutcome[]> {\n const concurrency = opts.concurrency ?? 4\n if (!Number.isSafeInteger(concurrency) || concurrency < 1) {\n throw new RangeError('askTraceQuestions: concurrency must be an integer >= 1')\n }\n const minimum = opts.minimumEvidenceCitations ?? 2\n if (!Number.isSafeInteger(minimum) || minimum < 1) {\n throw new RangeError('askTraceQuestions: minimumEvidenceCitations must be an integer >= 1')\n }\n const seen = new Set<string>()\n for (const question of opts.questions) {\n if (!QUESTION_ID.test(question.id)) {\n throw new TypeError(\n `askTraceQuestions: question id ${JSON.stringify(question.id)} is malformed`,\n )\n }\n if (seen.has(question.id)) {\n throw new TypeError(`askTraceQuestions: duplicate question id ${JSON.stringify(question.id)}`)\n }\n seen.add(question.id)\n if (question.question.trim() === '') {\n throw new TypeError(`askTraceQuestions: question ${question.id} is empty`)\n }\n }\n\n const askOne = async (question: TraceQuestionSpec): Promise<TraceQuestionOutcome> => {\n if (opts.signal?.aborted) {\n return failed(question, 'the run was aborted before the question started')\n }\n let completed: Awaited<ReturnType<typeof runTraceAnalyst>>\n try {\n completed = await runTraceAnalyst({\n definition: defineTraceAnalyst({\n id: `question.${question.id}`,\n description: `trace question ${question.id}`,\n area: 'question',\n version: DEFINITION_VERSION,\n question: question.question.trim(),\n instructions: [QUESTION_RULES, question.instructions?.trim() ?? '']\n .filter(Boolean)\n .join('\\n\\n'),\n toolGroup: 'all',\n minimumEvidenceCitations: minimum,\n ...(opts.context ? { prepareContext: () => opts.context } : {}),\n ...(opts.limits ? { limits: opts.limits } : {}),\n }),\n engine: opts.engine,\n store: opts.store,\n context: {\n runId: opts.runId,\n correlationId: `${opts.runId}:${question.id}`,\n costLedger: opts.costLedger,\n costPhase: 'trace-question',\n ...(opts.signal ? { signal: opts.signal } : {}),\n ...(opts.log ? { log: opts.log } : {}),\n },\n })\n } catch (error) {\n return failed(question, errorText(error))\n }\n const findings: VerifiedTraceFinding[] = []\n for (const [index, finding] of completed.findings.entries()) {\n const citations = finding.evidence\n .map((citation) => citation.uri.trim())\n .filter((uri) => parseTraceSpanEvidenceUri(uri) !== null)\n findings.push(\n opts.verify === false\n ? { finding, citations, verified: null }\n : await verifyFinding(opts, `${question.id}.v${index + 1}`, finding, citations),\n )\n }\n const answer = completed.answer.trim() === '' ? null : completed.answer\n return {\n id: question.id,\n question: question.question,\n status: 'answered',\n answer,\n findings,\n modelCalls: completed.modelCalls,\n toolCalls: completed.toolCalls,\n }\n }\n\n // A pool, not Promise.all: at most `concurrency` engines exist at once.\n const outcomes = new Array<TraceQuestionOutcome>(opts.questions.length)\n let next = 0\n await Promise.all(\n Array.from({ length: Math.min(concurrency, opts.questions.length) }, async () => {\n while (next < opts.questions.length) {\n const index = next\n next += 1\n const question = opts.questions[index] as TraceQuestionSpec\n outcomes[index] = await askOne(question)\n }\n }),\n )\n return outcomes\n}\n\n/** The verifier reads only the spans the finding cites, through a store that holds nothing else. */\nasync function verifyFinding(\n opts: AskTraceQuestionsOptions,\n id: string,\n finding: RawAnalystFinding,\n citations: readonly string[],\n): Promise<VerifiedTraceFinding> {\n const allowed = new Map<string, Set<string>>()\n for (const uri of citations) {\n const location = parseTraceSpanEvidenceUri(uri)\n if (location === null) continue\n const spans = allowed.get(location.traceId) ?? new Set<string>()\n spans.add(location.spanId)\n allowed.set(location.traceId, spans)\n }\n if (allowed.size === 0) return { finding, citations, verified: false }\n try {\n const verdict = await runTraceAnalyst({\n definition: defineTraceAnalyst({\n id: `verify.${id}`,\n description: `independent check of finding ${id}`,\n area: 'question',\n version: DEFINITION_VERSION,\n question: `CLAIM: ${finding.claim}\\nCITED SPANS: ${citations.join(', ')}`,\n instructions: VERIFIER_RULES,\n toolGroup: 'targeted',\n ...(opts.limits ? { limits: opts.limits } : {}),\n }),\n engine: opts.engine,\n store: citedSpansOnly(opts.store, allowed),\n context: {\n runId: opts.runId,\n correlationId: `${opts.runId}:verify:${id}`,\n costLedger: opts.costLedger,\n costPhase: 'trace-question-verifier',\n ...(opts.signal ? { signal: opts.signal } : {}),\n ...(opts.log ? { log: opts.log } : {}),\n },\n })\n const first = verdict.answer.trim().split('\\n')[0]?.trim().toUpperCase() ?? ''\n return {\n finding,\n citations,\n verified: first.startsWith('SUPPORTED'),\n verifierAnswer: verdict.answer.trim(),\n }\n } catch (error) {\n opts.log?.('verifier failed', { finding: id, error: errorText(error) })\n return { finding, citations, verified: null }\n }\n}\n\n/**\n * A store that exposes exactly the cited spans. Discovery and whole-trace reads refuse, so the\n * verifier cannot go looking for other support; the underlying store's bounds still apply.\n */\nfunction citedSpansOnly(\n store: TraceAnalysisStore,\n allowed: ReadonlyMap<string, ReadonlySet<string>>,\n): TraceAnalysisStore {\n const refuse = (what: string) => async (): Promise<never> => {\n throw new Error(`${what} is not available to a verifier: read the cited spans with viewSpans`)\n }\n return {\n hasTrace: async (traceId) => allowed.has(traceId),\n hasSpans: async (input, context) => {\n const spans = allowed.get(input.trace_id)\n if (spans === undefined) return []\n return store.hasSpans(\n { trace_id: input.trace_id, span_ids: input.span_ids.filter((span) => spans.has(span)) },\n context,\n )\n },\n getOverview: refuse('getOverview'),\n queryTraces: refuse('queryTraces'),\n countTraces: refuse('countTraces'),\n viewTrace: refuse('viewTrace'),\n viewSpans: async (input, context) => {\n const spans = allowed.get(input.trace_id)\n const wanted = input.span_ids.filter((span) => spans?.has(span) === true)\n if (wanted.length === 0) {\n throw new Error('viewSpans: only the cited spans are readable')\n }\n return store.viewSpans({ ...input, span_ids: wanted }, context)\n },\n searchTrace: refuse('searchTrace'),\n searchSpan: async (input, context) => {\n if (allowed.get(input.trace_id)?.has(input.span_id) !== true) {\n throw new Error('searchSpan: only the cited spans are readable')\n }\n return store.searchSpan(input, context)\n },\n }\n}\n\nfunction failed(question: TraceQuestionSpec, failure: string): TraceQuestionOutcome {\n return {\n id: question.id,\n question: question.question,\n status: 'failed',\n failure,\n answer: null,\n findings: [],\n modelCalls: null,\n toolCalls: null,\n }\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? `${error.name}: ${error.message}` : String(error)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA4FA,MAAMA,aAAW,EAAE,OAAO,CAAC,CAAC,OAAO,qBAAqB;AACxD,MAAM,aAAa,EAAE,KACnB,OAAO,KAAK,0BAA0B,CAIxC;AACA,MAAM,SAAS,EAAE,KAAK;CAAC;CAAO;CAAM;AA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,UAAU;IAAE,GAAG;IAAO,UAAU;GAAO,GAAG,OAAO;EAChE;EACA,aAAa,OAAO,aAAa;EACjC,YAAY,OAAO,OAAO,YAAY;GACpC,IAAI,QAAQ,IAAI,MAAM,QAAQ,CAAC,EAAE,IAAI,MAAM,OAAO,MAAM,MACtD,MAAM,IAAI,MAAM,+CAA+C;GAEjE,OAAO,MAAM,WAAW,OAAO,OAAO;EACxC;CACF;AACF;AAEA,SAAS,OAAO,UAA6B,SAAuC;CAClF,OAAO;EACL,IAAI,SAAS;EACb,UAAU,SAAS;EACnB,QAAQ;EACR;EACA,QAAQ;EACR,UAAU,CAAC;EACX,YAAY;EACZ,WAAW;CACb;AACF;AAEA,SAAS,UAAU,OAAwB;CACzC,OAAO,iBAAiB,QAAQ,GAAG,MAAM,KAAK,IAAI,MAAM,YAAY,OAAO,KAAK;AAClF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["identity"],"sources":["../../src/analyst/benchmark-behavioral-calibration.ts","../../src/analyst/bind.ts","../../src/analyst/define.ts","../../src/analyst/domain-taxonomy.ts","../../src/analyst/failure-modes.ts","../../src/analyst/findings-ledger.ts","../../src/analyst/kinds/skill-usage.ts","../../src/analyst/promote.ts","../../src/analyst/rollup.ts","../../src/analyst/team-shape.ts","../../src/analyst/trace-questions.ts"],"sourcesContent":["import { z } from 'zod'\nimport { DECISION_POINT_AUC_BAR, DECISION_POINT_MIN_KAPPA } from '../decision-point'\nimport { validDecisionIdentity } from '../decision-point-records'\nimport { type NominalAgreementOptions, nominalAgreement } from '../statistics/agreement-irr'\nimport { rocAuc } from '../statistics/comparison-effects'\nimport { type BootstrapInterval, clusterBootstrap } from '../statistics/internal'\nimport {\n BEHAVIORAL_TRACE_QUESTIONS,\n type BehavioralQuestionCalibration,\n type BehavioralTraceAnswer,\n type BehavioralTraceLayer,\n type BehavioralTraceQuestionId,\n type BehavioralTraceSupport,\n type BehavioralWindowPolicy,\n behavioralTraceQuestionDigest,\n} from './behavioral-trace-questions'\nimport { behavioralTraceSupportSchema } from './behavioral-trace-support'\nimport { validBehavioralCalibration } from './behavioral-trace-validation'\nimport type { ExactExecutionComponentIdentity } from './exact-types'\nimport type { CalibrationInterval } from './finding-scope'\nimport type { AnalystFinding, EvidenceRef } from './types'\n\n/** Independently acquired labels. Null and unsure are exclusions, never negative labels. */\nexport interface BehavioralTraceGold {\n questionId: BehavioralTraceQuestionId\n windowId: string\n label: BehavioralTraceAnswer | null\n source: 'human' | 'agentrx'\n}\n/** One-vs-rest reading of a class: precision and recall from hard answers; the AUC of its probability\n * (null without a scored member of each class) with a seeded cluster bootstrap; the AUC bar line. */\nexport interface ClassCalibration {\n precision: number | null\n recall: number | null\n auc: number | null\n ci: CalibrationInterval | null\n eligibleAuc: boolean\n}\nexport interface BehavioralTraceCalibrationRow extends ClassCalibration {\n questionId: BehavioralTraceQuestionId\n layer: BehavioralTraceLayer\n method: 'computed' | 'judged'\n gold_n: number\n missingLabels: number\n unsureLabels: number\n missingPredictions: number\n abstentions: number\n sourceCounts: { human: number; agentrx: number }\n agreement: number | null\n kappa: number | null\n kappaCi: BootstrapInterval | null\n confusion: Record<'yes' | 'no', Record<'yes' | 'no' | 'unsure' | 'missing', number>>\n /** Wrong/unsure/missing semantic answers retain the selected event and complete scoped map.\n * Cross-map nominal agreement is separate from exact-definition decision reliability. */\n disagreements: Array<{\n windowId: string\n expected: 'yes' | 'no'\n predicted: BehavioralTraceAnswer | null\n support: BehavioralTraceSupport | null\n }>\n eligible: boolean\n /** Finite measured evidence, even if it misses the activation bar. */\n calibration: BehavioralQuestionCalibration | null\n}\nexport interface ChoiceGold {\n id: string\n label: string | null\n}\nexport interface ChoicePrediction {\n id: string\n cluster?: string\n choice: string | null\n probabilities: Record<string, number> | null\n}\n/** `gold_n` is the gold items labeled with this option, `predicted` the labeled items that chose it. */\nexport interface ChoiceOptionCalibration extends ClassCalibration {\n option: string\n gold_n: number\n predicted: number\n}\nexport interface ChoiceCalibration {\n options: string[]\n gold_n: number\n missingLabels: number\n missingPredictions: number\n abstentions: number\n agreement: number | null\n /** Multi-class Cohen's κ over the hard choices, with its cluster bootstrap. */\n kappa: number | null\n kappaCi: BootstrapInterval | null\n rows: ChoiceOptionCalibration[]\n}\nconst identity = z.string().refine(validDecisionIdentity)\nconst questionId = z.enum(\n Object.keys(BEHAVIORAL_TRACE_QUESTIONS) as [\n BehavioralTraceQuestionId,\n ...BehavioralTraceQuestionId[],\n ],\n)\nconst answer = z.enum(['yes', 'no', 'unsure'])\nconst goldSchema = z\n .object({\n questionId,\n windowId: identity,\n label: answer.nullable(),\n source: z.enum(['human', 'agentrx']),\n })\n .strict()\nconst predictionSchema = z\n .object({\n questionId,\n windowId: identity,\n traceId: identity.optional(),\n answer: answer.nullable(),\n probabilities: z.record(z.string(), z.number().finite()).nullable().optional(),\n questionDigest: z.string().nullable(),\n requestedModel: identity.nullable(),\n servedModel: identity.nullable(),\n support: behavioralTraceSupportSchema.optional(),\n })\n .passthrough()\nconst finite = (value: number) => (Number.isFinite(value) ? value : null)\nconst { auc: minAuc, ciLow, gold_n: minGold } = DECISION_POINT_AUC_BAR\n\n/** Same nominalAgreement owner as the existing AgentRx/failure-mode calibration path. */\nexport function calibrateBehavioralTraceQuestions(input: {\n layer: BehavioralTraceLayer\n windowPolicy: BehavioralWindowPolicy\n model: string\n servedModel: string\n evaluatorIdentity: ExactExecutionComponentIdentity\n gold: readonly BehavioralTraceGold[]\n findings: readonly AnalystFinding[]\n evidenceRefs: EvidenceRef[]\n resamples?: number\n seed?: number\n}): BehavioralTraceCalibrationRow[] {\n const predictions = new Map<string, z.infer<typeof predictionSchema> & { cluster: string }>()\n const gold = input.gold.map((row) => goldSchema.parse(row))\n const seen = new Set<string>()\n for (const row of gold) {\n const key = JSON.stringify([row.questionId, row.windowId])\n if (seen.has(key)) throw new TypeError('Duplicate behavioral gold label')\n seen.add(key)\n }\n for (const finding of input.findings) {\n if (finding.area !== 'behavioral-trace-question' || finding.layer !== input.layer) continue\n const row = predictionSchema.parse(finding.metadata?.behavioral_trace_question)\n if (\n row.support &&\n (row.support.map.windowId !== row.windowId ||\n row.support.method !== (row.questionId === 'identical-tool-repeat' ? 'computed' : 'judged'))\n )\n throw new TypeError('Behavioral support does not match its prediction')\n const key = JSON.stringify([row.questionId, row.windowId])\n if (predictions.has(key)) throw new TypeError('Duplicate behavioral prediction')\n // Windows of one agent are resampled together; a finding without a subject clusters by trace.\n predictions.set(key, { ...row, cluster: finding.subject ?? row.traceId ?? row.windowId })\n }\n const bootstrap = { resamples: input.resamples, seed: input.seed, options: ['yes', 'no'] }\n return (Object.keys(BEHAVIORAL_TRACE_QUESTIONS) as BehavioralTraceQuestionId[]).map((id) => {\n const computed = id === 'identical-tool-repeat'\n const digest = behavioralTraceQuestionDigest({\n questionId: id,\n ...input,\n servedModel: computed ? null : input.servedModel,\n })\n const counts = { missingLabels: 0, unsureLabels: 0, sourceCounts: { human: 0, agentrx: 0 } }\n const confusion = {\n yes: { yes: 0, no: 0, unsure: 0, missing: 0 },\n no: { yes: 0, no: 0, unsure: 0, missing: 0 },\n }\n const disagreements: BehavioralTraceCalibrationRow['disagreements'] = []\n const labels: ChoiceGold[] = []\n const answers: ChoicePrediction[] = []\n for (const item of gold.filter((item) => item.questionId === id)) {\n if (item.label === null) {\n counts.missingLabels++\n continue\n }\n if (item.label === 'unsure') {\n counts.unsureLabels++\n continue\n }\n counts.sourceCounts[item.source]++\n const prediction = predictions.get(JSON.stringify([id, item.windowId]))\n const matches =\n prediction?.questionDigest === digest &&\n prediction.requestedModel === (computed ? null : input.model) &&\n prediction.servedModel === (computed ? null : input.servedModel)\n const value = matches ? prediction.answer : null\n confusion[item.label][value ?? 'missing']++\n if (value !== item.label) {\n const support = matches ? (prediction.support ?? null) : null\n if (support && support.map.windowId !== item.windowId)\n throw new TypeError('Behavioral support map is outside the prediction window')\n disagreements.push({\n windowId: item.windowId,\n expected: item.label,\n predicted: value,\n support: support ? structuredClone(support) : null,\n })\n }\n // Missing predictions remain disagreements in the denominator.\n labels.push({ id: item.windowId, label: item.label })\n if (matches)\n answers.push({\n id: item.windowId,\n cluster: prediction.cluster,\n choice: prediction.answer,\n probabilities: prediction.probabilities ?? null,\n })\n }\n const result = calibrateChoiceQuestion(labels, answers, bootstrap)\n const { option: _option, gold_n: positives, predicted: _predicted, ...yes } = result.rows[0]!\n const bothClasses = positives > 0 && positives < result.gold_n\n // A one-class sample or a missing prediction must never supply a certificate that can authorize actions.\n const certified = bothClasses && result.missingPredictions === 0 && result.kappa !== null\n const row: BehavioralTraceCalibrationRow = {\n questionId: id,\n layer: input.layer,\n method: computed ? 'computed' : 'judged',\n ...counts,\n gold_n: result.gold_n,\n missingPredictions: result.missingPredictions,\n abstentions: result.abstentions,\n agreement: result.agreement,\n kappa: result.kappa,\n kappaCi: result.kappaCi,\n ...yes,\n ci: yes.ci && { ...yes.ci, cluster: 'subject' },\n confusion,\n disagreements,\n eligible: certified && result.kappa! >= DECISION_POINT_MIN_KAPPA,\n calibration: null,\n }\n if (certified) {\n row.calibration = {\n gold_n: row.gold_n,\n agreement: row.agreement!,\n kappa: row.kappa!,\n auc: row.auc,\n ci: row.ci,\n questionDigest: digest,\n servedModel: computed ? null : input.servedModel,\n evidenceRefs: structuredClone(input.evidenceRefs),\n }\n validBehavioralCalibration(row.calibration)\n }\n return row\n })\n}\n\n/** A Choice question over any option set: a one-vs-rest row per option plus the multi-class κ. A null\n * or out-of-set gold label is an exclusion; an out-of-set choice an abstention, a null choice missing. */\nexport function calibrateChoiceQuestion(\n gold: readonly ChoiceGold[],\n findings: readonly ChoicePrediction[],\n options: NominalAgreementOptions & { options?: readonly string[] } = {},\n): ChoiceCalibration {\n const predictions = new Map(findings.map((finding) => [finding.id, finding]))\n if (predictions.size !== findings.length) throw new TypeError('Duplicate choice prediction')\n const names = [\n ...(options.options ?? new Set(findings.flatMap((f) => Object.keys(f.probabilities ?? {})))),\n ]\n const labeled = gold.filter((item) => item.label !== null && names.includes(item.label))\n if (new Set(labeled.map((item) => item.id)).size !== labeled.length)\n throw new TypeError('Duplicate choice gold label')\n const joined = labeled.map((item) => ({ ...item, prediction: predictions.get(item.id) }))\n const cluster = (item: (typeof joined)[number]) => item.prediction?.cluster ?? item.id\n const agreement = nominalAgreement(\n joined.map((item) => [item.label!, item.prediction?.choice ?? '(missing prediction)'] as const),\n { ...options, clusters: joined.map(cluster) },\n )\n return {\n options: names,\n gold_n: agreement.n,\n missingLabels: gold.length - labeled.length,\n missingPredictions: joined.filter((item) => item.prediction?.choice == null).length,\n abstentions: joined.filter(\n (item) => item.prediction?.choice != null && !names.includes(item.prediction.choice),\n ).length,\n agreement: finite(agreement.agreement),\n kappa: finite(agreement.kappa),\n kappaCi: Number.isFinite(agreement.kappaCi.low) ? agreement.kappaCi : null,\n rows: names.map((option) => {\n const items = joined.map((item) => ({\n cluster: cluster(item),\n gold: item.label === option,\n chosen: item.prediction?.choice === option,\n score: item.prediction?.probabilities?.[option] ?? null,\n }))\n const chosen = items.filter((item) => item.chosen)\n const hits = chosen.filter((item) => item.gold).length\n const gold_n = items.filter((item) => item.gold).length\n // Precision and recall read every labeled item; the AUC and its interval read scored items only.\n const scored = items.filter((item) => item.score !== null)\n const area = (sample: typeof items) =>\n rocAuc(\n sample.map((i) => i.score!),\n sample.map((i) => Number(i.gold)),\n ) ?? Number.NaN\n const auc = finite(scored.length ? area(scored) : Number.NaN)\n const boot = auc !== null && clusterBootstrap(scored, (i) => i.cluster, area, options)\n const ci = boot && Number.isFinite(boot.low) ? { ...boot, cluster: 'cluster' } : null\n return {\n option,\n gold_n,\n predicted: chosen.length,\n precision: chosen.length ? hits / chosen.length : null,\n recall: gold_n ? hits / gold_n : null,\n auc,\n ci,\n eligibleAuc: ci !== null && auc! >= minAuc && ci.low >= ciLow && gold_n >= minGold,\n }\n }),\n }\n}\n","/**\n * bindAnalyst — compile an `AnalystDefinition` into a runnable arm.\n *\n * The definition declares protocol (question, task text, reply grammar,\n * evidence projection, budget, repair turns); the transport binding supplies\n * execution (a bridge endpoint, or the caller-owned model path). Each\n * projection mode dispatches to the same strategy its arm's entry point runs,\n * so a compiled definition and the historical creator send byte-identical\n * requests — the definition parity suite asserts this per arm.\n *\n * A projection × transport pair with no strategy fails loud with\n * `AnalystExpressivenessError` naming the pair: an arm shape this layer cannot\n * express must be reported, never approximated.\n */\n\nimport type { CustomTokenPricing } from '../cost-ledger'\nimport type { AnalystBenchmarkRunner } from './benchmark'\nimport { runChunkedAnalystDefinition } from './benchmark-public-chunked'\nimport { runReplVariableAnalystDefinition } from './benchmark-public-rlm'\nimport type { PublicAnalystBenchmarkModelConfig } from './benchmark-public-types'\nimport { runInlineAnalystDefinition } from './benchmark-runner-prime'\nimport { type AnalystDefinition, AnalystExpressivenessError } from './definition'\nimport type { PrimeBridgeTransport } from './prime-bridge-transport'\nimport type { AnalystRunInputs } from './types'\n\n/** Execution half of a binding: who actually reaches the model. */\nexport type AnalystTransportBinding =\n | {\n /** An OpenAI-compatible cli-bridge endpoint (inline projections). */\n readonly kind: 'prime-bridge'\n readonly baseUrl: string\n readonly model: string\n readonly transport?: PrimeBridgeTransport\n readonly pricing?: CustomTokenPricing\n }\n | {\n /** The caller-owned model path (chunked and repl-variable projections). */\n readonly kind: 'model-owner'\n readonly config: PublicAnalystBenchmarkModelConfig\n }\n\n/**\n * Compile a definition plus a transport binding into a runnable arm. Dispatch\n * is total over the expressible pairs; everything else is a loud refusal.\n */\nexport function bindAnalyst<TRow, TAssignment, TBlock>(\n definition: AnalystDefinition<TRow, TAssignment, TBlock>,\n transports: AnalystTransportBinding,\n): AnalystBenchmarkRunner<AnalystRunInputs> {\n const mode = definition.projection.mode\n if (mode === 'inline' && transports.kind === 'prime-bridge') {\n return runInlineAnalystDefinition(definition, {\n baseUrl: transports.baseUrl,\n model: transports.model,\n ...(transports.transport ? { transport: transports.transport } : {}),\n ...(transports.pricing ? { pricing: transports.pricing } : {}),\n })\n }\n if (mode === 'chunked' && transports.kind === 'model-owner') {\n return runChunkedAnalystDefinition(definition, transports.config)\n }\n if (mode === 'repl-variable' && transports.kind === 'model-owner') {\n return runReplVariableAnalystDefinition(\n // The repl-variable strategy is written against the engine's raw-finding\n // row type; the definition's own row declaration carries it.\n definition as Parameters<typeof runReplVariableAnalystDefinition>[0],\n transports.config,\n )\n }\n throw new AnalystExpressivenessError(\n `no strategy compiles a '${mode}' projection over a '${transports.kind}' transport; ` +\n `definition '${definition.id}' cannot be expressed by this layer yet`,\n )\n}\n","import type { TraceAnalysisStore } from '../trace-analyst/store'\nimport type { ExactCapableAnalyst } from './exact-types'\nimport type { TraceAnalystDefinition } from './kind-factory'\nimport type { Analyst, AnalystCost } from './types'\n\n/**\n * Define a reusable trace-research question.\n *\n * The returned value contains no model, credentials, or execution state. Bind\n * it to any TraceAnalysisEngine with `runTraceAnalyst` or\n * `createTraceAnalyst`.\n */\nexport function defineTraceAnalyst(definition: TraceAnalystDefinition): TraceAnalystDefinition {\n for (const [name, value] of [\n ['id', definition.id],\n ['description', definition.description],\n ['area', definition.area],\n ['version', definition.version],\n ['instructions', definition.instructions],\n ] as const) {\n if (typeof value !== 'string' || !value.trim()) {\n throw new TypeError(`defineTraceAnalyst: ${name} must be a non-empty string`)\n }\n }\n return {\n ...definition,\n limits: definition.limits ? { ...definition.limits } : undefined,\n }\n}\n\nexport interface DefineCustomAnalystOptions {\n id: string\n description: string\n version?: string\n cost: AnalystCost\n analyze: Analyst<TraceAnalysisStore>['analyze']\n}\n\nexport interface DefineExactCustomAnalystOptions extends DefineCustomAnalystOptions {\n /** Canonical JSON for behavior knobs not already bound by `version`. */\n executionConfig: Readonly<Record<string, unknown>>\n}\n\n/** Construct a registrable analyst from a hand-written analyze function. */\nexport function defineCustomAnalyst(\n options: DefineExactCustomAnalystOptions,\n): ExactCapableAnalyst<TraceAnalysisStore>\nexport function defineCustomAnalyst(\n options: DefineCustomAnalystOptions,\n): Analyst<TraceAnalysisStore>\nexport function defineCustomAnalyst(\n options: DefineCustomAnalystOptions | DefineExactCustomAnalystOptions,\n): Analyst<TraceAnalysisStore> | ExactCapableAnalyst<TraceAnalysisStore> {\n if (!options.id.trim()) throw new TypeError('defineCustomAnalyst: id must not be empty')\n if (!options.description.trim()) {\n throw new TypeError('defineCustomAnalyst: description must not be empty')\n }\n if (options.cost === undefined) {\n throw new TypeError('defineCustomAnalyst: cost must be declared')\n }\n if (\n 'executionConfig' in options &&\n (!options.executionConfig ||\n typeof options.executionConfig !== 'object' ||\n Array.isArray(options.executionConfig))\n ) {\n throw new TypeError('defineCustomAnalyst: executionConfig must be an object')\n }\n return {\n id: options.id,\n description: options.description,\n version: options.version ?? '1.0.0',\n inputKind: 'trace-store',\n cost: options.cost,\n analyze: options.analyze,\n ...('executionConfig' in options ? { executionConfig: options.executionConfig } : {}),\n }\n}\n","/**\n * Domain taxonomy — one versioned tree that both the layer ladder and the\n * domain hierarchy live in.\n *\n * Domain nodes nest to any depth (\"building systems\" → \"cryptographic\" →\n * \"zk proving\" → \"binary fields\"). Problems attach to one primary domain path\n * plus free tags, plays attach to a problem, and runs attach to a play. Every\n * node hangs under the implicit `lab` root, so one parent map answers both\n * \"which play holds this run\" and \"which domain holds this problem\", and\n * `promote` walks a single ladder: run → play → problem → domain path → lab.\n *\n * Plain data in, plain data out: every function returns a new value or a\n * typed failure, and nothing here reads a file or the network.\n */\n\nconst DOMAIN_TAXONOMY_SCHEMA = 'agent-eval.domain-taxonomy.v1'\n\n/** Id of the implicit root every top-level domain hangs under. */\nexport const LAB_NODE_ID = 'lab'\n\n/** Layers a taxonomy node can sit at, lowest first. */\nconst TAXONOMY_NODE_LAYERS = ['run', 'play', 'problem', 'domain'] as const\n\nexport type TaxonomyNodeLayer = (typeof TAXONOMY_NODE_LAYERS)[number]\n\nexport interface TaxonomyNode {\n id: string\n label: string\n layer: TaxonomyNodeLayer\n /** Null only for a top-level domain, whose parent is the implicit lab root. */\n parent: string | null\n /** Secondary classifications; they never change the node's place in the tree. */\n tags?: string[]\n}\n\nexport interface DomainTaxonomy {\n schema: typeof DOMAIN_TAXONOMY_SCHEMA\n /** Caller-chosen version; promoted findings record the version they were lifted under. */\n version: string\n nodes: TaxonomyNode[]\n}\n\nexport type TaxonomyOutcome<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; error: { message: string } }\n\n/** The layer a node of each kind must hang under. */\nconst PARENT_LAYER: Record<TaxonomyNodeLayer, TaxonomyNodeLayer | null> = {\n run: 'play',\n play: 'problem',\n problem: 'domain',\n domain: 'domain',\n}\n\nfunction fail<T>(message: string): TaxonomyOutcome<T> {\n return { succeeded: false, error: { message } }\n}\n\n/**\n * Validate a taxonomy: unique ids, known parents, each node under a parent of\n * the right layer, no cycles. `lab` is reserved for the implicit root.\n */\nexport function defineDomainTaxonomy(input: {\n version: string\n nodes: ReadonlyArray<TaxonomyNode>\n}): TaxonomyOutcome<DomainTaxonomy> {\n if (typeof input.version !== 'string' || !input.version.trim()) {\n return fail('taxonomy version must be a non-empty string')\n }\n const nodes = input.nodes.map((node) => ({\n id: node.id,\n label: node.label,\n layer: node.layer,\n parent: node.parent,\n ...(node.tags === undefined ? {} : { tags: [...node.tags] }),\n }))\n const byId = new Map<string, TaxonomyNode>()\n for (const node of nodes) {\n if (typeof node.id !== 'string' || !node.id.trim()) return fail('node ids must be non-empty')\n if (node.id === LAB_NODE_ID) return fail(`'${LAB_NODE_ID}' is the implicit root id`)\n if (byId.has(node.id)) return fail(`node '${node.id}' appears twice`)\n if (!(TAXONOMY_NODE_LAYERS as readonly string[]).includes(node.layer)) {\n return fail(`node '${node.id}' has unknown layer '${String(node.layer)}'`)\n }\n if (typeof node.label !== 'string' || !node.label.trim()) {\n return fail(`node '${node.id}' needs a label`)\n }\n byId.set(node.id, node)\n }\n for (const node of nodes) {\n if (node.parent === null) {\n if (node.layer !== 'domain') return fail(`${node.layer} '${node.id}' needs a parent`)\n continue\n }\n const parent = byId.get(node.parent)\n if (!parent) return fail(`node '${node.id}' names unknown parent '${node.parent}'`)\n if (parent.layer !== PARENT_LAYER[node.layer]) {\n return fail(\n `${node.layer} '${node.id}' must hang under a ${PARENT_LAYER[node.layer]}, not ${parent.layer} '${parent.id}'`,\n )\n }\n }\n for (const node of nodes) {\n const seen = new Set<string>()\n let current: TaxonomyNode | undefined = node\n while (current) {\n if (seen.has(current.id)) return fail(`node '${node.id}' sits on a parent cycle`)\n seen.add(current.id)\n current = current.parent === null ? undefined : byId.get(current.parent)\n }\n }\n return {\n succeeded: true,\n value: { schema: DOMAIN_TAXONOMY_SCHEMA, version: input.version, nodes },\n }\n}\n\nexport interface TaxonomyAttachment {\n id: string\n label: string\n layer: Exclude<TaxonomyNodeLayer, 'domain'>\n /**\n * For a problem: its primary domain path, broadest first. It must be a\n * chain of domain nodes from the top level down. Ignored for plays and runs.\n */\n path?: readonly string[]\n /** For a play or run: the problem or play it belongs to. */\n parent?: string\n tags?: readonly string[]\n}\n\n/** Attach a problem to one primary domain path, a play to a problem, or a run to a play. */\nexport function attachToTaxonomy(\n taxonomy: DomainTaxonomy,\n attachment: TaxonomyAttachment,\n): TaxonomyOutcome<DomainTaxonomy> {\n let parent: string\n if (attachment.layer === 'problem') {\n if (!attachment.path || attachment.path.length === 0) {\n return fail(`problem '${attachment.id}' needs a primary domain path`)\n }\n const resolved = resolveDomainPath(taxonomy, attachment.path)\n if (!resolved.succeeded) return resolved\n parent = attachment.path[attachment.path.length - 1]!\n } else {\n if (!attachment.parent) return fail(`${attachment.layer} '${attachment.id}' needs a parent`)\n parent = attachment.parent\n }\n return defineDomainTaxonomy({\n version: taxonomy.version,\n nodes: [\n ...taxonomy.nodes,\n {\n id: attachment.id,\n label: attachment.label,\n layer: attachment.layer,\n parent,\n ...(attachment.tags === undefined ? {} : { tags: [...attachment.tags] }),\n },\n ],\n })\n}\n\n/** Check that a path is a top-down chain of domain nodes. */\nexport function resolveDomainPath(\n taxonomy: DomainTaxonomy,\n path: readonly string[],\n): TaxonomyOutcome<readonly TaxonomyNode[]> {\n const byId = nodeIndex(taxonomy)\n const chain: TaxonomyNode[] = []\n let expectedParent: string | null = null\n for (const id of path) {\n const node = byId.get(id)\n if (node?.layer !== 'domain') return fail(`'${id}' is not a domain node`)\n if (node.parent !== expectedParent) {\n return fail(`domain path breaks at '${id}': its parent is '${node.parent ?? LAB_NODE_ID}'`)\n }\n chain.push(node)\n expectedParent = id\n }\n return { succeeded: true, value: chain }\n}\n\n/** Layer of a node id, with `lab` for the implicit root; undefined when unknown. */\nexport function taxonomyLayerOf(\n taxonomy: DomainTaxonomy,\n id: string,\n): TaxonomyNodeLayer | 'lab' | undefined {\n if (id === LAB_NODE_ID) return 'lab'\n return nodeIndex(taxonomy).get(id)?.layer\n}\n\n/** Parent id, with `lab` above every top-level domain and null above `lab`. */\nexport function taxonomyParentOf(taxonomy: DomainTaxonomy, id: string): string | null | undefined {\n if (id === LAB_NODE_ID) return null\n const node = nodeIndex(taxonomy).get(id)\n if (!node) return undefined\n return node.parent ?? LAB_NODE_ID\n}\n\n/** The node and its ancestors, nearest first, ending at `lab`. Empty for an unknown id. */\nexport function taxonomyAncestry(taxonomy: DomainTaxonomy, id: string): string[] {\n const byId = nodeIndex(taxonomy)\n const chain: string[] = []\n let current: string | null = id\n while (current !== null) {\n if (current === LAB_NODE_ID) {\n chain.push(current)\n break\n }\n const node = byId.get(current)\n if (!node) return []\n chain.push(current)\n current = node.parent ?? LAB_NODE_ID\n }\n return chain\n}\n\n/** Domain path of a node, broadest first: the domain ids above it, and itself when a domain. */\nexport function domainPathOf(taxonomy: DomainTaxonomy, id: string): string[] {\n const byId = nodeIndex(taxonomy)\n return taxonomyAncestry(taxonomy, id)\n .filter((ancestor) => byId.get(ancestor)?.layer === 'domain')\n .reverse()\n}\n\n/**\n * Deepest node that is an ancestor of (or equal to) every id, or undefined\n * when an id is unknown. `lab` is the answer when they share nothing else.\n */\nexport function lowestCommonAncestor(\n taxonomy: DomainTaxonomy,\n ids: readonly string[],\n): string | undefined {\n if (ids.length === 0) return undefined\n const chains = ids.map((id) => taxonomyAncestry(taxonomy, id))\n if (chains.some((chain) => chain.length === 0)) return undefined\n const others = chains.slice(1).map((chain) => new Set(chain))\n return chains[0]!.find((id) => others.every((chain) => chain.has(id)))\n}\n\nfunction nodeIndex(taxonomy: DomainTaxonomy): Map<string, TaxonomyNode> {\n return new Map(taxonomy.nodes.map((node) => [node.id, node]))\n}\n","/**\n * failure-modes — a judged analyst with fixed-choice labels, gated on its own\n * calibration.\n *\n * Labels are adapted from the MAST multi-agent failure taxonomy (Cemri et al.,\n * \"Why Do Multi-Agent LLM Systems Fail?\", 2025): its fourteen modes in three\n * groups, plus four single-agent modes so the public AgentRx set maps onto the\n * same labels, plus `none`. Two more fixed questions cover delegation-brief\n * completeness and steer handling.\n *\n * The judge runs through the System One decision path (`systemOneAnalyst`).\n * Construction requires a calibration — gold labels compared with the judge's\n * labels on the same items — and refuses to build an analyst whose Cohen's κ\n * is below `FAILURE_MODES_MIN_KAPPA`. A rubric that does not agree with its\n * gold set has nothing to report, so it reports nothing.\n */\n\nimport { readFile } from 'node:fs/promises'\nimport { nominalAgreement } from '../statistics/agreement-irr'\nimport { type SystemOneEvaluatorOptions, systemOneAnalyst } from '../systemone'\nimport type { SystemOneQuestions, SystemOneState } from '../systemone-protocol'\nimport { normalizeAgentRxCategory } from './benchmark-dataset-agentrx'\nimport type { AgentRxRow } from './benchmark-dataset-types'\nimport { externalId, positiveStep } from './benchmark-dataset-utils'\nimport { loadPublicBenchmarkRows } from './benchmark-public-data'\nimport type { FindingCalibration, FindingScope } from './finding-scope'\nimport { type Analyst, type AnalystContext, type AnalystFinding, makeFinding } from './types'\n\nexport const FAILURE_MODES_ANALYST_ID = 'failure-modes'\nexport const FAILURE_MODES_VERSION = '2'\n\n/** κ below this refuses the rubric. */\nexport const FAILURE_MODES_MIN_KAPPA = 0.6\n\nexport const FAILURE_MODE_LABELS = {\n // MAST 1 — specification and system design\n 'disobey-task-specification': 'Ignored or violated the stated task requirements or constraints.',\n 'disobey-role-specification': 'Acted outside its assigned role or took over another role.',\n 'step-repetition': 'Repeated a step already completed without new reason.',\n 'loss-of-conversation-history': 'Lost earlier context and acted as if it was never given.',\n 'unaware-of-termination-conditions': 'Did not recognize when the task was done or must stop.',\n // MAST 2 — inter-agent misalignment\n 'conversation-reset': 'Restarted the exchange and discarded progress.',\n 'fail-to-ask-for-clarification': 'Proceeded on an ambiguous instruction without asking.',\n 'task-derailment': 'Drifted from the task toward a different goal.',\n 'information-withholding': 'Kept back information another agent needed.',\n 'ignored-other-agent-input': \"Disregarded another agent's input or recommendation.\",\n 'reasoning-action-mismatch': 'Acted against its own stated reasoning or plan.',\n // MAST 3 — task verification and termination\n 'premature-termination': 'Stopped before the goal of the task was met.',\n 'no-or-incomplete-verification': 'Delivered without verifying, or verified only part.',\n 'incorrect-verification': 'Verified, but the check was wrong or passed bad output.',\n // Single-agent modes, so AgentRx labels map onto this set.\n 'invented-information': 'Stated facts, results or tool output that do not exist.',\n 'invalid-tool-invocation': 'Called a tool with an invalid name, argument or format.',\n 'misread-tool-output': 'Misinterpreted what a tool or handoff returned.',\n 'system-failure': 'Failed because of infrastructure, not the agent.',\n none: 'No failure mode applies.',\n} as const\n\nexport type FailureModeLabel = keyof typeof FAILURE_MODE_LABELS\n\n/**\n * AgentRx root-cause category → failure-mode label. `null` categories have no\n * counterpart here and are left out of the gold set, counted as unmapped.\n */\nconst AGENT_RX_FAILURE_MODE_MAP: Readonly<Record<string, FailureModeLabel | null>> = {\n 'instruction-plan-adherence-failure': 'disobey-task-specification',\n 'invention-of-new-information': 'invented-information',\n 'invalid-invocation': 'invalid-tool-invocation',\n 'misinterpretation-of-tool-output-handoff-failure': 'misread-tool-output',\n 'intent-plan-misalignment': 'task-derailment',\n // An underspecified user request is not evidence that an agent failed to clarify it.\n 'underspecified-user-intent': null,\n 'intent-not-supported': null,\n 'guardrails-triggered': null,\n 'system-failure': 'system-failure',\n inconclusive: null,\n}\n\n/** Agent roles in the pinned public AgentRx datasets; unfamiliar actors stay unknown. */\nconst AGENT_RX_AGENT_ACTORS = new Set(['assistant', 'orchestrator', 'websurfer', 'filesurfer'])\n\nexport const FAILURE_MODES_QUESTIONS = {\n failure_mode: {\n type: 'choice',\n instructions:\n 'Which agent or team root-cause failure best explains the observed shortfall? Identify the causal error rather than a downstream symptom; a corrected earlier mistake need not be the root cause. Use only the provided task, policy, actions, tool results and outcome evidence. Do not invent missing outcomes or infrastructure errors. Choose none when the evidence establishes that no failure occurred.',\n criteria: FAILURE_MODE_LABELS,\n },\n delegation_brief: {\n type: 'choice',\n instructions:\n 'When this agent delegated work, did the brief state the goal, the constraints, the expected output, and how the result would be checked?',\n criteria: {\n complete: 'Every delegated brief stated goal, constraints, output and check.',\n partial: 'Some brief left out one or more of goal, constraints, output or check.',\n missing: 'Work was delegated with no usable brief.',\n 'no-delegation': 'Nothing was delegated.',\n },\n },\n steer_handling: {\n type: 'choice',\n instructions: 'When a steer or correction arrived mid-task, what did the agent do with it?',\n criteria: {\n applied: 'Changed course as the steer asked.',\n ignored: 'Continued as before, or acknowledged without acting.',\n 'no-steer': 'No steer arrived.',\n },\n },\n} as const satisfies SystemOneQuestions\n\nexport interface FailureModeLabelItem {\n id: string\n label: FailureModeLabel\n}\n\nexport interface FailureModesCalibration extends FindingCalibration {\n /** Gold items with no judge label; each counts as a disagreement. */\n missingPredictions: number\n}\n\nexport type FailureModesOutcome<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; error: { kind: 'invalid' | 'uncalibrated'; message: string } }\n\nfunction isLabel(value: unknown): value is FailureModeLabel {\n return typeof value === 'string' && Object.hasOwn(FAILURE_MODE_LABELS, value)\n}\n\n/** Gold labels from AgentRx rows: each trajectory's root-cause category, mapped onto this set. */\nfunction failureModeGoldFromAgentRx(\n rows: readonly AgentRxRow[],\n): Pick<FailureModeGold, 'gold' | 'unmapped'> {\n const gold: FailureModeLabelItem[] = []\n const unmapped: FailureModeGold['unmapped'] = []\n const ids = new Set<string>()\n for (const row of rows) {\n const id = `agentrx:${externalId(row.trajectory_id, 'AgentRx trajectory id')}`\n if (ids.has(id)) throw new TypeError(`AgentRx trajectory '${row.trajectory_id}' repeats`)\n ids.add(id)\n const rootId = externalId(\n row.root_cause_failure_id ?? row.root_cause?.failure_id,\n `AgentRx trajectory '${row.trajectory_id}' root-cause failure id`,\n )\n const root = row.failures.find((failure) => String(failure.failure_id) === String(rootId))\n if (!root)\n throw new TypeError(`AgentRx trajectory '${row.trajectory_id}' has no root-cause failure`)\n const step = positiveStep(\n root.step_number,\n `AgentRx trajectory '${row.trajectory_id}' root step`,\n )\n const category = normalizeAgentRxCategory(root.failure_category)\n if (!Object.hasOwn(AGENT_RX_FAILURE_MODE_MAP, category)) {\n throw new RangeError(\n `AgentRx category '${root.failure_category}' is outside the AgentRx taxonomy`,\n )\n }\n const label = AGENT_RX_FAILURE_MODE_MAP[category]\n const actor = typeof root.failed_agent === 'string' ? root.failed_agent.trim() || null : null\n const reason =\n actor === null\n ? 'unknown-root-actor'\n : !AGENT_RX_AGENT_ACTORS.has(actor.toLowerCase())\n ? 'unsupported-root-actor'\n : label === null || label === undefined\n ? 'category-without-counterpart'\n : null\n if (reason !== null) {\n unmapped.push({\n id,\n category,\n reason,\n root: { failureId: rootId, step, actor },\n })\n } else if (label !== null && label !== undefined) {\n gold.push({ id, label })\n }\n }\n return { gold, unmapped }\n}\n\n/** Validate caller gold with unique, whitespace-unambiguous ids and known labels. */\nfunction parseFailureModeGold(raw: unknown): FailureModesOutcome<FailureModeLabelItem[]> {\n if (!Array.isArray(raw)) {\n return { succeeded: false, error: { kind: 'invalid', message: 'gold must be a JSON array' } }\n }\n const seen = new Set<string>()\n const items: FailureModeLabelItem[] = []\n for (const [index, row] of raw.entries()) {\n const id = (row as { id?: unknown } | null)?.id\n const label = (row as { label?: unknown } | null)?.label\n if (typeof id !== 'string' || !id.trim() || !isLabel(label)) {\n return {\n succeeded: false,\n error: {\n kind: 'invalid',\n message: `gold row ${index} needs a string id and a known label`,\n },\n }\n }\n if (id !== id.trim()) {\n return {\n succeeded: false,\n error: {\n kind: 'invalid',\n message: `gold row ${index} id must not have surrounding whitespace`,\n },\n }\n }\n if (seen.has(id)) {\n return { succeeded: false, error: { kind: 'invalid', message: `gold id '${id}' repeats` } }\n }\n seen.add(id)\n items.push({ id, label })\n }\n return { succeeded: true, value: items }\n}\n\nexport interface FailureModeGoldSources {\n /** The public AgentRx label file, the same file `analyst-benchmark --dataset agentrx --labels` reads. */\n agentRxLabelsPath?: string\n /** The caller's gold file: a JSON array of `{ id, label }`. */\n goldPath?: string\n}\n\nexport interface FailureModeGold {\n gold: FailureModeLabelItem[]\n /** Parsed sources with no eligible labels are unknown, never a successful calibration. */\n eligibility: 'eligible' | 'unknown'\n /** AgentRx rows read from `agentRxLabelsPath`; every one is either in `gold` or in `unmapped`. */\n agentRxRows: number\n /** Record this rule beside a new calibration; null when no AgentRx source was supplied. */\n agentRxMapping: { version: string; target: 'agent-or-team-root-cause' } | null\n unmapped: Array<{\n id: string\n category: string\n reason: 'unknown-root-actor' | 'unsupported-root-actor' | 'category-without-counterpart'\n root: { failureId: string; step: number; actor: string | null }\n }>\n}\n\n/**\n * Load the calibration gold set from the public AgentRx labels and the\n * caller's gold file, through the analyst module's public-dataset loader.\n * Caller gold ids must be disjoint from all AgentRx ids, including exclusions.\n * No source or an empty source is invalid. A parsed AgentRx source whose rows are all excluded returns\n * unknown eligibility with its reasons; it supplies no labels to calibrate.\n */\nexport async function loadFailureModeGold(\n sources: FailureModeGoldSources,\n): Promise<FailureModesOutcome<FailureModeGold>> {\n const invalid = (message: string) =>\n ({ succeeded: false, error: { kind: 'invalid', message } }) as const\n const gold: FailureModeLabelItem[] = []\n let agentRxRows = 0\n let agentRxMapping: FailureModeGold['agentRxMapping'] = null\n let unmapped: FailureModeGold['unmapped'] = []\n try {\n if (sources.agentRxLabelsPath !== undefined) {\n const rows = await loadPublicBenchmarkRows(sources.agentRxLabelsPath)\n agentRxRows = rows.length\n const mapped = failureModeGoldFromAgentRx(rows as unknown as AgentRxRow[])\n agentRxMapping = { version: '2', target: 'agent-or-team-root-cause' }\n gold.push(...mapped.gold)\n unmapped = mapped.unmapped\n }\n if (sources.goldPath !== undefined) {\n const parsed = parseFailureModeGold(JSON.parse(await readFile(sources.goldPath, 'utf8')))\n if (!parsed.succeeded) return parsed\n gold.push(...parsed.value)\n }\n } catch (error) {\n return invalid(error instanceof Error ? error.message : String(error))\n }\n if (gold.length === 0 && unmapped.length === 0)\n return invalid('failure-modes calibration needs at least one gold item')\n const ids = new Set(unmapped.map((item) => item.id))\n for (const item of gold) {\n if (ids.has(item.id)) return invalid(`gold id '${item.id}' repeats across sources`)\n ids.add(item.id)\n }\n return {\n succeeded: true,\n value: {\n gold,\n eligibility: gold.length > 0 ? 'eligible' : 'unknown',\n agentRxRows,\n agentRxMapping,\n unmapped,\n },\n }\n}\n\n/**\n * Score the judge's labels against gold labels for the same items, usually\n * the set `loadFailureModeGold` returns.\n */\nexport function calibrateFailureModes(\n gold: readonly FailureModeLabelItem[],\n predictions: readonly FailureModeLabelItem[],\n): FailureModesCalibration {\n const predicted = new Map<string, FailureModeLabel>()\n for (const prediction of predictions) {\n if (predicted.has(prediction.id))\n throw new TypeError(`prediction id '${prediction.id}' repeats`)\n predicted.set(prediction.id, prediction.label)\n }\n const ids = new Set<string>()\n let missingPredictions = 0\n const pairs: Array<readonly [string, string]> = []\n for (const item of gold) {\n if (ids.has(item.id)) throw new TypeError(`gold id '${item.id}' repeats`)\n ids.add(item.id)\n const label = predicted.get(item.id)\n if (label === undefined) missingPredictions += 1\n // A missing prediction is its own label: it can never match gold.\n pairs.push([item.label, label ?? '(no prediction)'])\n }\n const agreement = nominalAgreement(pairs)\n return {\n gold_n: agreement.n,\n agreement: agreement.agreement,\n kappa: agreement.kappa,\n missingPredictions,\n }\n}\n\nexport interface FailureModesAnalystOptions<I> extends SystemOneEvaluatorOptions {\n model: string\n /** The layer the judged subject sits at. */\n layer: 'agent' | 'team' | 'run'\n calibration: FindingCalibration\n renderState: (input: I, context: AnalystContext) => SystemOneState | Promise<SystemOneState>\n /** The judged population: the agent, team or run the state describes. */\n scope: (input: I, context: AnalystContext) => FindingScope\n subject?: (input: I, context: AnalystContext) => string\n}\n\n/**\n * Build the failure-modes analyst, or refuse when its calibration does not\n * clear `FAILURE_MODES_MIN_KAPPA`. An undefined κ (no gold, or one label\n * everywhere) is refused the same way.\n */\nexport function createFailureModesAnalyst<I>(\n options: FailureModesAnalystOptions<I>,\n): FailureModesOutcome<Analyst<I>> {\n const { calibration, layer, model, renderState, scope, subject, ...transport } = options\n if (!(calibration.gold_n > 0) || !(calibration.kappa >= FAILURE_MODES_MIN_KAPPA)) {\n return {\n succeeded: false,\n error: {\n kind: 'uncalibrated',\n message: `failure-modes rubric has kappa ${Number.isNaN(calibration.kappa) ? 'undefined' : calibration.kappa.toFixed(3)} over ${calibration.gold_n} gold items; reporting requires kappa >= ${FAILURE_MODES_MIN_KAPPA}`,\n },\n }\n }\n const method = {\n kind: 'judged' as const,\n name: FAILURE_MODES_ANALYST_ID,\n version: FAILURE_MODES_VERSION,\n calibration: {\n gold_n: calibration.gold_n,\n agreement: calibration.agreement,\n kappa: calibration.kappa,\n },\n }\n const analyst = systemOneAnalyst({\n ...transport,\n model,\n renderState,\n id: FAILURE_MODES_ANALYST_ID,\n description: 'Labels agent, team and run failures with a calibrated fixed-choice rubric.',\n inputKind: 'custom',\n version: FAILURE_MODES_VERSION,\n questions: FAILURE_MODES_QUESTIONS,\n findings: (value, input, context) => {\n const judgedSubject = subject?.(input, context)\n const base = {\n analyst_id: FAILURE_MODES_ANALYST_ID,\n derived_from_judge: true,\n layer,\n scope: scope(input, context),\n method,\n evidence_refs: [{ kind: 'artifact' as const, uri: `run://${context.runId}` }],\n ...(judgedSubject === undefined ? {} : { subject: judgedSubject }),\n }\n const out: AnalystFinding[] = []\n const mode = value.answers.failure_mode\n if (mode.choice !== 'none') {\n out.push(\n makeFinding({\n ...base,\n area: 'failure-mode',\n severity: 'medium',\n confidence: mode.confidence,\n claim: `Failure mode: ${mode.choice}`,\n claim_id: `failure-mode:${mode.choice}`,\n rationale: FAILURE_MODE_LABELS[mode.choice],\n }),\n )\n }\n const brief = value.answers.delegation_brief\n if (brief.choice === 'partial' || brief.choice === 'missing') {\n out.push(\n makeFinding({\n ...base,\n area: 'delegation-brief',\n severity: brief.choice === 'missing' ? 'high' : 'medium',\n confidence: brief.confidence,\n claim: `Delegation brief ${brief.choice}`,\n claim_id: `delegation-brief:${brief.choice}`,\n }),\n )\n }\n const steer = value.answers.steer_handling\n if (steer.choice === 'ignored') {\n out.push(\n makeFinding({\n ...base,\n area: 'steer-handling',\n severity: 'high',\n confidence: steer.confidence,\n claim: 'Steer ignored',\n claim_id: 'steer-handling:ignored',\n }),\n )\n }\n return out\n },\n })\n return { succeeded: true, value: analyst }\n}\n","/**\n * Findings ledger — analyst findings in the shared ledger-core journal.\n *\n * Each appended finding is one hash-chained, canonical JSON entry, fsynced and\n * pinned to a trusted head, so a later reader can prove nothing was rewritten\n * or cut from the end. A row is validated by `AnalystFindingSchema` before it\n * is written and again when it is read, so a 1.1.0 finding whose declared\n * population disagrees with its evidence never enters the record.\n *\n * Appends are idempotent per (run, finding): replaying a run's findings is a\n * no-op, and the same finding id with different content is a conflict.\n * `FindingsStore` remains the unchained JSONL store for existing consumers.\n */\n\nimport { z } from 'zod'\nimport type { LedgerHash } from '../ledger-core/canonical'\nimport { FileLedgerJournal, type LedgerJournalCodec } from '../ledger-core/journal'\nimport { merkleRoot } from '../ledger-core/merkle'\nimport { AnalystFindingSchema, type FindingLayer } from './finding-scope'\nimport {\n type DiffPolicy,\n diffFindings,\n type FindingsDiff,\n type PersistedFinding,\n} from './findings-store'\nimport type { AnalystFinding } from './types'\n\nconst schema = 'agent-eval.findings-ledger.v1' as const\nconst digest = z.string().regex(/^sha256:[a-f0-9]{64}$/)\nconst identity = z\n .string()\n .min(1)\n .refine((value) => value.trim() === value, { message: 'must not carry surrounding space' })\n\nconst eventSchema = z\n .object({\n kind: z.literal('finding'),\n eventId: identity,\n run_id: identity,\n finding: AnalystFindingSchema,\n })\n .strict()\n\ntype Event = z.infer<typeof eventSchema>\n\nconst entrySchema = z\n .object({\n schema: z.literal(schema),\n sequence: z.number().int().nonnegative(),\n previousHash: digest.nullable(),\n event: eventSchema,\n entryHash: digest,\n })\n .strict()\n\n/** One finding as the ledger holds it. */\nexport interface LedgerFinding extends PersistedFinding {\n /** Position in the journal; later entries were appended later. */\n sequence: number\n entryHash: LedgerHash\n}\n\nexport interface FindingsLedgerRead {\n findings: LedgerFinding[]\n /** RFC 9162 Merkle root over every entry hash, in journal order. */\n merkleRoot: LedgerHash\n}\n\nexport type FindingsLedgerOutcome<T> =\n | { succeeded: true; value: T }\n | {\n succeeded: false\n error: { kind: 'invalid' | 'conflict' | 'unavailable'; message: string }\n }\n\nexport interface FindingsLedger {\n readonly path: string\n append(\n runId: string,\n findings: readonly AnalystFinding[],\n ): Promise<FindingsLedgerOutcome<{ appended: number; replayed: number }>>\n read(): Promise<FindingsLedgerOutcome<FindingsLedgerRead>>\n}\n\nclass FindingsLedgerConflictError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'FindingsLedgerConflictError'\n }\n}\n\nclass FindingsLedgerInvalidError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'FindingsLedgerInvalidError'\n }\n}\n\nfunction codec(): LedgerJournalCodec<{ schema: typeof schema }, Event, LedgerFinding[]> {\n return {\n subject: 'findings ledger',\n header: { schema },\n integrityError: (message, options) => new Error(message, options),\n conflictError: (message) => new FindingsLedgerConflictError(message),\n parseEntry: (raw, context) => {\n const decoded = entrySchema.safeParse(raw)\n if (!decoded.success) {\n const issue = decoded.error.issues[0]\n throw new FindingsLedgerInvalidError(\n `findings ledger ${context.path}:${context.line} is invalid at ${(issue?.path ?? []).join('.')}: ${issue?.message}`,\n )\n }\n return {\n ...decoded.data,\n event: decoded.data.event as Event,\n previousHash: decoded.data.previousHash as LedgerHash | null,\n entryHash: decoded.data.entryHash as LedgerHash,\n }\n },\n checkEntryHeader: (entry) => {\n if (entry.schema !== schema) throw new FindingsLedgerInvalidError('unsupported ledger schema')\n },\n createProjector: () => {\n const rows: LedgerFinding[] = []\n return {\n apply: (entry) => {\n const { event } = entry\n if (event.eventId !== eventIdFor(event.run_id, event.finding.finding_id)) {\n throw new FindingsLedgerInvalidError(\n `event id ${event.eventId} does not name its finding`,\n )\n }\n rows.push({\n ...(event.finding as AnalystFinding),\n run_id: event.run_id,\n sequence: entry.sequence,\n entryHash: entry.entryHash,\n })\n },\n snapshot: () => [...rows],\n }\n },\n }\n}\n\nfunction eventIdFor(runId: string, findingId: string): string {\n return `finding:${runId}:${findingId}`\n}\n\nasync function outcome<T>(operation: () => Promise<T>): Promise<FindingsLedgerOutcome<T>> {\n try {\n return { succeeded: true, value: await operation() }\n } catch (error) {\n return {\n succeeded: false,\n error: {\n kind:\n error instanceof FindingsLedgerConflictError\n ? 'conflict'\n : error instanceof FindingsLedgerInvalidError || error instanceof z.ZodError\n ? 'invalid'\n : 'unavailable',\n message: error instanceof Error ? error.message : String(error),\n },\n }\n }\n}\n\n/** Open (or create on first append) the findings journal at `path`; every reopen requires its pin. */\nexport function openFindingsLedger(options: { path: string }): FindingsLedger {\n if (!options.path.trim()) throw new TypeError('findings ledger: path is empty')\n const journal = new FileLedgerJournal(options.path, codec(), { requireTrustedHead: true })\n return {\n path: journal.path,\n append: (runId, findings) =>\n outcome(async () => {\n identity.parse(runId)\n let appended = 0\n let replayed = 0\n for (const finding of findings) {\n const parsed = AnalystFindingSchema.safeParse(finding)\n if (!parsed.success) {\n const issue = parsed.error.issues[0]\n throw new FindingsLedgerInvalidError(\n `finding ${finding.finding_id} is invalid at ${(issue?.path ?? []).join('.')}: ${issue?.message}`,\n )\n }\n const result = await journal.append(\n {\n kind: 'finding',\n eventId: eventIdFor(runId, finding.finding_id),\n run_id: runId,\n finding: parsed.data,\n },\n { pinHead: true },\n )\n if (result.appended) appended += 1\n else replayed += 1\n }\n return { appended, replayed }\n }),\n read: () =>\n outcome(async () => {\n const findings = await journal.replay()\n return { findings, merkleRoot: merkleRoot(findings.map((row) => row.entryHash)) }\n }),\n }\n}\n\n// ── Queries ──────────────────────────────────────────────────────────\n\nexport interface FindingsQuery {\n layer?: FindingLayer | readonly FindingLayer[]\n subject?: string\n analystId?: string\n runId?: string\n claimId?: string\n /**\n * Findings whose `scope.domain_path` starts with this path. A finding with no\n * domain path never matches, so a path query cannot return unscoped findings.\n */\n domainPath?: readonly string[]\n}\n\n/** Filter ledger rows. Every set criterion must hold; 1.0.0 rows have no layer and never match one. */\nexport function queryFindings<T extends AnalystFinding & { run_id?: string }>(\n rows: readonly T[],\n query: FindingsQuery,\n): T[] {\n const layers =\n query.layer === undefined\n ? null\n : new Set(typeof query.layer === 'string' ? [query.layer] : query.layer)\n return rows.filter((row) => {\n if (layers && (row.layer === undefined || !layers.has(row.layer))) return false\n if (query.subject !== undefined && row.subject !== query.subject) return false\n if (query.analystId !== undefined && row.analyst_id !== query.analystId) return false\n if (query.runId !== undefined && row.run_id !== query.runId) return false\n if (query.claimId !== undefined && row.claim_id !== query.claimId) return false\n if (query.domainPath !== undefined) {\n const path = row.scope?.domain_path\n if (!path || path.length < query.domainPath.length) return false\n if (query.domainPath.some((id, index) => path[index] !== id)) return false\n }\n return true\n })\n}\n\nexport interface FindingsTimeStep {\n previous_run_id: string\n run_id: string\n diff: FindingsDiff\n}\n\n/**\n * Diff each run against the run before it, in the order runs first entered\n * the ledger. Uses `diffFindings`, so `appeared`, `disappeared`, `persisted`\n * and `changed` mean exactly what they mean for two runs.\n */\nexport function diffFindingsOverTime(\n rows: readonly LedgerFinding[],\n policy: DiffPolicy = {},\n): FindingsTimeStep[] {\n const runs: string[] = []\n const byRun = new Map<string, PersistedFinding[]>()\n for (const row of [...rows].sort((a, b) => a.sequence - b.sequence)) {\n const list = byRun.get(row.run_id)\n if (list) list.push(row)\n else {\n runs.push(row.run_id)\n byRun.set(row.run_id, [row])\n }\n }\n return runs.slice(1).map((runId, index) => ({\n previous_run_id: runs[index]!,\n run_id: runId,\n diff: diffFindings(byRun.get(runs[index]!)!, byRun.get(runId)!, policy),\n }))\n}\n","/**\n * Skill-usage analyst — a DETERMINISTIC `Analyst` over a Claude/Codex skill\n * library + its trace corpus. Unlike the trace-store kinds (failure-mode,\n * improvement, ...) this kind calls no LLM: it mines real usage and skill\n * structure and emits findings by rule.\n *\n * It exists because the naive \"Skill-tool invocation count\" lies low — it\n * misses orchestrated sub-dispatch (a leaf skill run BY /pursue or /governor\n * logs under the parent), slash-command entry, local-script bypass, and\n * on-disk artifacts. The 2026-05-30 skill audit found 39/53 skills at zero\n * direct invocations, yet only one was a genuine cut: the rest were\n * measurement-invisible or discovery-limited. This analyst encodes that\n * lesson as a multi-signal usage model so a cheap repeatable pass can keep\n * the library honest, and so the expensive audit workflow's verdicts can\n * GEPA-distill it toward agreement (see `gold/skill-verdicts.gold.jsonl`).\n *\n * Report-building (`buildSkillUsageReport`, an fs scan) is separated from\n * finding emission (`SkillUsageAnalyst.analyze`, pure) so the slow scan runs\n * once at the registry boundary and the rule logic stays unit-testable.\n */\n\nimport { type Dirent, existsSync, readdirSync, readFileSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\n\n\n\n\n// ── Input model ──────────────────────────────────────────────────────\n\ntype SkillKind = 'public' | 'private'\n\n/** One skill's multi-signal usage + structure. All counts are deterministic. */\nexport interface SkillUsageRecord {\n name: string\n kind: SkillKind\n /** Absolute path to the skill's SKILL.md. */\n path: string\n lines: number\n /** `\"skill\":\"<name>\"` Skill-tool invocations across the trace corpus. */\n directInvocations: number\n /** `<command-name>/<name>` slash invocations across the trace corpus. */\n slashInvocations: number\n /** Sibling skills whose SKILL.md dispatches to this one (`/<name>`). Proxy\n * for orchestrated sub-dispatch the per-skill counter cannot see. */\n inboundRefs: number\n /** On-disk artifacts attributable to the skill (e.g. `.evolve/<name>/**`). */\n artifactCount: number\n /** Tangle-private reference count in the body (leak signal for public skills). */\n tanglePrivateRefs: number\n hasReferencesDir: boolean\n hasEvalsDir: boolean\n /** Body mentions `skill-runs.jsonl` (visible to /reflect + /governor). */\n logsRuns: boolean\n /** Description carries an explicit `Triggers:` clause / trigger phrases. */\n hasTriggerPhrases: boolean\n}\n\nexport interface SkillUsageReport {\n generatedFromTraces: number\n records: SkillUsageRecord[]\n}\n\nexport interface SkillUsageScanConfig {\n /** Dirs holding `*.jsonl` transcripts (Claude `~/.claude/projects`, Codex sessions). */\n transcriptDirs: string[]\n /** Skill roots to scan; each dir directly under `root` with a `SKILL.md` is a skill. */\n skillRoots: { root: string; kind: SkillKind }[]\n /** Roots scanned for `<root>/.evolve/<skill>` artifact dirs. */\n artifactRoots?: string[]\n /** Token-prefixed mappings: skill name → extra artifact subpaths under an artifactRoot\n * (e.g. reflect → `.evolve/reflections`). Catches non-eponymous artifact dirs. */\n artifactAliases?: Record<string, string[]>\n /** Cap files read per transcript dir (bounds a huge corpus); 0 = unbounded. */\n maxTranscriptsPerDir?: number\n}\n\n// ── Deterministic thresholds ─────────────────────────────────────────\n\n\n\nconst TANGLE_PRIVATE_RE =\n /\\b(cli-bridge|tangletools|ops-board|drew-gtr-pro|@tangle-network\\/|~\\/company|tangle\\.tools|gtm-agent)\\b|\\bkimi\\b|\\btcloud\\b/gi\nconst TRIGGER_RE = /triggers?\\s*[:-]/i\n\n// ── Report builder (fs scan — slow, runs once at the registry boundary) ──\n\nfunction listSkillDirs(root: string): { name: string; path: string }[] {\n if (!existsSync(root)) return []\n const out: { name: string; path: string }[] = []\n for (const entry of readdirSync(root, { withFileTypes: true })) {\n if (!entry.isDirectory() && !entry.isSymbolicLink()) continue\n const skillMd = join(root, entry.name, 'SKILL.md')\n if (existsSync(skillMd)) out.push({ name: entry.name, path: skillMd })\n }\n return out\n}\n\nfunction walkJsonl(dir: string, cap: number): string[] {\n if (!existsSync(dir)) return []\n const files: string[] = []\n const stack = [dir]\n while (stack.length) {\n const cur = stack.pop()!\n let entries: Dirent[]\n try {\n entries = readdirSync(cur, { withFileTypes: true })\n } catch {\n continue\n }\n for (const e of entries) {\n const full = join(cur, e.name)\n if (e.isDirectory()) stack.push(full)\n else if (e.name.endsWith('.jsonl')) {\n files.push(full)\n if (cap > 0 && files.length >= cap) return files\n }\n }\n }\n return files\n}\n\nfunction frontmatterDescription(body: string): string {\n const fm = /^---\\n([\\s\\S]*?)\\n---/.exec(body)\n const block = fm?.[1] ?? ''\n const m = /description:\\s*(.+)/i.exec(block)\n return m?.[1] ?? ''\n}\n\nfunction countArtifacts(roots: string[], name: string, aliases: string[]): number {\n let n = 0\n for (const root of roots) {\n const candidates = [join(root, '.evolve', name), ...aliases.map((a) => join(root, a))]\n for (const dir of candidates) {\n if (!existsSync(dir)) continue\n try {\n if (statSync(dir).isDirectory()) n += readdirSync(dir).length\n else n += 1\n } catch {\n /* unreadable — skip */\n }\n }\n }\n return n\n}\n\n/** Scan the corpus + skill roots into a {@link SkillUsageReport}. Deterministic. */\nexport function buildSkillUsageReport(config: SkillUsageScanConfig): SkillUsageReport {\n const skills = config.skillRoots.flatMap(({ root, kind }) =>\n listSkillDirs(root).map((s) => ({ ...s, kind })),\n )\n const names = skills.map((s) => s.name)\n\n // One pass over the corpus accumulating direct + slash counts per skill.\n const direct = new Map<string, number>(names.map((n) => [n, 0]))\n const slash = new Map<string, number>(names.map((n) => [n, 0]))\n const skillRe = /\"skill\"\\s*:\\s*\"([a-z0-9_:-]+)\"/g\n const cmdRe = /<command-name>\\/?([a-z0-9_:-]+)<\\/command-name>/g\n let transcripts = 0\n for (const dir of config.transcriptDirs) {\n for (const file of walkJsonl(dir, config.maxTranscriptsPerDir ?? 0)) {\n transcripts += 1\n let data: string\n try {\n data = readFileSync(file, 'utf8')\n } catch {\n continue\n }\n for (const m of data.matchAll(skillRe)) {\n const g = m[1]\n if (!g) continue\n const n = g.split(':').pop() ?? g\n const prev = direct.get(n)\n if (prev !== undefined) direct.set(n, prev + 1)\n }\n for (const m of data.matchAll(cmdRe)) {\n const g = m[1]\n if (g === undefined) continue\n const prev = slash.get(g)\n if (prev !== undefined) slash.set(g, prev + 1)\n }\n }\n }\n\n // Read each skill body once; compute structure + inbound refs across siblings.\n const bodies = new Map<string, string>()\n for (const s of skills) {\n try {\n bodies.set(s.name, readFileSync(s.path, 'utf8'))\n } catch {\n bodies.set(s.name, '')\n }\n }\n const inbound = new Map<string, number>(names.map((n) => [n, 0]))\n for (const target of names) {\n const ref = new RegExp(`/${target}\\\\b|\\\\[\\\\[${target}\\\\]\\\\]`)\n for (const s of skills) {\n if (s.name === target) continue\n if (ref.test(bodies.get(s.name) ?? '')) inbound.set(target, inbound.get(target)! + 1)\n }\n }\n\n const records: SkillUsageRecord[] = skills.map((s) => {\n const body = bodies.get(s.name) ?? ''\n const dir = s.path.replace(/\\/SKILL\\.md$/, '')\n return {\n name: s.name,\n kind: s.kind,\n path: s.path,\n lines: body ? body.split('\\n').length : 0,\n directInvocations: direct.get(s.name) ?? 0,\n slashInvocations: slash.get(s.name) ?? 0,\n inboundRefs: inbound.get(s.name) ?? 0,\n artifactCount: countArtifacts(\n config.artifactRoots ?? [],\n s.name,\n config.artifactAliases?.[s.name] ?? [],\n ),\n tanglePrivateRefs: (body.match(TANGLE_PRIVATE_RE) ?? []).length,\n hasReferencesDir: existsSync(join(dir, 'references')),\n hasEvalsDir: existsSync(join(dir, 'evals')),\n logsRuns: body.includes('skill-runs.jsonl'),\n hasTriggerPhrases: TRIGGER_RE.test(frontmatterDescription(body) || body.slice(0, 600)),\n }\n })\n return { generatedFromTraces: transcripts, records }\n}\n\n// ── Finding emission (pure — unit-testable, no LLM, no fs) ────────────\n\n\n\n\n\n\n\n// ── The Analyst ──────────────────────────────────────────────────────\n\n\n\n\n","import {\n assertConsistentFindingConditions,\n findingCompositionKey,\n mergeFindingComposition,\n} from './finding-composition'\n/**\n * Promotion — the only way a claim moves above the layer it was measured at.\n *\n * A claim is restated at a parent node only when at least `k` independent\n * children carry the same `claim_id` with intervals that agree. Otherwise it\n * stays where it is, reported as untested above. The rule is the same on every\n * rung of the ladder: run → play → problem → each domain node up the path →\n * lab.\n *\n * The rule, exactly:\n * - A finding sits at the node that is the lowest common ancestor of its\n * `scope.population` in the taxonomy, and that node's layer must equal the\n * finding's `layer`. Four runs of one play place a claim at that play; the\n * same claim stored at `domain` or `lab` is refused as exceeding its\n * evidence.\n * - Only children with `measure.interval` vote. Voters must name the same\n * measure and unit, and their intervals must share a common point.\n * - Children are counted by lineage, not by node: two children whose evidence\n * units share a lineage root (run 2 built on run 1's code) count once, and\n * a child with no recorded lineage shares one root with every other such\n * child.\n * - Promoted findings cite every voting child by `finding://<finding_id>`.\n *\n * Event, turn, agent, team and meta findings sit outside the ladder and never\n * promote.\n */\n\nimport {\n type DomainTaxonomy,\n domainPathOf,\n LAB_NODE_ID,\n lowestCommonAncestor,\n taxonomyAncestry,\n taxonomyLayerOf,\n taxonomyParentOf,\n} from './domain-taxonomy'\nimport {\n type FindingLayer,\n type FindingMeasure,\n lineageRoots,\n mergeEvidenceUnits,\n mostSevere,\n spanningWindow,\n UNKNOWN_LINEAGE,\n} from './finding-scope'\nimport { type AnalystFinding, makeFinding } from './types'\n\n/** Bump when the promotion rule changes, so promoted findings name the rule that lifted them. */\nconst PROMOTE_VERSION = '1'\n\n/** The analyst id a promoted finding carries when its children came from different analysts. */\nconst PROMOTE_ANALYST_ID = 'promote'\n\nexport interface PromoteOptions {\n /** Independent agreeing children required to lift a claim. Default 2, minimum 2. */\n k?: number\n /** Timestamp stamped on promoted findings; defaults to now. */\n produced_at?: string\n}\n\n/** A finding promote did not lift, with the reason in words. */\nexport interface PromotionHold {\n finding_id: string\n claim_id: string | null\n /** The node the finding sits at, or null when it could not be placed. */\n node: string | null\n reason: string\n}\n\nexport interface PromotionResult {\n /** The input findings followed by every promoted finding. */\n findings: AnalystFinding[]\n promoted: AnalystFinding[]\n /** Placed findings whose claim was not lifted; they stay true at their own node. */\n untestedAbove: PromotionHold[]\n /** Findings promote cannot place on the ladder, and why. */\n unplaced: PromotionHold[]\n}\n\ninterface Placement {\n finding: AnalystFinding\n claimId: string\n node: string\n}\n\nconst LADDER: readonly FindingLayer[] = ['run', 'play', 'problem', 'domain', 'lab']\n\nexport function promote(\n findings: readonly AnalystFinding[],\n taxonomy: DomainTaxonomy,\n options: PromoteOptions = {},\n): PromotionResult {\n assertConsistentFindingConditions(findings)\n const k = options.k ?? 2\n if (!Number.isInteger(k) || k < 2) {\n throw new RangeError(`promote: k must be an integer of at least 2, got ${k}`)\n }\n const unplaced: PromotionHold[] = []\n const buckets = new Map<number, Placement[]>()\n const addPlacement = (placement: Placement): void => {\n const depth = taxonomyAncestry(taxonomy, placement.node).length\n const bucket = buckets.get(depth) ?? []\n bucket.push(placement)\n buckets.set(depth, bucket)\n }\n for (const finding of findings) {\n const placed = place(finding, taxonomy)\n if ('reason' in placed) unplaced.push(placed)\n else addPlacement(placed)\n }\n\n const roots = lineageRoots(\n mergeEvidenceUnits(findings.flatMap((finding) => finding.evidence_units ?? [])),\n )\n const promoted: AnalystFinding[] = []\n const untestedAbove: PromotionHold[] = []\n const hold = (placement: Placement, reason: string): void => {\n untestedAbove.push({\n finding_id: placement.finding.finding_id,\n claim_id: placement.claimId,\n node: placement.node,\n reason,\n })\n }\n\n // Deepest nodes first: a parent's bucket is complete, native findings and\n // lifted ones alike, before it is itself grouped for the next rung.\n for (let depth = Math.max(0, ...buckets.keys()); depth > 1; depth -= 1) {\n const groups = new Map<string, { parent: string; members: Placement[] }>()\n for (const placement of buckets.get(depth) ?? []) {\n const parent = taxonomyParentOf(taxonomy, placement.node)\n if (parent === null || parent === undefined) continue\n const key = JSON.stringify([\n placement.claimId,\n parent,\n findingCompositionKey(placement.finding),\n ])\n const group = groups.get(key) ?? { parent, members: [] }\n group.members.push(placement)\n groups.set(key, group)\n }\n for (const { parent, members } of groups.values()) {\n const verdict = judgeGroup(members, k, roots)\n if (!verdict.lift) {\n for (const member of members) hold(member, verdict.reason)\n continue\n }\n const lifted = liftedFinding(verdict.voters, parent, taxonomy, options.produced_at)\n promoted.push(lifted)\n addPlacement({ finding: lifted, claimId: members[0]!.claimId, node: parent })\n for (const member of members) {\n if (!verdict.voters.includes(member)) {\n hold(member, 'no interval, so it could not vote; the claim was lifted by its siblings')\n }\n }\n }\n }\n return { findings: [...findings, ...promoted], promoted, untestedAbove, unplaced }\n}\n\nfunction place(finding: AnalystFinding, taxonomy: DomainTaxonomy): Placement | PromotionHold {\n const unplaced = (reason: string, node: string | null = null): PromotionHold => ({\n finding_id: finding.finding_id,\n claim_id: finding.claim_id ?? null,\n node,\n reason,\n })\n if (finding.schema_version !== '1.1.0' || !finding.layer || !finding.scope) {\n return unplaced('no layer or scope (schema 1.0.0)')\n }\n if (finding.layer === 'meta')\n return unplaced('meta findings describe the instrument and never promote')\n if (!LADDER.includes(finding.layer)) {\n return unplaced(`${finding.layer} findings sit below the run → lab ladder`)\n }\n if (!finding.claim_id) return unplaced('no claim_id to match siblings by')\n const population = finding.scope.population\n if (population.length === 0) return unplaced('population names no units')\n const node = lowestCommonAncestor(taxonomy, population)\n if (node === undefined) return unplaced('population names ids outside the taxonomy')\n const nodeLayer = taxonomyLayerOf(taxonomy, node)\n if (nodeLayer !== finding.layer) {\n return unplaced(\n LADDER.indexOf(finding.layer) > LADDER.indexOf(nodeLayer as FindingLayer)\n ? `stated at ${finding.layer} but its population sits within ${nodeLayer} '${node}'`\n : `stated at ${finding.layer} but its population spans ${nodeLayer} '${node}'`,\n node,\n )\n }\n const path = finding.scope.domain_path\n if (path) {\n const expected = domainPathOf(taxonomy, node)\n if (path.length !== expected.length || path.some((id, index) => id !== expected[index])) {\n return unplaced(`domain_path ${JSON.stringify(path)} disagrees with the taxonomy`, node)\n }\n }\n return { finding, claimId: finding.claim_id, node }\n}\n\ntype GroupVerdict = { lift: true; voters: Placement[] } | { lift: false; reason: string }\n\nfunction judgeGroup(\n members: readonly Placement[],\n k: number,\n roots: ReadonlyMap<string, string>,\n): GroupVerdict {\n const voters = members.filter((member) => member.finding.measure?.interval !== undefined)\n if (voters.length === 0) return { lift: false, reason: 'no child carries an interval' }\n const first = voters[0]!.finding.measure!\n if (\n voters.some(\n ({ finding }) => finding.measure!.name !== first.name || finding.measure!.unit !== first.unit,\n )\n ) {\n return { lift: false, reason: 'children measure different quantities' }\n }\n const lo = Math.max(...voters.map(({ finding }) => finding.measure!.interval![0]))\n const hi = Math.min(...voters.map(({ finding }) => finding.measure!.interval![1]))\n if (lo > hi) return { lift: false, reason: 'child intervals do not agree' }\n\n const independent = independentChildren(voters, roots)\n if (independent < k) {\n const children = new Set(voters.map((voter) => voter.node)).size\n return {\n lift: false,\n reason:\n children > independent\n ? `${children} children agree but share lineage, leaving ${independent} independent of ${k} required`\n : `${independent} independent agreeing child${independent === 1 ? '' : 'ren'} of ${k} required`,\n }\n }\n return { lift: true, voters }\n}\n\n/**\n * Children joined when they share a lineage root, counted as components. A\n * child's roots are those of all its voters' evidence units; a voter with no\n * units has unknown lineage.\n */\nfunction independentChildren(\n voters: readonly Placement[],\n roots: ReadonlyMap<string, string>,\n): number {\n const rootsByNode = new Map<string, Set<string>>()\n for (const voter of voters) {\n const set = rootsByNode.get(voter.node) ?? new Set<string>()\n const units = voter.finding.evidence_units\n if (!units) set.add(UNKNOWN_LINEAGE)\n else for (const unit of units) set.add(roots.get(unit.id) ?? UNKNOWN_LINEAGE)\n rootsByNode.set(voter.node, set)\n }\n const parent = new Map<string, string>()\n const find = (id: string): string => {\n let current = id\n while (parent.get(current) !== current) current = parent.get(current)!\n return current\n }\n const owner = new Map<string, string>()\n for (const [node, nodeRoots] of rootsByNode) {\n parent.set(node, node)\n for (const root of nodeRoots) {\n const other = owner.get(root)\n if (other === undefined) owner.set(root, node)\n else parent.set(find(node), find(other))\n }\n }\n return new Set([...rootsByNode.keys()].map(find)).size\n}\n\nfunction liftedFinding(\n voters: readonly Placement[],\n parent: string,\n taxonomy: DomainTaxonomy,\n producedAt: string | undefined,\n): AnalystFinding {\n const findings = voters.map((voter) => voter.finding)\n const first = findings[0]!\n const measures = findings.map((finding) => finding.measure!) as FindingMeasure[]\n const levels = new Set(measures.map((measure) => measure.level))\n const level = levels.size === 1 ? measures[0]!.level : undefined\n const population = [...new Set(findings.flatMap((finding) => finding.scope!.population))].sort()\n const allUnits = findings.every((finding) => finding.evidence_units !== undefined)\n ? mergeEvidenceUnits(findings.flatMap((finding) => finding.evidence_units!))\n : undefined\n const confounders = [...new Set(findings.flatMap((finding) => finding.confounders ?? []))].sort()\n const analysts = new Set(findings.map((finding) => finding.analyst_id))\n const domainPath = domainPathOf(taxonomy, parent)\n const parentLayer = taxonomyLayerOf(taxonomy, parent) as FindingLayer\n return makeFinding({\n analyst_id: analysts.size === 1 ? first.analyst_id : PROMOTE_ANALYST_ID,\n area: first.area,\n claim: first.claim,\n claim_id: first.claim_id!,\n id_basis: `${first.claim_id}@${parent}`,\n ...mergeFindingComposition(findings),\n subject: parent,\n severity: mostSevere(findings),\n confidence: Math.min(...findings.map((finding) => finding.confidence)),\n evidence_refs: findings.map((finding) => ({\n kind: 'finding' as const,\n uri: `finding://${finding.finding_id}`,\n })),\n layer: parentLayer,\n scope: {\n population,\n n: population.length,\n window: spanningWindow(findings),\n ...(domainPath.length > 0 && parent !== LAB_NODE_ID ? { domain_path: domainPath } : {}),\n },\n method: { kind: 'computed', name: 'promote', version: PROMOTE_VERSION },\n measure: {\n name: measures[0]!.name,\n unit: measures[0]!.unit,\n value: measures.reduce((sum, measure) => sum + measure.value, 0) / measures.length,\n interval: [\n Math.max(...measures.map((measure) => measure.interval![0])),\n Math.min(...measures.map((measure) => measure.interval![1])),\n ],\n ...(level === undefined ? {} : { level }),\n },\n ...(confounders.length > 0 ? { confounders } : {}),\n ...(allUnits ? { evidence_units: allUnits } : {}),\n rationale: `Lifted to ${parentLayer} '${parent}': ${new Set(voters.map((voter) => voter.node)).size} children carry claim '${first.claim_id}' with intervals that share [${Math.max(...measures.map((m) => m.interval![0]))}, ${Math.min(...measures.map((m) => m.interval![1]))}].`,\n metadata: {\n taxonomy_version: taxonomy.version,\n promoted_from: [...new Set(voters.map((voter) => voter.node))].sort(),\n },\n ...(producedAt === undefined ? {} : { produced_at: producedAt }),\n })\n}\n","import {\n assertConsistentFindingConditions,\n findingCompositionKey,\n mergeFindingComposition,\n} from './finding-composition'\n/**\n * rollup — run findings aggregated up the ladder, with bootstrap intervals and\n * denominators, lifted only where `promote` allows.\n *\n * Run-layer findings that share a `claim_id` and a measure are pooled per play\n * into one play-layer finding. Its interval is a cluster bootstrap where each\n * cluster is a lineage root, so runs that built on each other move together\n * and four runs of one lineage yield one cluster and no interval. Those play\n * findings then go through `promote`; each finding it lifts to a problem,\n * domain node or the lab gets the pooled bootstrap over every run underneath\n * it, with its observation and cluster counts.\n */\n\nimport { clusterBootstrapMean } from '../meta-eval/cluster-bootstrap'\nimport {\n type DomainTaxonomy,\n domainPathOf,\n lowestCommonAncestor,\n taxonomyLayerOf,\n taxonomyParentOf,\n} from './domain-taxonomy'\nimport {\n lineageRoots,\n mergeEvidenceUnits,\n mostSevere,\n spanningWindow,\n UNKNOWN_LINEAGE,\n} from './finding-scope'\nimport { type PromotionHold, promote } from './promote'\nimport { type AnalystFinding, makeFinding } from './types'\n\nconst ROLLUP_ANALYST_ID = 'rollup'\nconst ROLLUP_VERSION = '1'\n\nexport interface RollupOptions {\n /** Independent agreeing children `promote` requires. Default 2. */\n k?: number\n /** Bootstrap seed; absent, the seed derives from the values, so reruns match. */\n seed?: number\n resamples?: number\n /** Interval confidence. Default 0.95. */\n confidence?: number\n produced_at?: string\n}\n\nexport interface RollupResult {\n /** Play aggregates followed by every finding promote lifted from them. */\n findings: AnalystFinding[]\n untestedAbove: PromotionHold[]\n /** Input findings rollup could not use, and why. */\n skipped: PromotionHold[]\n}\n\ninterface Observation {\n finding: AnalystFinding\n claimId: string\n run: string\n value: number\n cluster: string\n}\n\nexport function rollupFindings(\n findings: readonly AnalystFinding[],\n taxonomy: DomainTaxonomy,\n options: RollupOptions = {},\n): RollupResult {\n assertConsistentFindingConditions(findings)\n const confidence = options.confidence ?? 0.95\n const skipped: PromotionHold[] = []\n const skip = (finding: AnalystFinding, reason: string): void => {\n skipped.push({\n finding_id: finding.finding_id,\n claim_id: finding.claim_id ?? null,\n node: null,\n reason,\n })\n }\n const roots = lineageRoots(findings.flatMap((finding) => finding.evidence_units ?? []))\n const observations: Observation[] = []\n for (const finding of findings) {\n if (finding.layer !== 'run' || !finding.scope) continue\n if (!finding.claim_id) {\n skip(finding, 'no claim_id')\n continue\n }\n if (!finding.measure) {\n skip(finding, 'no measure to aggregate')\n continue\n }\n const run = lowestCommonAncestor(taxonomy, finding.scope.population)\n if (run === undefined || taxonomyLayerOf(taxonomy, run) !== 'run') {\n skip(finding, 'population is not one run in the taxonomy')\n continue\n }\n const units = finding.evidence_units\n const runRoots = new Set(\n units ? units.map((unit) => roots.get(unit.id) ?? UNKNOWN_LINEAGE) : [UNKNOWN_LINEAGE],\n )\n observations.push({\n finding,\n claimId: finding.claim_id,\n run,\n value: finding.measure.value,\n // A run whose units reach several roots is clustered on the first; one\n // run is one observation either way.\n cluster: [...runRoots].sort()[0]!,\n })\n }\n\n const groups = new Map<string, { play: string; members: Observation[] }>()\n for (const observation of observations) {\n const play = taxonomyParentOf(taxonomy, observation.run)!\n const key = JSON.stringify([\n observation.claimId,\n play,\n findingCompositionKey(observation.finding),\n ])\n const group = groups.get(key) ?? { play, members: [] }\n group.members.push(observation)\n groups.set(key, group)\n }\n const aggregates: AnalystFinding[] = []\n for (const { play, members } of groups.values()) {\n const measure = members[0]!.finding.measure!\n if (\n members.some(\n ({ finding }) =>\n finding.measure!.name !== measure.name || finding.measure!.unit !== measure.unit,\n )\n ) {\n for (const member of members)\n skip(member.finding, `runs of play '${play}' measure different quantities`)\n continue\n }\n const pooled = pool(members, options, confidence)\n const findingsInGroup = members.map((member) => member.finding)\n const population = [...new Set(members.map((member) => member.run))].sort()\n const units = findingsInGroup.every((finding) => finding.evidence_units !== undefined)\n ? mergeEvidenceUnits(findingsInGroup.flatMap((finding) => finding.evidence_units!))\n : undefined\n const domainPath = domainPathOf(taxonomy, play)\n const first = findingsInGroup[0]!\n aggregates.push(\n makeFinding({\n analyst_id: ROLLUP_ANALYST_ID,\n area: first.area,\n claim: first.claim,\n claim_id: first.claim_id!,\n id_basis: `${first.claim_id}@${play}`,\n ...mergeFindingComposition(findingsInGroup),\n subject: play,\n severity: mostSevere(findingsInGroup),\n confidence: Math.min(...findingsInGroup.map((finding) => finding.confidence)),\n evidence_refs: findingsInGroup.map((finding) => ({\n kind: 'finding' as const,\n uri: `finding://${finding.finding_id}`,\n })),\n layer: 'play',\n scope: {\n population,\n n: population.length,\n window: spanningWindow(findingsInGroup),\n ...(domainPath.length > 0 ? { domain_path: domainPath } : {}),\n },\n method: { kind: 'computed', name: ROLLUP_ANALYST_ID, version: ROLLUP_VERSION },\n measure: { name: measure.name, unit: measure.unit, ...pooled.measure },\n ...(units ? { evidence_units: units } : {}),\n metadata: { denominators: pooled.denominators },\n ...(options.produced_at === undefined ? {} : { produced_at: options.produced_at }),\n }),\n )\n }\n\n const promotion = promote(aggregates, taxonomy, {\n ...(options.k === undefined ? {} : { k: options.k }),\n ...(options.produced_at === undefined ? {} : { produced_at: options.produced_at }),\n })\n const promoted = promotion.promoted.map((finding) => {\n const covered = new Set(finding.scope!.population)\n const members = observations.filter(\n (observation) =>\n observation.claimId === finding.claim_id &&\n covered.has(observation.run) &&\n findingCompositionKey(observation.finding) === findingCompositionKey(finding),\n )\n const pooled = pool(members, options, confidence)\n return {\n ...finding,\n measure: { name: finding.measure!.name, unit: finding.measure!.unit, ...pooled.measure },\n metadata: { ...finding.metadata, denominators: pooled.denominators },\n }\n })\n return {\n findings: [...aggregates, ...promoted],\n untestedAbove: promotion.untestedAbove,\n skipped: [...skipped, ...promotion.unplaced],\n }\n}\n\n/**\n * Cluster bootstrap of the run values. With one cluster there is no spread\n * between independent sources, so the measure carries no interval and cannot\n * vote in `promote`.\n */\nfunction pool(members: readonly Observation[], options: RollupOptions, confidence: number) {\n const result = clusterBootstrapMean(\n members.map((member) => ({ cluster: member.cluster, value: member.value })),\n {\n confidence,\n ...(options.seed === undefined ? {} : { seed: options.seed }),\n ...(options.resamples === undefined ? {} : { resamples: options.resamples }),\n },\n )\n return {\n measure:\n result.clusters >= 2\n ? {\n value: result.mean,\n interval: [result.low, result.high] as [number, number],\n level: confidence,\n }\n : { value: result.mean },\n denominators: { observations: result.n, independent_clusters: result.clusters },\n }\n}\n\nexport interface RollupInput {\n findings: readonly AnalystFinding[]\n taxonomy: DomainTaxonomy\n options?: RollupOptions\n}\n","/**\n * team-shape — classify how a supervision tree was organized, from a Runtime\n * spawn journal and its coordination log.\n *\n * Input rows come in either of two shapes, read by the same parser:\n * - Runtime envelopes, as `readRuntimeSupervisorRun` returns them in\n * `SupervisorRunSources.journal` and `.coordinationLog`\n * (`teamShapeInputFromSources`);\n * - the structure-only reduction under `tests/fixtures/team-shape`\n * (`extract.py`): spawn rows `{ kind, journal, id, at }`, coordination\n * rows `{ at, type, owner, toWorker?, from?, by?, delivered? }`.\n *\n * Three edge sets over the agents:\n * - E, command, parent → child. The parent is the child id minus its last\n * `:sN` segment (`R:s1:s0` is child `s0` of `R:s1`); the spawn journal has\n * no parent field. An id outside that path is an unplaced agent: its E\n * edge is not observable, and it is never read as depth 1.\n * - G, governance, receiver → child: the agent whose journal holds the\n * child's `settled` row, plus the sender of each `steer`.\n * - C, communication, sender → receiver: coordination rows that name a\n * receiver (`toWorker`). The sender is `from`/`by` when the row names an\n * agent, else the log owner's digest, which no record joins to an agent.\n * `instruction` and `delivery-attempt` rows are the queue and transport\n * stages of the steer row that follows them, so they are not counted.\n *\n * Classes, version 1, checked in order; the first the record shows wins:\n * 1. single — one agent.\n * 2. governed-swarm — E runs between peers, or a team's governor\n * changes over the run.\n * 3. fleet — one dispatcher, and governance from a non-parent\n * agent inside the team or lateral C ≥ 20%.\n * 4. partition — two or more lead subtrees with no C or G between\n * them, and no lead settles to the root.\n * 5. hive — depth ≥ 2 and at least half the root's children\n * delegate (`hive depth N`).\n * 6. star-with-sub-leads — depth ≥ 2, fewer than half delegate.\n * 7. flat-star — depth 1; qualified by root integration share.\n * The thresholds are provisional and travel in `method.version`. A check the\n * record cannot decide (an owner digest is not an agent id, so lateral C and\n * steer governance often are not) reads `not observable from this record`,\n * never `no`, and the classification moves on to the next class.\n */\n\nimport type { SupervisorRunSources } from '../supervisor-run/types'\nimport type { Analyst } from './types'\nimport { makeFinding } from './types'\n\nexport const TEAM_SHAPE_ANALYST_ID = 'team-shape'\n\nconst TEAM_SHAPE_THRESHOLDS = {\n /** Share of the root's children that delegate at or above which depth ≥ 2 is a hive. */\n hiveDelegatingShare: 0.5,\n /** Lateral share of C edges at or above which a one-dispatcher team is a fleet. */\n fleetLateralCShare: 0.2,\n /** Root share of integrating commits at or above which a flat star reads `root integrates`. */\n rootIntegrationShare: 0.5,\n} as const\n\n/** Version 1, provisional, with the thresholds it was decided at. */\nexport const TEAM_SHAPE_VERSION = `1-provisional;hive-delegating=${TEAM_SHAPE_THRESHOLDS.hiveDelegatingShare};fleet-lateral-c=${TEAM_SHAPE_THRESHOLDS.fleetLateralCShare};root-integration=${TEAM_SHAPE_THRESHOLDS.rootIntegrationShare}`\n\nexport const TEAM_SHAPE_CLASSES = [\n 'single',\n 'governed-swarm',\n 'fleet',\n 'partition',\n 'hive',\n 'star-with-sub-leads',\n 'flat-star',\n] as const\n\nexport type TeamShapeClass = (typeof TEAM_SHAPE_CLASSES)[number]\n\nexport const NOT_OBSERVABLE = 'not observable from this record'\nexport type NotObservable = typeof NOT_OBSERVABLE\nexport type TeamShapeObserved<T> = T | NotObservable\n\nexport interface TeamIntegration {\n commit: string\n /** Agent id, in the record's id space, that authored the integrating commit. */\n by: string\n}\n\nexport interface TeamShapeInput {\n /** The run the record came from, cited as the finding's evidence. */\n runRef: string\n /** Spawn journal JSONL. */\n spawnJournal: string\n /** Coordination log JSONL; null or absent when the run kept none. */\n coordinationLog?: string | null\n /** The release's integrating commits; disco derives them from commit trailers. */\n integrations?: readonly TeamIntegration[]\n}\n\nexport interface TeamShapeEdge {\n from: string\n to: string\n count: number\n}\n\nexport interface TeamShapeFeatures {\n agents: number\n /** Agents other than the root. */\n tasks: number\n /** Agents whose id is outside the root's `:sN` path; their E edge is not observable. */\n unplacedAgents: number\n depth: number\n fanOut: { root: number; max: number }\n /** Root's children that delegate ÷ root's children; null when the root has none. */\n delegatingShare: number | null\n /** Spawns after the first settlement. */\n reHires: number\n settlementsByReceiver: Record<string, number>\n steers: { sent: number; delivered: number }\n /** Coordination messages per task; null with no tasks or no coordination log. */\n messagesPerTask: number | null\n /** Lateral C edges ÷ C edges. */\n lateralCShare: TeamShapeObserved<number>\n /** G edges from a non-parent agent ÷ G edges. */\n nonParentGShare: TeamShapeObserved<number>\n /** Root-authored integrating commits ÷ integrating commits. */\n rootIntegrationShare: TeamShapeObserved<number>\n}\n\nexport interface TeamShapeCheck {\n result: 'yes' | 'no' | NotObservable\n reason: string\n}\n\nexport interface TeamShape {\n class: TeamShapeClass\n depth: number\n /** Only a flat star carries one: `root integrates`, `root does not integrate` or `integration unknown`. */\n qualifier: string | null\n /** Class in words: `hive depth 2`, `flat-star (integration unknown)`. */\n label: string\n rootId: string\n features: TeamShapeFeatures\n /** Every class's rule against this record, in check order. */\n checks: Record<TeamShapeClass, TeamShapeCheck>\n graph: { command: TeamShapeEdge[]; governance: TeamShapeEdge[]; communication: TeamShapeEdge[] }\n invalidRows: { spawn: number; coordination: number }\n window: { from: string; to: string } | null\n}\n\nexport type TeamShapeOutcome =\n | { succeeded: true; value: TeamShape }\n | { succeeded: false; error: { message: string } }\n\ninterface SpawnRow {\n kind: 'spawned' | 'settled'\n /** Agent whose journal holds the row: the last segment of the journal key. */\n owner: string\n /** The whole journal key, to find the root marker. */\n journal: string\n id: string\n at: number\n}\n\ninterface CoordinationRow {\n at: number | null\n type: string\n owner: string | null\n toWorker?: string\n from?: string\n by?: string\n delivered?: boolean\n}\n\n/** Team-shape input for a run read through a supervisor-run reader. */\nexport function teamShapeInputFromSources(\n sources: SupervisorRunSources,\n integrations?: readonly TeamIntegration[],\n): { succeeded: true; value: TeamShapeInput } | { succeeded: false; error: { message: string } } {\n if (sources.journal === null) {\n return {\n succeeded: false,\n error: { message: sources.journalMissingReason ?? `no spawn journal for ${sources.runRef}` },\n }\n }\n return {\n succeeded: true,\n value: {\n runRef: sources.runRef,\n spawnJournal: sources.journal,\n coordinationLog: sources.coordinationLog ?? null,\n ...(integrations === undefined ? {} : { integrations }),\n },\n }\n}\n\nexport function classifyTeamShape(input: TeamShapeInput): TeamShapeOutcome {\n const spawnLog = parseSpawnRows(input.spawnJournal)\n const coordination =\n typeof input.coordinationLog === 'string' ? parseCoordinationRows(input.coordinationLog) : null\n const spawnedAt = new Map<string, number>()\n for (const row of spawnLog.rows) {\n if (row.kind !== 'spawned') continue\n spawnedAt.set(row.id, Math.min(row.at, spawnedAt.get(row.id) ?? Number.POSITIVE_INFINITY))\n }\n const rootIds = [\n ...new Set(\n spawnLog.rows\n .filter((row) => row.kind === 'spawned' && row.journal === row.id)\n .map((r) => r.id),\n ),\n ]\n if (rootIds.length !== 1) {\n return {\n succeeded: false,\n error: {\n message: `spawn journal for ${input.runRef} has ${rootIds.length} root markers; team-shape needs exactly one`,\n },\n }\n }\n const rootId = rootIds[0]!\n const agents = new Set(spawnedAt.keys())\n\n // E: the id path. A parent outside the record leaves the agent unplaced.\n const parentOf = new Map<string, string>()\n let unplacedAgents = 0\n for (const id of agents) {\n if (id === rootId) continue\n const parent = pathParent(id)\n if (parent !== null && agents.has(parent) && id.startsWith(`${rootId}:`)) {\n parentOf.set(id, parent)\n } else unplacedAgents += 1\n }\n const children = new Map<string, string[]>()\n const command = new Map<string, TeamShapeEdge>()\n for (const [child, parent] of parentOf) {\n children.set(parent, [...(children.get(parent) ?? []), child])\n addEdge(command, parent, child)\n }\n const depthOf = (id: string): number => {\n let hops = 0\n for (let at = parentOf.get(id); at !== undefined; at = parentOf.get(at)) hops += 1\n return hops\n }\n const depth = Math.max(0, ...[...parentOf.keys()].map(depthOf))\n const rootChildren = children.get(rootId) ?? []\n const leads = rootChildren.filter((child) => (children.get(child)?.length ?? 0) > 0)\n const delegatingShare = rootChildren.length === 0 ? null : leads.length / rootChildren.length\n const subtreeOf = (id: string): string | null => {\n let at: string | undefined = id\n while (at !== undefined && parentOf.get(at) !== rootId) at = parentOf.get(at)\n return at ?? null\n }\n\n // A spawn row in a journal that belongs to neither the parent nor the child itself.\n let peerSpawns = 0\n for (const row of spawnLog.rows) {\n if (row.kind !== 'spawned' || row.id === rootId) continue\n if (row.owner !== row.id && row.owner !== parentOf.get(row.id)) peerSpawns += 1\n }\n\n // G: settlements, receiver → child.\n const governance = new Map<string, TeamShapeEdge>()\n const settlementsByReceiver: Record<string, number> = {}\n const governorsByParent = new Map<string, { agents: Set<string>; digests: Set<string> }>()\n const governorsOf = (child: string) => {\n const parent = parentOf.get(child) ?? `unplaced:${child}`\n const entry = governorsByParent.get(parent) ?? { agents: new Set(), digests: new Set() }\n governorsByParent.set(parent, entry)\n return entry\n }\n let gResolved = 0\n let gUnresolved = 0\n let gNonParent = 0\n let firstSettlement = Number.POSITIVE_INFINITY\n for (const row of spawnLog.rows) {\n if (row.kind !== 'settled' || row.owner === row.id) continue\n firstSettlement = Math.min(firstSettlement, row.at)\n settlementsByReceiver[row.owner] = (settlementsByReceiver[row.owner] ?? 0) + 1\n addEdge(governance, row.owner, row.id)\n governorsOf(row.id).agents.add(row.owner)\n gResolved += 1\n if (parentOf.get(row.id) !== row.owner) gNonParent += 1\n }\n const reHires = [...spawnedAt.entries()].filter(\n ([id, at]) => id !== rootId && at > firstSettlement,\n ).length\n\n // C, and G from steers.\n const communication = new Map<string, TeamShapeEdge>()\n let messages = 0\n let cResolved = 0\n let cUnresolved = 0\n let cLateral = 0\n let cCrossSubtree = 0\n let gCrossSubtree = 0\n const steers = { sent: 0, delivered: 0 }\n const isAgent = (value: string | undefined): value is string =>\n value !== undefined && agents.has(value)\n for (const row of coordination?.rows ?? []) {\n if (row.type === 'instruction' || row.type === 'delivery-attempt') continue\n if (row.toWorker === undefined && row.from === undefined && row.by === undefined) continue\n messages += 1\n if (row.type === 'steer') {\n steers.sent += 1\n if (row.delivered === true) steers.delivered += 1\n }\n // A refused steer reached nobody: it is counted as sent, not as an edge.\n if (!isAgent(row.toWorker) || row.delivered === false) continue\n const receiver = row.toWorker\n const agentSender = [row.from, row.by].find(isAgent)\n const sender = agentSender ?? (row.owner === null ? null : `owner:${row.owner}`)\n if (sender === null) continue\n addEdge(communication, sender, receiver)\n if (agentSender === undefined) cUnresolved += 1\n else {\n cResolved += 1\n const parent = parentOf.get(receiver)\n if (parent !== undefined && parent === parentOf.get(agentSender)) cLateral += 1\n if (crosses(subtreeOf(agentSender), subtreeOf(receiver))) cCrossSubtree += 1\n }\n if (row.type === 'steer') {\n addEdge(governance, sender, receiver)\n if (agentSender === undefined) {\n gUnresolved += 1\n governorsOf(receiver).digests.add(sender)\n } else {\n gResolved += 1\n governorsOf(receiver).agents.add(agentSender)\n if (parentOf.get(receiver) !== agentSender) gNonParent += 1\n if (crosses(subtreeOf(agentSender), subtreeOf(receiver))) gCrossSubtree += 1\n }\n }\n }\n for (const [child, receiver] of spawnLog.rows\n .filter((row) => row.kind === 'settled' && row.owner !== row.id)\n .map((row) => [row.id, row.owner] as const)) {\n if (crosses(subtreeOf(receiver), subtreeOf(child))) gCrossSubtree += 1\n }\n\n const cTotal = cResolved + cUnresolved\n const gTotal = gResolved + gUnresolved\n const lateralCShare: TeamShapeObserved<number> =\n coordination === null || cTotal === 0 || cUnresolved > 0 ? NOT_OBSERVABLE : cLateral / cTotal\n const nonParentGShare: TeamShapeObserved<number> =\n gTotal === 0 || gUnresolved > 0 ? NOT_OBSERVABLE : gNonParent / gTotal\n const integrations = input.integrations ?? []\n const rootIntegrationShare: TeamShapeObserved<number> =\n integrations.length === 0\n ? NOT_OBSERVABLE\n : integrations.filter((row) => row.by === rootId).length / integrations.length\n\n const features: TeamShapeFeatures = {\n agents: agents.size,\n tasks: agents.size - 1,\n unplacedAgents,\n depth,\n fanOut: {\n root: rootChildren.length,\n max: Math.max(0, ...[...children.values()].map((c) => c.length)),\n },\n delegatingShare,\n reHires,\n settlementsByReceiver,\n steers,\n messagesPerTask: coordination === null || agents.size < 2 ? null : messages / (agents.size - 1),\n lateralCShare,\n nonParentGShare,\n rootIntegrationShare,\n }\n\n const checks = {} as Record<TeamShapeClass, TeamShapeCheck>\n checks.single = verdict(agents.size === 1, `${agents.size} agents`)\n\n const rotating = [...governorsByParent.entries()].find(([, g]) => g.agents.size > 1)\n const digestTeams = [...governorsByParent.values()].filter((g) => g.digests.size > 1).length\n checks['governed-swarm'] =\n peerSpawns > 0\n ? { result: 'yes', reason: `${peerSpawns} spawns recorded by a peer, not the parent` }\n : rotating !== undefined\n ? {\n result: 'yes',\n reason: `children of ${rotating[0]} are governed by ${[...rotating[1].agents].join(', ')}`,\n }\n : digestTeams > 0\n ? {\n result: NOT_OBSERVABLE,\n reason: `${digestTeams} teams were steered by more than one owner digest; a digest is not an agent id, so a rotating governor cannot be told from the operator`,\n }\n : {\n result: 'no',\n reason: 'every E edge runs parent to child and no team changed governor',\n }\n\n const dispatchers = [...children.keys()]\n if (dispatchers.length !== 1 || unplacedAgents > 0) {\n checks.fleet = {\n result: unplacedAgents > 0 && dispatchers.length <= 1 ? NOT_OBSERVABLE : 'no',\n reason:\n unplacedAgents > 0 && dispatchers.length <= 1\n ? `${unplacedAgents} unplaced agents hide who dispatched their work`\n : `${dispatchers.length} agents dispatch work`,\n }\n } else if (gNonParent > 0) {\n checks.fleet = { result: 'yes', reason: `${gNonParent} G edges come from a non-parent agent` }\n } else if (cLateral / Math.max(cTotal, 1) >= TEAM_SHAPE_THRESHOLDS.fleetLateralCShare) {\n checks.fleet = { result: 'yes', reason: `lateral C ${cLateral} of ${cTotal}` }\n } else if (gUnresolved > 0 || lateralCShare === NOT_OBSERVABLE) {\n checks.fleet = {\n result: NOT_OBSERVABLE,\n reason: `one dispatcher; ${gUnresolved} steer G and ${cUnresolved} C edges are sent from owner digests that no record joins to an agent${coordination === null ? ', and the run has no coordination log' : ''}`,\n }\n } else {\n checks.fleet = verdict(\n false,\n `one dispatcher, no non-parent G, lateral C ${cLateral} of ${cTotal}`,\n )\n }\n\n const rootSettledByLeads = spawnLog.rows.filter(\n (row) => row.kind === 'settled' && row.owner === rootId && leads.includes(row.id),\n ).length\n if (leads.length < 2 || rootSettledByLeads > 0 || gCrossSubtree > 0 || cCrossSubtree > 0) {\n checks.partition = verdict(\n false,\n `${leads.length} lead subtrees, ${rootSettledByLeads} lead settlements to the root, ${gCrossSubtree + cCrossSubtree} edges between subtrees`,\n )\n } else if (gUnresolved > 0 || cUnresolved > 0 || coordination === null) {\n checks.partition = {\n result: NOT_OBSERVABLE,\n reason: `${leads.length} lead subtrees and no lead settles to the root, but edges sent from owner digests cannot be placed in a subtree`,\n }\n } else {\n checks.partition = verdict(true, `${leads.length} lead subtrees with no C or G between them`)\n }\n\n const delegating = `${leads.length} of ${rootChildren.length} root children delegate`\n const hive = depth >= 2 && (delegatingShare ?? 0) >= TEAM_SHAPE_THRESHOLDS.hiveDelegatingShare\n checks.hive = verdict(hive, `depth ${depth}; ${delegating}`)\n checks['star-with-sub-leads'] = verdict(depth >= 2 && !hive, `depth ${depth}; ${delegating}`)\n checks['flat-star'] = verdict(depth === 1, `depth ${depth}`)\n\n const shapeClass = TEAM_SHAPE_CLASSES.find((name) => checks[name].result === 'yes')\n if (shapeClass === undefined) {\n return {\n succeeded: false,\n error: { message: `no team-shape class matches ${input.runRef} (depth ${depth})` },\n }\n }\n const qualifier =\n shapeClass !== 'flat-star'\n ? null\n : rootIntegrationShare === NOT_OBSERVABLE\n ? 'integration unknown'\n : rootIntegrationShare >= TEAM_SHAPE_THRESHOLDS.rootIntegrationShare\n ? 'root integrates'\n : 'root does not integrate'\n const label =\n shapeClass === 'hive'\n ? `hive depth ${depth}`\n : qualifier === null\n ? shapeClass\n : `${shapeClass} (${qualifier})`\n\n const times = [\n ...spawnLog.rows.map((row) => row.at),\n ...(coordination?.rows ?? []).flatMap((row) => (row.at === null ? [] : [row.at])),\n ]\n return {\n succeeded: true,\n value: {\n class: shapeClass,\n depth,\n qualifier,\n label,\n rootId,\n features,\n checks,\n graph: {\n command: [...command.values()],\n governance: [...governance.values()],\n communication: [...communication.values()],\n },\n invalidRows: { spawn: spawnLog.invalid, coordination: coordination?.invalid ?? 0 },\n window:\n times.length === 0\n ? null\n : {\n from: new Date(Math.min(...times)).toISOString(),\n to: new Date(Math.max(...times)).toISOString(),\n },\n },\n }\n}\n\nfunction verdict(holds: boolean, reason: string): TeamShapeCheck {\n return { result: holds ? 'yes' : 'no', reason }\n}\n\nfunction crosses(a: string | null, b: string | null): boolean {\n return a !== null && b !== null && a !== b\n}\n\nfunction pathParent(id: string): string | null {\n const match = /^(.+):s\\d+$/.exec(id)\n return match ? match[1]! : null\n}\n\nfunction addEdge(edges: Map<string, TeamShapeEdge>, from: string, to: string): void {\n const key = JSON.stringify([from, to])\n const edge = edges.get(key)\n if (edge) edge.count += 1\n else edges.set(key, { from, to, count: 1 })\n}\n\nfunction jsonLines(text: string): Array<Record<string, unknown> | null> {\n return text\n .split('\\n')\n .filter((line) => line.trim())\n .map((line) => {\n try {\n const value: unknown = JSON.parse(line)\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null\n } catch {\n return null\n }\n })\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null\n}\n\nfunction epochMs(value: unknown): number | null {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string') {\n const ms = Date.parse(value)\n return Number.isNaN(ms) ? null : ms\n }\n return null\n}\n\n/**\n * Spawned and settled rows from a Runtime envelope (`{ root, event }`) or a\n * reduced row (`{ kind, journal, id, at }`). Other Runtime event kinds are\n * read and skipped; a spawned or settled row without an id, journal or time\n * is invalid.\n */\nfunction parseSpawnRows(text: string): { rows: SpawnRow[]; invalid: number } {\n const rows: SpawnRow[] = []\n let invalid = 0\n for (const line of jsonLines(text)) {\n if (line === null) {\n invalid += 1\n continue\n }\n const event = asRecord(line.event) ?? line\n const journal = event === line ? line.journal : line.root\n const { kind, id } = event\n if (kind !== 'spawned' && kind !== 'settled') continue\n const at = epochMs(event.at)\n if (typeof id !== 'string' || typeof journal !== 'string' || at === null) {\n invalid += 1\n continue\n }\n rows.push({ kind, journal, owner: journal.slice(journal.lastIndexOf('/') + 1), id, at })\n }\n return { rows, invalid }\n}\n\n/**\n * Coordination rows from a Runtime record (`{ at, ownerId, event: { type,\n * <body> } }`, endpoints inside the event's one object-valued field) or a\n * reduced row (`{ at, type, owner, ... }`).\n */\nfunction parseCoordinationRows(text: string): { rows: CoordinationRow[]; invalid: number } {\n const rows: CoordinationRow[] = []\n let invalid = 0\n for (const line of jsonLines(text)) {\n const event = line === null ? null : (asRecord(line.event) ?? line)\n if (line === null || event === null || typeof event.type !== 'string') {\n invalid += 1\n continue\n }\n const body =\n event === line\n ? line\n : (Object.entries(event)\n .filter(([key]) => key !== 'type')\n .map(([, value]) => asRecord(value))\n .find((value) => value !== null) ?? {})\n const owner = typeof line.owner === 'string' ? line.owner : line.ownerId\n const row: CoordinationRow = {\n at: epochMs(line.at),\n type: event.type,\n owner: typeof owner === 'string' && owner ? owner : null,\n }\n for (const key of ['toWorker', 'from', 'by'] as const) {\n const value = body[key]\n if (typeof value === 'string') row[key] = value\n }\n const delivered = body.delivered ?? line.delivered\n if (typeof delivered === 'boolean') row.delivered = delivered\n rows.push(row)\n }\n return { rows, invalid }\n}\n\n/**\n * The team-shape analyst: one `team`-layer finding per run naming its class,\n * with the features and every class check in metadata. A record with no\n * timestamps fails the analyst instead of emitting a shape it did not measure.\n */\nexport function teamShapeAnalyst(): Analyst<TeamShapeInput> {\n return {\n id: TEAM_SHAPE_ANALYST_ID,\n description:\n 'Classifies a supervision tree as single, governed swarm, fleet, partition, hive, star with sub-leads or flat star.',\n inputKind: 'custom',\n cost: { kind: 'deterministic' },\n version: TEAM_SHAPE_VERSION,\n async analyze(input) {\n const outcome = classifyTeamShape(input)\n if (!outcome.succeeded) throw new Error(`team-shape: ${outcome.error.message}`)\n const shape = outcome.value\n if (shape.window === null) {\n throw new Error(`team-shape: record for ${input.runRef} carries no event timestamps`)\n }\n return [\n makeFinding({\n analyst_id: TEAM_SHAPE_ANALYST_ID,\n area: 'team-shape',\n severity: 'info',\n confidence: 1,\n subject: shape.rootId,\n claim: `Team shape is ${shape.label}`,\n claim_id: `team-shape:${shape.class}`,\n evidence_refs: [{ kind: 'artifact', uri: input.runRef }],\n layer: 'team',\n scope: { population: [input.runRef], n: 1, window: shape.window },\n method: { kind: 'computed', name: TEAM_SHAPE_ANALYST_ID, version: TEAM_SHAPE_VERSION },\n metadata: {\n class: shape.class,\n depth: shape.depth,\n qualifier: shape.qualifier,\n features: shape.features,\n checks: shape.checks,\n edges: {\n command: shape.graph.command.length,\n governance: shape.graph.governance.length,\n communication: shape.graph.communication.length,\n },\n invalid_rows: shape.invalidRows,\n },\n }),\n ]\n },\n }\n}\n","/**\n * Many questions over one trace store, concurrently, under one cost ledger, with an independent\n * verifier for every finding.\n *\n * `traces ask` answered questions this way for people. A continuation panel (agent-runtime,\n * discovery `docs/38-one-loop-and-continuation.md`, section 5) asks dozens to hundreds of atomic\n * questions of a director's own trace every time the outside check fails, so the runner lives here,\n * beside `runTraceAnalyst`, where both callers reach one implementation.\n *\n * Each question is one `runTraceAnalyst` call, which already refuses a finding with fewer distinct\n * citations than required or with a citation the store cannot resolve. What this module adds:\n *\n * - a worker pool: at most `concurrency` investigations at once, and one failed question never\n * stops the others; its failure is its answer;\n * - one shared `CostLedger`, so a single ceiling bounds every question and every verifier;\n * - an independent verifier per admitted finding, shown only the spans the finding cites. Analysts\n * misattribute often: the best method in Who&When found the failing step 14.2% of the time. A\n * finding a verifier reading only its own evidence does not support never reaches a caller as\n * verified.\n */\n\nimport type { CostLedgerHandle } from '../cost-ledger'\nimport type { TraceAnalysisStore } from '../trace-analyst/store'\nimport { defineTraceAnalyst } from './define'\nimport type { TraceAnalysisEngine, TraceAnalystLimits } from './engine'\nimport { parseTraceSpanEvidenceUri, type RawAnalystFinding } from './finding-signature'\nimport { runTraceAnalyst } from './kind-factory'\n\n/** One question to ask of the store. */\nexport interface TraceQuestionSpec {\n /** Stable id: letters, digits, dot, underscore, hyphen. */\n readonly id: string\n readonly question: string\n /** Guidance for this question only, after the shared rules. */\n readonly instructions?: string\n}\n\nexport interface AskTraceQuestionsOptions {\n readonly questions: readonly TraceQuestionSpec[]\n readonly store: TraceAnalysisStore\n readonly engine: TraceAnalysisEngine\n /** Every question and verifier charges this ledger; its ceiling bounds the whole call. */\n readonly costLedger: CostLedgerHandle\n /** Stable id for cost attribution and logs. */\n readonly runId: string\n /** Material every question receives before its first model call, such as the check's verdict. */\n readonly context?: string\n /** Investigations running at once. Default 4. */\n readonly concurrency?: number\n /** Distinct citations a finding needs. Default 2. */\n readonly minimumEvidenceCitations?: number\n /** Run the independent verifier on every admitted finding. Default true. */\n readonly verify?: boolean\n readonly limits?: Partial<TraceAnalystLimits>\n readonly signal?: AbortSignal\n readonly log?: (message: string, fields?: Record<string, unknown>) => void\n}\n\n/** A finding and what the verifier, shown only its cited spans, concluded. */\nexport interface VerifiedTraceFinding {\n readonly finding: RawAnalystFinding\n /** The finding's trace citations, as `trace://` URIs. */\n readonly citations: readonly string[]\n /** `true` supported, `false` not supported, `null` when verification was off or failed. */\n readonly verified: boolean | null\n /** The verifier's own words, when it answered. */\n readonly verifierAnswer?: string\n}\n\nexport interface TraceQuestionOutcome {\n readonly id: string\n readonly question: string\n readonly status: 'answered' | 'failed'\n readonly failure?: string\n /** The engine's prose answer, verbatim; `null` when it returned none. */\n readonly answer: string | null\n readonly findings: readonly VerifiedTraceFinding[]\n /** `null` when the engine failed before reporting. */\n readonly modelCalls: number | null\n readonly toolCalls: number | null\n}\n\nconst QUESTION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u\nconst DEFINITION_VERSION = '1.0.0'\n\nconst QUESTION_RULES = [\n 'Answer QUESTION only from trace tool results retrieved in this run.',\n 'Cite each fact as trace://<trace_id>/span/<span_id>, and quote the span in the excerpt.',\n 'If the trace does not record a fact, say \"not in trace\". Never infer a trace fact from the question.',\n].join('\\n')\n\nconst VERIFIER_RULES = [\n 'You check one CLAIM against the spans it cites, and nothing else.',\n 'Read each cited span with viewSpans. No other trace is readable.',\n 'First line: SUPPORTED if the spans themselves establish the claim, otherwise NOT SUPPORTED.',\n 'Second line: one sentence naming the span that decides it.',\n 'Return no findings.',\n].join('\\n')\n\n/**\n * Ask every question, then verify every admitted finding. Never throws for a failed question or\n * verifier: each failure is recorded on its outcome. Throws before any model call for a malformed\n * question list or options.\n */\nexport async function askTraceQuestions(\n opts: AskTraceQuestionsOptions,\n): Promise<TraceQuestionOutcome[]> {\n const concurrency = opts.concurrency ?? 4\n if (!Number.isSafeInteger(concurrency) || concurrency < 1) {\n throw new RangeError('askTraceQuestions: concurrency must be an integer >= 1')\n }\n const minimum = opts.minimumEvidenceCitations ?? 2\n if (!Number.isSafeInteger(minimum) || minimum < 1) {\n throw new RangeError('askTraceQuestions: minimumEvidenceCitations must be an integer >= 1')\n }\n const seen = new Set<string>()\n for (const question of opts.questions) {\n if (!QUESTION_ID.test(question.id)) {\n throw new TypeError(\n `askTraceQuestions: question id ${JSON.stringify(question.id)} is malformed`,\n )\n }\n if (seen.has(question.id)) {\n throw new TypeError(`askTraceQuestions: duplicate question id ${JSON.stringify(question.id)}`)\n }\n seen.add(question.id)\n if (question.question.trim() === '') {\n throw new TypeError(`askTraceQuestions: question ${question.id} is empty`)\n }\n }\n\n const askOne = async (question: TraceQuestionSpec): Promise<TraceQuestionOutcome> => {\n if (opts.signal?.aborted) {\n return failed(question, 'the run was aborted before the question started')\n }\n let completed: Awaited<ReturnType<typeof runTraceAnalyst>>\n try {\n completed = await runTraceAnalyst({\n definition: defineTraceAnalyst({\n id: `question.${question.id}`,\n description: `trace question ${question.id}`,\n area: 'question',\n version: DEFINITION_VERSION,\n question: question.question.trim(),\n instructions: [QUESTION_RULES, question.instructions?.trim() ?? '']\n .filter(Boolean)\n .join('\\n\\n'),\n toolGroup: 'all',\n minimumEvidenceCitations: minimum,\n ...(opts.context ? { prepareContext: () => opts.context } : {}),\n ...(opts.limits ? { limits: opts.limits } : {}),\n }),\n engine: opts.engine,\n store: opts.store,\n context: {\n runId: opts.runId,\n correlationId: `${opts.runId}:${question.id}`,\n costLedger: opts.costLedger,\n costPhase: 'trace-question',\n ...(opts.signal ? { signal: opts.signal } : {}),\n ...(opts.log ? { log: opts.log } : {}),\n },\n })\n } catch (error) {\n return failed(question, errorText(error))\n }\n const findings: VerifiedTraceFinding[] = []\n for (const [index, finding] of completed.findings.entries()) {\n const citations = finding.evidence\n .map((citation) => citation.uri.trim())\n .filter((uri) => parseTraceSpanEvidenceUri(uri) !== null)\n findings.push(\n opts.verify === false\n ? { finding, citations, verified: null }\n : await verifyFinding(opts, `${question.id}.v${index + 1}`, finding, citations),\n )\n }\n const answer = completed.answer.trim() === '' ? null : completed.answer\n return {\n id: question.id,\n question: question.question,\n status: 'answered',\n answer,\n findings,\n modelCalls: completed.modelCalls,\n toolCalls: completed.toolCalls,\n }\n }\n\n // A pool, not Promise.all: at most `concurrency` engines exist at once.\n const outcomes = new Array<TraceQuestionOutcome>(opts.questions.length)\n let next = 0\n await Promise.all(\n Array.from({ length: Math.min(concurrency, opts.questions.length) }, async () => {\n while (next < opts.questions.length) {\n const index = next\n next += 1\n const question = opts.questions[index] as TraceQuestionSpec\n outcomes[index] = await askOne(question)\n }\n }),\n )\n return outcomes\n}\n\n/** The verifier reads only the spans the finding cites, through a store that holds nothing else. */\nasync function verifyFinding(\n opts: AskTraceQuestionsOptions,\n id: string,\n finding: RawAnalystFinding,\n citations: readonly string[],\n): Promise<VerifiedTraceFinding> {\n const allowed = new Map<string, Set<string>>()\n for (const uri of citations) {\n const location = parseTraceSpanEvidenceUri(uri)\n if (location === null) continue\n const spans = allowed.get(location.traceId) ?? new Set<string>()\n spans.add(location.spanId)\n allowed.set(location.traceId, spans)\n }\n if (allowed.size === 0) return { finding, citations, verified: false }\n try {\n const verdict = await runTraceAnalyst({\n definition: defineTraceAnalyst({\n id: `verify.${id}`,\n description: `independent check of finding ${id}`,\n area: 'question',\n version: DEFINITION_VERSION,\n question: `CLAIM: ${finding.claim}\\nCITED SPANS: ${citations.join(', ')}`,\n instructions: VERIFIER_RULES,\n toolGroup: 'targeted',\n ...(opts.limits ? { limits: opts.limits } : {}),\n }),\n engine: opts.engine,\n store: citedSpansOnly(opts.store, allowed),\n context: {\n runId: opts.runId,\n correlationId: `${opts.runId}:verify:${id}`,\n costLedger: opts.costLedger,\n costPhase: 'trace-question-verifier',\n ...(opts.signal ? { signal: opts.signal } : {}),\n ...(opts.log ? { log: opts.log } : {}),\n },\n })\n const first = verdict.answer.trim().split('\\n')[0]?.trim().toUpperCase() ?? ''\n return {\n finding,\n citations,\n verified: first.startsWith('SUPPORTED'),\n verifierAnswer: verdict.answer.trim(),\n }\n } catch (error) {\n opts.log?.('verifier failed', { finding: id, error: errorText(error) })\n return { finding, citations, verified: null }\n }\n}\n\n/**\n * A store that exposes exactly the cited spans. Discovery and whole-trace reads refuse, so the\n * verifier cannot go looking for other support; the underlying store's bounds still apply.\n */\nfunction citedSpansOnly(\n store: TraceAnalysisStore,\n allowed: ReadonlyMap<string, ReadonlySet<string>>,\n): TraceAnalysisStore {\n const refuse = (what: string) => async (): Promise<never> => {\n throw new Error(`${what} is not available to a verifier: read the cited spans with viewSpans`)\n }\n return {\n hasTrace: async (traceId) => allowed.has(traceId),\n hasSpans: async (input, context) => {\n const spans = allowed.get(input.trace_id)\n if (spans === undefined) return []\n return store.hasSpans(\n { trace_id: input.trace_id, span_ids: input.span_ids.filter((span) => spans.has(span)) },\n context,\n )\n },\n getOverview: refuse('getOverview'),\n queryTraces: refuse('queryTraces'),\n countTraces: refuse('countTraces'),\n viewTrace: refuse('viewTrace'),\n viewSpans: async (input, context) => {\n const spans = allowed.get(input.trace_id)\n const wanted = input.span_ids.filter((span) => spans?.has(span) === true)\n if (wanted.length === 0) {\n throw new Error('viewSpans: only the cited spans are readable')\n }\n return store.viewSpans({ ...input, span_ids: wanted }, context)\n },\n searchTrace: refuse('searchTrace'),\n searchSpan: async (input, context) => {\n if (allowed.get(input.trace_id)?.has(input.span_id) !== true) {\n throw new Error('searchSpan: only the cited spans are readable')\n }\n return store.searchSpan(input, context)\n },\n }\n}\n\nfunction failed(question: TraceQuestionSpec, failure: string): TraceQuestionOutcome {\n return {\n id: question.id,\n question: question.question,\n status: 'failed',\n failure,\n answer: null,\n findings: [],\n modelCalls: null,\n toolCalls: null,\n }\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? `${error.name}: ${error.message}` : String(error)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA4FA,MAAMA,aAAW,EAAE,OAAO,CAAC,CAAC,OAAO,qBAAqB;AACxD,MAAM,aAAa,EAAE,KACnB,OAAO,KAAK,0BAA0B,CAIxC;AACA,MAAM,SAAS,EAAE,KAAK;CAAC;CAAO;CAAM;AAAQ,CAAC;AAC7C,MAAM,aAAa,EAChB,OAAO;CACN;CACA,UAAUA;CACV,OAAO,OAAO,SAAS;CACvB,QAAQ,EAAE,KAAK,CAAC,SAAS,SAAS,CAAC;AACrC,CAAC,CAAC,CACD,OAAO;AACV,MAAM,mBAAmB,EACtB,OAAO;CACN;CACA,UAAUA;CACV,SAASA,WAAS,SAAS;CAC3B,QAAQ,OAAO,SAAS;CACxB,eAAe,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS;CAC7E,gBAAgB,EAAE,OAAO,CAAC,CAAC,SAAS;CAC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