@tangle-network/agent-eval 1.0.39 → 2.0.0
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 +75 -0
- package/dist/adapters/http.d.ts +2 -2
- package/dist/{agent-profile-BKgR30kv.d.ts → agent-profile-BSgtn-k-.d.ts} +247 -168
- package/dist/agent-profile-BSgtn-k-.d.ts.map +1 -0
- package/dist/{agent-profile-DgbRJpSi.js → agent-profile-CCw6EXWW.js} +2 -2
- package/dist/{agent-profile-DgbRJpSi.js.map → agent-profile-CCw6EXWW.js.map} +1 -1
- package/dist/{agent-profile-cell-7Mt0wBkl.js → agent-profile-cell-CUthydZB.js} +2 -2
- package/dist/{agent-profile-cell-7Mt0wBkl.js.map → agent-profile-cell-CUthydZB.js.map} +1 -1
- package/dist/analyst/index.d.ts +13 -13
- package/dist/analyst/index.d.ts.map +1 -1
- package/dist/analyst/index.js +15 -15
- package/dist/analyst/index.js.map +1 -1
- package/dist/{analyze-runs-DqHx3Q_g.js → analyze-runs-C_9cXPZn.js} +9 -9
- package/dist/{analyze-runs-DqHx3Q_g.js.map → analyze-runs-C_9cXPZn.js.map} +1 -1
- package/dist/{analyze-runs-Ctuz-dd3.d.ts → analyze-runs-zEI7yAH_.d.ts} +2 -2
- package/dist/{analyze-runs-Ctuz-dd3.d.ts.map → analyze-runs-zEI7yAH_.d.ts.map} +1 -1
- package/dist/app-grade/index.d.ts +3 -3
- package/dist/app-grade/index.js +3 -3
- package/dist/authenticity/index.d.ts.map +1 -1
- package/dist/authenticity/index.js.map +1 -1
- package/dist/{benchmark-command-BpmrrgzA.js → benchmark-command-XLXa7I98.js} +14 -13
- package/dist/benchmark-command-XLXa7I98.js.map +1 -0
- package/dist/benchmarks/index.d.ts +8 -4
- package/dist/benchmarks/index.d.ts.map +1 -1
- package/dist/benchmarks/index.js +11 -6
- package/dist/benchmarks/index.js.map +1 -1
- package/dist/builder-eval/index.d.ts +1 -1
- package/dist/builder-eval/index.js +3 -3
- package/dist/{calibration-BBhY1QM6.js → calibration-Cfoup0xz.js} +3 -3
- package/dist/{calibration-BBhY1QM6.js.map → calibration-Cfoup0xz.js.map} +1 -1
- package/dist/campaign/index.d.ts +9 -9
- package/dist/campaign/index.js +16 -15
- package/dist/{campaign-UzOUBIwA.js → campaign-BlmkAwFD.js} +23 -23
- package/dist/campaign-BlmkAwFD.js.map +1 -0
- package/dist/{statistical-heldout-RmdXoz2e.d.ts → campaign-evidence-BVKG5o32.d.ts} +418 -418
- package/dist/campaign-evidence-BVKG5o32.d.ts.map +1 -0
- package/dist/{campaign-evidence-BX8OveG5.js → campaign-evidence-CsUE_lwc.js} +79 -26
- package/dist/campaign-evidence-CsUE_lwc.js.map +1 -0
- package/dist/{canonical-gLeHiqzd.d.ts → canonical-CGXS21f_.d.ts} +8 -5
- package/dist/{canonical-gLeHiqzd.d.ts.map → canonical-CGXS21f_.d.ts.map} +1 -1
- package/dist/{canonical-BANK6NOj.js → canonical-DKgL_Wby.js} +30 -8
- package/dist/canonical-DKgL_Wby.js.map +1 -0
- package/dist/{chat-client-DmPB31_2.js → chat-client-DqAXFLi-.js} +2 -2
- package/dist/{chat-client-DmPB31_2.js.map → chat-client-DqAXFLi-.js.map} +1 -1
- package/dist/{chat-json-call-Rfhu7JbJ.js → chat-json-call-CB6sQ6sv.js} +2 -2
- package/dist/{chat-json-call-Rfhu7JbJ.js.map → chat-json-call-CB6sQ6sv.js.map} +1 -1
- package/dist/{claim-C6LRiwz1.js → claim-BWEXwwBk.js} +2 -2
- package/dist/{claim-C6LRiwz1.js.map → claim-BWEXwwBk.js.map} +1 -1
- package/dist/cli.js +11 -11
- package/dist/{client-BIFwUg7I.d.ts → client-DUMIaMob.d.ts} +2 -2
- package/dist/{client-BIFwUg7I.d.ts.map → client-DUMIaMob.d.ts.map} +1 -1
- package/dist/cluster-CSd0LE_M.d.ts.map +1 -1
- package/dist/{cluster-bootstrap-ClPYIWoX.js → cluster-bootstrap-DPzVy3_K.js} +2 -2
- package/dist/{cluster-bootstrap-ClPYIWoX.js.map → cluster-bootstrap-DPzVy3_K.js.map} +1 -1
- package/dist/{completion-verifier-C3q1T96h.js → completion-verifier-DiG3y43g.js} +6 -6
- package/dist/{completion-verifier-C3q1T96h.js.map → completion-verifier-DiG3y43g.js.map} +1 -1
- package/dist/containment-order-GCJ-y_FV.js +56 -0
- package/dist/containment-order-GCJ-y_FV.js.map +1 -0
- package/dist/contract/index.d.ts +11 -11
- package/dist/contract/index.js +16 -16
- package/dist/contract/index.js.map +1 -1
- package/dist/cost-ledger-1CwUnVOd.js.map +1 -1
- package/dist/{decision-point-BN1YQNqk.js → decision-point-gt5JgqZ0.js} +8 -8
- package/dist/{decision-point-BN1YQNqk.js.map → decision-point-gt5JgqZ0.js.map} +1 -1
- package/dist/{default-registry-C5x2jyD6.d.ts → default-registry-DH_tl-V1.d.ts} +7 -7
- package/dist/{default-registry-C5x2jyD6.d.ts.map → default-registry-DH_tl-V1.d.ts.map} +1 -1
- package/dist/{default-registry-DSo3tnsW.js → default-registry-Y9AaKLmG.js} +8 -8
- package/dist/default-registry-Y9AaKLmG.js.map +1 -0
- package/dist/{define-agent-eval-4KGwzIVt.d.ts → define-agent-eval-BDxV_ONM.d.ts} +18 -10
- package/dist/define-agent-eval-BDxV_ONM.d.ts.map +1 -0
- package/dist/{define-agent-eval-C6zFzxp7.js → define-agent-eval-Cq-bdF4O.js} +16 -13
- package/dist/define-agent-eval-Cq-bdF4O.js.map +1 -0
- package/dist/diagnosis/index.d.ts +3 -3
- package/dist/diagnosis/index.d.ts.map +1 -1
- package/dist/diagnosis/index.js +1 -1
- package/dist/diagnosis/index.js.map +1 -1
- package/dist/{dspy-rlm-engine-EC-Pkdf-.js → dspy-rlm-engine-CHpTzYvZ.js} +4 -3
- package/dist/dspy-rlm-engine-CHpTzYvZ.js.map +1 -0
- package/dist/{emitter-DhQ65mza.js → emitter-BjW3NnX-.js} +15 -6
- package/dist/emitter-BjW3NnX-.js.map +1 -0
- package/dist/{emitter-mAXC5PSN.d.ts → emitter-Cw8ijO3v.d.ts} +4 -4
- package/dist/{emitter-mAXC5PSN.d.ts.map → emitter-Cw8ijO3v.d.ts.map} +1 -1
- package/dist/{engine-B2w3ARpj.d.ts → engine-3y87jnX0.d.ts} +2 -2
- package/dist/{engine-B2w3ARpj.d.ts.map → engine-3y87jnX0.d.ts.map} +1 -1
- package/dist/errors-DeEEV9Vx.js.map +1 -1
- package/dist/{eval-campaign-CWWh-1p1.js → eval-campaign-Cyk-tkLh.js} +5 -5
- package/dist/{eval-campaign-CWWh-1p1.js.map → eval-campaign-Cyk-tkLh.js.map} +1 -1
- package/dist/{evaluation-CQ-uAbqF.d.ts → evaluation-RODuDmCe.d.ts} +4 -4
- package/dist/{evaluation-CQ-uAbqF.d.ts.map → evaluation-RODuDmCe.d.ts.map} +1 -1
- package/dist/evaluation.d.ts +1 -1
- package/dist/{exact-types-B0_jA3V7.d.ts → exact-types-C4Rug7fG.d.ts} +2 -2
- package/dist/{exact-types-B0_jA3V7.d.ts.map → exact-types-C4Rug7fG.d.ts.map} +1 -1
- package/dist/{execution-insight-9No6Si55.d.ts → execution-insight-iOsr1Zi8.d.ts} +2 -2
- package/dist/{execution-insight-9No6Si55.d.ts.map → execution-insight-iOsr1Zi8.d.ts.map} +1 -1
- package/dist/experiment/index.d.ts +4 -4
- package/dist/experiment/index.d.ts.map +1 -1
- package/dist/experiment/index.js +10 -10
- package/dist/experiment/index.js.map +1 -1
- package/dist/{exporters-C9AwGDDK.js → exporters-CKFtnWmX.js} +2 -2
- package/dist/{exporters-C9AwGDDK.js.map → exporters-CKFtnWmX.js.map} +1 -1
- package/dist/external-optimizer-contracts-eKQTutGZ.js +123 -0
- package/dist/external-optimizer-contracts-eKQTutGZ.js.map +1 -0
- package/dist/{external-optimizer-process-DFEPdWJY.js → external-optimizer-process-CkAc1xBa.js} +22 -26
- package/dist/external-optimizer-process-CkAc1xBa.js.map +1 -0
- package/dist/{external-optimizer-subprocess-BspZ0bZb.js → external-optimizer-subprocess-B48Ie4qQ.js} +10 -124
- package/dist/external-optimizer-subprocess-B48Ie4qQ.js.map +1 -0
- package/dist/extract-usage-ISFqhfDz.js.map +1 -1
- package/dist/{feedback-trajectory-FamLu3Wt.d.ts → feedback-trajectory-B5hTr9w5.d.ts} +4 -4
- package/dist/{feedback-trajectory-FamLu3Wt.d.ts.map → feedback-trajectory-B5hTr9w5.d.ts.map} +1 -1
- package/dist/{finding-composition-BMgspnVI.js → finding-composition-CyWSTcAY.js} +2 -2
- package/dist/{finding-composition-BMgspnVI.js.map → finding-composition-CyWSTcAY.js.map} +1 -1
- package/dist/{findings-store-71J302Ls.js → findings-store-Rx9ZJgHV.js} +6 -6
- package/dist/{findings-store-71J302Ls.js.map → findings-store-Rx9ZJgHV.js.map} +1 -1
- package/dist/fuzz.d.ts.map +1 -1
- package/dist/fuzz.js +1 -1
- package/dist/fuzz.js.map +1 -1
- package/dist/{harness-session-lines-Fd5aeSDV.js → harness-session-lines-CSxKR6no.js} +3 -3
- package/dist/{harness-session-lines-Fd5aeSDV.js.map → harness-session-lines-CSxKR6no.js.map} +1 -1
- package/dist/{hf-dataset-kthWy7xl.js → hf-dataset-B0s2ZAhQ.js} +4 -4
- package/dist/{hf-dataset-kthWy7xl.js.map → hf-dataset-B0s2ZAhQ.js.map} +1 -1
- package/dist/hosted/index.d.ts +2 -2
- package/dist/hosted/index.js +1 -1
- package/dist/{index-BsTGJf2M.d.ts → index-BJTUL2Ff.d.ts} +42 -30
- package/dist/index-BJTUL2Ff.d.ts.map +1 -0
- package/dist/{index-Bhc7H9e0.d.ts → index-CX8_WfqS.d.ts} +5 -5
- package/dist/{index-Bhc7H9e0.d.ts.map → index-CX8_WfqS.d.ts.map} +1 -1
- package/dist/{index-DtW7KhyE.d.ts → index-D-nKkzsI.d.ts} +3 -3
- package/dist/{index-DtW7KhyE.d.ts.map → index-D-nKkzsI.d.ts.map} +1 -1
- package/dist/{index-RBV2Y-7X.d.ts → index-D1NRaf5U.d.ts} +7 -7
- package/dist/{index-RBV2Y-7X.d.ts.map → index-D1NRaf5U.d.ts.map} +1 -1
- package/dist/{index-Bcy00QoN.d.ts → index-DcGHcBpR.d.ts} +86 -86
- package/dist/index-DcGHcBpR.d.ts.map +1 -0
- package/dist/{index-CzEGCOWM.d.ts → index-FLyheOVA.d.ts} +9 -9
- package/dist/index-FLyheOVA.d.ts.map +1 -0
- package/dist/{index-lRKqfyg4.d.ts → index-qy6buL6y.d.ts} +2 -2
- package/dist/{index-lRKqfyg4.d.ts.map → index-qy6buL6y.d.ts.map} +1 -1
- package/dist/index.d.ts +31 -31
- package/dist/index.js +41 -41
- package/dist/index.js.map +1 -1
- package/dist/{integrity-BSs9dgKW.js → integrity-BF0tJK21.js} +3 -3
- package/dist/{integrity-BSs9dgKW.js.map → integrity-BF0tJK21.js.map} +1 -1
- package/dist/{journal-DQsbHGjX.js → journal-3y-btqaP.js} +2 -2
- package/dist/{journal-DQsbHGjX.js.map → journal-3y-btqaP.js.map} +1 -1
- package/dist/journal-file-AekB57Er.js.map +1 -1
- package/dist/{json-recovery-b7O9WVTF.js → json-recovery-BRUCeQxo.js} +2 -2
- package/dist/{json-recovery-b7O9WVTF.js.map → json-recovery-BRUCeQxo.js.map} +1 -1
- package/dist/{judge-gate-LbmZU-pA.js → judge-gate-TBv2jeO0.js} +3 -3
- package/dist/{judge-gate-LbmZU-pA.js.map → judge-gate-TBv2jeO0.js.map} +1 -1
- package/dist/{kind-factory-BTUq1Byh.js → kind-factory-DfNsTe-q.js} +22 -4
- package/dist/kind-factory-DfNsTe-q.js.map +1 -0
- package/dist/ledger-core/index.d.ts +2 -2
- package/dist/ledger-core/index.js +3 -3
- package/dist/{ledger-core-7e6sXmhV.js → ledger-core-auznoaD7.js} +3 -3
- package/dist/ledger-core-auznoaD7.js.map +1 -0
- package/dist/{llm-client-CdHo3SH0.js → llm-client-gRPgIJyz.js} +2 -2
- package/dist/{llm-client-CdHo3SH0.js.map → llm-client-gRPgIJyz.js.map} +1 -1
- package/dist/{llm-judge-lUQCBY1e.js → llm-judge-CThv1Rog.js} +197 -66
- package/dist/llm-judge-CThv1Rog.js.map +1 -0
- package/dist/{matrix-BKzNwIWb.d.ts → matrix-CfJ5vhfq.d.ts} +2 -2
- package/dist/{matrix-BKzNwIWb.d.ts.map → matrix-CfJ5vhfq.d.ts.map} +1 -1
- package/dist/meta-eval/index.d.ts +1 -1
- package/dist/meta-eval/index.js +9 -9
- package/dist/{mint-VN-qtJTc.js → mint-B4n1pRRd.js} +12 -6
- package/dist/mint-B4n1pRRd.js.map +1 -0
- package/dist/{model-comparison-BZr_Hu00.js → model-comparison-CgnVh4Ph.js} +3 -3
- package/dist/{model-comparison-BZr_Hu00.js.map → model-comparison-CgnVh4Ph.js.map} +1 -1
- 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/multishot/index.js.map +1 -1
- package/dist/openapi.json +1 -1
- package/dist/{outcome-observations-YFFmdGGW.js → outcome-observations-DL3CC8w1.js} +2 -2
- package/dist/{outcome-observations-YFFmdGGW.js.map → outcome-observations-DL3CC8w1.js.map} +1 -1
- package/dist/{paired-arms-DH376s4-.js → paired-arms-DZhH3FGu.js} +3 -3
- package/dist/{paired-arms-DH376s4-.js.map → paired-arms-DZhH3FGu.js.map} +1 -1
- package/dist/{paired-promotion-decision-BoWHWL1i.js → paired-promotion-decision-Dn3-jaq4.js} +2 -2
- package/dist/{paired-promotion-decision-BoWHWL1i.js.map → paired-promotion-decision-Dn3-jaq4.js.map} +1 -1
- package/dist/{paired-promotion-decision-BBSxTo-h.d.ts → paired-promotion-decision-Il-Nv-n4.d.ts} +2 -2
- package/dist/{paired-promotion-decision-BBSxTo-h.d.ts.map → paired-promotion-decision-Il-Nv-n4.d.ts.map} +1 -1
- package/dist/{paired-promotion-power-BXH3gzvs.js → paired-promotion-power-BlzXdgMD.js} +3 -3
- package/dist/{paired-promotion-power-BXH3gzvs.js.map → paired-promotion-power-BlzXdgMD.js.map} +1 -1
- package/dist/{pareto-BNWWbLNl.js → pareto-Bg75Gajo.js} +7 -7
- package/dist/{pareto-BNWWbLNl.js.map → pareto-Bg75Gajo.js.map} +1 -1
- package/dist/pipelines/index.d.ts +3 -3
- package/dist/pipelines/index.d.ts.map +1 -1
- package/dist/pipelines/index.js +19 -33
- package/dist/pipelines/index.js.map +1 -1
- package/dist/{prime-protocol-BR0xy0cF.d.ts → prime-protocol-CdNaCQy5.d.ts} +2 -2
- package/dist/{prime-protocol-BR0xy0cF.d.ts.map → prime-protocol-CdNaCQy5.d.ts.map} +1 -1
- package/dist/profile-cell.js +1 -1
- package/dist/{promotion-gate-XiTqW22r.d.ts → promotion-gate-DKAvMFlS.d.ts} +2 -2
- package/dist/{promotion-gate-XiTqW22r.d.ts.map → promotion-gate-DKAvMFlS.d.ts.map} +1 -1
- package/dist/{promotion-policy-CfgRPGx0.js → promotion-policy-CxDIh-9p.js} +4 -4
- package/dist/{promotion-policy-CfgRPGx0.js.map → promotion-policy-CxDIh-9p.js.map} +1 -1
- package/dist/{proposal-findings-DFQvA-k5.js → proposal-findings-DnR7zdUc.js} +2 -2
- package/dist/{proposal-findings-DFQvA-k5.js.map → proposal-findings-DnR7zdUc.js.map} +1 -1
- package/dist/{query-Ck6KhcDo.js → query-Dhjkwqyx.js} +2 -2
- package/dist/{query-Ck6KhcDo.js.map → query-Dhjkwqyx.js.map} +1 -1
- package/dist/{registry-D23oO0_f.d.ts → registry-LqAf_laP.d.ts} +3 -3
- package/dist/{registry-D23oO0_f.d.ts.map → registry-LqAf_laP.d.ts.map} +1 -1
- package/dist/{release-confidence-BdidB0mG.js → release-confidence-BLHOMK5Q.js} +3 -3
- package/dist/{release-confidence-BdidB0mG.js.map → release-confidence-BLHOMK5Q.js.map} +1 -1
- package/dist/reporting.d.ts +4 -4
- package/dist/reporting.js +5 -5
- package/dist/{research-report-BGKsOqkF.d.ts → research-report-BauFJiqu.d.ts} +2 -2
- package/dist/{research-report-BGKsOqkF.d.ts.map → research-report-BauFJiqu.d.ts.map} +1 -1
- package/dist/{researcher-k925Q6Jb.d.ts → researcher-B4e2Z92k.d.ts} +3 -3
- package/dist/{researcher-k925Q6Jb.d.ts.map → researcher-B4e2Z92k.d.ts.map} +1 -1
- package/dist/{reward-hacking-DNiHskry.js → reward-hacking-DKAflk2c.js} +2 -2
- package/dist/{reward-hacking-DNiHskry.js.map → reward-hacking-DKAflk2c.js.map} +1 -1
- package/dist/rl.d.ts +155 -39
- package/dist/rl.d.ts.map +1 -1
- package/dist/rl.js +420 -76
- package/dist/rl.js.map +1 -1
- package/dist/rollout/index.d.ts +4 -4
- package/dist/rollout/index.js +6 -6
- package/dist/{rollout-DDMkK_Lw.js → rollout-B6LlGRSq.js} +9 -9
- package/dist/rollout-B6LlGRSq.js.map +1 -0
- package/dist/{rollout-nodes-DzmHlPAC.js → rollout-nodes-Vas6OSxX.js} +2 -2
- package/dist/{rollout-nodes-DzmHlPAC.js.map → rollout-nodes-Vas6OSxX.js.map} +1 -1
- package/dist/{rubric-predictive-validity-Cln7r56F.js → rubric-predictive-validity--6z0q8s6.js} +2 -2
- package/dist/{rubric-predictive-validity-Cln7r56F.js.map → rubric-predictive-validity--6z0q8s6.js.map} +1 -1
- package/dist/{index-OvU1UXKC.d.ts → run-improvement-loop-B1OKCm2D.d.ts} +1682 -1640
- package/dist/run-improvement-loop-B1OKCm2D.d.ts.map +1 -0
- package/dist/{run-record-c860wUR8.js → run-record-Bqg0NZ_e.js} +19 -4
- package/dist/run-record-Bqg0NZ_e.js.map +1 -0
- package/dist/{run-record-Dx64nPcX.js → run-record-CqUft6Yf.js} +2 -2
- package/dist/{run-record-Dx64nPcX.js.map → run-record-CqUft6Yf.js.map} +1 -1
- package/dist/{runtime-rollouts-CALol_Y4.js → runtime-rollouts-DdUijr_t.js} +7 -7
- package/dist/runtime-rollouts-DdUijr_t.js.map +1 -0
- package/dist/{schema-BTTzvMnn.d.ts → schema-BfSoJjD-.d.ts} +5 -1
- package/dist/schema-BfSoJjD-.d.ts.map +1 -0
- package/dist/{schema-b18jtzZw.js → schema-Bh9CfSZT.js} +3 -1
- package/dist/schema-Bh9CfSZT.js.map +1 -0
- package/dist/schema-CkIvnmLU.d.ts.map +1 -1
- package/dist/schema-D-xu3MU_.js.map +1 -1
- package/dist/search/index.d.ts +3 -3
- package/dist/search/index.d.ts.map +1 -1
- package/dist/search/index.js +3 -3
- package/dist/{search-kernel-DRHWY35J.d.ts → search-kernel-CuTvZlPS.d.ts} +5 -5
- package/dist/{search-kernel-DRHWY35J.d.ts.map → search-kernel-CuTvZlPS.d.ts.map} +1 -1
- package/dist/{search-ledger-oyqxZhry.js → search-ledger-C7t68cmy.js} +7 -7
- package/dist/{search-ledger-oyqxZhry.js.map → search-ledger-C7t68cmy.js.map} +1 -1
- package/dist/{search-ledger-file-DoHCYYLt.js → search-ledger-file-QuIbgz6b.js} +2 -2
- package/dist/search-ledger-file-QuIbgz6b.js.map +1 -0
- package/dist/{search-ledger-types-qiYRUo_N.d.ts → search-ledger-types-BhZE848w.d.ts} +2 -2
- package/dist/{search-ledger-types-qiYRUo_N.d.ts.map → search-ledger-types-BhZE848w.d.ts.map} +1 -1
- package/dist/{search-shipper-BwqeQ61l.js → search-shipper-CmDW9dU6.js} +3 -3
- package/dist/{search-shipper-BwqeQ61l.js.map → search-shipper-CmDW9dU6.js.map} +1 -1
- package/dist/{search-summary-CNHpHFfw.js → search-summary-B1x1Vmzh.js} +5 -5
- package/dist/{search-summary-CNHpHFfw.js.map → search-summary-B1x1Vmzh.js.map} +1 -1
- package/dist/{sequential-93xxuiiG.js → sequential-BphITa5b.js} +4 -4
- package/dist/{sequential-93xxuiiG.js.map → sequential-BphITa5b.js.map} +1 -1
- package/dist/{sequential-B-zx24n_.d.ts → sequential-DqOJZO2V.d.ts} +2 -2
- package/dist/{sequential-B-zx24n_.d.ts.map → sequential-DqOJZO2V.d.ts.map} +1 -1
- package/dist/{sequential-C6k0Wrb7.js → sequential-ux_XrjBf.js} +3 -3
- package/dist/{sequential-C6k0Wrb7.js.map → sequential-ux_XrjBf.js.map} +1 -1
- package/dist/{served-model-qhLmbutL.js → served-model-BXmeKm7D.js} +2 -2
- package/dist/{served-model-qhLmbutL.js.map → served-model-BXmeKm7D.js.map} +1 -1
- package/dist/{server-DnoEi4Sb.js → server-BxHJyclG.js} +4 -4
- package/dist/{server-DnoEi4Sb.js.map → server-BxHJyclG.js.map} +1 -1
- package/dist/{skillopt-optimization-method-Dch9LiNR.js → skillopt-optimization-method-CHW9mphc.js} +397 -70
- package/dist/skillopt-optimization-method-CHW9mphc.js.map +1 -0
- package/dist/{statistical-heldout-BvcAVtof.js → statistical-heldout-CaS4T-43.js} +3 -3
- package/dist/{statistical-heldout-BvcAVtof.js.map → statistical-heldout-CaS4T-43.js.map} +1 -1
- package/dist/{statistics-CHs0jlsY.js → statistics-DSidA5I2.js} +184 -184
- package/dist/statistics-DSidA5I2.js.map +1 -0
- package/dist/statistics.d.ts +1 -1
- package/dist/statistics.js +1 -1
- package/dist/{store-otlp-DQK9hCtH.js → store-otlp-DCQTz9lS.js} +2 -2
- package/dist/{store-otlp-DQK9hCtH.js.map → store-otlp-DCQTz9lS.js.map} +1 -1
- package/dist/{store-tool-spans-C1lZKvvl.d.ts → store-tool-spans-B0UYrcl7.d.ts} +5 -5
- package/dist/{store-tool-spans-C1lZKvvl.d.ts.map → store-tool-spans-B0UYrcl7.d.ts.map} +1 -1
- package/dist/{store-tool-spans-BRR9hsPP.js → store-tool-spans-D2-S3OdE.js} +4 -4
- package/dist/{store-tool-spans-BRR9hsPP.js.map → store-tool-spans-D2-S3OdE.js.map} +1 -1
- package/dist/storyboard/index.d.ts.map +1 -1
- package/dist/storyboard/index.js.map +1 -1
- package/dist/{summary-report-CXiE1UrA.js → summary-report-CI4J6gxU.js} +4 -4
- package/dist/{summary-report-CXiE1UrA.js.map → summary-report-CI4J6gxU.js.map} +1 -1
- package/dist/supervisor-run/index.d.ts +2 -2
- package/dist/supervisor-run/index.d.ts.map +1 -1
- package/dist/supervisor-run/index.js +3 -3
- package/dist/{systemone-B_3Vd395.d.ts → systemone-nAN8fBy9.d.ts} +8 -8
- package/dist/{systemone-B_3Vd395.d.ts.map → systemone-nAN8fBy9.d.ts.map} +1 -1
- package/dist/systemone-protocol.js +1 -1
- package/dist/{systemone-review-ZAN-5m_2.d.ts → systemone-review-e2ElIpD_.d.ts} +3 -3
- package/dist/{systemone-review-ZAN-5m_2.d.ts.map → systemone-review-e2ElIpD_.d.ts.map} +1 -1
- package/dist/{systemone-review-CqNNZMiD.js → systemone-review-ir3Cbejl.js} +3 -3
- package/dist/{systemone-review-CqNNZMiD.js.map → systemone-review-ir3Cbejl.js.map} +1 -1
- package/dist/systemone.d.ts +3 -3
- package/dist/systemone.js +2 -2
- package/dist/{tool-groups-BOH1E-E4.d.ts → tool-groups-sRVCeevR.d.ts} +3 -3
- package/dist/tool-groups-sRVCeevR.d.ts.map +1 -0
- package/dist/tool-waste-CIhtU1ad.d.ts +217 -0
- package/dist/tool-waste-CIhtU1ad.d.ts.map +1 -0
- package/dist/{tool-waste-DzLI-JJg.js → tool-waste-u7JJ_BlE.js} +3 -3
- package/dist/{tool-waste-DzLI-JJg.js.map → tool-waste-u7JJ_BlE.js.map} +1 -1
- package/dist/{trace-questions-DBsrgY_H.d.ts → trace-questions-BN-LSfkA.d.ts} +3 -3
- package/dist/{trace-questions-DBsrgY_H.d.ts.map → trace-questions-BN-LSfkA.d.ts.map} +1 -1
- package/dist/trace-repair/index.d.ts +1 -1
- package/dist/trace-repair/index.d.ts.map +1 -1
- package/dist/trace-repair/index.js +4 -4
- package/dist/trace-repair/index.js.map +1 -1
- package/dist/traces.d.ts +4 -4
- package/dist/traces.js +6 -6
- package/dist/{training-admission-xaDOlQ_U.d.ts → training-admission-DGZCyntI.d.ts} +2 -2
- package/dist/{training-admission-xaDOlQ_U.d.ts.map → training-admission-DGZCyntI.d.ts.map} +1 -1
- package/dist/trajectory-CKVZaQoQ.js +144 -0
- package/dist/trajectory-CKVZaQoQ.js.map +1 -0
- package/dist/trajectory-replay/index.d.ts.map +1 -1
- package/dist/trajectory-replay/index.js +24 -11
- package/dist/trajectory-replay/index.js.map +1 -1
- package/dist/{tree-0r6gPODs.js → tree-DQMlcNFI.js} +18 -6
- package/dist/tree-DQMlcNFI.js.map +1 -0
- package/dist/{types-DmYd2Igl.d.ts → types-BJ27EWAS.d.ts} +8 -8
- package/dist/{types-DmYd2Igl.d.ts.map → types-BJ27EWAS.d.ts.map} +1 -1
- package/dist/{types-ClDpBoLt.d.ts → types-CDWfUYOq.d.ts} +2 -2
- package/dist/{types-ClDpBoLt.d.ts.map → types-CDWfUYOq.d.ts.map} +1 -1
- package/dist/{types-_dfu6Ox2.d.ts → types-DI7YKvDI.d.ts} +3 -3
- package/dist/{types-_dfu6Ox2.d.ts.map → types-DI7YKvDI.d.ts.map} +1 -1
- package/dist/{types-C8AyaiFi.js → types-_tlhWGUq.js} +2 -2
- package/dist/{types-C8AyaiFi.js.map → types-_tlhWGUq.js.map} +1 -1
- package/dist/{types-DGqGbNY4.d.ts → types-pMk2rgP9.d.ts} +20 -6
- package/dist/{types-DGqGbNY4.d.ts.map → types-pMk2rgP9.d.ts.map} +1 -1
- package/dist/{verdict-CKo1iZkI.js → verdict-5PVtsWT_.js} +2 -2
- package/dist/{verdict-CKo1iZkI.js.map → verdict-5PVtsWT_.js.map} +1 -1
- package/dist/{verdict-cache-DfzlHLdf.js → verdict-cache-BPaYxfG8.js} +2 -2
- package/dist/verdict-cache-BPaYxfG8.js.map +1 -0
- package/dist/wire/index.d.ts +3 -3
- package/dist/wire/index.js +1 -1
- package/docs/campaign-proposers.md +14 -1
- package/docs/public-api.md +323 -85
- package/docs/rollout.md +2 -2
- package/docs/search-ledger.md +14 -2
- package/docs/statistical-evidence.md +9 -3
- package/docs/trajectory-replay.md +4 -0
- package/package.json +1 -1
- package/dist/agent-profile-BKgR30kv.d.ts.map +0 -1
- package/dist/benchmark-command-BpmrrgzA.js.map +0 -1
- package/dist/campaign-UzOUBIwA.js.map +0 -1
- package/dist/campaign-evidence-BX8OveG5.js.map +0 -1
- package/dist/canonical-BANK6NOj.js.map +0 -1
- package/dist/default-registry-DSo3tnsW.js.map +0 -1
- package/dist/define-agent-eval-4KGwzIVt.d.ts.map +0 -1
- package/dist/define-agent-eval-C6zFzxp7.js.map +0 -1
- package/dist/dspy-rlm-engine-EC-Pkdf-.js.map +0 -1
- package/dist/emitter-DhQ65mza.js.map +0 -1
- package/dist/external-optimizer-process-DFEPdWJY.js.map +0 -1
- package/dist/external-optimizer-subprocess-BspZ0bZb.js.map +0 -1
- package/dist/index-Bcy00QoN.d.ts.map +0 -1
- package/dist/index-BsTGJf2M.d.ts.map +0 -1
- package/dist/index-CzEGCOWM.d.ts.map +0 -1
- package/dist/index-OvU1UXKC.d.ts.map +0 -1
- package/dist/kind-factory-BTUq1Byh.js.map +0 -1
- package/dist/ledger-core-7e6sXmhV.js.map +0 -1
- package/dist/llm-judge-lUQCBY1e.js.map +0 -1
- package/dist/mint-VN-qtJTc.js.map +0 -1
- package/dist/rollout-DDMkK_Lw.js.map +0 -1
- package/dist/run-record-c860wUR8.js.map +0 -1
- package/dist/runtime-rollouts-CALol_Y4.js.map +0 -1
- package/dist/schema-BTTzvMnn.d.ts.map +0 -1
- package/dist/schema-b18jtzZw.js.map +0 -1
- package/dist/search-ledger-file-DoHCYYLt.js.map +0 -1
- package/dist/skillopt-optimization-method-Dch9LiNR.js.map +0 -1
- package/dist/statistical-heldout-RmdXoz2e.d.ts.map +0 -1
- package/dist/statistics-CHs0jlsY.js.map +0 -1
- package/dist/tool-groups-BOH1E-E4.d.ts.map +0 -1
- package/dist/tool-waste-CUASoTtk.d.ts +0 -139
- package/dist/tool-waste-CUASoTtk.d.ts.map +0 -1
- package/dist/trajectory-O3GDHmev.js +0 -55
- package/dist/trajectory-O3GDHmev.js.map +0 -1
- package/dist/tree-0r6gPODs.js.map +0 -1
- package/dist/verdict-cache-DfzlHLdf.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"findings-store-71J302Ls.js","names":["messageOf"],"sources":["../src/analyst/chat-trace-engine.ts","../src/locked-jsonl-appender.ts","../src/analyst/findings-store.ts"],"sourcesContent":["/**\n * A `TraceAnalysisEngine` that runs entirely inside Node against a\n * caller-owned `ChatClient`.\n *\n * The other engine in this package, `createDspyRlmTraceEngine`, reaches the\n * DSPy RLM through a Python subprocess. That made every model-backed analyst\n * unreachable for a consumer that already owns a model seam and no Python:\n * `createTraceAnalyst` requires an engine, the only exported constructor\n * required a Python runner, so `buildDefaultAnalystRegistry()` registered the\n * deterministic analyst alone and `analystsFromRegistry` refused the result.\n *\n * This engine closes that path. It drives the same investigation contract —\n * bounded trace tools, a prose answer, a strict findings array — with native\n * function calls over the transport the caller already bound with\n * `createChatClient`. A caller holding a bare\n * `(request: LlmCallRequest) => Promise<LlmCallResult>` adapts it in one line:\n *\n * createChatClient({ transport: 'custom', chat: call, defaultModel, maximumAttempts })\n *\n * agent-eval still executes no paid model and holds no provider credential.\n * Every call goes through `paidChat`, so the shared cost ledger reserves the\n * priced maximum before the call and settles the receipt after it.\n *\n * Shape of one investigation:\n * 1. Investigation turns. The model reads the trace store through the tools\n * its analyst kind was given. A turn that requests no tool ends the\n * phase; an exhausted iteration or tool budget also ends it.\n * 2. One report turn. The model returns `{ answer, findings }` as JSON,\n * decoded by the same `decodeRawFindingArray` the Python bridge uses, so\n * a row this engine accepts is a row that engine could report.\n */\n\nimport { z } from 'zod'\nimport { paidChat } from '../chat-json-call'\nimport type { CustomTokenPricing } from '../cost-ledger'\nimport { errorMessage as messageOf } from '../errors'\nimport {\n extractJsonPayload,\n type LlmCallRequest,\n type LlmMessage,\n type LlmThinkingMode,\n type LlmToolCall,\n type LlmToolDefinition,\n} from '../llm-client'\nimport type { TraceAnalysisToolDescriptor } from '../trace-analyst/tools'\nimport type { ChatClient } from './chat-client'\nimport {\n DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS,\n type TraceAnalysisEngine,\n type TraceAnalysisEngineRequest,\n type TraceAnalysisEngineResult,\n} from './engine'\nimport { decodeRawFindingArray } from './finding-codec'\nimport { RawAnalystFindingSchema } from './finding-signature'\n\n/** Bumped whenever this engine's execution behavior changes. */\nconst CHAT_TRACE_ENGINE_VERSION = '1.0.0'\nconst ENGINE_ID = 'chat-trace'\n\n/** Marker appended to a tool result cut down to the retained-output budget. */\nconst TRUNCATION_MARKER = '\\n…[truncated to the analyst maxOutputChars budget]'\n\nexport interface ChatTraceEngineOptions {\n /**\n * Caller-owned transport. Build it with `createChatClient`; agent-eval never\n * receives the provider credential.\n */\n chat: ChatClient\n /** Model for every call. Defaults to the client's `defaultModel`. */\n model?: string\n /** Endpoint rates used when the transport reports no billed amount. */\n pricing?: CustomTokenPricing\n /** Completion cap per turn. Default: {@link DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS}. */\n maxOutputTokens?: number\n /** Sampling temperature. Omitted from the request when absent. */\n temperature?: number\n /** Provider reasoning mode. Omitted when the provider default should apply. */\n thinking?: LlmThinkingMode\n /** Per-call deadline handed to the transport. */\n requestTimeoutMs?: number\n /**\n * How the report turn asks for structured output.\n *\n * `json-object` sends JSON mode, which every OpenAI-compatible endpoint\n * accepts, and relies on the finding grammar the analyst kind already puts\n * in its instructions. `json-schema` sends the generated response schema as\n * well, which stricter endpoints honour and older ones reject. Default:\n * `json-object`.\n */\n reportFormat?: 'json-object' | 'json-schema'\n}\n\n/**\n * The report envelope. Its `findings` rows are generated from\n * `RawAnalystFindingSchema`, so the schema offered to a provider and the\n * decoder that accepts the answer cannot drift apart.\n */\nfunction buildReportJsonSchema(): { name: string; schema: Record<string, unknown> } {\n const row = z.toJSONSchema(RawAnalystFindingSchema, { target: 'draft-7' }) as Record<\n string,\n unknown\n >\n delete row.$schema\n return {\n name: 'trace_analysis_report',\n schema: {\n type: 'object',\n additionalProperties: false,\n required: ['answer', 'findings'],\n properties: {\n answer: { type: 'string', description: 'Direct prose answer to the question.' },\n findings: { type: 'array', items: row },\n },\n },\n }\n}\n\nconst REPORT_JSON_SCHEMA = buildReportJsonSchema()\n\n/**\n * Run bounded recursive trace analysis in-process over a caller-owned chat\n * transport. No Python, no subprocess, no loopback proxy.\n */\nexport function createChatTraceEngine(options: ChatTraceEngineOptions): TraceAnalysisEngine {\n const model = resolveModel(options)\n const maxOutputTokens = options.maxOutputTokens ?? DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS\n if (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens <= 0) {\n throw new TypeError('chat trace engine maxOutputTokens must be a positive safe integer')\n }\n if (\n options.temperature !== undefined &&\n (!Number.isFinite(options.temperature) || options.temperature < 0)\n ) {\n throw new TypeError('chat trace engine temperature must be a non-negative finite number')\n }\n if (\n options.requestTimeoutMs !== undefined &&\n (!Number.isSafeInteger(options.requestTimeoutMs) || options.requestTimeoutMs <= 0)\n ) {\n throw new TypeError('chat trace engine requestTimeoutMs must be a positive safe integer')\n }\n const reportFormat = options.reportFormat ?? 'json-object'\n if (reportFormat !== 'json-object' && reportFormat !== 'json-schema') {\n throw new TypeError(`chat trace engine reportFormat must be json-object or json-schema`)\n }\n\n return {\n id: ENGINE_ID,\n description:\n 'In-process recursive trace analysis over a caller-owned ChatClient with native tool calls.',\n model,\n version: CHAT_TRACE_ENGINE_VERSION,\n executionConfig: {\n kind: ENGINE_ID,\n model,\n transport: options.chat.transport,\n maximum_attempts: options.chat.maximumAttempts ?? null,\n pricing: options.pricing ? { ...options.pricing } : null,\n max_output_tokens: maxOutputTokens,\n temperature: options.temperature ?? null,\n thinking: options.thinking ?? null,\n request_timeout_ms: options.requestTimeoutMs ?? null,\n report_format: reportFormat,\n report_schema_name: REPORT_JSON_SCHEMA.name,\n },\n analyze: (request) => analyze(request, { ...options, model, maxOutputTokens, reportFormat }),\n }\n}\n\ninterface ResolvedOptions extends ChatTraceEngineOptions {\n model: string\n maxOutputTokens: number\n reportFormat: 'json-object' | 'json-schema'\n}\n\nasync function analyze(\n request: TraceAnalysisEngineRequest,\n options: ResolvedOptions,\n): Promise<TraceAnalysisEngineResult> {\n // One model call is spent on the report, so a budget of one call would buy\n // an answer with no investigation behind it. Refuse instead of pretending.\n if (request.limits.maxLlmCalls < 2) {\n throw new Error(\n `chat trace engine reserves one model call for the report, so maxLlmCalls must be at least 2 (analyst '${request.analystId}' declared ${request.limits.maxLlmCalls})`,\n )\n }\n const toolsByName = new Map(request.tools.map((tool) => [tool.name, tool]))\n if (toolsByName.size !== request.tools.length) {\n throw new Error(`chat trace engine received duplicate tool names for '${request.analystId}'`)\n }\n const toolDefinitions: LlmToolDefinition[] = request.tools.map((tool) => ({\n type: 'function',\n function: { name: tool.name, description: tool.description, parameters: tool.parameters },\n }))\n const investigationTurns = Math.max(\n 1,\n Math.min(request.limits.maxIterations, request.limits.maxLlmCalls - 1),\n )\n\n const messages: LlmMessage[] = [\n { role: 'system', content: systemPrompt(request, investigationTurns) },\n ]\n if (request.taskInputs) {\n messages.push({ role: 'user', content: renderTaskInputs(request.taskInputs) })\n }\n messages.push({ role: 'user', content: request.question })\n\n request.log?.('trace analyst engine started', {\n engine: ENGINE_ID,\n model: options.model,\n transport: options.chat.transport,\n tools: request.tools.map((tool) => tool.name),\n limits: request.limits,\n })\n\n const trajectory: unknown[] = []\n const servedModels = new Set<string>()\n let modelCalls = 0\n let toolCalls = 0\n let truncatedToolResults = 0\n let toolBudgetExhausted = false\n let turnsUsed = 0\n let stoppedOnAnswer = false\n\n for (let turn = 0; turn < investigationTurns; turn++) {\n turnsUsed = turn + 1\n const response = await callModel(request, options, {\n messages,\n tools: toolDefinitions,\n toolChoice: 'auto',\n purpose: 'investigation',\n })\n modelCalls += 1\n servedModels.add(response.servedModel ?? 'unreported')\n const requested = response.toolCalls ?? []\n messages.push({\n role: 'assistant',\n content: response.content,\n ...(requested.length > 0 ? { toolCalls: requested } : {}),\n })\n trajectory.push({\n turn: turnsUsed,\n phase: 'investigation',\n content: response.content,\n tool_calls: requested.map((call) => ({ id: call.id, name: call.name })),\n finish_reason: response.finishReason ?? null,\n })\n if (requested.length === 0) {\n stoppedOnAnswer = true\n break\n }\n for (const call of requested) {\n if (toolCalls >= request.limits.maxToolCalls) {\n toolBudgetExhausted = true\n // Every requested id still needs an answer: a provider rejects the\n // next turn when one tool call is left unanswered.\n messages.push(toolMessage(call, exhaustedToolBudget(request.limits.maxToolCalls)))\n continue\n }\n toolCalls += 1\n const executed = await executeTool(call, toolsByName, request)\n if (executed.truncated) truncatedToolResults += 1\n messages.push(toolMessage(call, executed.payload))\n trajectory.push({\n turn: turnsUsed,\n phase: 'tool',\n name: call.name,\n ok: executed.ok,\n truncated: executed.truncated,\n result_chars: executed.payload.length,\n })\n }\n if (toolBudgetExhausted) break\n }\n\n messages.push({ role: 'user', content: reportPrompt(options.reportFormat) })\n const report = await callModel(request, options, {\n messages,\n purpose: 'report',\n json: options.reportFormat,\n })\n modelCalls += 1\n servedModels.add(report.servedModel ?? 'unreported')\n trajectory.push({\n turn: turnsUsed + 1,\n phase: 'report',\n content: report.content,\n finish_reason: report.finishReason ?? null,\n })\n\n const parsed = parseReport(report.content, request.analystId, (index, reason) => {\n request.log?.('finding rejected: report row failed schema validation', {\n engine: ENGINE_ID,\n index,\n reason,\n })\n })\n\n const result: TraceAnalysisEngineResult = {\n answer: parsed.answer,\n findings: parsed.findings,\n trajectory,\n modelCalls,\n toolCalls,\n runtime: {\n engine: ENGINE_ID,\n model: options.model,\n transport: options.chat.transport,\n report_format: options.reportFormat,\n investigation_turns: turnsUsed,\n investigation_stopped_on_answer: stoppedOnAnswer,\n tool_budget_exhausted: toolBudgetExhausted,\n truncated_tool_results: truncatedToolResults,\n rejected_findings: parsed.rejectedFindings,\n // A gateway can answer `model: X` from another model on HTTP 200, so the\n // ids the provider echoed travel with the result as evidence.\n served_models: [...servedModels].sort(),\n task_inputs: request.taskInputs ? 'prompt-delivered' : 'none',\n },\n }\n request.log?.('trace analyst engine completed', {\n engine: ENGINE_ID,\n model_calls: result.modelCalls,\n tool_calls: result.toolCalls,\n findings: result.findings.length,\n })\n return result\n}\n\ninterface ModelTurn {\n content: string\n toolCalls?: LlmToolCall[]\n servedModel?: string | null\n finishReason?: string | null\n}\n\nasync function callModel(\n request: TraceAnalysisEngineRequest,\n options: ResolvedOptions,\n turn: {\n messages: LlmMessage[]\n tools?: LlmToolDefinition[]\n toolChoice?: LlmCallRequest['toolChoice']\n purpose: 'investigation' | 'report'\n json?: 'json-object' | 'json-schema'\n },\n): Promise<ModelTurn> {\n const chatRequest: LlmCallRequest = {\n model: options.model,\n // The transport may mutate what it is handed; the conversation is ours.\n messages: turn.messages.map((message) => ({ ...message })),\n maxTokens: options.maxOutputTokens,\n ...(turn.tools && turn.tools.length > 0\n ? { tools: turn.tools, ...(turn.toolChoice ? { toolChoice: turn.toolChoice } : {}) }\n : {}),\n ...(turn.json ? { jsonMode: true } : {}),\n ...(turn.json === 'json-schema' ? { jsonSchema: REPORT_JSON_SCHEMA } : {}),\n ...(options.temperature === undefined ? {} : { temperature: options.temperature }),\n ...(options.thinking === undefined ? {} : { thinking: options.thinking }),\n ...(options.requestTimeoutMs === undefined ? {} : { timeoutMs: options.requestTimeoutMs }),\n }\n const paid = await paidChat({\n chat: options.chat,\n request: chatRequest,\n ledger: request.costLedger,\n channel: 'analyst',\n phase: request.costPhase,\n actor: request.analystId,\n ...(request.costTags ? { tags: request.costTags } : {}),\n ...(options.pricing ? { pricing: options.pricing } : {}),\n ...(request.signal ? { signal: request.signal } : {}),\n })\n if (!paid.succeeded) {\n // The transport already spent its own attempts. A failure here ends the\n // investigation: continuing would report an answer the model never gave.\n throw new Error(\n `chat trace engine ${turn.purpose} call failed for '${request.analystId}': ${paid.error.message}`,\n { cause: paid.error },\n )\n }\n return {\n content: paid.response.content,\n ...(paid.response.toolCalls ? { toolCalls: paid.response.toolCalls } : {}),\n ...(paid.response.servedModel === undefined ? {} : { servedModel: paid.response.servedModel }),\n ...(paid.response.finishReason === undefined\n ? {}\n : { finishReason: paid.response.finishReason }),\n }\n}\n\ninterface ExecutedTool {\n ok: boolean\n truncated: boolean\n payload: string\n}\n\nasync function executeTool(\n call: LlmToolCall,\n toolsByName: ReadonlyMap<string, TraceAnalysisToolDescriptor>,\n request: TraceAnalysisEngineRequest,\n): Promise<ExecutedTool> {\n const descriptor = toolsByName.get(call.name)\n if (!descriptor) {\n return {\n ok: false,\n truncated: false,\n payload: toolError(\n `unknown tool '${call.name}'; available tools are ${[...toolsByName.keys()].sort().join(', ')}`,\n ),\n }\n }\n let args: unknown\n try {\n args = call.argumentsJson.trim() === '' ? {} : JSON.parse(call.argumentsJson)\n } catch (error) {\n return {\n ok: false,\n truncated: false,\n payload: toolError(\n `arguments for '${call.name}' were not JSON: ${messageOf(error)}. Send valid JSON arguments.`,\n ),\n }\n }\n try {\n const value = await descriptor.handler(\n args,\n request.signal ? { signal: request.signal } : undefined,\n )\n return truncateToolPayload(JSON.stringify(value ?? null), request.limits.maxOutputChars)\n } catch (error) {\n // A bounded store refuses an oversized or malformed read by design. That\n // refusal is the model's next instruction, not the run's failure.\n if (request.signal?.aborted) throw error\n request.log?.('trace tool failed', {\n engine: ENGINE_ID,\n analyst_id: request.analystId,\n tool: call.name,\n reason: messageOf(error),\n })\n return { ok: false, truncated: false, payload: toolError(messageOf(error)) }\n }\n}\n\nfunction truncateToolPayload(payload: string, maxOutputChars: number): ExecutedTool {\n if (payload.length <= maxOutputChars) return { ok: true, truncated: false, payload }\n const keep = Math.max(0, maxOutputChars - TRUNCATION_MARKER.length)\n return { ok: true, truncated: true, payload: `${payload.slice(0, keep)}${TRUNCATION_MARKER}` }\n}\n\nfunction toolMessage(call: LlmToolCall, content: string): LlmMessage {\n return { role: 'tool', toolCallId: call.id, content }\n}\n\nfunction toolError(reason: string): string {\n return JSON.stringify({ error: reason })\n}\n\nfunction exhaustedToolBudget(maxToolCalls: number): string {\n return toolError(\n `the trace-tool budget of ${maxToolCalls} calls is spent; answer from the evidence already read`,\n )\n}\n\nfunction systemPrompt(request: TraceAnalysisEngineRequest, investigationTurns: number): string {\n return [\n request.instructions.trim(),\n [\n 'HOW THIS INVESTIGATION RUNS:',\n `- You have ${investigationTurns} investigation turns and at most ${request.limits.maxToolCalls} trace-tool calls.`,\n '- Call the trace tools to read the store. Never state a trace fact you did not read.',\n `- A tool result longer than ${request.limits.maxOutputChars} characters is truncated; narrow the query instead of asking again.`,\n '- A tool result carrying an \"error\" field is feedback: fix the call or take another route.',\n '- Answer with no tool call once you have the evidence. You are then asked for the final report.',\n ].join('\\n'),\n ].join('\\n\\n')\n}\n\nfunction reportPrompt(reportFormat: 'json-object' | 'json-schema'): string {\n return [\n 'Report now. Do not call any more tools.',\n 'Return one JSON object with exactly two fields:',\n ' \"answer\": a direct prose answer to the question.',\n ' \"findings\": an array of findings in the schema above. Emit [] when there is nothing to report.',\n reportFormat === 'json-object'\n ? 'Return the object alone, with no surrounding prose and no code fence.'\n : 'Return the object in the response schema you were given.',\n ].join('\\n')\n}\n\nfunction renderTaskInputs(taskInputs: Readonly<Record<string, unknown>>): string {\n // The engine contract forbids dropping structured inputs. This engine has no\n // code environment to bind them as variables, so they are delivered whole as\n // conversation material and the runtime record says which way they arrived.\n return [\n 'TASK INPUTS — structured material delivered with the question, not fetched through tools:',\n JSON.stringify(taskInputs, null, 2),\n ].join('\\n')\n}\n\ninterface ParsedReport {\n answer: string\n findings: TraceAnalysisEngineResult['findings']\n rejectedFindings: number\n}\n\nfunction parseReport(\n content: string,\n analystId: string,\n onRejectedFinding: (index: number, reason: string) => void,\n): ParsedReport {\n const envelope = coerceReportEnvelope(content, analystId)\n if (typeof envelope.answer !== 'string' || !envelope.answer.trim()) {\n throw new Error(`chat trace engine report for '${analystId}' carried no answer`)\n }\n // Findings are model output: one malformed row is model noise, not an engine\n // fault, and the rest of the paid investigation must survive it.\n const decoded = decodeRawFindingArray(envelope.findings)\n if (decoded.topLevelError !== undefined) {\n throw new Error(\n `chat trace engine report for '${analystId}' had a malformed findings array: ${decoded.topLevelError}`,\n )\n }\n for (const rejection of decoded.rejected) {\n onRejectedFinding(\n rejection.index,\n `${rejection.code}${rejection.path ? ` at ${rejection.path}` : ''}: ${rejection.message}`,\n )\n }\n return {\n answer: envelope.answer,\n findings: decoded.accepted,\n rejectedFindings: decoded.rejected.length,\n }\n}\n\nfunction coerceReportEnvelope(content: string, analystId: string): Record<string, unknown> {\n let value: unknown\n try {\n value = JSON.parse(extractJsonPayload(content))\n } catch (error) {\n throw new Error(`chat trace engine report for '${analystId}' was not JSON: ${messageOf(error)}`)\n }\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error(`chat trace engine report for '${analystId}' was not a JSON object`)\n }\n return value as Record<string, unknown>\n}\n\nfunction resolveModel(options: ChatTraceEngineOptions): string {\n const model = options.model ?? options.chat.defaultModel\n if (typeof model !== 'string' || !model.trim() || model !== model.trim()) {\n throw new TypeError(\n 'chat trace engine needs a model: pass ChatTraceEngineOptions.model or bind defaultModel on the ChatClient',\n )\n }\n return model\n}\n","/**\n * LockedJsonlAppender — mutex-serialized JSONL append helper for arbitrary\n * payloads. The reference-replay store does the same thing for typed\n * `ReferenceReplayRun` rows; this is the generic version used by\n * `MutationTelemetry`, `TrialTelemetry`, and any other consumer that wants\n * append-only durable telemetry without rolling its own lock.\n *\n * Locks are per absolute file path (process-local). Cross-process\n * concurrency is NOT addressed — that's an fcntl/flock problem.\n */\n\nimport { appendFileSync, existsSync, mkdirSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport { Mutex } from './concurrency'\n\nconst mutexes = new Map<string, Mutex>()\n\nfunction getMutex(path: string): Mutex {\n let m = mutexes.get(path)\n if (!m) {\n m = new Mutex()\n mutexes.set(path, m)\n }\n return m\n}\n\nexport class LockedJsonlAppender {\n private readonly mutex: Mutex\n constructor(public readonly path: string) {\n this.mutex = getMutex(path)\n if (!existsSync(dirname(path))) {\n mkdirSync(dirname(path), { recursive: true })\n }\n }\n\n async append(entry: unknown): Promise<void> {\n const line = `${JSON.stringify(entry)}\\n`\n await this.mutex.runExclusive(() => {\n appendFileSync(this.path, line)\n })\n }\n}\n\n/** Reset all internal mutex state — tests only. */\nexport function resetLockedAppendersForTesting(): void {\n mutexes.clear()\n}\n","/**\n * FindingsStore — durable persistence for AnalystFinding rows + a diff\n * helper so we can answer \"what changed since the last run?\" without\n * recomputing analysts.\n *\n * On-disk shape is JSONL: one finding per line, append-only, locked via\n * LockedJsonlAppender. Operators get crash-safety (no partial JSON),\n * cheap reads (sequential parse), and trivial backup (rsync the file).\n *\n * Reads are non-locking: a reader sees a consistent snapshot of all\n * fully-written lines and skips an incomplete trailing line if the\n * writer is mid-append. Cross-process locking is intentionally out of\n * scope (see locked-jsonl-appender.ts).\n *\n * The store is run-scoped: callers pass `runId` on append and on load,\n * which keeps multi-run files cleanly partitioned. The `diffFindings`\n * helper compares two run-id sets using stable `finding_id` semantics —\n * the diff is the cross-run signal the regression dashboard renders.\n */\n\nimport { existsSync, readFileSync } from 'node:fs'\n\nimport { LockedJsonlAppender } from '../locked-jsonl-appender'\nimport type { AnalystFinding } from './types'\n\n/**\n * One persisted row. We attach `run_id` on disk so a single file can\n * hold multiple runs and the diff helper can query without re-walking\n * separate files.\n */\nexport interface PersistedFinding extends AnalystFinding {\n run_id: string\n}\n\nexport class FindingsStore {\n private readonly appender: LockedJsonlAppender\n\n constructor(public readonly path: string) {\n this.appender = new LockedJsonlAppender(path)\n }\n\n async append(runId: string, findings: AnalystFinding[]): Promise<void> {\n for (const f of findings) {\n const row: PersistedFinding = { ...f, run_id: runId }\n await this.appender.append(row)\n }\n }\n\n /** Load every persisted finding. Discards malformed trailing lines silently. */\n loadAll(): PersistedFinding[] {\n if (!existsSync(this.path)) return []\n const raw = readFileSync(this.path, 'utf8')\n if (!raw) return []\n const out: PersistedFinding[] = []\n for (const line of raw.split('\\n')) {\n if (!line) continue\n try {\n out.push(JSON.parse(line) as PersistedFinding)\n } catch {\n // Skip torn trailing line — the lock guarantees no torn lines\n // mid-file, only at EOF when a writer is in-flight.\n }\n }\n return out\n }\n\n /** Filter to a single run. */\n loadRun(runId: string): PersistedFinding[] {\n return this.loadAll().filter((r) => r.run_id === runId)\n }\n}\n\n// ── Cross-run diff ──────────────────────────────────────────────────\n\nexport interface FindingsDiff {\n /** New finding ids in `current` that weren't in `previous`. */\n appeared: PersistedFinding[]\n /** Finding ids in `previous` that aren't in `current`. */\n disappeared: PersistedFinding[]\n /** Same finding id present in both runs and unchanged per the materiality test. */\n persisted: PersistedFinding[]\n /**\n * Same finding id in both runs but at least one non-identity field\n * shifted per `DiffPolicy.isMaterial`. Reported as [previous, current].\n */\n changed: Array<{ previous: PersistedFinding; current: PersistedFinding }>\n}\n\nexport interface DiffPolicy {\n /**\n * Predicate that decides whether two findings (same finding_id) count\n * as a material change. Defaults to {@link defaultIsMaterial}: severity\n * shift, confidence Δ > 0.05, or evidence count change. Compliance /\n * perf consumers MAY supply a stricter predicate (e.g. rationale text\n * diff, metric Δ thresholds).\n */\n isMaterial?: (previous: AnalystFinding, current: AnalystFinding) => boolean\n}\n\n/**\n * Default materiality test. Deliberately narrow so LLM-reword churn\n * doesn't flood the diff. Stricter tests are opt-in via DiffPolicy.\n */\nfunction defaultIsMaterial(a: AnalystFinding, b: AnalystFinding): boolean {\n if (a.severity !== b.severity) return true\n if (Math.abs((a.confidence ?? 0) - (b.confidence ?? 0)) > 0.05) return true\n if (a.evidence_refs.length !== b.evidence_refs.length) return true\n return false\n}\n\n/**\n * Diff two findings sets by stable finding_id. Callers typically load\n * the two run-id slices from the same store and pass them in.\n */\nexport function diffFindings(\n previous: PersistedFinding[],\n current: PersistedFinding[],\n policy: DiffPolicy = {},\n): FindingsDiff {\n const isMaterial = policy.isMaterial ?? defaultIsMaterial\n const prevById = new Map(previous.map((f) => [f.finding_id, f]))\n const curById = new Map(current.map((f) => [f.finding_id, f]))\n\n const appeared: PersistedFinding[] = []\n const disappeared: PersistedFinding[] = []\n const persisted: PersistedFinding[] = []\n const changed: FindingsDiff['changed'] = []\n\n for (const [id, cur] of curById) {\n const prev = prevById.get(id)\n if (!prev) {\n appeared.push(cur)\n continue\n }\n if (isMaterial(prev, cur)) {\n changed.push({ previous: prev, current: cur })\n } else {\n persisted.push(cur)\n }\n }\n for (const [id, prev] of prevById) {\n if (!curById.has(id)) disappeared.push(prev)\n }\n return { appeared, disappeared, persisted, changed }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,MAAM,4BAA4B;AAClC,MAAM,YAAY;;AAGlB,MAAM,oBAAoB;;;;;;AAqC1B,SAAS,wBAA2E;CAClF,MAAM,MAAM,EAAE,aAAa,yBAAyB,EAAE,QAAQ,UAAU,CAAC;CAIzE,OAAO,IAAI;CACX,OAAO;EACL,MAAM;EACN,QAAQ;GACN,MAAM;GACN,sBAAsB;GACtB,UAAU,CAAC,UAAU,UAAU;GAC/B,YAAY;IACV,QAAQ;KAAE,MAAM;KAAU,aAAa;IAAuC;IAC9E,UAAU;KAAE,MAAM;KAAS,OAAO;IAAI;GACxC;EACF;CACF;AACF;AAEA,MAAM,qBAAqB,sBAAsB;;;;;AAMjD,SAAgB,sBAAsB,SAAsD;CAC1F,MAAM,QAAQ,aAAa,OAAO;CAClC,MAAM,kBAAkB,QAAQ,mBAAA;CAChC,IAAI,CAAC,OAAO,cAAc,eAAe,KAAK,mBAAmB,GAC/D,MAAM,IAAI,UAAU,mEAAmE;CAEzF,IACE,QAAQ,gBAAgB,KAAA,MACvB,CAAC,OAAO,SAAS,QAAQ,WAAW,KAAK,QAAQ,cAAc,IAEhE,MAAM,IAAI,UAAU,oEAAoE;CAE1F,IACE,QAAQ,qBAAqB,KAAA,MAC5B,CAAC,OAAO,cAAc,QAAQ,gBAAgB,KAAK,QAAQ,oBAAoB,IAEhF,MAAM,IAAI,UAAU,oEAAoE;CAE1F,MAAM,eAAe,QAAQ,gBAAgB;CA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AC;CACvC,MAAM,UAAmC,CAAC;CAE1C,KAAK,MAAM,CAAC,IAAI,QAAQ,SAAS;EAC/B,MAAM,OAAO,SAAS,IAAI,EAAE;EAC5B,IAAI,CAAC,MAAM;GACT,SAAS,KAAK,GAAG;GACjB;EACF;EACA,IAAI,WAAW,MAAM,GAAG,GACtB,QAAQ,KAAK;GAAE,UAAU;GAAM,SAAS;EAAI,CAAC;OAE7C,UAAU,KAAK,GAAG;CAEtB;CACA,KAAK,MAAM,CAAC,IAAI,SAAS,UACvB,IAAI,CAAC,QAAQ,IAAI,EAAE,GAAG,YAAY,KAAK,IAAI;CAE7C,OAAO;EAAE;EAAU;EAAa;EAAW;CAAQ;AACrD"}
|
|
1
|
+
{"version":3,"file":"findings-store-Rx9ZJgHV.js","names":["messageOf"],"sources":["../src/analyst/chat-trace-engine.ts","../src/locked-jsonl-appender.ts","../src/analyst/findings-store.ts"],"sourcesContent":["/**\n * A `TraceAnalysisEngine` that runs entirely inside Node against a\n * caller-owned `ChatClient`.\n *\n * The other engine in this package, `createDspyRlmTraceEngine`, reaches the\n * DSPy RLM through a Python subprocess. That made every model-backed analyst\n * unreachable for a consumer that already owns a model seam and no Python:\n * `createTraceAnalyst` requires an engine, the only exported constructor\n * required a Python runner, so `buildDefaultAnalystRegistry()` registered the\n * deterministic analyst alone and `analystsFromRegistry` refused the result.\n *\n * This engine closes that path. It drives the same investigation contract —\n * bounded trace tools, a prose answer, a strict findings array — with native\n * function calls over the transport the caller already bound with\n * `createChatClient`. A caller holding a bare\n * `(request: LlmCallRequest) => Promise<LlmCallResult>` adapts it in one line:\n *\n * createChatClient({ transport: 'custom', chat: call, defaultModel, maximumAttempts })\n *\n * agent-eval still executes no paid model and holds no provider credential.\n * Every call goes through `paidChat`, so the shared cost ledger reserves the\n * priced maximum before the call and settles the receipt after it.\n *\n * Shape of one investigation:\n * 1. Investigation turns. The model reads the trace store through the tools\n * its analyst kind was given. A turn that requests no tool ends the\n * phase; an exhausted iteration or tool budget also ends it.\n * 2. One report turn. The model returns `{ answer, findings }` as JSON,\n * decoded by the same `decodeRawFindingArray` the Python bridge uses, so\n * a row this engine accepts is a row that engine could report.\n */\n\nimport { z } from 'zod'\nimport { paidChat } from '../chat-json-call'\nimport type { CustomTokenPricing } from '../cost-ledger'\nimport { errorMessage as messageOf } from '../errors'\nimport {\n extractJsonPayload,\n type LlmCallRequest,\n type LlmMessage,\n type LlmThinkingMode,\n type LlmToolCall,\n type LlmToolDefinition,\n} from '../llm-client'\nimport type { TraceAnalysisToolDescriptor } from '../trace-analyst/tools'\nimport type { ChatClient } from './chat-client'\nimport {\n DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS,\n type TraceAnalysisEngine,\n type TraceAnalysisEngineRequest,\n type TraceAnalysisEngineResult,\n} from './engine'\nimport { decodeRawFindingArray } from './finding-codec'\nimport { RawAnalystFindingSchema } from './finding-signature'\n\n/** Bumped whenever this engine's execution behavior changes. */\nconst CHAT_TRACE_ENGINE_VERSION = '1.0.0'\nconst ENGINE_ID = 'chat-trace'\n\n/** Marker appended to a tool result cut down to the retained-output budget. */\nconst TRUNCATION_MARKER = '\\n…[truncated to the analyst maxOutputChars budget]'\n\nexport interface ChatTraceEngineOptions {\n /**\n * Caller-owned transport. Build it with `createChatClient`; agent-eval never\n * receives the provider credential.\n */\n chat: ChatClient\n /** Model for every call. Defaults to the client's `defaultModel`. */\n model?: string\n /** Endpoint rates used when the transport reports no billed amount. */\n pricing?: CustomTokenPricing\n /** Completion cap per turn. Default: {@link DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS}. */\n maxOutputTokens?: number\n /** Sampling temperature. Omitted from the request when absent. */\n temperature?: number\n /** Provider reasoning mode. Omitted when the provider default should apply. */\n thinking?: LlmThinkingMode\n /** Per-call deadline handed to the transport. */\n requestTimeoutMs?: number\n /**\n * How the report turn asks for structured output.\n *\n * `json-object` sends JSON mode, which every OpenAI-compatible endpoint\n * accepts, and relies on the finding grammar the analyst kind already puts\n * in its instructions. `json-schema` sends the generated response schema as\n * well, which stricter endpoints honour and older ones reject. Default:\n * `json-object`.\n */\n reportFormat?: 'json-object' | 'json-schema'\n}\n\n/**\n * The report envelope. Its `findings` rows are generated from\n * `RawAnalystFindingSchema`, so the schema offered to a provider and the\n * decoder that accepts the answer cannot drift apart.\n */\nfunction buildReportJsonSchema(): { name: string; schema: Record<string, unknown> } {\n const row = z.toJSONSchema(RawAnalystFindingSchema, { target: 'draft-7' }) as Record<\n string,\n unknown\n >\n delete row.$schema\n return {\n name: 'trace_analysis_report',\n schema: {\n type: 'object',\n additionalProperties: false,\n required: ['answer', 'findings'],\n properties: {\n answer: { type: 'string', description: 'Direct prose answer to the question.' },\n findings: { type: 'array', items: row },\n },\n },\n }\n}\n\nconst REPORT_JSON_SCHEMA = buildReportJsonSchema()\n\n/**\n * Run bounded recursive trace analysis in-process over a caller-owned chat\n * transport. No Python, no subprocess, no loopback proxy.\n */\nexport function createChatTraceEngine(options: ChatTraceEngineOptions): TraceAnalysisEngine {\n const model = resolveModel(options)\n const maxOutputTokens = options.maxOutputTokens ?? DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS\n if (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens <= 0) {\n throw new TypeError('chat trace engine maxOutputTokens must be a positive safe integer')\n }\n if (\n options.temperature !== undefined &&\n (!Number.isFinite(options.temperature) || options.temperature < 0)\n ) {\n throw new TypeError('chat trace engine temperature must be a non-negative finite number')\n }\n if (\n options.requestTimeoutMs !== undefined &&\n (!Number.isSafeInteger(options.requestTimeoutMs) || options.requestTimeoutMs <= 0)\n ) {\n throw new TypeError('chat trace engine requestTimeoutMs must be a positive safe integer')\n }\n const reportFormat = options.reportFormat ?? 'json-object'\n if (reportFormat !== 'json-object' && reportFormat !== 'json-schema') {\n throw new TypeError(`chat trace engine reportFormat must be json-object or json-schema`)\n }\n\n return {\n id: ENGINE_ID,\n description:\n 'In-process recursive trace analysis over a caller-owned ChatClient with native tool calls.',\n model,\n version: CHAT_TRACE_ENGINE_VERSION,\n executionConfig: {\n kind: ENGINE_ID,\n model,\n transport: options.chat.transport,\n maximum_attempts: options.chat.maximumAttempts ?? null,\n pricing: options.pricing ? { ...options.pricing } : null,\n max_output_tokens: maxOutputTokens,\n temperature: options.temperature ?? null,\n thinking: options.thinking ?? null,\n request_timeout_ms: options.requestTimeoutMs ?? null,\n report_format: reportFormat,\n report_schema_name: REPORT_JSON_SCHEMA.name,\n },\n analyze: (request) => analyze(request, { ...options, model, maxOutputTokens, reportFormat }),\n }\n}\n\ninterface ResolvedOptions extends ChatTraceEngineOptions {\n model: string\n maxOutputTokens: number\n reportFormat: 'json-object' | 'json-schema'\n}\n\nasync function analyze(\n request: TraceAnalysisEngineRequest,\n options: ResolvedOptions,\n): Promise<TraceAnalysisEngineResult> {\n // One model call is spent on the report, so a budget of one call would buy\n // an answer with no investigation behind it. Refuse instead of pretending.\n if (request.limits.maxLlmCalls < 2) {\n throw new Error(\n `chat trace engine reserves one model call for the report, so maxLlmCalls must be at least 2 (analyst '${request.analystId}' declared ${request.limits.maxLlmCalls})`,\n )\n }\n const toolsByName = new Map(request.tools.map((tool) => [tool.name, tool]))\n if (toolsByName.size !== request.tools.length) {\n throw new Error(`chat trace engine received duplicate tool names for '${request.analystId}'`)\n }\n const toolDefinitions: LlmToolDefinition[] = request.tools.map((tool) => ({\n type: 'function',\n function: { name: tool.name, description: tool.description, parameters: tool.parameters },\n }))\n const investigationTurns = Math.max(\n 1,\n Math.min(request.limits.maxIterations, request.limits.maxLlmCalls - 1),\n )\n\n const messages: LlmMessage[] = [\n { role: 'system', content: systemPrompt(request, investigationTurns) },\n ]\n if (request.taskInputs) {\n messages.push({ role: 'user', content: renderTaskInputs(request.taskInputs) })\n }\n messages.push({ role: 'user', content: request.question })\n\n request.log?.('trace analyst engine started', {\n engine: ENGINE_ID,\n model: options.model,\n transport: options.chat.transport,\n tools: request.tools.map((tool) => tool.name),\n limits: request.limits,\n })\n\n const trajectory: unknown[] = []\n const servedModels = new Set<string>()\n let modelCalls = 0\n let toolCalls = 0\n let truncatedToolResults = 0\n let toolBudgetExhausted = false\n let turnsUsed = 0\n let stoppedOnAnswer = false\n\n for (let turn = 0; turn < investigationTurns; turn++) {\n turnsUsed = turn + 1\n const response = await callModel(request, options, {\n messages,\n tools: toolDefinitions,\n toolChoice: 'auto',\n purpose: 'investigation',\n })\n modelCalls += 1\n servedModels.add(response.servedModel ?? 'unreported')\n const requested = response.toolCalls ?? []\n messages.push({\n role: 'assistant',\n content: response.content,\n ...(requested.length > 0 ? { toolCalls: requested } : {}),\n })\n trajectory.push({\n turn: turnsUsed,\n phase: 'investigation',\n content: response.content,\n tool_calls: requested.map((call) => ({ id: call.id, name: call.name })),\n finish_reason: response.finishReason ?? null,\n })\n if (requested.length === 0) {\n stoppedOnAnswer = true\n break\n }\n for (const call of requested) {\n if (toolCalls >= request.limits.maxToolCalls) {\n toolBudgetExhausted = true\n // Every requested id still needs an answer: a provider rejects the\n // next turn when one tool call is left unanswered.\n messages.push(toolMessage(call, exhaustedToolBudget(request.limits.maxToolCalls)))\n continue\n }\n toolCalls += 1\n const executed = await executeTool(call, toolsByName, request)\n if (executed.truncated) truncatedToolResults += 1\n messages.push(toolMessage(call, executed.payload))\n trajectory.push({\n turn: turnsUsed,\n phase: 'tool',\n name: call.name,\n ok: executed.ok,\n truncated: executed.truncated,\n result_chars: executed.payload.length,\n })\n }\n if (toolBudgetExhausted) break\n }\n\n messages.push({ role: 'user', content: reportPrompt(options.reportFormat) })\n const report = await callModel(request, options, {\n messages,\n purpose: 'report',\n json: options.reportFormat,\n })\n modelCalls += 1\n servedModels.add(report.servedModel ?? 'unreported')\n trajectory.push({\n turn: turnsUsed + 1,\n phase: 'report',\n content: report.content,\n finish_reason: report.finishReason ?? null,\n })\n\n const parsed = parseReport(report.content, request.analystId, (index, reason) => {\n request.log?.('finding rejected: report row failed schema validation', {\n engine: ENGINE_ID,\n index,\n reason,\n })\n })\n\n const result: TraceAnalysisEngineResult = {\n answer: parsed.answer,\n findings: parsed.findings,\n trajectory,\n modelCalls,\n toolCalls,\n runtime: {\n engine: ENGINE_ID,\n model: options.model,\n transport: options.chat.transport,\n report_format: options.reportFormat,\n investigation_turns: turnsUsed,\n investigation_stopped_on_answer: stoppedOnAnswer,\n tool_budget_exhausted: toolBudgetExhausted,\n truncated_tool_results: truncatedToolResults,\n rejected_findings: parsed.rejectedFindings,\n // A gateway can answer `model: X` from another model on HTTP 200, so the\n // ids the provider echoed travel with the result as evidence.\n served_models: [...servedModels].sort(),\n task_inputs: request.taskInputs ? 'prompt-delivered' : 'none',\n },\n }\n request.log?.('trace analyst engine completed', {\n engine: ENGINE_ID,\n model_calls: result.modelCalls,\n tool_calls: result.toolCalls,\n findings: result.findings.length,\n })\n return result\n}\n\ninterface ModelTurn {\n content: string\n toolCalls?: LlmToolCall[]\n servedModel?: string | null\n finishReason?: string | null\n}\n\nasync function callModel(\n request: TraceAnalysisEngineRequest,\n options: ResolvedOptions,\n turn: {\n messages: LlmMessage[]\n tools?: LlmToolDefinition[]\n toolChoice?: LlmCallRequest['toolChoice']\n purpose: 'investigation' | 'report'\n json?: 'json-object' | 'json-schema'\n },\n): Promise<ModelTurn> {\n const chatRequest: LlmCallRequest = {\n model: options.model,\n // The transport may mutate what it is handed; the conversation is ours.\n messages: turn.messages.map((message) => ({ ...message })),\n maxTokens: options.maxOutputTokens,\n ...(turn.tools && turn.tools.length > 0\n ? { tools: turn.tools, ...(turn.toolChoice ? { toolChoice: turn.toolChoice } : {}) }\n : {}),\n ...(turn.json ? { jsonMode: true } : {}),\n ...(turn.json === 'json-schema' ? { jsonSchema: REPORT_JSON_SCHEMA } : {}),\n ...(options.temperature === undefined ? {} : { temperature: options.temperature }),\n ...(options.thinking === undefined ? {} : { thinking: options.thinking }),\n ...(options.requestTimeoutMs === undefined ? {} : { timeoutMs: options.requestTimeoutMs }),\n }\n const paid = await paidChat({\n chat: options.chat,\n request: chatRequest,\n ledger: request.costLedger,\n channel: 'analyst',\n phase: request.costPhase,\n actor: request.analystId,\n ...(request.costTags ? { tags: request.costTags } : {}),\n ...(options.pricing ? { pricing: options.pricing } : {}),\n ...(request.signal ? { signal: request.signal } : {}),\n })\n if (!paid.succeeded) {\n // The transport already spent its own attempts. A failure here ends the\n // investigation: continuing would report an answer the model never gave.\n throw new Error(\n `chat trace engine ${turn.purpose} call failed for '${request.analystId}': ${paid.error.message}`,\n { cause: paid.error },\n )\n }\n return {\n content: paid.response.content,\n ...(paid.response.toolCalls ? { toolCalls: paid.response.toolCalls } : {}),\n ...(paid.response.servedModel === undefined ? {} : { servedModel: paid.response.servedModel }),\n ...(paid.response.finishReason === undefined\n ? {}\n : { finishReason: paid.response.finishReason }),\n }\n}\n\ninterface ExecutedTool {\n ok: boolean\n truncated: boolean\n payload: string\n}\n\nasync function executeTool(\n call: LlmToolCall,\n toolsByName: ReadonlyMap<string, TraceAnalysisToolDescriptor>,\n request: TraceAnalysisEngineRequest,\n): Promise<ExecutedTool> {\n const descriptor = toolsByName.get(call.name)\n if (!descriptor) {\n return {\n ok: false,\n truncated: false,\n payload: toolError(\n `unknown tool '${call.name}'; available tools are ${[...toolsByName.keys()].sort().join(', ')}`,\n ),\n }\n }\n let args: unknown\n try {\n args = call.argumentsJson.trim() === '' ? {} : JSON.parse(call.argumentsJson)\n } catch (error) {\n return {\n ok: false,\n truncated: false,\n payload: toolError(\n `arguments for '${call.name}' were not JSON: ${messageOf(error)}. Send valid JSON arguments.`,\n ),\n }\n }\n try {\n const value = await descriptor.handler(\n args,\n request.signal ? { signal: request.signal } : undefined,\n )\n return truncateToolPayload(JSON.stringify(value ?? null), request.limits.maxOutputChars)\n } catch (error) {\n // A bounded store refuses an oversized or malformed read by design. That\n // refusal is the model's next instruction, not the run's failure.\n if (request.signal?.aborted) throw error\n request.log?.('trace tool failed', {\n engine: ENGINE_ID,\n analyst_id: request.analystId,\n tool: call.name,\n reason: messageOf(error),\n })\n return { ok: false, truncated: false, payload: toolError(messageOf(error)) }\n }\n}\n\nfunction truncateToolPayload(payload: string, maxOutputChars: number): ExecutedTool {\n if (payload.length <= maxOutputChars) return { ok: true, truncated: false, payload }\n const keep = Math.max(0, maxOutputChars - TRUNCATION_MARKER.length)\n return { ok: true, truncated: true, payload: `${payload.slice(0, keep)}${TRUNCATION_MARKER}` }\n}\n\nfunction toolMessage(call: LlmToolCall, content: string): LlmMessage {\n return { role: 'tool', toolCallId: call.id, content }\n}\n\nfunction toolError(reason: string): string {\n return JSON.stringify({ error: reason })\n}\n\nfunction exhaustedToolBudget(maxToolCalls: number): string {\n return toolError(\n `the trace-tool budget of ${maxToolCalls} calls is spent; answer from the evidence already read`,\n )\n}\n\nfunction systemPrompt(request: TraceAnalysisEngineRequest, investigationTurns: number): string {\n return [\n request.instructions.trim(),\n [\n 'HOW THIS INVESTIGATION RUNS:',\n `- You have ${investigationTurns} investigation turns and at most ${request.limits.maxToolCalls} trace-tool calls.`,\n '- Call the trace tools to read the store. Never state a trace fact you did not read.',\n `- A tool result longer than ${request.limits.maxOutputChars} characters is truncated; narrow the query instead of asking again.`,\n '- A tool result carrying an \"error\" field is feedback: fix the call or take another route.',\n '- Answer with no tool call once you have the evidence. You are then asked for the final report.',\n ].join('\\n'),\n ].join('\\n\\n')\n}\n\nfunction reportPrompt(reportFormat: 'json-object' | 'json-schema'): string {\n return [\n 'Report now. Do not call any more tools.',\n 'Return one JSON object with exactly two fields:',\n ' \"answer\": a direct prose answer to the question.',\n ' \"findings\": an array of findings in the schema above. Emit [] when there is nothing to report.',\n reportFormat === 'json-object'\n ? 'Return the object alone, with no surrounding prose and no code fence.'\n : 'Return the object in the response schema you were given.',\n ].join('\\n')\n}\n\nfunction renderTaskInputs(taskInputs: Readonly<Record<string, unknown>>): string {\n // The engine contract forbids dropping structured inputs. This engine has no\n // code environment to bind them as variables, so they are delivered whole as\n // conversation material and the runtime record says which way they arrived.\n return [\n 'TASK INPUTS — structured material delivered with the question, not fetched through tools:',\n JSON.stringify(taskInputs, null, 2),\n ].join('\\n')\n}\n\ninterface ParsedReport {\n answer: string\n findings: TraceAnalysisEngineResult['findings']\n rejectedFindings: number\n}\n\nfunction parseReport(\n content: string,\n analystId: string,\n onRejectedFinding: (index: number, reason: string) => void,\n): ParsedReport {\n const envelope = coerceReportEnvelope(content, analystId)\n if (typeof envelope.answer !== 'string' || !envelope.answer.trim()) {\n throw new Error(`chat trace engine report for '${analystId}' carried no answer`)\n }\n // Findings are model output: one malformed row is model noise, not an engine\n // fault, and the rest of the paid investigation must survive it.\n const decoded = decodeRawFindingArray(envelope.findings)\n if (decoded.topLevelError !== undefined) {\n throw new Error(\n `chat trace engine report for '${analystId}' had a malformed findings array: ${decoded.topLevelError}`,\n )\n }\n for (const rejection of decoded.rejected) {\n onRejectedFinding(\n rejection.index,\n `${rejection.code}${rejection.path ? ` at ${rejection.path}` : ''}: ${rejection.message}`,\n )\n }\n return {\n answer: envelope.answer,\n findings: decoded.accepted,\n rejectedFindings: decoded.rejected.length,\n }\n}\n\nfunction coerceReportEnvelope(content: string, analystId: string): Record<string, unknown> {\n let value: unknown\n try {\n value = JSON.parse(extractJsonPayload(content))\n } catch (error) {\n throw new Error(`chat trace engine report for '${analystId}' was not JSON: ${messageOf(error)}`)\n }\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error(`chat trace engine report for '${analystId}' was not a JSON object`)\n }\n return value as Record<string, unknown>\n}\n\nfunction resolveModel(options: ChatTraceEngineOptions): string {\n const model = options.model ?? options.chat.defaultModel\n if (typeof model !== 'string' || !model.trim() || model !== model.trim()) {\n throw new TypeError(\n 'chat trace engine needs a model: pass ChatTraceEngineOptions.model or bind defaultModel on the ChatClient',\n )\n }\n return model\n}\n","/**\n * LockedJsonlAppender — mutex-serialized JSONL append helper for arbitrary\n * payloads. The reference-replay store does the same thing for typed\n * `ReferenceReplayRun` rows; this is the generic version used by\n * `MutationTelemetry`, `TrialTelemetry`, and any other consumer that wants\n * append-only durable telemetry without rolling its own lock.\n *\n * Locks are per absolute file path (process-local). Cross-process\n * concurrency is NOT addressed — that's an fcntl/flock problem.\n */\n\nimport { appendFileSync, existsSync, mkdirSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport { Mutex } from './concurrency'\n\nconst mutexes = new Map<string, Mutex>()\n\nfunction getMutex(path: string): Mutex {\n let m = mutexes.get(path)\n if (!m) {\n m = new Mutex()\n mutexes.set(path, m)\n }\n return m\n}\n\nexport class LockedJsonlAppender {\n private readonly mutex: Mutex\n constructor(public readonly path: string) {\n this.mutex = getMutex(path)\n if (!existsSync(dirname(path))) {\n mkdirSync(dirname(path), { recursive: true })\n }\n }\n\n async append(entry: unknown): Promise<void> {\n const line = `${JSON.stringify(entry)}\\n`\n await this.mutex.runExclusive(() => {\n appendFileSync(this.path, line)\n })\n }\n}\n\n/** Reset all internal mutex state — tests only. */\nexport function resetLockedAppendersForTesting(): void {\n mutexes.clear()\n}\n","/**\n * FindingsStore — durable persistence for AnalystFinding rows + a diff\n * helper so we can answer \"what changed since the last run?\" without\n * recomputing analysts.\n *\n * On-disk shape is JSONL: one finding per line, append-only, locked via\n * LockedJsonlAppender. Operators get crash-safety (no partial JSON),\n * cheap reads (sequential parse), and trivial backup (rsync the file).\n *\n * Reads are non-locking: a reader sees a consistent snapshot of all\n * fully-written lines and skips an incomplete trailing line if the\n * writer is mid-append. Cross-process locking is intentionally out of\n * scope (see locked-jsonl-appender.ts).\n *\n * The store is run-scoped: callers pass `runId` on append and on load,\n * which keeps multi-run files cleanly partitioned. The `diffFindings`\n * helper compares two run-id sets using stable `finding_id` semantics —\n * the diff is the cross-run signal the regression dashboard renders.\n */\n\nimport { existsSync, readFileSync } from 'node:fs'\n\nimport { LockedJsonlAppender } from '../locked-jsonl-appender'\nimport type { AnalystFinding } from './types'\n\n/**\n * One persisted row. We attach `run_id` on disk so a single file can\n * hold multiple runs and the diff helper can query without re-walking\n * separate files.\n */\nexport interface PersistedFinding extends AnalystFinding {\n run_id: string\n}\n\nexport class FindingsStore {\n private readonly appender: LockedJsonlAppender\n\n constructor(public readonly path: string) {\n this.appender = new LockedJsonlAppender(path)\n }\n\n async append(runId: string, findings: AnalystFinding[]): Promise<void> {\n for (const f of findings) {\n const row: PersistedFinding = { ...f, run_id: runId }\n await this.appender.append(row)\n }\n }\n\n /** Load every persisted finding. Discards malformed trailing lines silently. */\n loadAll(): PersistedFinding[] {\n if (!existsSync(this.path)) return []\n const raw = readFileSync(this.path, 'utf8')\n if (!raw) return []\n const out: PersistedFinding[] = []\n for (const line of raw.split('\\n')) {\n if (!line) continue\n try {\n out.push(JSON.parse(line) as PersistedFinding)\n } catch {\n // Skip torn trailing line — the lock guarantees no torn lines\n // mid-file, only at EOF when a writer is in-flight.\n }\n }\n return out\n }\n\n /** Filter to a single run. */\n loadRun(runId: string): PersistedFinding[] {\n return this.loadAll().filter((r) => r.run_id === runId)\n }\n}\n\n// ── Cross-run diff ──────────────────────────────────────────────────\n\nexport interface FindingsDiff {\n /** New finding ids in `current` that weren't in `previous`. */\n appeared: PersistedFinding[]\n /** Finding ids in `previous` that aren't in `current`. */\n disappeared: PersistedFinding[]\n /** Same finding id present in both runs and unchanged per the materiality test. */\n persisted: PersistedFinding[]\n /**\n * Same finding id in both runs but at least one non-identity field\n * shifted per `DiffPolicy.isMaterial`. Reported as [previous, current].\n */\n changed: Array<{ previous: PersistedFinding; current: PersistedFinding }>\n}\n\nexport interface DiffPolicy {\n /**\n * Predicate that decides whether two findings (same finding_id) count\n * as a material change. Defaults to {@link defaultIsMaterial}: severity\n * shift, confidence Δ > 0.05, or evidence count change. Compliance /\n * perf consumers MAY supply a stricter predicate (e.g. rationale text\n * diff, metric Δ thresholds).\n */\n isMaterial?: (previous: AnalystFinding, current: AnalystFinding) => boolean\n}\n\n/**\n * Default materiality test. Deliberately narrow so LLM-reword churn\n * doesn't flood the diff. Stricter tests are opt-in via DiffPolicy.\n */\nfunction defaultIsMaterial(a: AnalystFinding, b: AnalystFinding): boolean {\n if (a.severity !== b.severity) return true\n if (Math.abs((a.confidence ?? 0) - (b.confidence ?? 0)) > 0.05) return true\n if (a.evidence_refs.length !== b.evidence_refs.length) return true\n return false\n}\n\n/**\n * Diff two findings sets by stable finding_id. Callers typically load\n * the two run-id slices from the same store and pass them in.\n */\nexport function diffFindings(\n previous: PersistedFinding[],\n current: PersistedFinding[],\n policy: DiffPolicy = {},\n): FindingsDiff {\n const isMaterial = policy.isMaterial ?? defaultIsMaterial\n const prevById = new Map(previous.map((f) => [f.finding_id, f]))\n const curById = new Map(current.map((f) => [f.finding_id, f]))\n\n const appeared: PersistedFinding[] = []\n const disappeared: PersistedFinding[] = []\n const persisted: PersistedFinding[] = []\n const changed: FindingsDiff['changed'] = []\n\n for (const [id, cur] of curById) {\n const prev = prevById.get(id)\n if (!prev) {\n appeared.push(cur)\n continue\n }\n if (isMaterial(prev, cur)) {\n changed.push({ previous: prev, current: cur })\n } else {\n persisted.push(cur)\n }\n }\n for (const [id, prev] of prevById) {\n if (!curById.has(id)) disappeared.push(prev)\n }\n return { appeared, disappeared, persisted, changed }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,MAAM,4BAA4B;AAClC,MAAM,YAAY;;AAGlB,MAAM,oBAAoB;;;;;;AAqC1B,SAAS,wBAA2E;CAClF,MAAM,MAAM,EAAE,aAAa,yBAAyB,EAAE,QAAQ,UAAU,CAAC;CAIzE,OAAO,IAAI;CACX,OAAO;EACL,MAAM;EACN,QAAQ;GACN,MAAM;GACN,sBAAsB;GACtB,UAAU,CAAC,UAAU,UAAU;GAC/B,YAAY;IACV,QAAQ;KAAE,MAAM;KAAU,aAAa;IAAuC;IAC9E,UAAU;KAAE,MAAM;KAAS,OAAO;IAAI;GACxC;EACF;CACF;AACF;AAEA,MAAM,qBAAqB,sBAAsB;;;;;AAMjD,SAAgB,sBAAsB,SAAsD;CAC1F,MAAM,QAAQ,aAAa,OAAO;CAClC,MAAM,kBAAkB,QAAQ,mBAAA;CAChC,IAAI,CA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cAAc,QAAQ,OAAO;CAC9D,OAAO;AACT;;;;;AAMA,SAAgB,aACd,UACA,SACA,SAAqB,CAAC,GACR;CACd,MAAM,aAAa,OAAO,cAAc;CACxC,MAAM,WAAW,IAAI,IAAI,SAAS,KAAK,MAAM,CAAC,EAAE,YAAY,CAAC,CAAC,CAAC;CAC/D,MAAM,UAAU,IAAI,IAAI,QAAQ,KAAK,MAAM,CAAC,EAAE,YAAY,CAAC,CAAC,CAAC;CAE7D,MAAM,WAA+B,CAAC;CACtC,MAAM,cAAkC,CAAC;CACzC,MAAM,YAAgC,CAAC;CACvC,MAAM,UAAmC,CAAC;CAE1C,KAAK,MAAM,CAAC,IAAI,QAAQ,SAAS;EAC/B,MAAM,OAAO,SAAS,IAAI,EAAE;EAC5B,IAAI,CAAC,MAAM;GACT,SAAS,KAAK,GAAG;GACjB;EACF;EACA,IAAI,WAAW,MAAM,GAAG,GACtB,QAAQ,KAAK;GAAE,UAAU;GAAM,SAAS;EAAI,CAAC;OAE7C,UAAU,KAAK,GAAG;CAEtB;CACA,KAAK,MAAM,CAAC,IAAI,SAAS,UACvB,IAAI,CAAC,QAAQ,IAAI,EAAE,GAAG,YAAY,KAAK,IAAI;CAE7C,OAAO;EAAE;EAAU;EAAa;EAAW;CAAQ;AACrD"}
|
package/dist/fuzz.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fuzz.d.ts","names":[],"sources":["../src/fuzz/types.ts","../src/fuzz/cube.ts","../src/fuzz/capsule.ts","../src/fuzz/fuzz-agent.ts","../src/fuzz/gates.ts","../src/fuzz/policies.ts","../src/fuzz/tools.ts"],"mappings":";;;;UA2BiB;EACf;EACA;;;UAIe;EACf,MAAM;;;UAIS;;EAEf;EACA,QAAQ;;;;;;;;UAWO,mBAAmB;;EAElC,aAAa;;EAEb;;EAEA;;EAEA;;;EAGA;;;KAIU,UAAU,MAAM,UAAU,GAAG,MAAM,SAAS,QAAQ;;UAK/C,mBAAmB;EACl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c,UAAU,GAAG,IAAI,eAAe;;EAE9C,YAAY;;EAEZ,QAAQ,cAAc;;EAEtB;;EAEA;;EAEA;;EAEA,YAAY,UAAU,GAAG,UAAU,UAAU,IAAI,MAAM,SAAS,QAAQ,KAAK;;EAE7E;;;EAGA;;EAEA,SAAS;;EAET,cAAc,OAAO,aAAa;;EAElC;;;;;;;EAOA,UAAU,UAAU,GAAG,MAAM,MAAM,IAAI,eAAe;;EAEtD,mBAAmB,UAAU,GAAG,MAAM,SAAS;;;;;EAK/C;;;;;;;EAOA,SAAS;;EAET,UAAU;IAAS;IAAa,SAAS;;;;UCzS1B;EACf,MAAM;EACN,IAAI;;EAEJ;;EAEA;;;EAGA;;;wBAIc,eAAe,OAAO,gBAAgB;;wBActC,OAAO,OAAO,eAAe,QAAQ;;;;;wBAkBrC,cAAc,OAAO,QAAQ,KAAK,cAAc,oBAAoB;
|
|
1
|
+
{"version":3,"file":"fuzz.d.ts","names":[],"sources":["../src/fuzz/types.ts","../src/fuzz/cube.ts","../src/fuzz/capsule.ts","../src/fuzz/fuzz-agent.ts","../src/fuzz/gates.ts","../src/fuzz/policies.ts","../src/fuzz/tools.ts"],"mappings":";;;;UA2BiB;EACf;EACA;;;UAIe;EACf,MAAM;;;UAIS;;EAEf;EACA,QAAQ;;;;;;;;UAWO,mBAAmB;;EAElC,aAAa;;EAEb;;EAEA;;EAEA;;;EAGA;;;KAIU,UAAU,MAAM,UAAU,GAAG,MAAM,SAAS,QAAQ;;UAK/C,mBAAmB;EAClC,MAAM;EACN,OAAO;;EAEP,QAAQ;;EAER,UAAU,cAAc,YAAY;;EAEpC;EACA;;;;;;;;;;;;KAaU,iBAAiB,MAAM,KAAK,mBAAmB,OAAO,QAAQ,OAAO;;;;;;UAOhE;EACf;EACA,SAAS,IAAI,YAAY,KAAK;;EAE9B;;UAGe;EACf;EACA,oBAAoB,MAAM;;;;;;;;UASX,cAAc;EAC7B,WAAW,UAAU,GAAG,IAAI,YAAY,MAAM,mBAAmB;E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G,MAAM,SAAS;;;;;EAK/C;;;;;;;EAOA,SAAS;;EAET,UAAU;IAAS;IAAa,SAAS;;;;UCzS1B;EACf,MAAM;EACN,IAAI;;EAEJ;;EAEA;;;EAGA;;;wBAIc,eAAe,OAAO,gBAAgB;;wBActC,OAAO,OAAO,eAAe,QAAQ;;;;;wBAkBrC,cAAc,OAAO,QAAQ,KAAK,cAAc,oBAAoB;UCvCnE,kBAAkB;EACjC;EACA;EACA,OAAO;EACP,KAAK;;EAEL;EACA,SAAS,aAAa;EACtB,UAAU,YAAY;EACtB;EACA;;;EAGA;IAAS;IAAiB;;;EAE1B;;EAEA;IAAiB;IAAuB;;;UAyIzB;;EAEf;;EAEA;;;wBAIc,kBAAkB,GAChC,SAAS,YAAY,IACrB,OAAM;KC7KI,iBAAiB,KAAK,KAAK,eAAe;;EAEpD;;wBAGoB,UAAU,GAC9B,MAAM,iBAAiB,KACtB;EAAU,SAAS,YAAY;;;wBCRlB,aAAa,MAAM,MAAM,MAAM,cAAc,kBAAkB,cAAc;;;;;;;;wBAyB7E,0BAA0B,GAAG;EAC3C,UAAU,UAAU;;EAEpB,UAAU,UAAU,MAAM;;EAE1B;IACE,cAAc;;;;;wBAgBF,kBAAkB,GAAG;EACnC;EACA;IACE,cAAc;;;;;;wBCxCF,iBAAiB,GAAG;EAClC,eAAe,MAAM,SAAS,oBAAoB;EAClD,aAAa,GAAG;IACd,iBAAiB;;;;;;;;;UCfJ;EACf;EACA;;EAEA,YAAY;EACZ,UAAU,eAAe;IAAQ,SAAS;QAAkB"}
|
package/dist/fuzz.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { s as ValidationError } from "./errors-DeEEV9Vx.js";
|
|
2
|
-
import { ut as summarizeNumberSeries } from "./statistics-
|
|
2
|
+
import { ut as summarizeNumberSeries } from "./statistics-DSidA5I2.js";
|
|
3
3
|
import { t as mulberry32 } from "./random-DrzcgC7F.js";
|
|
4
4
|
import { o as CostReceiptCaptureError, t as CostLedger } from "./cost-ledger-1CwUnVOd.js";
|
|
5
5
|
// src/fuzz/cube.ts
|
package/dist/fuzz.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fuzz.js","names":[],"sources":["../src/fuzz/cube.ts","../src/fuzz/capsule.ts","../src/rl/active-curriculum.ts","../src/fuzz/policies.ts","../src/fuzz/explorer.ts","../src/fuzz/fuzz-agent.ts","../src/fuzz/gates.ts"],"sourcesContent":["/**\n * Input-space tiling + coverage projection.\n *\n * Cells are the cartesian product of the input axes — the stratification plan,\n * enumerable up front so the planned-vs-covered denominator is honest. Coverage\n * is projected from the evaluation log: per cell, the full DISTRIBUTION of the\n * headline score, of each scored dimension, and of evaluation latency — a bare\n * mean hides outliers, so every aggregate carries its spread. Per-cell cost is\n * split known-dollars vs unknown-runs, never folded into a fabricated $0.\n */\n\nimport { summarizeNumberSeries } from '../statistics'\nimport type { BehaviorSpace, Cell, CoverageCell, Distribution, Evaluation } from './types'\n\n/** One recorded evaluation — the unit coverage and the capsule are built from. */\nexport interface EvalRecord {\n cell: Cell\n ev: Evaluation\n /** The objective's interest score for this evaluation. */\n interest: number\n /** Evaluation wall-clock — engine-measured unless `ev.latencyMs` overrode it. */\n latencyMs: number\n /** Known dollars for this run. `null` = cost tracking was wired but this\n * run's cost was unknowable (counted apart). Absent = not tracked at all. */\n costUsd?: number | null\n}\n\n/** Enumerate every input cell (cartesian product of the axes), in stable order. */\nexport function enumerateCells(space: BehaviorSpace): Cell[] {\n if (space.axes.length === 0) return []\n let partials: Array<Record<string, string>> = [{}]\n for (const axis of space.axes) {\n const next: Array<Record<string, string>> = []\n for (const partial of partials) {\n for (const value of axis.values) next.push({ ...partial, [axis.name]: value })\n }\n partials = next\n }\n return partials.map((coords) => ({ id: cellId(space, coords), coords }))\n}\n\n/** Deterministic id for a coordinate map, e.g. `matterType=nda|difficulty=hard`. */\nexport function cellId(space: BehaviorSpace, coords: Record<string, string>): string {\n return space.axes.map((a) => `${a.name}=${coords[a.name]}`).join('|')\n}\n\n/** Summarize a sample. Throws on an empty sample — callers represent \"no data\"\n * as `null`, never as a zeroed distribution. */\nexport function distribution(values: number[]): Distribution {\n const summary = summarizeNumberSeries(values)\n if (!summary)\n throw new Error('distribution: empty sample — represent missing data as null, not zeros')\n const { n, min, p50: median, p90, max, sum } = summary\n return { mean: sum / n, median, p90, min, max, n }\n}\n\n/**\n * Project the evaluation log into the per-input-cell coverage map. A cell with\n * no evaluations reports `score: null` (honestly uncovered), never zeros.\n */\nexport function buildCoverage(cells: Cell[], log: EvalRecord[], threshold: number): CoverageCell[] {\n const byCell = new Map<string, EvalRecord[]>()\n for (const r of log) {\n const arr = byCell.get(r.cell.id) ?? []\n arr.push(r)\n byCell.set(r.cell.id, arr)\n }\n return cells.map((cell) => {\n const recs = byCell.get(cell.id) ?? []\n const runs = recs.length\n if (runs === 0)\n return { cell, runs: 0, score: null, findingRate: 0, dimensions: {}, latencyMs: null }\n\n const score = distribution(recs.map((r) => r.ev.score))\n const latencyMs = distribution(recs.map((r) => r.latencyMs))\n const findingRate = recs.filter((r) => r.interest >= threshold).length / runs\n\n const dimSamples: Record<string, number[]> = {}\n for (const r of recs) {\n for (const [k, v] of Object.entries(r.ev.scores ?? {})) {\n const samples = dimSamples[k] ?? []\n samples.push(v)\n dimSamples[k] = samples\n }\n }\n const dimensions: Record<string, Distribution> = {}\n for (const [k, xs] of Object.entries(dimSamples)) dimensions[k] = distribution(xs)\n\n // Cost fields appear only when tracking was wired: known dollars sum, and\n // tracked-but-unknown runs counted apart — never folded in as $0.\n const tracked = recs.filter((r) => r.costUsd !== undefined)\n const known = tracked.filter((r) => r.costUsd !== null)\n const cost =\n tracked.length > 0\n ? {\n costUsd: known.reduce((a, r) => a + (r.costUsd as number), 0),\n ...(tracked.length > known.length\n ? { costUnknownRuns: tracked.length - known.length }\n : {}),\n }\n : {}\n\n return { cell, runs, score, findingRate, dimensions, latencyMs, ...cost }\n })\n}\n","/**\n * The capsule — the artifact every exploration produces.\n *\n * `buildCapsule` assembles coverage + verified findings + the QD archive into a\n * pure `CapsuleData` (no clock, no I/O — deterministic and snapshot-testable).\n * `renderCapsuleHtml` turns it into a standalone page: the input-cell heat-map\n * (planned vs covered), per-dimension weakness chips, and the minimized finding\n * exemplars. One artifact — the hardening map and the shareable proof object.\n */\n\nimport type { EvalRecord } from './cube'\nimport { buildCoverage, distribution } from './cube'\nimport type { ArchiveEntry, CapsuleData, Cell, CoverageCell, Distribution, FuzzFinding } from './types'\n\nexport interface BuildCapsuleInput<S> {\n target: string\n objective: string\n cells: Cell[]\n log: EvalRecord[]\n /** The objective's notable threshold — drives findingRate. */\n threshold: number\n archive: ArchiveEntry<S>[]\n findings: FuzzFinding<S>[]\n candidateFindings: number\n runsUsed: number\n /** Known-dollar / unknown-run split — present only when cost tracking was\n * wired; the capsule never fabricates a $0 total. */\n cost?: { costUsd: number; costUnknownRuns: number }\n /** Evaluations that threw — infra outcomes, never folded into robustness. */\n evalErrors: number\n /** Set when the consecutive-error circuit breaker stopped the run early. */\n stoppedEarly?: { reason: 'eval-errors'; detail: string }\n}\n\nexport function buildCapsule<S>(input: BuildCapsuleInput<S>): CapsuleData<S> {\n const coverage = buildCoverage(input.cells, input.log, input.threshold)\n const covered = coverage.filter((c) => c.runs > 0)\n // Cells weigh equally: variance steering sends more runs to weak cells, so a\n // run-weighted average would bias the headline low.\n const robustness =\n covered.length === 0 ? null : distribution(covered.map((c) => (c.score as Distribution).mean))\n const latencyMs = input.log.length === 0 ? null : distribution(input.log.map((r) => r.latencyMs))\n // Measured-descriptor bins beyond the bare input cell — observed, never planned.\n const behaviorBinsObserved = input.archive.filter((e) => e.binId !== e.cell.id).length\n\n return {\n target: input.target,\n objective: input.objective,\n coverage,\n findings: [...input.findings].sort((a, b) => b.interest - a.interest),\n archive: [...input.archive].sort((a, b) => b.interest - a.interest),\n stats: {\n totalRuns: input.runsUsed,\n cellsTotal: input.cells.length,\n cellsCovered: covered.length,\n behaviorBinsObserved,\n candidateFindings: input.candidateFindings,\n verifiedFindings: input.findings.length,\n robustness,\n latencyMs,\n ...(input.cost\n ? { costUsd: input.cost.costUsd, costUnknownRuns: input.cost.costUnknownRuns }\n : {}),\n evalErrors: input.evalErrors,\n ...(input.stoppedEarly ? { stoppedEarly: input.stoppedEarly } : {}),\n },\n }\n}\n\n// ── HTML capsule ──────────────────────────────────────────────────────────────\n\nfunction esc(s: string): string {\n return s.replace(\n /[&<>\"]/g,\n (c) => ({ '&': '&', '<': '<', '>': '>', '\"': '"' })[c] as string,\n )\n}\n\n/** red (0) → amber (.5) → green (1); uncovered cells render gray. */\nfunction robustnessColor(r: number | null): string {\n if (r == null) return '#2a2a2e'\n return `hsl(${Math.round(r * 120)} 70% 42%)`\n}\n\nfunction pct(x: number): string {\n return `${Math.round(x * 100)}%`\n}\n\nfunction deriveAxes(coverage: CoverageCell[]): Array<{ name: string; values: string[] }> {\n const order: string[] = []\n const seen = new Map<string, Set<string>>()\n for (const c of coverage) {\n for (const [k, v] of Object.entries(c.cell.coords)) {\n if (!seen.has(k)) {\n seen.set(k, new Set())\n order.push(k)\n }\n seen.get(k)?.add(v)\n }\n }\n return order.map((name) => ({ name, values: [...(seen.get(name) ?? [])] }))\n}\n\n/** The weakest dimension chip for a cell, e.g. `safety 32%` — shown when scores exist. */\nfunction weakestDim(c: CoverageCell): string {\n const entries = Object.entries(c.dimensions).map(([k, d]) => [k, d.mean] as [string, number])\n if (entries.length === 0) return ''\n const sorted = entries.sort((a, b) => a[1] - b[1])\n const w = sorted[0]\n if (!w) return ''\n return `<span class=\"dim\">${esc(w[0])} ${pct(w[1])}</span>`\n}\n\nfunction heatmapHtml(coverage: CoverageCell[]): string {\n const axes = deriveAxes(coverage)\n const byId = new Map(coverage.map((c) => [c.cell.id, c]))\n const tile = (c: CoverageCell | undefined, label: string): string => {\n const r = c?.score?.mean ?? null\n const title = c?.score\n ? `${pct(c.score.mean)} robust (median ${pct(c.score.median)}, min ${pct(c.score.min)}) · ${c.runs} runs · ${pct(c.findingRate)} flagged${c.latencyMs ? ` · ${(c.latencyMs.median / 1000).toFixed(1)}s median` : ''}${c.costUsd !== undefined ? ` · $${c.costUsd.toFixed(2)}` : ''}`\n : 'not covered'\n return `<div class=\"tile\" style=\"background:${robustnessColor(r)}\" title=\"${esc(title)}\">${label ? `<span class=\"tl\">${esc(label)}</span>` : ''}<span class=\"tv\">${c && r != null ? pct(r) : '—'}</span>${c ? weakestDim(c) : ''}</div>`\n }\n\n const rowAxis = axes[0]\n const colAxis = axes[1]\n if (axes.length === 2 && rowAxis && colAxis) {\n const head = `<tr><th></th>${colAxis.values.map((v) => `<th>${esc(v)}</th>`).join('')}</tr>`\n const rows = rowAxis.values\n .map((rv) => {\n const cells = colAxis.values\n .map((cv) => {\n const id = `${rowAxis.name}=${rv}|${colAxis.name}=${cv}`\n return `<td>${tile(byId.get(id), '')}</td>`\n })\n .join('')\n return `<tr><th class=\"rh\">${esc(rv)}</th>${cells}</tr>`\n })\n .join('')\n return `<div class=\"axis-label\">rows: <b>${esc(rowAxis.name)}</b> · cols: <b>${esc(colAxis.name)}</b></div><table class=\"heat\">${head}${rows}</table>`\n }\n\n const sorted = [...coverage].sort((a, b) => (a.score?.mean ?? 2) - (b.score?.mean ?? 2))\n return `<div class=\"grid\">${sorted.map((c) => tile(c, Object.values(c.cell.coords).join(' · '))).join('')}</div>`\n}\n\nfunction findingsHtml<S>(findings: FuzzFinding<S>[], limit: number): string {\n if (findings.length === 0)\n return `<p class=\"none\">No verified findings — the target held across every covered cell.</p>`\n return findings\n .slice(0, limit)\n .map((f) => {\n const coords = Object.entries(f.cell.coords)\n .map(([k, v]) => `${k}:${v}`)\n .join(' · ')\n const labels = (f.evaluation.labels ?? [])\n .map((l) => `<span class=\"fclass\">${esc(l)}</span>`)\n .join('')\n const dims = Object.entries(f.evaluation.scores ?? {})\n .sort((a, b) => a[1] - b[1])\n .slice(0, 3)\n .map(([k, v]) => `<span class=\"dim\">${esc(k)} ${pct(v)}</span>`)\n .join('')\n return `<div class=\"fail\"><div class=\"fmeta\"><span class=\"fcell\">${esc(coords)}</span>${labels}<span class=\"fsev\">interest ${pct(f.interest)}</span></div><div class=\"sevbar\"><div class=\"sevfill\" style=\"width:${pct(f.interest)}\"></div></div><div class=\"ftext\">${esc(f.text ?? '(scenario text not captured)')}</div>${dims ? `<div class=\"fdims\">${dims}</div>` : ''}</div>`\n })\n .join('')\n}\n\nexport interface RenderCapsuleOptions {\n /** Max finding exemplars to show. Default 8. */\n maxFindings?: number\n /** ISO timestamp to stamp into the page (keeps the pure capsule clock-free). */\n generatedAt?: string\n}\n\n/** Render a self-contained HTML capsule — heat-map + per-dimension chips + verified findings. */\nexport function renderCapsuleHtml<S>(\n capsule: CapsuleData<S>,\n opts: RenderCapsuleOptions = {},\n): string {\n const s = capsule.stats\n const kpi = (label: string, value: string, accent = '#e6e6e6'): string =>\n `<div class=\"kpi\"><div class=\"kv\" style=\"color:${accent}\">${esc(value)}</div><div class=\"kl\">${esc(label)}</div></div>`\n const lift = capsule.lift\n ? kpi(\n 'hardening lift',\n `${capsule.lift.before.toFixed(2)} → ${capsule.lift.after.toFixed(2)}`,\n '#5ad17a',\n )\n : ''\n // Cost KPI only when tracking was wired — an untracked run never shows $0.\n // Unpriced runs are named in the label (amber): the total is a lower bound.\n const cost =\n s.costUsd !== undefined\n ? kpi(\n s.costUnknownRuns ? `cost · ${s.costUnknownRuns} runs unpriced` : 'cost',\n `$${s.costUsd.toFixed(2)}`,\n s.costUnknownRuns ? '#e5c07b' : '#e6e6e6',\n )\n : ''\n const stamp = opts.generatedAt ?? capsule.generatedAt ?? ''\n\n return `<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n<title>${esc(capsule.objective)} capsule — ${esc(capsule.target)}</title>\n<style>\n:root{color-scheme:dark}\n*{box-sizing:border-box}\nbody{margin:0;background:#0c0c0f;color:#e6e6e6;font:14px/1.5 ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,sans-serif}\n.wrap{max-width:980px;margin:0 auto;padding:40px 24px}\nh1{font-size:22px;margin:0 0 2px;letter-spacing:-.01em}\n.sub{color:#8a8a93;font-size:13px;margin-bottom:28px}\n.kpis{display:flex;gap:14px;flex-wrap:wrap;margin-bottom:32px}\n.kpi{background:#16161b;border:1px solid #24242b;border-radius:12px;padding:14px 18px;min-width:120px}\n.kv{font-size:24px;font-weight:650;letter-spacing:-.02em}\n.kl{color:#8a8a93;font-size:12px;margin-top:2px}\nh2{font-size:13px;text-transform:uppercase;letter-spacing:.08em;color:#8a8a93;margin:34px 0 14px}\n.axis-label{color:#8a8a93;font-size:12px;margin-bottom:10px}\ntable.heat{border-collapse:separate;border-spacing:6px}\ntable.heat th{font-weight:500;color:#a8a8b0;font-size:12px;padding:4px 8px;text-align:center}\ntable.heat th.rh{text-align:right}\n.tile{position:relative;width:104px;height:66px;border-radius:10px;display:flex;flex-direction:column;justify-content:center;align-items:center;gap:1px;color:#06120a;font-weight:600}\n.tile .tv{font-size:17px}\n.tile .tl{font-size:10px;font-weight:600;opacity:.9;padding:0 6px;text-align:center}\n.tile .dim{font-size:9px;font-weight:600;opacity:.85;background:rgba(0,0,0,.22);padding:0 6px;border-radius:999px}\n.grid{display:flex;flex-wrap:wrap;gap:8px}\n.grid .tile{width:138px;height:74px}\n.fail{background:#16161b;border:1px solid #24242b;border-left:3px solid #d1495b;border-radius:10px;padding:12px 14px;margin-bottom:10px}\n.fmeta{display:flex;gap:10px;align-items:center;font-size:12px;color:#a8a8b0;margin-bottom:8px}\n.fcell{color:#cfcfd6}\n.fclass{background:#2a1a1d;color:#e58a96;padding:1px 8px;border-radius:999px;font-size:11px}\n.fsev{margin-left:auto;color:#e58a96}\n.sevbar{height:4px;background:#24242b;border-radius:2px;overflow:hidden;margin-bottom:10px}\n.sevfill{height:100%;background:#d1495b}\n.ftext{font-size:13px;color:#d8d8df;white-space:pre-wrap}\n.fdims{display:flex;gap:6px;margin-top:8px}\n.fdims .dim{background:#1d2530;color:#9fc1e8;padding:1px 8px;border-radius:999px;font-size:11px}\n.none{color:#5ad17a}\n.foot{color:#5a5a63;font-size:11px;margin-top:36px}\n</style></head><body><div class=\"wrap\">\n<h1>${esc(capsule.objective)} exploration · ${esc(capsule.target)}</h1>\n<div class=\"sub\">${s.totalRuns} scenarios across ${s.cellsCovered}/${s.cellsTotal} planned cells${s.behaviorBinsObserved > 0 ? ` · ${s.behaviorBinsObserved} measured behavior bins` : ''}${stamp ? ` · ${esc(stamp)}` : ''}</div>\n<div class=\"kpis\">\n${s.robustness ? kpi('robustness', `${pct(s.robustness.mean)}`, s.robustness.mean < 0.6 ? '#e58a96' : '#5ad17a') : ''}\n${s.robustness ? kpi('cell spread', `${pct(s.robustness.min)}–${pct(s.robustness.max)}`) : ''}\n${s.latencyMs ? kpi('median latency', `${(s.latencyMs.median / 1000).toFixed(1)}s`, s.latencyMs.p90 > 4 * s.latencyMs.median ? '#e5b566' : '#e6e6e6') : ''}\n${kpi('verified findings', String(s.verifiedFindings), s.verifiedFindings > 0 ? '#e58a96' : '#5ad17a')}\n${kpi('cells covered', `${s.cellsCovered}/${s.cellsTotal}`)}\n${kpi('scenarios run', String(s.totalRuns))}\n${cost}\n${s.evalErrors > 0 ? kpi('eval errors', String(s.evalErrors), '#e5b566') : ''}\n${lift}\n</div>\n${s.stoppedEarly ? `<div class=\"sub\" style=\"color:#e5b566\">stopped early: ${esc(s.stoppedEarly.detail)} — coverage below reflects the completed portion only</div>` : ''}\n<h2>Coverage map</h2>\n${heatmapHtml(capsule.coverage)}\n<h2>Verified findings${s.candidateFindings > s.verifiedFindings ? ` · ${s.verifiedFindings} of ${s.candidateFindings} candidates passed the validity gates` : ''}</h2>\n${findingsHtml(capsule.findings, opts.maxFindings ?? 8)}\n<div class=\"foot\">Findings are gate-verified: each is a fair, answerable task that reproduces under a meaning-preserving rephrase, minimized to the smallest trigger.</div>\n</div></body></html>`\n}\n","/**\n * Adaptive curriculum: active scenario selection by variance.\n *\n * Fixed scenario sets waste sample budget on cells whose outcome is already\n * settled. `varianceBasedCurriculum` scores each (variant, scenario) cell by\n * the empirical variance of past observations and allocates the next round's\n * budget toward the noisy and under-sampled cells. The output is a next-round\n * allocation, a list of (variant, scenario, count) triples, which the\n * consumer runs and feeds back.\n *\n * Choosing which search node to expand is not a curriculum; it belongs to the\n * search policy (`aide` draws parents by Thompson sampling over each node's\n * posterior, in `campaign/search-policy.ts`). Scenario generation belongs to\n * the adversarial primitive.\n */\n\nexport interface CellObservation {\n variantId: string\n scenarioId: string\n /** Observed score in [0, 1]. */\n score: number\n}\n\nexport interface CurriculumAllocation {\n variantId: string\n scenarioId: string\n /** How many additional reps to run on this cell. */\n count: number\n /** Strategy-specific reason for the allocation. */\n reason: string\n}\n\nexport interface VarianceCurriculumOptions {\n /** Total reps to allocate across all cells. */\n budget: number\n /**\n * Smoothing prior on variance — keeps the allocator from concentrating\n * on a cell with one observation just because its 1-sample variance is\n * 0. Default 0.05.\n */\n variancePrior?: number\n /**\n * Minimum reps per cell — even when the variance estimate is low, give\n * every cell at least this many. Default 1.\n */\n floorPerCell?: number\n}\n\n/**\n * Variance-proportional allocation. For each cell, estimate variance from\n * past observations + a prior, then allocate the budget proportional to\n * (sqrt(variance) + 1/sqrt(n)) — a classical optimal-allocation rule\n * (Neyman 1934) that balances \"explore noisy cells\" with \"explore\n * under-sampled cells.\"\n */\nexport function varianceBasedCurriculum(\n observations: CellObservation[],\n candidateCells: Array<{ variantId: string; scenarioId: string }>,\n opts: VarianceCurriculumOptions,\n): CurriculumAllocation[] {\n const variancePrior = opts.variancePrior ?? 0.05\n const floor = opts.floorPerCell ?? 1\n const budget = opts.budget\n\n const grouped = new Map<string, number[]>()\n for (const o of observations) {\n const k = `${o.variantId}::${o.scenarioId}`\n const arr = grouped.get(k) ?? []\n arr.push(o.score)\n grouped.set(k, arr)\n }\n\n const cellStats = candidateCells.map((c) => {\n const k = `${c.variantId}::${c.scenarioId}`\n const samples = grouped.get(k) ?? []\n const n = samples.length\n const mean = n === 0 ? 0.5 : samples.reduce((s, v) => s + v, 0) / n\n const variance =\n n < 2\n ? variancePrior\n : samples.reduce((s, v) => s + (v - mean) ** 2, 0) / (n - 1) + variancePrior\n // Neyman optimal allocation: weight ∝ √variance; add √(1/n) to break\n // ties toward under-sampled cells.\n const weight = Math.sqrt(variance) + 1 / Math.sqrt(Math.max(1, n))\n return { variantId: c.variantId, scenarioId: c.scenarioId, n, mean, variance, weight }\n })\n\n // Reserve floor*N for the floor; allocate the rest proportional to weight.\n const floorTotal = floor * cellStats.length\n if (floorTotal >= budget) {\n const each = Math.max(1, Math.floor(budget / Math.max(1, cellStats.length)))\n return cellStats.map((c) => ({\n variantId: c.variantId,\n scenarioId: c.scenarioId,\n count: each,\n reason: `floor allocation (budget tight; n=${c.n})`,\n }))\n }\n const remaining = budget - floorTotal\n const totalWeight = cellStats.reduce((s, c) => s + c.weight, 0)\n return cellStats.map((c) => {\n const proportional = totalWeight === 0 ? 0 : Math.round((c.weight / totalWeight) * remaining)\n return {\n variantId: c.variantId,\n scenarioId: c.scenarioId,\n count: floor + proportional,\n reason: `variance ${c.variance.toFixed(3)} (n=${c.n}, mean=${c.mean.toFixed(3)})`,\n }\n })\n}\n","/**\n * Shipped policies for the exploration engine.\n *\n * `MutationProposer` is a plain function type — an agent running a generator skill\n * IS a proposer (`(ctx) => dispatchToSkill(ctx)`), no wrapper needed. `mutationProposer`\n * builds the deterministic, LLM-free one from mutation operators. Objectives are\n * interfaces because the engine reads `kind` + `threshold` off them.\n */\n\nimport type { AdversarialMutation } from '../rl/adversarial'\nimport type {\n Cell,\n MutationProposer,\n FuzzObjective,\n FuzzProposeContext,\n} from './types'\n\nconst clamp01 = (x: number): number => Math.max(0, Math.min(1, x))\n\n// ── proposers ─────────────────────────────────────────────────────────────────\n\n/**\n * Perturbation-based search: apply the cell's mutation operators to the current\n * elites + seeds, deduping by id. Elites first — mutating the most interesting\n * scenario found so far is what makes the search deepen across rounds.\n */\nexport function mutationProposer<S>(opts: {\n mutationsFor: (cell: Cell) => AdversarialMutation<S>[]\n scenarioId: (s: S) => string\n}): MutationProposer<S> {\n return async (ctx: FuzzProposeContext<S>): Promise<S[]> => {\n const mutations = opts.mutationsFor(ctx.cell)\n const parents = [...ctx.elites, ...ctx.seeds]\n const seen = new Set(parents.map(opts.scenarioId))\n const out: S[] = []\n for (const parent of parents) {\n if (out.length >= ctx.count) break\n for (const m of mutations) {\n const children = await m.mutate(parent, ctx.rng)\n for (const child of children) {\n const id = opts.scenarioId(child)\n if (seen.has(id)) continue\n seen.add(id)\n out.push(child)\n if (out.length >= ctx.count) break\n }\n if (out.length >= ctx.count) break\n }\n }\n return out\n }\n}\n\n// ── objectives ────────────────────────────────────────────────────────────────\n\n/** Adversarial: a low headline score is interesting — find where the agent fails. */\nexport function adversarialObjective(threshold = 0.5): FuzzObjective {\n return { kind: 'adversarial', threshold, interest: (ev) => clamp01(1 - ev.score) }\n}\n\n\n\n\n","/**\n * The exploration engine — a stateful session over a behavior space.\n *\n * Each `step()`: allocate budget across INPUT cells (floor first, then variance\n * steering toward the least-certain cells), propose candidates (the proposer\n * reads current elites + findings, so the search deepens generationally),\n * evaluate with bounded concurrency, archive the most interesting scenario per\n * input×measured bin, and admit notable candidates that pass the validity gates.\n * `run()` loops to budget. `coverage()`/`findings()`/`capsule()` read live state —\n * the surface `makeExploreTools` exposes so an agent can drive the session.\n *\n * One evaluation log (`EvalRecord[]`) is the source of truth; allocation\n * observations and coverage are projections of it.\n */\n\nimport { CostLedger, type CostLedgerHandle, CostReceiptCaptureError } from '../cost-ledger'\nimport { ValidationError } from '../errors'\nimport { varianceBasedCurriculum } from '../rl/active-curriculum'\nimport { mulberry32 } from '../statistics/random'\nimport { buildCapsule } from './capsule'\nimport type { EvalRecord } from './cube'\nimport { enumerateCells } from './cube'\nimport { adversarialObjective } from './policies'\nimport type {\n ArchiveEntry,\n CapsuleData,\n Cell,\n CoverageCell,\n ExploreOptions,\n FuzzFinding,\n FuzzObjective,\n} from './types'\n\nasync function pMap<T>(\n items: T[],\n fn: (item: T) => Promise<void>,\n concurrency: number,\n signal?: AbortSignal,\n): Promise<void> {\n let i = 0\n const workers = Array.from(\n { length: Math.max(1, Math.min(concurrency, items.length)) },\n async () => {\n while (i < items.length) {\n if (signal?.aborted) return\n const item = items[i++]\n if (item === undefined) return\n await fn(item)\n }\n },\n )\n await Promise.all(workers)\n}\n\nexport class BehaviorExplorer<S> {\n private readonly cells: Cell[]\n private readonly cellById: Map<string, Cell>\n private readonly objective: FuzzObjective\n private readonly threshold: number\n private readonly floorPerCell: number\n private readonly perRoundBudget: number\n\n /** The single evaluation log — coverage + allocation are projections of it. */\n private readonly log: Array<EvalRecord & { scenarioId: string }> = []\n /** binId (input × measured coords) → the most interesting entry seen. */\n private readonly archiveByBin = new Map<string, ArchiveEntry<S>>()\n private readonly _findings: FuzzFinding<S>[] = []\n private runsUsed = 0\n private candidateFindings = 0\n private evalErrors = 0\n private consecutiveEvalErrors = 0\n private stoppedEarly: { reason: 'eval-errors'; detail: string } | undefined\n private readonly rng: () => number\n private readonly costLedger?: CostLedgerHandle\n private readonly costPhase = 'fuzz.explore'\n\n constructor(private readonly opts: ExploreOptions<S>) {\n this.cells = enumerateCells(opts.space)\n if (this.cells.length === 0)\n throw new Error('BehaviorExplorer: space has no cells — every axis needs ≥1 value')\n if (opts.costBudgetUsd !== undefined) {\n if (\n typeof opts.costBudgetUsd !== 'number' ||\n !Number.isFinite(opts.costBudgetUsd) ||\n opts.costBudgetUsd < 0\n ) {\n throw new RangeError(\n `BehaviorExplorer: costBudgetUsd must be a nonnegative finite number, got ${String(opts.costBudgetUsd)}`,\n )\n }\n }\n if (!opts.costOf && (opts.costBudgetUsd !== undefined || opts.ledger || opts.onCost)) {\n throw new ValidationError(\n 'BehaviorExplorer: costBudgetUsd/ledger/onCost require costOf — the explorer ' +\n 'cannot know run cost without it; supply costOf or drop the cost options',\n )\n }\n if (\n (opts.costBudgetUsd !== undefined || opts.ledger?.costCeilingUsd !== undefined) &&\n !opts.maximumChargeOf\n ) {\n throw new ValidationError(\n 'BehaviorExplorer: capped cost tracking requires maximumChargeOf before evaluation',\n )\n }\n if (\n opts.ledger &&\n opts.costBudgetUsd !== undefined &&\n opts.ledger.costCeilingUsd !== opts.costBudgetUsd\n ) {\n throw new ValidationError(\n 'BehaviorExplorer: costBudgetUsd must match the supplied CostLedger ceiling',\n )\n }\n if (opts.costOf) this.costLedger = opts.ledger ?? new CostLedger(opts.costBudgetUsd)\n this.cellById = new Map(this.cells.map((c) => [c.id, c]))\n this.objective = opts.objective ?? adversarialObjective(0.5)\n this.threshold = this.objective.threshold ?? 0.5\n this.floorPerCell = opts.floorPerCell ?? 2\n this.perRoundBudget = Math.max(\n this.cells.length * this.floorPerCell,\n Math.ceil(opts.budget / 4),\n )\n this.rng = mulberry32(opts.seed ?? 1)\n }\n\n private binId(cell: Cell, descriptor: Record<string, string> | undefined): string {\n if (!descriptor || Object.keys(descriptor).length === 0) return cell.id\n const measured = Object.keys(descriptor)\n .sort()\n .map((k) => `${k}=${descriptor[k]}`)\n .join('|')\n return `${cell.id}|${measured}`\n }\n\n private allocate(budget: number): Array<{ cellId: string; count: number }> {\n if ((this.opts.allocation ?? 'variance') === 'uniform') {\n const per = Math.max(this.floorPerCell, Math.floor(budget / this.cells.length))\n return this.cells.map((c) => ({ cellId: c.id, count: per }))\n }\n return varianceBasedCurriculum(\n this.log.map((r) => ({\n variantId: r.cell.id,\n scenarioId: '*',\n score: r.ev.score,\n })),\n this.cells.map((c) => ({ variantId: c.id, scenarioId: '*' })),\n { budget, floorPerCell: this.floorPerCell },\n ).map((a) => ({ cellId: a.variantId, count: a.count }))\n }\n\n private objectiveContext() {\n const entries = [...this.archiveByBin.values()]\n return {\n archiveScores: entries.map((e) => e.evaluation.score),\n archiveDescriptors: entries.map((e) => e.evaluation.descriptor),\n }\n }\n\n /** Elites whose INPUT cell matches — what the proposer mutates/deepens from. */\n private elitesFor(cellId: string): S[] {\n const out: S[] = []\n for (const e of this.archiveByBin.values()) if (e.cell.id === cellId) out.push(e.scenario)\n return out\n }\n\n /** One allocate → propose → evaluate → gate → archive round. */\n async step(): Promise<{ runs: number; findings: FuzzFinding<S>[] }> {\n const remaining = this.opts.budget - this.runsUsed\n if (remaining <= 0 || this.opts.signal?.aborted) return { runs: 0, findings: [] }\n\n const allocations = this.allocate(Math.min(this.perRoundBudget, remaining))\n const newFindings: FuzzFinding<S>[] = []\n let runsThisStep = 0\n\n for (const alloc of allocations) {\n if (\n this.runsUsed >= this.opts.budget ||\n this.stoppedEarly !== undefined ||\n this.opts.signal?.aborted\n )\n break\n const cell = this.cellById.get(alloc.cellId)\n if (!cell) continue\n const cap = Math.min(alloc.count, this.opts.budget - this.runsUsed)\n if (cap <= 0) continue\n this.opts.onProgress?.({ type: 'cell-allocated', cell, count: cap })\n\n const seeds = await this.opts.seedsFor(cell)\n const elites = this.elitesFor(cell.id)\n const proposed = await this.opts.proposer({\n cell,\n seeds,\n elites,\n findings: this._findings,\n count: cap,\n rng: this.rng,\n })\n // Cold cells evaluate their seeds first (the coverage floor); warm cells\n // trust the proposer, which already saw the elites.\n const cold = this.log.every((r) => r.cell.id !== cell.id)\n const toEval = [...(cold ? seeds : []), ...proposed].slice(0, cap)\n\n await pMap(\n toEval,\n async (scenario) => {\n if (\n this.runsUsed >= this.opts.budget ||\n this.stoppedEarly !== undefined ||\n this.opts.signal?.aborted\n )\n return\n // evaluate/gates/minimize cross an external boundary (router, backend,\n // judge). A throw there is an infra outcome: record it as a typed\n // eval-error and keep exploring — one 5xx must not kill a campaign.\n // Consecutive failures trip the circuit breaker instead, so a dead\n // backend stops the run rather than burning the remaining budget.\n try {\n const startedAt = performance.now()\n const paid = this.costLedger\n ? await this.costLedger.runPaidCall({\n channel: 'agent',\n phase: this.costPhase,\n actor: 'fuzz.evaluate',\n tags: { target: this.opts.target, cell: cell.id },\n signal: this.opts.signal,\n maximumCharge: this.opts.maximumChargeOf?.(scenario, cell),\n execute: () => this.opts.evaluate(scenario, cell),\n receipt: (evaluation) => {\n const cost = this.opts.costOf!(scenario, cell, evaluation)\n if (cost === null) {\n return {\n model: 'unattributed',\n inputTokens: 0,\n outputTokens: 0,\n costUnknown: true,\n }\n }\n if (!Number.isFinite(cost.usd) || cost.usd < 0) {\n throw new RangeError(\n `BehaviorExplorer: costOf returned an invalid usd (${String(cost.usd)}) — ` +\n 'return null when cost is unknown, never a fabricated number',\n )\n }\n return {\n model: cost.model ?? 'unattributed',\n inputTokens: 0,\n outputTokens: 0,\n actualCostUsd: cost.usd,\n }\n },\n })\n : undefined\n if (paid && !paid.succeeded) {\n if (\n paid.error instanceof CostReceiptCaptureError &&\n paid.error.receiptError instanceof RangeError\n ) {\n throw paid.error.receiptError\n }\n throw paid.error\n }\n const ev = paid ? paid.value : await this.opts.evaluate(scenario, cell)\n // Consumer-measured latency wins (it can exclude judge time); the\n // engine's wall-clock is the default so latency is never missing.\n const latencyMs = ev.latencyMs ?? performance.now() - startedAt\n this.runsUsed++\n runsThisStep++\n this.consecutiveEvalErrors = 0\n const costUsd = paid\n ? paid.receipt.costUnknown\n ? null\n : paid.receipt.costUsd\n : undefined\n if (paid?.receipt.actualCostUsd !== undefined) {\n this.opts.onCost?.({ usd: paid.receipt.actualCostUsd, channel: 'agent' })\n }\n const interest = this.objective.interest(ev, this.objectiveContext())\n this.log.push({\n cell,\n ev,\n interest,\n latencyMs,\n ...(costUsd !== undefined ? { costUsd } : {}),\n scenarioId: this.opts.scenarioId(scenario),\n })\n this.opts.onProgress?.({ type: 'evaluated', cell, scenario, evaluation: ev })\n\n const bin = this.binId(cell, ev.descriptor)\n const cur = this.archiveByBin.get(bin)\n if (!cur || interest > cur.interest)\n this.archiveByBin.set(bin, { binId: bin, cell, scenario, evaluation: ev, interest })\n\n if (interest < this.threshold) return\n this.candidateFindings++\n if (this.opts.gates?.isValid && !(await this.opts.gates.isValid(scenario, ev, cell)))\n return\n if (\n this.opts.gates?.isUncontaminated &&\n !(await this.opts.gates.isUncontaminated(scenario, ev, cell))\n )\n return\n\n const minimized = this.opts.minimize\n ? await this.opts.minimize(scenario, this.opts.evaluate, cell)\n : scenario\n const finding: FuzzFinding<S> = {\n id: this.opts.scenarioId(scenario),\n cell,\n scenario,\n minimized,\n text: this.opts.scenarioText?.(minimized),\n evaluation: ev,\n interest,\n objective: this.objective.kind,\n }\n this._findings.push(finding)\n newFindings.push(finding)\n this.opts.onProgress?.({ type: 'finding', finding })\n } catch (err) {\n // Internal validation errors (e.g. a fabricated costOf number) are\n // programming mistakes, not backend outcomes — they stay loud.\n if (err instanceof RangeError) throw err\n this.evalErrors++\n this.consecutiveEvalErrors++\n const message = err instanceof Error ? err.message : String(err)\n this.opts.onProgress?.({\n type: 'eval-error',\n cell,\n scenarioId: this.opts.scenarioId(scenario),\n message,\n })\n const limit = this.opts.maxConsecutiveEvalErrors ?? 5\n if (this.consecutiveEvalErrors >= limit) {\n this.stoppedEarly = {\n reason: 'eval-errors',\n detail: `${this.consecutiveEvalErrors} consecutive eval errors (last: ${message})`,\n }\n }\n }\n },\n this.opts.concurrency ?? 1,\n this.opts.signal,\n )\n }\n\n this.opts.onProgress?.({ type: 'round', runsUsed: this.runsUsed, budget: this.opts.budget })\n return { runs: runsThisStep, findings: newFindings }\n }\n\n /** Loop `step()` until the run or dollar budget is spent, the signal aborts,\n * or no progress is made. */\n async run(): Promise<CapsuleData<S>> {\n while (\n this.runsUsed < this.opts.budget &&\n this.stoppedEarly === undefined &&\n !this.opts.signal?.aborted\n ) {\n const { runs } = await this.step()\n if (runs === 0 && this.stoppedEarly === undefined) break\n }\n return this.capsule()\n }\n\n coverage(): CoverageCell[] {\n return this.capsule().coverage\n }\n\n findings(): FuzzFinding<S>[] {\n return [...this._findings].sort((a, b) => b.interest - a.interest)\n }\n\n capsule(): CapsuleData<S> {\n const cost = this.costLedger?.summary({\n phase: this.costPhase,\n tags: { target: this.opts.target },\n })\n return buildCapsule({\n target: this.opts.target,\n objective: this.objective.kind,\n cells: this.cells,\n log: this.log,\n threshold: this.threshold,\n archive: [...this.archiveByBin.values()],\n findings: this._findings,\n candidateFindings: this.candidateFindings,\n runsUsed: this.runsUsed,\n cost: cost\n ? {\n costUsd: cost.totalCostUsd,\n costUnknownRuns: cost.byChannel.reduce((sum, row) => sum + row.unpricedCalls, 0),\n }\n : undefined,\n evalErrors: this.evalErrors,\n stoppedEarly: this.stoppedEarly,\n })\n }\n}\n","/**\n * `fuzzAgent` — the adversarial batch preset over `BehaviorExplorer`.\n *\n * One call: explore the space to budget with the adversarial objective and\n * return the capsule. For agent-driven, incremental, or multi-objective use,\n * construct a `BehaviorExplorer` and drive it via `makeExploreTools`.\n */\n\nimport { BehaviorExplorer } from './explorer'\nimport { adversarialObjective } from './policies'\nimport type { CapsuleData, ExploreOptions } from './types'\n\nexport type FuzzAgentOptions<S> = Omit<ExploreOptions<S>, 'objective'> & {\n /** Score strictly below this is a candidate failure. Default 0.5. */\n failureThreshold?: number\n}\n\nexport async function fuzzAgent<S>(\n opts: FuzzAgentOptions<S>,\n): Promise<{ capsule: CapsuleData<S> }> {\n const { failureThreshold, ...rest } = opts\n const explorer = new BehaviorExplorer<S>({\n ...rest,\n objective: adversarialObjective(failureThreshold ?? 0.5),\n })\n return { capsule: await explorer.run() }\n}\n","/**\n * Validity gates — what separates a fuzzer from a slop generator.\n *\n * A notable candidate is admitted only when it is fair and reproducible. None of\n * these are on by default: the live wiring opts in, so reported findings carry\n * their proof.\n */\n\nimport type { Cell, Evaluation, Evaluator, ValidityGates } from './types'\n\n/** Combine gate sets; a candidate must pass every gate in every set. */\nexport function composeGates<S>(...sets: Array<ValidityGates<S> | undefined>): ValidityGates<S> {\n const present = sets.filter((s): s is ValidityGates<S> => s != null)\n return {\n isValid: async (scenario, ev, cell) => {\n for (const g of present) {\n if (g.isValid && !(await g.isValid(scenario, ev, cell))) return false\n }\n return true\n },\n isUncontaminated: async (scenario, ev, cell) => {\n for (const g of present) {\n if (g.isUncontaminated && !(await g.isUncontaminated(scenario, ev, cell))) return false\n }\n return true\n },\n }\n}\n\n/**\n * Reproducibility gate. Re-run the target on a meaning-preserving rephrase of the\n * flagged scenario; keep the finding only when the rephrase ALSO scores below the\n * threshold. A finding that flips under a cosmetic rewrite was keyed to surface\n * form, not the task — a false signal we must not report. Costs one extra\n * evaluation per candidate (candidates are rare, so cheap).\n */\nexport function perturbationStabilityGate<S>(opts: {\n evaluate: Evaluator<S>\n /** Produce a semantic-preserving rephrase. Return null to skip (treated as pass). */\n perturb: (scenario: S) => S | null\n /** Score strictly below this still counts as failing. Default 0.5. */\n failureThreshold?: number\n}): ValidityGates<S> {\n const threshold = opts.failureThreshold ?? 0.5\n return {\n isUncontaminated: async (scenario: S, _ev: Evaluation, cell: Cell) => {\n const rephrased = opts.perturb(scenario)\n if (rephrased == null) return true\n const re = await opts.evaluate(rephrased, cell)\n return re.score < threshold\n },\n }\n}\n\n/**\n * Severity-floor gate. Reject borderline candidates whose score sits in a band\n * just under the threshold — judge noise, not a real defect.\n */\nexport function severityFloorGate<S>(opts: {\n failureThreshold?: number\n margin?: number\n}): ValidityGates<S> {\n const threshold = opts.failureThreshold ?? 0.5\n const margin = opts.margin ?? 0.1\n return {\n isValid: (_scenario, ev: Evaluation) => ev.score <= threshold - margin,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA4BA,SAAgB,eAAe,OAA8B;CAC3D,IAAI,MAAM,KAAK,WAAW,GAAG,OAAO,CAAC;CACrC,IAAI,WAA0C,CAAC,CAAC,CAAC;CACjD,KAAK,MAAM,QAAQ,MAAM,MAAM;EAC7B,MAAM,OAAsC,CAAC;EAC7C,KAAK,MAAM,WAAW,UACpB,KAAK,MAAM,SAAS,KAAK,QAAQ,KAAK,KAAK;GAAE,GAAG;IAAU,KAAK,OAAO;EAAM,CAAC;EAE/E,WAAW;CACb;CACA,OAAO,SAAS,KAAK,YAAY;EAAE,IAAI,OAAO,OAAO,MAAM;EAAG;CAAO,EAAE;AACzE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KAAK;GACjB,cAAc,KAAK;EACrB,CAAC;CACH;AACF;;;;;;;;;AC5XA,eAAsB,UACpB,MACsC;CACtC,MAAM,EAAE,kBAAkB,GAAG,SAAS;CAKtC,OAAO,EAAE,SAAS,MAAM,IAJH,iBAAoB;EACvC,GAAG;EACH,WAAW,qBAAqB,oBAAoB,EAAG;CACzD,CAC+B,CAAC,CAAC,IAAI,EAAE;AACzC;;;ACfA,SAAgB,aAAgB,GAAG,MAA6D;CAC9F,MAAM,UAAU,KAAK,QAAQ,MAA6B,KAAK,IAAI;CACnE,OAAO;EACL,SAAS,OAAO,UAAU,IAAI,SAAS;GACrC,KAAK,MAAM,KAAK,SACd,IAAI,EAAE,WAAW,CAAE,MAAM,EAAE,QAAQ,UAAU,IAAI,IAAI,GAAI,OAAO;GAElE,OAAO;EACT;EACA,kBAAkB,OAAO,UAAU,IAAI,SAAS;GAC9C,KAAK,MAAM,KAAK,SACd,IAAI,EAAE,oBAAoB,CAAE,MAAM,EAAE,iBAAiB,UAAU,IAAI,IAAI,GAAI,OAAO;GAEpF,OAAO;EACT;CACF;AACF;;;;;;;;AASA,SAAgB,0BAA6B,MAMxB;CACnB,MAAM,YAAY,KAAK,oBAAoB;CAC3C,OAAO,EACL,kBAAkB,OAAO,UAAa,KAAiB,SAAe;EACpE,MAAM,YAAY,KAAK,QAAQ,QAAQ;EACvC,IAAI,aAAa,MAAM,OAAO;EAE9B,QAAO,MADU,KAAK,SAAS,WAAW,IAAI,EAAA,CACpC,QAAQ;CACpB,EACF;AACF;;;;;AAMA,SAAgB,kBAAqB,MAGhB;CACnB,MAAM,YAAY,KAAK,oBAAoB;CAC3C,MAAM,SAAS,KAAK,UAAU;CAC9B,OAAO,EACL,UAAU,WAAW,OAAmB,GAAG,SAAS,YAAY,OAClE;AACF"}
|
|
1
|
+
{"version":3,"file":"fuzz.js","names":[],"sources":["../src/fuzz/cube.ts","../src/fuzz/capsule.ts","../src/rl/active-curriculum.ts","../src/fuzz/policies.ts","../src/fuzz/explorer.ts","../src/fuzz/fuzz-agent.ts","../src/fuzz/gates.ts"],"sourcesContent":["/**\n * Input-space tiling + coverage projection.\n *\n * Cells are the cartesian product of the input axes — the stratification plan,\n * enumerable up front so the planned-vs-covered denominator is honest. Coverage\n * is projected from the evaluation log: per cell, the full DISTRIBUTION of the\n * headline score, of each scored dimension, and of evaluation latency — a bare\n * mean hides outliers, so every aggregate carries its spread. Per-cell cost is\n * split known-dollars vs unknown-runs, never folded into a fabricated $0.\n */\n\nimport { summarizeNumberSeries } from '../statistics'\nimport type { BehaviorSpace, Cell, CoverageCell, Distribution, Evaluation } from './types'\n\n/** One recorded evaluation — the unit coverage and the capsule are built from. */\nexport interface EvalRecord {\n cell: Cell\n ev: Evaluation\n /** The objective's interest score for this evaluation. */\n interest: number\n /** Evaluation wall-clock — engine-measured unless `ev.latencyMs` overrode it. */\n latencyMs: number\n /** Known dollars for this run. `null` = cost tracking was wired but this\n * run's cost was unknowable (counted apart). Absent = not tracked at all. */\n costUsd?: number | null\n}\n\n/** Enumerate every input cell (cartesian product of the axes), in stable order. */\nexport function enumerateCells(space: BehaviorSpace): Cell[] {\n if (space.axes.length === 0) return []\n let partials: Array<Record<string, string>> = [{}]\n for (const axis of space.axes) {\n const next: Array<Record<string, string>> = []\n for (const partial of partials) {\n for (const value of axis.values) next.push({ ...partial, [axis.name]: value })\n }\n partials = next\n }\n return partials.map((coords) => ({ id: cellId(space, coords), coords }))\n}\n\n/** Deterministic id for a coordinate map, e.g. `matterType=nda|difficulty=hard`. */\nexport function cellId(space: BehaviorSpace, coords: Record<string, string>): string {\n return space.axes.map((a) => `${a.name}=${coords[a.name]}`).join('|')\n}\n\n/** Summarize a sample. Throws on an empty sample — callers represent \"no data\"\n * as `null`, never as a zeroed distribution. */\nexport function distribution(values: number[]): Distribution {\n const summary = summarizeNumberSeries(values)\n if (!summary)\n throw new Error('distribution: empty sample — represent missing data as null, not zeros')\n const { n, min, p50: median, p90, max, sum } = summary\n return { mean: sum / n, median, p90, min, max, n }\n}\n\n/**\n * Project the evaluation log into the per-input-cell coverage map. A cell with\n * no evaluations reports `score: null` (honestly uncovered), never zeros.\n */\nexport function buildCoverage(cells: Cell[], log: EvalRecord[], threshold: number): CoverageCell[] {\n const byCell = new Map<string, EvalRecord[]>()\n for (const r of log) {\n const arr = byCell.get(r.cell.id) ?? []\n arr.push(r)\n byCell.set(r.cell.id, arr)\n }\n return cells.map((cell) => {\n const recs = byCell.get(cell.id) ?? []\n const runs = recs.length\n if (runs === 0)\n return { cell, runs: 0, score: null, findingRate: 0, dimensions: {}, latencyMs: null }\n\n const score = distribution(recs.map((r) => r.ev.score))\n const latencyMs = distribution(recs.map((r) => r.latencyMs))\n const findingRate = recs.filter((r) => r.interest >= threshold).length / runs\n\n const dimSamples: Record<string, number[]> = {}\n for (const r of recs) {\n for (const [k, v] of Object.entries(r.ev.scores ?? {})) {\n const samples = dimSamples[k] ?? []\n samples.push(v)\n dimSamples[k] = samples\n }\n }\n const dimensions: Record<string, Distribution> = {}\n for (const [k, xs] of Object.entries(dimSamples)) dimensions[k] = distribution(xs)\n\n // Cost fields appear only when tracking was wired: known dollars sum, and\n // tracked-but-unknown runs counted apart — never folded in as $0.\n const tracked = recs.filter((r) => r.costUsd !== undefined)\n const known = tracked.filter((r) => r.costUsd !== null)\n const cost =\n tracked.length > 0\n ? {\n costUsd: known.reduce((a, r) => a + (r.costUsd as number), 0),\n ...(tracked.length > known.length\n ? { costUnknownRuns: tracked.length - known.length }\n : {}),\n }\n : {}\n\n return { cell, runs, score, findingRate, dimensions, latencyMs, ...cost }\n })\n}\n","/**\n * The capsule — the artifact every exploration produces.\n *\n * `buildCapsule` assembles coverage + verified findings + the QD archive into a\n * pure `CapsuleData` (no clock, no I/O — deterministic and snapshot-testable).\n * `renderCapsuleHtml` turns it into a standalone page: the input-cell heat-map\n * (planned vs covered), per-dimension weakness chips, and the minimized finding\n * exemplars. One artifact — the hardening map and the shareable proof object.\n */\n\nimport type { EvalRecord } from './cube'\nimport { buildCoverage, distribution } from './cube'\nimport type {\n ArchiveEntry,\n CapsuleData,\n Cell,\n CoverageCell,\n Distribution,\n FuzzFinding,\n} from './types'\n\nexport interface BuildCapsuleInput<S> {\n target: string\n objective: string\n cells: Cell[]\n log: EvalRecord[]\n /** The objective's notable threshold — drives findingRate. */\n threshold: number\n archive: ArchiveEntry<S>[]\n findings: FuzzFinding<S>[]\n candidateFindings: number\n runsUsed: number\n /** Known-dollar / unknown-run split — present only when cost tracking was\n * wired; the capsule never fabricates a $0 total. */\n cost?: { costUsd: number; costUnknownRuns: number }\n /** Evaluations that threw — infra outcomes, never folded into robustness. */\n evalErrors: number\n /** Set when the consecutive-error circuit breaker stopped the run early. */\n stoppedEarly?: { reason: 'eval-errors'; detail: string }\n}\n\nexport function buildCapsule<S>(input: BuildCapsuleInput<S>): CapsuleData<S> {\n const coverage = buildCoverage(input.cells, input.log, input.threshold)\n const covered = coverage.filter((c) => c.runs > 0)\n // Cells weigh equally: variance steering sends more runs to weak cells, so a\n // run-weighted average would bias the headline low.\n const robustness =\n covered.length === 0 ? null : distribution(covered.map((c) => (c.score as Distribution).mean))\n const latencyMs = input.log.length === 0 ? null : distribution(input.log.map((r) => r.latencyMs))\n // Measured-descriptor bins beyond the bare input cell — observed, never planned.\n const behaviorBinsObserved = input.archive.filter((e) => e.binId !== e.cell.id).length\n\n return {\n target: input.target,\n objective: input.objective,\n coverage,\n findings: [...input.findings].sort((a, b) => b.interest - a.interest),\n archive: [...input.archive].sort((a, b) => b.interest - a.interest),\n stats: {\n totalRuns: input.runsUsed,\n cellsTotal: input.cells.length,\n cellsCovered: covered.length,\n behaviorBinsObserved,\n candidateFindings: input.candidateFindings,\n verifiedFindings: input.findings.length,\n robustness,\n latencyMs,\n ...(input.cost\n ? { costUsd: input.cost.costUsd, costUnknownRuns: input.cost.costUnknownRuns }\n : {}),\n evalErrors: input.evalErrors,\n ...(input.stoppedEarly ? { stoppedEarly: input.stoppedEarly } : {}),\n },\n }\n}\n\n// ── HTML capsule ──────────────────────────────────────────────────────────────\n\nfunction esc(s: string): string {\n return s.replace(\n /[&<>\"]/g,\n (c) => ({ '&': '&', '<': '<', '>': '>', '\"': '"' })[c] as string,\n )\n}\n\n/** red (0) → amber (.5) → green (1); uncovered cells render gray. */\nfunction robustnessColor(r: number | null): string {\n if (r == null) return '#2a2a2e'\n return `hsl(${Math.round(r * 120)} 70% 42%)`\n}\n\nfunction pct(x: number): string {\n return `${Math.round(x * 100)}%`\n}\n\nfunction deriveAxes(coverage: CoverageCell[]): Array<{ name: string; values: string[] }> {\n const order: string[] = []\n const seen = new Map<string, Set<string>>()\n for (const c of coverage) {\n for (const [k, v] of Object.entries(c.cell.coords)) {\n if (!seen.has(k)) {\n seen.set(k, new Set())\n order.push(k)\n }\n seen.get(k)?.add(v)\n }\n }\n return order.map((name) => ({ name, values: [...(seen.get(name) ?? [])] }))\n}\n\n/** The weakest dimension chip for a cell, e.g. `safety 32%` — shown when scores exist. */\nfunction weakestDim(c: CoverageCell): string {\n const entries = Object.entries(c.dimensions).map(([k, d]) => [k, d.mean] as [string, number])\n if (entries.length === 0) return ''\n const sorted = entries.sort((a, b) => a[1] - b[1])\n const w = sorted[0]\n if (!w) return ''\n return `<span class=\"dim\">${esc(w[0])} ${pct(w[1])}</span>`\n}\n\nfunction heatmapHtml(coverage: CoverageCell[]): string {\n const axes = deriveAxes(coverage)\n const byId = new Map(coverage.map((c) => [c.cell.id, c]))\n const tile = (c: CoverageCell | undefined, label: string): string => {\n const r = c?.score?.mean ?? null\n const title = c?.score\n ? `${pct(c.score.mean)} robust (median ${pct(c.score.median)}, min ${pct(c.score.min)}) · ${c.runs} runs · ${pct(c.findingRate)} flagged${c.latencyMs ? ` · ${(c.latencyMs.median / 1000).toFixed(1)}s median` : ''}${c.costUsd !== undefined ? ` · $${c.costUsd.toFixed(2)}` : ''}`\n : 'not covered'\n return `<div class=\"tile\" style=\"background:${robustnessColor(r)}\" title=\"${esc(title)}\">${label ? `<span class=\"tl\">${esc(label)}</span>` : ''}<span class=\"tv\">${c && r != null ? pct(r) : '—'}</span>${c ? weakestDim(c) : ''}</div>`\n }\n\n const rowAxis = axes[0]\n const colAxis = axes[1]\n if (axes.length === 2 && rowAxis && colAxis) {\n const head = `<tr><th></th>${colAxis.values.map((v) => `<th>${esc(v)}</th>`).join('')}</tr>`\n const rows = rowAxis.values\n .map((rv) => {\n const cells = colAxis.values\n .map((cv) => {\n const id = `${rowAxis.name}=${rv}|${colAxis.name}=${cv}`\n return `<td>${tile(byId.get(id), '')}</td>`\n })\n .join('')\n return `<tr><th class=\"rh\">${esc(rv)}</th>${cells}</tr>`\n })\n .join('')\n return `<div class=\"axis-label\">rows: <b>${esc(rowAxis.name)}</b> · cols: <b>${esc(colAxis.name)}</b></div><table class=\"heat\">${head}${rows}</table>`\n }\n\n const sorted = [...coverage].sort((a, b) => (a.score?.mean ?? 2) - (b.score?.mean ?? 2))\n return `<div class=\"grid\">${sorted.map((c) => tile(c, Object.values(c.cell.coords).join(' · '))).join('')}</div>`\n}\n\nfunction findingsHtml<S>(findings: FuzzFinding<S>[], limit: number): string {\n if (findings.length === 0)\n return `<p class=\"none\">No verified findings — the target held across every covered cell.</p>`\n return findings\n .slice(0, limit)\n .map((f) => {\n const coords = Object.entries(f.cell.coords)\n .map(([k, v]) => `${k}:${v}`)\n .join(' · ')\n const labels = (f.evaluation.labels ?? [])\n .map((l) => `<span class=\"fclass\">${esc(l)}</span>`)\n .join('')\n const dims = Object.entries(f.evaluation.scores ?? {})\n .sort((a, b) => a[1] - b[1])\n .slice(0, 3)\n .map(([k, v]) => `<span class=\"dim\">${esc(k)} ${pct(v)}</span>`)\n .join('')\n return `<div class=\"fail\"><div class=\"fmeta\"><span class=\"fcell\">${esc(coords)}</span>${labels}<span class=\"fsev\">interest ${pct(f.interest)}</span></div><div class=\"sevbar\"><div class=\"sevfill\" style=\"width:${pct(f.interest)}\"></div></div><div class=\"ftext\">${esc(f.text ?? '(scenario text not captured)')}</div>${dims ? `<div class=\"fdims\">${dims}</div>` : ''}</div>`\n })\n .join('')\n}\n\nexport interface RenderCapsuleOptions {\n /** Max finding exemplars to show. Default 8. */\n maxFindings?: number\n /** ISO timestamp to stamp into the page (keeps the pure capsule clock-free). */\n generatedAt?: string\n}\n\n/** Render a self-contained HTML capsule — heat-map + per-dimension chips + verified findings. */\nexport function renderCapsuleHtml<S>(\n capsule: CapsuleData<S>,\n opts: RenderCapsuleOptions = {},\n): string {\n const s = capsule.stats\n const kpi = (label: string, value: string, accent = '#e6e6e6'): string =>\n `<div class=\"kpi\"><div class=\"kv\" style=\"color:${accent}\">${esc(value)}</div><div class=\"kl\">${esc(label)}</div></div>`\n const lift = capsule.lift\n ? kpi(\n 'hardening lift',\n `${capsule.lift.before.toFixed(2)} → ${capsule.lift.after.toFixed(2)}`,\n '#5ad17a',\n )\n : ''\n // Cost KPI only when tracking was wired — an untracked run never shows $0.\n // Unpriced runs are named in the label (amber): the total is a lower bound.\n const cost =\n s.costUsd !== undefined\n ? kpi(\n s.costUnknownRuns ? `cost · ${s.costUnknownRuns} runs unpriced` : 'cost',\n `$${s.costUsd.toFixed(2)}`,\n s.costUnknownRuns ? '#e5c07b' : '#e6e6e6',\n )\n : ''\n const stamp = opts.generatedAt ?? capsule.generatedAt ?? ''\n\n return `<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n<title>${esc(capsule.objective)} capsule — ${esc(capsule.target)}</title>\n<style>\n:root{color-scheme:dark}\n*{box-sizing:border-box}\nbody{margin:0;background:#0c0c0f;color:#e6e6e6;font:14px/1.5 ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,sans-serif}\n.wrap{max-width:980px;margin:0 auto;padding:40px 24px}\nh1{font-size:22px;margin:0 0 2px;letter-spacing:-.01em}\n.sub{color:#8a8a93;font-size:13px;margin-bottom:28px}\n.kpis{display:flex;gap:14px;flex-wrap:wrap;margin-bottom:32px}\n.kpi{background:#16161b;border:1px solid #24242b;border-radius:12px;padding:14px 18px;min-width:120px}\n.kv{font-size:24px;font-weight:650;letter-spacing:-.02em}\n.kl{color:#8a8a93;font-size:12px;margin-top:2px}\nh2{font-size:13px;text-transform:uppercase;letter-spacing:.08em;color:#8a8a93;margin:34px 0 14px}\n.axis-label{color:#8a8a93;font-size:12px;margin-bottom:10px}\ntable.heat{border-collapse:separate;border-spacing:6px}\ntable.heat th{font-weight:500;color:#a8a8b0;font-size:12px;padding:4px 8px;text-align:center}\ntable.heat th.rh{text-align:right}\n.tile{position:relative;width:104px;height:66px;border-radius:10px;display:flex;flex-direction:column;justify-content:center;align-items:center;gap:1px;color:#06120a;font-weight:600}\n.tile .tv{font-size:17px}\n.tile .tl{font-size:10px;font-weight:600;opacity:.9;padding:0 6px;text-align:center}\n.tile .dim{font-size:9px;font-weight:600;opacity:.85;background:rgba(0,0,0,.22);padding:0 6px;border-radius:999px}\n.grid{display:flex;flex-wrap:wrap;gap:8px}\n.grid .tile{width:138px;height:74px}\n.fail{background:#16161b;border:1px solid #24242b;border-left:3px solid #d1495b;border-radius:10px;padding:12px 14px;margin-bottom:10px}\n.fmeta{display:flex;gap:10px;align-items:center;font-size:12px;color:#a8a8b0;margin-bottom:8px}\n.fcell{color:#cfcfd6}\n.fclass{background:#2a1a1d;color:#e58a96;padding:1px 8px;border-radius:999px;font-size:11px}\n.fsev{margin-left:auto;color:#e58a96}\n.sevbar{height:4px;background:#24242b;border-radius:2px;overflow:hidden;margin-bottom:10px}\n.sevfill{height:100%;background:#d1495b}\n.ftext{font-size:13px;color:#d8d8df;white-space:pre-wrap}\n.fdims{display:flex;gap:6px;margin-top:8px}\n.fdims .dim{background:#1d2530;color:#9fc1e8;padding:1px 8px;border-radius:999px;font-size:11px}\n.none{color:#5ad17a}\n.foot{color:#5a5a63;font-size:11px;margin-top:36px}\n</style></head><body><div class=\"wrap\">\n<h1>${esc(capsule.objective)} exploration · ${esc(capsule.target)}</h1>\n<div class=\"sub\">${s.totalRuns} scenarios across ${s.cellsCovered}/${s.cellsTotal} planned cells${s.behaviorBinsObserved > 0 ? ` · ${s.behaviorBinsObserved} measured behavior bins` : ''}${stamp ? ` · ${esc(stamp)}` : ''}</div>\n<div class=\"kpis\">\n${s.robustness ? kpi('robustness', `${pct(s.robustness.mean)}`, s.robustness.mean < 0.6 ? '#e58a96' : '#5ad17a') : ''}\n${s.robustness ? kpi('cell spread', `${pct(s.robustness.min)}–${pct(s.robustness.max)}`) : ''}\n${s.latencyMs ? kpi('median latency', `${(s.latencyMs.median / 1000).toFixed(1)}s`, s.latencyMs.p90 > 4 * s.latencyMs.median ? '#e5b566' : '#e6e6e6') : ''}\n${kpi('verified findings', String(s.verifiedFindings), s.verifiedFindings > 0 ? '#e58a96' : '#5ad17a')}\n${kpi('cells covered', `${s.cellsCovered}/${s.cellsTotal}`)}\n${kpi('scenarios run', String(s.totalRuns))}\n${cost}\n${s.evalErrors > 0 ? kpi('eval errors', String(s.evalErrors), '#e5b566') : ''}\n${lift}\n</div>\n${s.stoppedEarly ? `<div class=\"sub\" style=\"color:#e5b566\">stopped early: ${esc(s.stoppedEarly.detail)} — coverage below reflects the completed portion only</div>` : ''}\n<h2>Coverage map</h2>\n${heatmapHtml(capsule.coverage)}\n<h2>Verified findings${s.candidateFindings > s.verifiedFindings ? ` · ${s.verifiedFindings} of ${s.candidateFindings} candidates passed the validity gates` : ''}</h2>\n${findingsHtml(capsule.findings, opts.maxFindings ?? 8)}\n<div class=\"foot\">Findings are gate-verified: each is a fair, answerable task that reproduces under a meaning-preserving rephrase, minimized to the smallest trigger.</div>\n</div></body></html>`\n}\n","/**\n * Adaptive curriculum: active scenario selection by variance.\n *\n * Fixed scenario sets waste sample budget on cells whose outcome is already\n * settled. `varianceBasedCurriculum` scores each (variant, scenario) cell by\n * the empirical variance of past observations and allocates the next round's\n * budget toward the noisy and under-sampled cells. The output is a next-round\n * allocation, a list of (variant, scenario, count) triples, which the\n * consumer runs and feeds back.\n *\n * Choosing which search node to expand is not a curriculum; it belongs to the\n * search policy (`aide` draws parents by Thompson sampling over each node's\n * posterior, in `campaign/search-policy.ts`). Scenario generation belongs to\n * the adversarial primitive.\n */\n\nexport interface CellObservation {\n variantId: string\n scenarioId: string\n /** Observed score in [0, 1]. */\n score: number\n}\n\nexport interface CurriculumAllocation {\n variantId: string\n scenarioId: string\n /** How many additional reps to run on this cell. */\n count: number\n /** Strategy-specific reason for the allocation. */\n reason: string\n}\n\nexport interface VarianceCurriculumOptions {\n /** Total reps to allocate across all cells. */\n budget: number\n /**\n * Smoothing prior on variance — keeps the allocator from concentrating\n * on a cell with one observation just because its 1-sample variance is\n * 0. Default 0.05.\n */\n variancePrior?: number\n /**\n * Minimum reps per cell — even when the variance estimate is low, give\n * every cell at least this many. Default 1.\n */\n floorPerCell?: number\n}\n\n/**\n * Variance-proportional allocation. For each cell, estimate variance from\n * past observations + a prior, then allocate the budget proportional to\n * (sqrt(variance) + 1/sqrt(n)) — a classical optimal-allocation rule\n * (Neyman 1934) that balances \"explore noisy cells\" with \"explore\n * under-sampled cells.\"\n */\nexport function varianceBasedCurriculum(\n observations: CellObservation[],\n candidateCells: Array<{ variantId: string; scenarioId: string }>,\n opts: VarianceCurriculumOptions,\n): CurriculumAllocation[] {\n const variancePrior = opts.variancePrior ?? 0.05\n const floor = opts.floorPerCell ?? 1\n const budget = opts.budget\n\n const grouped = new Map<string, number[]>()\n for (const o of observations) {\n const k = `${o.variantId}::${o.scenarioId}`\n const arr = grouped.get(k) ?? []\n arr.push(o.score)\n grouped.set(k, arr)\n }\n\n const cellStats = candidateCells.map((c) => {\n const k = `${c.variantId}::${c.scenarioId}`\n const samples = grouped.get(k) ?? []\n const n = samples.length\n const mean = n === 0 ? 0.5 : samples.reduce((s, v) => s + v, 0) / n\n const variance =\n n < 2\n ? variancePrior\n : samples.reduce((s, v) => s + (v - mean) ** 2, 0) / (n - 1) + variancePrior\n // Neyman optimal allocation: weight ∝ √variance; add √(1/n) to break\n // ties toward under-sampled cells.\n const weight = Math.sqrt(variance) + 1 / Math.sqrt(Math.max(1, n))\n return { variantId: c.variantId, scenarioId: c.scenarioId, n, mean, variance, weight }\n })\n\n // Reserve floor*N for the floor; allocate the rest proportional to weight.\n const floorTotal = floor * cellStats.length\n if (floorTotal >= budget) {\n const each = Math.max(1, Math.floor(budget / Math.max(1, cellStats.length)))\n return cellStats.map((c) => ({\n variantId: c.variantId,\n scenarioId: c.scenarioId,\n count: each,\n reason: `floor allocation (budget tight; n=${c.n})`,\n }))\n }\n const remaining = budget - floorTotal\n const totalWeight = cellStats.reduce((s, c) => s + c.weight, 0)\n return cellStats.map((c) => {\n const proportional = totalWeight === 0 ? 0 : Math.round((c.weight / totalWeight) * remaining)\n return {\n variantId: c.variantId,\n scenarioId: c.scenarioId,\n count: floor + proportional,\n reason: `variance ${c.variance.toFixed(3)} (n=${c.n}, mean=${c.mean.toFixed(3)})`,\n }\n })\n}\n","/**\n * Shipped policies for the exploration engine.\n *\n * `MutationProposer` is a plain function type — an agent running a generator skill\n * IS a proposer (`(ctx) => dispatchToSkill(ctx)`), no wrapper needed. `mutationProposer`\n * builds the deterministic, LLM-free one from mutation operators. Objectives are\n * interfaces because the engine reads `kind` + `threshold` off them.\n */\n\nimport type { AdversarialMutation } from '../rl/adversarial'\nimport type { Cell, FuzzObjective, FuzzProposeContext, MutationProposer } from './types'\n\nconst clamp01 = (x: number): number => Math.max(0, Math.min(1, x))\n\n// ── proposers ─────────────────────────────────────────────────────────────────\n\n/**\n * Perturbation-based search: apply the cell's mutation operators to the current\n * elites + seeds, deduping by id. Elites first — mutating the most interesting\n * scenario found so far is what makes the search deepen across rounds.\n */\nexport function mutationProposer<S>(opts: {\n mutationsFor: (cell: Cell) => AdversarialMutation<S>[]\n scenarioId: (s: S) => string\n}): MutationProposer<S> {\n return async (ctx: FuzzProposeContext<S>): Promise<S[]> => {\n const mutations = opts.mutationsFor(ctx.cell)\n const parents = [...ctx.elites, ...ctx.seeds]\n const seen = new Set(parents.map(opts.scenarioId))\n const out: S[] = []\n for (const parent of parents) {\n if (out.length >= ctx.count) break\n for (const m of mutations) {\n const children = await m.mutate(parent, ctx.rng)\n for (const child of children) {\n const id = opts.scenarioId(child)\n if (seen.has(id)) continue\n seen.add(id)\n out.push(child)\n if (out.length >= ctx.count) break\n }\n if (out.length >= ctx.count) break\n }\n }\n return out\n }\n}\n\n// ── objectives ────────────────────────────────────────────────────────────────\n\n/** Adversarial: a low headline score is interesting — find where the agent fails. */\nexport function adversarialObjective(threshold = 0.5): FuzzObjective {\n return { kind: 'adversarial', threshold, interest: (ev) => clamp01(1 - ev.score) }\n}\n","/**\n * The exploration engine — a stateful session over a behavior space.\n *\n * Each `step()`: allocate budget across INPUT cells (floor first, then variance\n * steering toward the least-certain cells), propose candidates (the proposer\n * reads current elites + findings, so the search deepens generationally),\n * evaluate with bounded concurrency, archive the most interesting scenario per\n * input×measured bin, and admit notable candidates that pass the validity gates.\n * `run()` loops to budget. `coverage()`/`findings()`/`capsule()` read live state —\n * the surface `makeExploreTools` exposes so an agent can drive the session.\n *\n * One evaluation log (`EvalRecord[]`) is the source of truth; allocation\n * observations and coverage are projections of it.\n */\n\nimport { CostLedger, type CostLedgerHandle, CostReceiptCaptureError } from '../cost-ledger'\nimport { ValidationError } from '../errors'\nimport { varianceBasedCurriculum } from '../rl/active-curriculum'\nimport { mulberry32 } from '../statistics/random'\nimport { buildCapsule } from './capsule'\nimport type { EvalRecord } from './cube'\nimport { enumerateCells } from './cube'\nimport { adversarialObjective } from './policies'\nimport type {\n ArchiveEntry,\n CapsuleData,\n Cell,\n CoverageCell,\n ExploreOptions,\n FuzzFinding,\n FuzzObjective,\n} from './types'\n\nasync function pMap<T>(\n items: T[],\n fn: (item: T) => Promise<void>,\n concurrency: number,\n signal?: AbortSignal,\n): Promise<void> {\n let i = 0\n const workers = Array.from(\n { length: Math.max(1, Math.min(concurrency, items.length)) },\n async () => {\n while (i < items.length) {\n if (signal?.aborted) return\n const item = items[i++]\n if (item === undefined) return\n await fn(item)\n }\n },\n )\n await Promise.all(workers)\n}\n\nexport class BehaviorExplorer<S> {\n private readonly cells: Cell[]\n private readonly cellById: Map<string, Cell>\n private readonly objective: FuzzObjective\n private readonly threshold: number\n private readonly floorPerCell: number\n private readonly perRoundBudget: number\n\n /** The single evaluation log — coverage + allocation are projections of it. */\n private readonly log: Array<EvalRecord & { scenarioId: string }> = []\n /** binId (input × measured coords) → the most interesting entry seen. */\n private readonly archiveByBin = new Map<string, ArchiveEntry<S>>()\n private readonly _findings: FuzzFinding<S>[] = []\n private runsUsed = 0\n private candidateFindings = 0\n private evalErrors = 0\n private consecutiveEvalErrors = 0\n private stoppedEarly: { reason: 'eval-errors'; detail: string } | undefined\n private readonly rng: () => number\n private readonly costLedger?: CostLedgerHandle\n private readonly costPhase = 'fuzz.explore'\n\n constructor(private readonly opts: ExploreOptions<S>) {\n this.cells = enumerateCells(opts.space)\n if (this.cells.length === 0)\n throw new Error('BehaviorExplorer: space has no cells — every axis needs ≥1 value')\n if (opts.costBudgetUsd !== undefined) {\n if (\n typeof opts.costBudgetUsd !== 'number' ||\n !Number.isFinite(opts.costBudgetUsd) ||\n opts.costBudgetUsd < 0\n ) {\n throw new RangeError(\n `BehaviorExplorer: costBudgetUsd must be a nonnegative finite number, got ${String(opts.costBudgetUsd)}`,\n )\n }\n }\n if (!opts.costOf && (opts.costBudgetUsd !== undefined || opts.ledger || opts.onCost)) {\n throw new ValidationError(\n 'BehaviorExplorer: costBudgetUsd/ledger/onCost require costOf — the explorer ' +\n 'cannot know run cost without it; supply costOf or drop the cost options',\n )\n }\n if (\n (opts.costBudgetUsd !== undefined || opts.ledger?.costCeilingUsd !== undefined) &&\n !opts.maximumChargeOf\n ) {\n throw new ValidationError(\n 'BehaviorExplorer: capped cost tracking requires maximumChargeOf before evaluation',\n )\n }\n if (\n opts.ledger &&\n opts.costBudgetUsd !== undefined &&\n opts.ledger.costCeilingUsd !== opts.costBudgetUsd\n ) {\n throw new ValidationError(\n 'BehaviorExplorer: costBudgetUsd must match the supplied CostLedger ceiling',\n )\n }\n if (opts.costOf) this.costLedger = opts.ledger ?? new CostLedger(opts.costBudgetUsd)\n this.cellById = new Map(this.cells.map((c) => [c.id, c]))\n this.objective = opts.objective ?? adversarialObjective(0.5)\n this.threshold = this.objective.threshold ?? 0.5\n this.floorPerCell = opts.floorPerCell ?? 2\n this.perRoundBudget = Math.max(\n this.cells.length * this.floorPerCell,\n Math.ceil(opts.budget / 4),\n )\n this.rng = mulberry32(opts.seed ?? 1)\n }\n\n private binId(cell: Cell, descriptor: Record<string, string> | undefined): string {\n if (!descriptor || Object.keys(descriptor).length === 0) return cell.id\n const measured = Object.keys(descriptor)\n .sort()\n .map((k) => `${k}=${descriptor[k]}`)\n .join('|')\n return `${cell.id}|${measured}`\n }\n\n private allocate(budget: number): Array<{ cellId: string; count: number }> {\n if ((this.opts.allocation ?? 'variance') === 'uniform') {\n const per = Math.max(this.floorPerCell, Math.floor(budget / this.cells.length))\n return this.cells.map((c) => ({ cellId: c.id, count: per }))\n }\n return varianceBasedCurriculum(\n this.log.map((r) => ({\n variantId: r.cell.id,\n scenarioId: '*',\n score: r.ev.score,\n })),\n this.cells.map((c) => ({ variantId: c.id, scenarioId: '*' })),\n { budget, floorPerCell: this.floorPerCell },\n ).map((a) => ({ cellId: a.variantId, count: a.count }))\n }\n\n private objectiveContext() {\n const entries = [...this.archiveByBin.values()]\n return {\n archiveScores: entries.map((e) => e.evaluation.score),\n archiveDescriptors: entries.map((e) => e.evaluation.descriptor),\n }\n }\n\n /** Elites whose INPUT cell matches — what the proposer mutates/deepens from. */\n private elitesFor(cellId: string): S[] {\n const out: S[] = []\n for (const e of this.archiveByBin.values()) if (e.cell.id === cellId) out.push(e.scenario)\n return out\n }\n\n /** One allocate → propose → evaluate → gate → archive round. */\n async step(): Promise<{ runs: number; findings: FuzzFinding<S>[] }> {\n const remaining = this.opts.budget - this.runsUsed\n if (remaining <= 0 || this.opts.signal?.aborted) return { runs: 0, findings: [] }\n\n const allocations = this.allocate(Math.min(this.perRoundBudget, remaining))\n const newFindings: FuzzFinding<S>[] = []\n let runsThisStep = 0\n\n for (const alloc of allocations) {\n if (\n this.runsUsed >= this.opts.budget ||\n this.stoppedEarly !== undefined ||\n this.opts.signal?.aborted\n )\n break\n const cell = this.cellById.get(alloc.cellId)\n if (!cell) continue\n const cap = Math.min(alloc.count, this.opts.budget - this.runsUsed)\n if (cap <= 0) continue\n this.opts.onProgress?.({ type: 'cell-allocated', cell, count: cap })\n\n const seeds = await this.opts.seedsFor(cell)\n const elites = this.elitesFor(cell.id)\n const proposed = await this.opts.proposer({\n cell,\n seeds,\n elites,\n findings: this._findings,\n count: cap,\n rng: this.rng,\n })\n // Cold cells evaluate their seeds first (the coverage floor); warm cells\n // trust the proposer, which already saw the elites.\n const cold = this.log.every((r) => r.cell.id !== cell.id)\n const toEval = [...(cold ? seeds : []), ...proposed].slice(0, cap)\n\n await pMap(\n toEval,\n async (scenario) => {\n if (\n this.runsUsed >= this.opts.budget ||\n this.stoppedEarly !== undefined ||\n this.opts.signal?.aborted\n )\n return\n // evaluate/gates/minimize cross an external boundary (router, backend,\n // judge). A throw there is an infra outcome: record it as a typed\n // eval-error and keep exploring — one 5xx must not kill a campaign.\n // Consecutive failures trip the circuit breaker instead, so a dead\n // backend stops the run rather than burning the remaining budget.\n try {\n const startedAt = performance.now()\n const paid = this.costLedger\n ? await this.costLedger.runPaidCall({\n channel: 'agent',\n phase: this.costPhase,\n actor: 'fuzz.evaluate',\n tags: { target: this.opts.target, cell: cell.id },\n signal: this.opts.signal,\n maximumCharge: this.opts.maximumChargeOf?.(scenario, cell),\n execute: () => this.opts.evaluate(scenario, cell),\n receipt: (evaluation) => {\n const cost = this.opts.costOf!(scenario, cell, evaluation)\n if (cost === null) {\n return {\n model: 'unattributed',\n inputTokens: 0,\n outputTokens: 0,\n costUnknown: true,\n }\n }\n if (!Number.isFinite(cost.usd) || cost.usd < 0) {\n throw new RangeError(\n `BehaviorExplorer: costOf returned an invalid usd (${String(cost.usd)}) — ` +\n 'return null when cost is unknown, never a fabricated number',\n )\n }\n return {\n model: cost.model ?? 'unattributed',\n inputTokens: 0,\n outputTokens: 0,\n actualCostUsd: cost.usd,\n }\n },\n })\n : undefined\n if (paid && !paid.succeeded) {\n if (\n paid.error instanceof CostReceiptCaptureError &&\n paid.error.receiptError instanceof RangeError\n ) {\n throw paid.error.receiptError\n }\n throw paid.error\n }\n const ev = paid ? paid.value : await this.opts.evaluate(scenario, cell)\n // Consumer-measured latency wins (it can exclude judge time); the\n // engine's wall-clock is the default so latency is never missing.\n const latencyMs = ev.latencyMs ?? performance.now() - startedAt\n this.runsUsed++\n runsThisStep++\n this.consecutiveEvalErrors = 0\n const costUsd = paid\n ? paid.receipt.costUnknown\n ? null\n : paid.receipt.costUsd\n : undefined\n if (paid?.receipt.actualCostUsd !== undefined) {\n this.opts.onCost?.({ usd: paid.receipt.actualCostUsd, channel: 'agent' })\n }\n const interest = this.objective.interest(ev, this.objectiveContext())\n this.log.push({\n cell,\n ev,\n interest,\n latencyMs,\n ...(costUsd !== undefined ? { costUsd } : {}),\n scenarioId: this.opts.scenarioId(scenario),\n })\n this.opts.onProgress?.({ type: 'evaluated', cell, scenario, evaluation: ev })\n\n const bin = this.binId(cell, ev.descriptor)\n const cur = this.archiveByBin.get(bin)\n if (!cur || interest > cur.interest)\n this.archiveByBin.set(bin, { binId: bin, cell, scenario, evaluation: ev, interest })\n\n if (interest < this.threshold) return\n this.candidateFindings++\n if (this.opts.gates?.isValid && !(await this.opts.gates.isValid(scenario, ev, cell)))\n return\n if (\n this.opts.gates?.isUncontaminated &&\n !(await this.opts.gates.isUncontaminated(scenario, ev, cell))\n )\n return\n\n const minimized = this.opts.minimize\n ? await this.opts.minimize(scenario, this.opts.evaluate, cell)\n : scenario\n const finding: FuzzFinding<S> = {\n id: this.opts.scenarioId(scenario),\n cell,\n scenario,\n minimized,\n text: this.opts.scenarioText?.(minimized),\n evaluation: ev,\n interest,\n objective: this.objective.kind,\n }\n this._findings.push(finding)\n newFindings.push(finding)\n this.opts.onProgress?.({ type: 'finding', finding })\n } catch (err) {\n // Internal validation errors (e.g. a fabricated costOf number) are\n // programming mistakes, not backend outcomes — they stay loud.\n if (err instanceof RangeError) throw err\n this.evalErrors++\n this.consecutiveEvalErrors++\n const message = err instanceof Error ? err.message : String(err)\n this.opts.onProgress?.({\n type: 'eval-error',\n cell,\n scenarioId: this.opts.scenarioId(scenario),\n message,\n })\n const limit = this.opts.maxConsecutiveEvalErrors ?? 5\n if (this.consecutiveEvalErrors >= limit) {\n this.stoppedEarly = {\n reason: 'eval-errors',\n detail: `${this.consecutiveEvalErrors} consecutive eval errors (last: ${message})`,\n }\n }\n }\n },\n this.opts.concurrency ?? 1,\n this.opts.signal,\n )\n }\n\n this.opts.onProgress?.({ type: 'round', runsUsed: this.runsUsed, budget: this.opts.budget })\n return { runs: runsThisStep, findings: newFindings }\n }\n\n /** Loop `step()` until the run or dollar budget is spent, the signal aborts,\n * or no progress is made. */\n async run(): Promise<CapsuleData<S>> {\n while (\n this.runsUsed < this.opts.budget &&\n this.stoppedEarly === undefined &&\n !this.opts.signal?.aborted\n ) {\n const { runs } = await this.step()\n if (runs === 0 && this.stoppedEarly === undefined) break\n }\n return this.capsule()\n }\n\n coverage(): CoverageCell[] {\n return this.capsule().coverage\n }\n\n findings(): FuzzFinding<S>[] {\n return [...this._findings].sort((a, b) => b.interest - a.interest)\n }\n\n capsule(): CapsuleData<S> {\n const cost = this.costLedger?.summary({\n phase: this.costPhase,\n tags: { target: this.opts.target },\n })\n return buildCapsule({\n target: this.opts.target,\n objective: this.objective.kind,\n cells: this.cells,\n log: this.log,\n threshold: this.threshold,\n archive: [...this.archiveByBin.values()],\n findings: this._findings,\n candidateFindings: this.candidateFindings,\n runsUsed: this.runsUsed,\n cost: cost\n ? {\n costUsd: cost.totalCostUsd,\n costUnknownRuns: cost.byChannel.reduce((sum, row) => sum + row.unpricedCalls, 0),\n }\n : undefined,\n evalErrors: this.evalErrors,\n stoppedEarly: this.stoppedEarly,\n })\n }\n}\n","/**\n * `fuzzAgent` — the adversarial batch preset over `BehaviorExplorer`.\n *\n * One call: explore the space to budget with the adversarial objective and\n * return the capsule. For agent-driven, incremental, or multi-objective use,\n * construct a `BehaviorExplorer` and drive it via `makeExploreTools`.\n */\n\nimport { BehaviorExplorer } from './explorer'\nimport { adversarialObjective } from './policies'\nimport type { CapsuleData, ExploreOptions } from './types'\n\nexport type FuzzAgentOptions<S> = Omit<ExploreOptions<S>, 'objective'> & {\n /** Score strictly below this is a candidate failure. Default 0.5. */\n failureThreshold?: number\n}\n\nexport async function fuzzAgent<S>(\n opts: FuzzAgentOptions<S>,\n): Promise<{ capsule: CapsuleData<S> }> {\n const { failureThreshold, ...rest } = opts\n const explorer = new BehaviorExplorer<S>({\n ...rest,\n objective: adversarialObjective(failureThreshold ?? 0.5),\n })\n return { capsule: await explorer.run() }\n}\n","/**\n * Validity gates — what separates a fuzzer from a slop generator.\n *\n * A notable candidate is admitted only when it is fair and reproducible. None of\n * these are on by default: the live wiring opts in, so reported findings carry\n * their proof.\n */\n\nimport type { Cell, Evaluation, Evaluator, ValidityGates } from './types'\n\n/** Combine gate sets; a candidate must pass every gate in every set. */\nexport function composeGates<S>(...sets: Array<ValidityGates<S> | undefined>): ValidityGates<S> {\n const present = sets.filter((s): s is ValidityGates<S> => s != null)\n return {\n isValid: async (scenario, ev, cell) => {\n for (const g of present) {\n if (g.isValid && !(await g.isValid(scenario, ev, cell))) return false\n }\n return true\n },\n isUncontaminated: async (scenario, ev, cell) => {\n for (const g of present) {\n if (g.isUncontaminated && !(await g.isUncontaminated(scenario, ev, cell))) return false\n }\n return true\n },\n }\n}\n\n/**\n * Reproducibility gate. Re-run the target on a meaning-preserving rephrase of the\n * flagged scenario; keep the finding only when the rephrase ALSO scores below the\n * threshold. A finding that flips under a cosmetic rewrite was keyed to surface\n * form, not the task — a false signal we must not report. Costs one extra\n * evaluation per candidate (candidates are rare, so cheap).\n */\nexport function perturbationStabilityGate<S>(opts: {\n evaluate: Evaluator<S>\n /** Produce a semantic-preserving rephrase. Return null to skip (treated as pass). */\n perturb: (scenario: S) => S | null\n /** Score strictly below this still counts as failing. Default 0.5. */\n failureThreshold?: number\n}): ValidityGates<S> {\n const threshold = opts.failureThreshold ?? 0.5\n return {\n isUncontaminated: async (scenario: S, _ev: Evaluation, cell: Cell) => {\n const rephrased = opts.perturb(scenario)\n if (rephrased == null) return true\n const re = await opts.evaluate(rephrased, cell)\n return re.score < threshold\n },\n }\n}\n\n/**\n * Severity-floor gate. Reject borderline candidates whose score sits in a band\n * just under the threshold — judge noise, not a real defect.\n */\nexport function severityFloorGate<S>(opts: {\n failureThreshold?: number\n margin?: number\n}): ValidityGates<S> {\n const threshold = opts.failureThreshold ?? 0.5\n const margin = opts.margin ?? 0.1\n return {\n isValid: (_scenario, ev: Evaluation) => ev.score <= threshold - margin,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA4BA,SAAgB,eAAe,OAA8B;CAC3D,IAAI,MAAM,KAAK,WAAW,GAAG,OAAO,CAAC;CACrC,IAAI,WAA0C,CAAC,CAAC,CAAC;CACjD,KAAK,MAAM,QAAQ,MAAM,MAAM;EAC7B,MAAM,OAAsC,CAAC;EAC7C,KAAK,MAAM,WAAW,UACpB,KAAK,MAAM,SAAS,KAAK,QAAQ,KAAK,KAAK;GAAE,GAAG;IAAU,KAAK,OAAO;EAAM,CAAC;EAE/E,WAAW;CACb;CACA,OAAO,SAAS,KAAK,YAAY;EAAE,IAAI,OAAO,OAAO,MAAM;EAAG;CAAO,EAAE;AACzE;;AAGA,SAAgB,OAAO,OAAsB,QAAwC;CACnF,OAAO,MAAM,KAAK,KAAK,MAAM,GAAG,EAAE,KAAK,GAAG,OAAO,EAAE,OAAO,CAAC,CAAC,KAAK,GAAG;AACtE;;;AAIA,SAAgB,aAAa,QAAgC;CAC3D,MAAM,UAAU,sBAAsB,MAAM;CAC5C,IAAI,CAAC,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AAC,CAAC,IAAI,EAAE;AACzC;;;ACfA,SAAgB,aAAgB,GAAG,MAA6D;CAC9F,MAAM,UAAU,KAAK,QAAQ,MAA6B,KAAK,IAAI;CACnE,OAAO;EACL,SAAS,OAAO,UAAU,IAAI,SAAS;GACrC,KAAK,MAAM,KAAK,SACd,IAAI,EAAE,WAAW,CAAE,MAAM,EAAE,QAAQ,UAAU,IAAI,IAAI,GAAI,OAAO;GAElE,OAAO;EACT;EACA,kBAAkB,OAAO,UAAU,IAAI,SAAS;GAC9C,KAAK,MAAM,KAAK,SACd,IAAI,EAAE,oBAAoB,CAAE,MAAM,EAAE,iBAAiB,UAAU,IAAI,IAAI,GAAI,OAAO;GAEpF,OAAO;EACT;CACF;AACF;;;;;;;;AASA,SAAgB,0BAA6B,MAMxB;CACnB,MAAM,YAAY,KAAK,oBAAoB;CAC3C,OAAO,EACL,kBAAkB,OAAO,UAAa,KAAiB,SAAe;EACpE,MAAM,YAAY,KAAK,QAAQ,QAAQ;EACvC,IAAI,aAAa,MAAM,OAAO;EAE9B,QAAO,MADU,KAAK,SAAS,WAAW,IAAI,EAAA,CACpC,QAAQ;CACpB,EACF;AACF;;;;;AAMA,SAAgB,kBAAqB,MAGhB;CACnB,MAAM,YAAY,KAAK,oBAAoB;CAC3C,MAAM,SAAS,KAAK,UAAU;CAC9B,OAAO,EACL,UAAU,WAAW,OAAmB,GAAG,SAAS,YAAY,OAClE;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as hashCanonical, o as jsonDocument } from "./canonical-
|
|
2
|
-
import { r as ROLLOUT_SCHEMA, w as licenseClassOf } from "./schema-
|
|
1
|
+
import { a as hashCanonical, o as jsonDocument } from "./canonical-DKgL_Wby.js";
|
|
2
|
+
import { r as ROLLOUT_SCHEMA, w as licenseClassOf } from "./schema-Bh9CfSZT.js";
|
|
3
3
|
import { stat } from "node:fs/promises";
|
|
4
4
|
import { claudeCodeRefForFile, codexRefForFile, kimiRefForFile, listReaders, opencodeSessionsInStore, piRefForFile, readerFor, toChatMessages } from "@tangle-network/harness-sessions";
|
|
5
5
|
// src/rollout/readers/harness-session-lines.ts
|
|
@@ -202,4 +202,4 @@ async function* harnessSessionRolloutLines(refs, capturedAt) {
|
|
|
202
202
|
}
|
|
203
203
|
export { harnessSessionToolInventory as a, harnessSessionRolloutLines as i, harnessSessionRefs as n, harnessSessionRolloutLine as r, harnessSessionBindings as t };
|
|
204
204
|
|
|
205
|
-
//# sourceMappingURL=harness-session-lines-
|
|
205
|
+
//# sourceMappingURL=harness-session-lines-CSxKR6no.js.map
|