@tangle-network/agent-eval 2.0.7 → 2.0.9
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 +16 -0
- package/dist/adapters/http.d.ts +2 -2
- package/dist/{agent-profile-CRdalpZv.d.ts → agent-profile-ORN4aArD.d.ts} +5 -5
- package/dist/{agent-profile-CRdalpZv.d.ts.map → agent-profile-ORN4aArD.d.ts.map} +1 -1
- package/dist/analyst/index.d.ts +14 -13
- package/dist/analyst/index.d.ts.map +1 -1
- package/dist/analyst/index.js +9 -9
- package/dist/{analyze-runs-C_9cXPZn.js → analyze-runs-CE_5VKh2.js} +6 -5
- package/dist/{analyze-runs-C_9cXPZn.js.map → analyze-runs-CE_5VKh2.js.map} +1 -1
- package/dist/analyze-runs-DT693FJ7.d.ts +65 -0
- package/dist/analyze-runs-DT693FJ7.d.ts.map +1 -0
- package/dist/app-grade/index.d.ts +4 -4
- package/dist/app-grade/index.js +1 -1
- package/dist/{benchmark-command-DkBMUDwy.js → benchmark-command-DLg8E4y8.js} +9 -6
- package/dist/benchmark-command-DLg8E4y8.js.map +1 -0
- package/dist/benchmarks/index.d.ts +4 -4
- package/dist/benchmarks/index.js +4 -4
- package/dist/builder-eval/index.js +2 -2
- package/dist/calibration-CrORXMWx.d.ts +128 -0
- package/dist/calibration-CrORXMWx.d.ts.map +1 -0
- package/dist/{calibration-Cfoup0xz.js → calibration-Dz8mQb5P.js} +2 -2
- package/dist/{calibration-Cfoup0xz.js.map → calibration-Dz8mQb5P.js.map} +1 -1
- package/dist/campaign/index.d.ts +8 -8
- package/dist/campaign/index.js +12 -11
- package/dist/{campaign-DfSWSreo.js → campaign-C_S3MOYa.js} +1589 -14
- package/dist/campaign-C_S3MOYa.js.map +1 -0
- package/dist/{campaign-evidence-D_oBFfLc.js → campaign-evidence-BTfzZo1u.js} +4 -4
- package/dist/{campaign-evidence-D_oBFfLc.js.map → campaign-evidence-BTfzZo1u.js.map} +1 -1
- package/dist/{campaign-evidence-BojANgU7.d.ts → campaign-evidence-CM4FBOkX.d.ts} +5 -5
- package/dist/{campaign-evidence-BojANgU7.d.ts.map → campaign-evidence-CM4FBOkX.d.ts.map} +1 -1
- package/dist/{cluster-Bj90LK-1.d.ts → chat-client-uQNXGuO4.d.ts} +3 -240
- package/dist/chat-client-uQNXGuO4.d.ts.map +1 -0
- package/dist/cli.js +5 -5
- package/dist/cluster-C-K0N2br.d.ts +241 -0
- package/dist/cluster-C-K0N2br.d.ts.map +1 -0
- package/dist/{cluster-bootstrap-DPzVy3_K.js → cluster-bootstrap-DXbnIdm8.js} +3 -2
- package/dist/{cluster-bootstrap-DPzVy3_K.js.map → cluster-bootstrap-DXbnIdm8.js.map} +1 -1
- package/dist/{completion-verifier-Cy38EpGE.d.ts → completion-verifier-C7wipJOK.d.ts} +2 -2
- package/dist/{completion-verifier-Cy38EpGE.d.ts.map → completion-verifier-C7wipJOK.d.ts.map} +1 -1
- package/dist/contract/index.d.ts +14 -12
- package/dist/contract/index.js +13 -11
- package/dist/contract/index.js.map +1 -1
- package/dist/{decision-point-C46p-p9v.js → decision-point-CfqtnGop.js} +3 -3
- package/dist/{decision-point-C46p-p9v.js.map → decision-point-CfqtnGop.js.map} +1 -1
- package/dist/{default-registry-xoX0PMCb.d.ts → default-registry-Bskl2HzV.d.ts} +6 -6
- package/dist/{default-registry-xoX0PMCb.d.ts.map → default-registry-Bskl2HzV.d.ts.map} +1 -1
- package/dist/{default-registry-BWFPtmuI.js → default-registry-kps1SOaD.js} +2 -2
- package/dist/{default-registry-BWFPtmuI.js.map → default-registry-kps1SOaD.js.map} +1 -1
- package/dist/define-agent-eval-Dnh4jXLX.js +96 -0
- package/dist/define-agent-eval-Dnh4jXLX.js.map +1 -0
- package/dist/define-agent-eval-tu3anVlk.d.ts +52 -0
- package/dist/define-agent-eval-tu3anVlk.d.ts.map +1 -0
- package/dist/diagnosis/index.d.ts +3 -3
- package/dist/diagnosis/index.js +1 -1
- package/dist/{dspy-rlm-engine-r7YpKLhS.js → dspy-rlm-engine-DQbPdT_o.js} +2 -2
- package/dist/{dspy-rlm-engine-r7YpKLhS.js.map → dspy-rlm-engine-DQbPdT_o.js.map} +1 -1
- package/dist/{emitter-BjW3NnX-.js → emitter-xN9wGTVw.js} +9 -2
- package/dist/{emitter-BjW3NnX-.js.map → emitter-xN9wGTVw.js.map} +1 -1
- package/dist/{eval-campaign-Cyk-tkLh.js → eval-campaign-DswSn7Gm.js} +3 -3
- package/dist/{eval-campaign-Cyk-tkLh.js.map → eval-campaign-DswSn7Gm.js.map} +1 -1
- package/dist/{evaluation-X5E22NQK.d.ts → evaluation-C4-tf3Z_.d.ts} +4 -4
- package/dist/{evaluation-X5E22NQK.d.ts.map → evaluation-C4-tf3Z_.d.ts.map} +1 -1
- package/dist/evaluation.d.ts +1 -1
- package/dist/{exact-types-DjuabhUV.d.ts → exact-types-CUsSMW3n.d.ts} +2 -2
- package/dist/{exact-types-DjuabhUV.d.ts.map → exact-types-CUsSMW3n.d.ts.map} +1 -1
- package/dist/{execution-insight-CE20Bxq0.d.ts → execution-insight-YihQrSqd.d.ts} +2 -2
- package/dist/{execution-insight-CE20Bxq0.d.ts.map → execution-insight-YihQrSqd.d.ts.map} +1 -1
- package/dist/experiment/index.d.ts +5 -5
- package/dist/experiment/index.js +10 -184
- package/dist/experiment/index.js.map +1 -1
- package/dist/{external-optimizer-process-4QdcF7Kd.js → external-optimizer-process-CVi1x2nb.js} +2 -2
- package/dist/{external-optimizer-process-4QdcF7Kd.js.map → external-optimizer-process-CVi1x2nb.js.map} +1 -1
- package/dist/{external-optimizer-subprocess-BW0ZWUUr.js → external-optimizer-subprocess-mV-2swJI.js} +3 -357
- package/dist/external-optimizer-subprocess-mV-2swJI.js.map +1 -0
- package/dist/{feedback-trajectory-BMkJezPc.d.ts → feedback-trajectory-D7hgL6y5.d.ts} +3 -3
- package/dist/{feedback-trajectory-BMkJezPc.d.ts.map → feedback-trajectory-D7hgL6y5.d.ts.map} +1 -1
- package/dist/finding-scope-B_As3F_v.js +359 -0
- package/dist/finding-scope-B_As3F_v.js.map +1 -0
- package/dist/{findings-store-DV8WA5nD.js → findings-store-CZy5kUDo.js} +2 -2
- package/dist/{findings-store-DV8WA5nD.js.map → findings-store-CZy5kUDo.js.map} +1 -1
- package/dist/fuzz.js +1 -1
- package/dist/{index-DKpMyD_Z.d.ts → index--vDCtdaj.d.ts} +7 -7
- package/dist/{index-DKpMyD_Z.d.ts.map → index--vDCtdaj.d.ts.map} +1 -1
- package/dist/{index-CKjqN9_U.d.ts → index-CIqYaySd.d.ts} +89 -3
- package/dist/index-CIqYaySd.d.ts.map +1 -0
- package/dist/{index-C6TG1LwA.d.ts → index-Cav3abKy.d.ts} +256 -131
- package/dist/index-Cav3abKy.d.ts.map +1 -0
- package/dist/{index-DAFZRMlF.d.ts → index-DmMHTDjT.d.ts} +10 -8
- package/dist/index-DmMHTDjT.d.ts.map +1 -0
- package/dist/{index-BqAPIToS.d.ts → index-Er8TKQ3q.d.ts} +3 -3
- package/dist/{index-BqAPIToS.d.ts.map → index-Er8TKQ3q.d.ts.map} +1 -1
- package/dist/{index-xEM_SoCl.d.ts → index-moZnazVj.d.ts} +22 -20
- package/dist/index-moZnazVj.d.ts.map +1 -0
- package/dist/index.d.ts +33 -29
- package/dist/index.js +23 -20
- package/dist/index.js.map +1 -1
- package/dist/{analyze-runs-xjKBBqIB.d.ts → insight-report-DYofCMLx.d.ts} +4 -64
- package/dist/insight-report-DYofCMLx.d.ts.map +1 -0
- package/dist/{integrity-B9320cw1.d.ts → integrity-BJGstiCh.d.ts} +2 -2
- package/dist/{integrity-B9320cw1.d.ts.map → integrity-BJGstiCh.d.ts.map} +1 -1
- package/dist/{judge-gate-DqlzOBOm.js → judge-gate-DANg5FLq.js} +2 -2
- package/dist/{judge-gate-DqlzOBOm.js.map → judge-gate-DANg5FLq.js.map} +1 -1
- package/dist/llm-judge-DFoSy4Qn.js +476 -0
- package/dist/llm-judge-DFoSy4Qn.js.map +1 -0
- package/dist/{matrix-CqZSpwgN.d.ts → matrix-OgdWQBQa.d.ts} +6 -2
- package/dist/matrix-OgdWQBQa.d.ts.map +1 -0
- package/dist/measure-validity-plan-B1_qYlsk.d.ts +143 -0
- package/dist/measure-validity-plan-B1_qYlsk.d.ts.map +1 -0
- package/dist/measure-validity-plan-t0YQRzJQ.js +117 -0
- package/dist/measure-validity-plan-t0YQRzJQ.js.map +1 -0
- package/dist/meta-eval/index.d.ts +5 -3
- package/dist/meta-eval/index.js +664 -14
- package/dist/meta-eval/index.js.map +1 -1
- package/dist/multishot/golden/index.d.ts +1 -1
- package/dist/multishot/index.d.ts +458 -4
- package/dist/multishot/index.d.ts.map +1 -1
- package/dist/multishot/index.js +926 -47
- package/dist/multishot/index.js.map +1 -1
- package/dist/openapi.json +1 -1
- package/dist/{llm-judge-DQJTQx01.js → optimization-method-D4CpYsVA.js} +18 -482
- package/dist/optimization-method-D4CpYsVA.js.map +1 -0
- package/dist/{outcome-observations-DL3CC8w1.js → outcome-observations-DEh8_V_P.js} +31 -6
- package/dist/outcome-observations-DEh8_V_P.js.map +1 -0
- package/dist/outcome-store-CHtuvstd.d.ts +56 -0
- package/dist/outcome-store-CHtuvstd.d.ts.map +1 -0
- package/dist/{paired-arms-DZhH3FGu.js → paired-arms-B6EXnI47.js} +3 -2
- package/dist/{paired-arms-DZhH3FGu.js.map → paired-arms-B6EXnI47.js.map} +1 -1
- package/dist/{paired-promotion-decision-ChHBuuHV.d.ts → paired-promotion-decision-DuvRdnsW.d.ts} +2 -2
- package/dist/{paired-promotion-decision-ChHBuuHV.d.ts.map → paired-promotion-decision-DuvRdnsW.d.ts.map} +1 -1
- package/dist/{paired-promotion-decision-Dn3-jaq4.js → paired-promotion-decision-xYe881cD.js} +3 -2
- package/dist/{paired-promotion-decision-Dn3-jaq4.js.map → paired-promotion-decision-xYe881cD.js.map} +1 -1
- package/dist/{paired-promotion-power-BlzXdgMD.js → paired-promotion-power-DirShsIs.js} +3 -3
- package/dist/{paired-promotion-power-BlzXdgMD.js.map → paired-promotion-power-DirShsIs.js.map} +1 -1
- package/dist/paired-tests-CXcD_B80.js +688 -0
- package/dist/paired-tests-CXcD_B80.js.map +1 -0
- package/dist/pareto-DIVE5D0T.js +81 -0
- package/dist/pareto-DIVE5D0T.js.map +1 -0
- package/dist/pipelines/index.d.ts +2 -1
- package/dist/pipelines/index.d.ts.map +1 -1
- package/dist/pipelines/index.js +1 -1
- package/dist/{sequential-BphITa5b.js → power-DTg6u30w.js} +181 -4
- package/dist/power-DTg6u30w.js.map +1 -0
- package/dist/{prime-protocol-Cv6_47rh.d.ts → prime-protocol-Jm2pWh--.d.ts} +2 -2
- package/dist/{prime-protocol-Cv6_47rh.d.ts.map → prime-protocol-Jm2pWh--.d.ts.map} +1 -1
- package/dist/{promotion-gate-CGkxh36r.d.ts → promotion-gate-BXgcORnM.d.ts} +2 -2
- package/dist/{promotion-gate-CGkxh36r.d.ts.map → promotion-gate-BXgcORnM.d.ts.map} +1 -1
- package/dist/{promotion-policy-CxDIh-9p.js → promotion-policy-Z5E-C32U.js} +4 -4
- package/dist/{promotion-policy-CxDIh-9p.js.map → promotion-policy-Z5E-C32U.js.map} +1 -1
- package/dist/{proposal-findings-DedMih-u.js → proposal-findings-CfRFCFXS.js} +2 -2
- package/dist/{proposal-findings-DedMih-u.js.map → proposal-findings-CfRFCFXS.js.map} +1 -1
- package/dist/{registry-CIjC6SdV.d.ts → registry-DEZDECdr.d.ts} +4 -4
- package/dist/{registry-CIjC6SdV.d.ts.map → registry-DEZDECdr.d.ts.map} +1 -1
- package/dist/{release-confidence-BLHOMK5Q.js → release-confidence-Cndq1hwi.js} +2 -2
- package/dist/{release-confidence-BLHOMK5Q.js.map → release-confidence-Cndq1hwi.js.map} +1 -1
- package/dist/reporting.d.ts +5 -5
- package/dist/reporting.js +6 -5
- package/dist/reporting.js.map +1 -1
- package/dist/{research-report-D6XIK0eK.d.ts → research-report-CIgUe1lv.d.ts} +2 -2
- package/dist/{research-report-D6XIK0eK.d.ts.map → research-report-CIgUe1lv.d.ts.map} +1 -1
- package/dist/{researcher---DhHG4J.d.ts → researcher-CY_byuZl.d.ts} +4 -4
- package/dist/{researcher---DhHG4J.d.ts.map → researcher-CY_byuZl.d.ts.map} +1 -1
- package/dist/{reward-hacking-DKAflk2c.js → reward-hacking-DMTm1OBd.js} +2 -2
- package/dist/{reward-hacking-DKAflk2c.js.map → reward-hacking-DMTm1OBd.js.map} +1 -1
- package/dist/rl.d.ts +9 -8
- package/dist/rl.d.ts.map +1 -1
- package/dist/rl.js +11 -10
- package/dist/rl.js.map +1 -1
- package/dist/rollout/index.d.ts +2 -2
- package/dist/{rubric-predictive-validity--6z0q8s6.js → rubric-predictive-validity-BXJ92Jp_.js} +3 -9
- package/dist/rubric-predictive-validity-BXJ92Jp_.js.map +1 -0
- package/dist/{rubric-predictive-validity-C9wc7f_D.d.ts → rubric-predictive-validity-DH94_0Q1.d.ts} +3 -56
- package/dist/rubric-predictive-validity-DH94_0Q1.d.ts.map +1 -0
- package/dist/{run-improvement-loop-BfwOUudy.d.ts → run-improvement-loop-BaPDVbW8.d.ts} +384 -11
- package/dist/run-improvement-loop-BaPDVbW8.d.ts.map +1 -0
- package/dist/{run-record-Bqg0NZ_e.js → run-record-CuO8ErrI.js} +3 -2
- package/dist/run-record-CuO8ErrI.js.map +1 -0
- package/dist/{runtime-rollouts-drQynu3t.js → runtime-rollouts-Vv-BAqmq.js} +2 -2
- package/dist/{runtime-rollouts-drQynu3t.js.map → runtime-rollouts-Vv-BAqmq.js.map} +1 -1
- package/dist/search/index.d.ts +2 -2
- package/dist/search/index.js +2 -2
- package/dist/{search-kernel-DJq9bUDU.d.ts → search-kernel-BzTeb89p.d.ts} +3 -3
- package/dist/{search-kernel-DJq9bUDU.d.ts.map → search-kernel-BzTeb89p.d.ts.map} +1 -1
- package/dist/{pareto-Bg75Gajo.js → search-kernel-DOPW08Hx.js} +6 -88
- package/dist/search-kernel-DOPW08Hx.js.map +1 -0
- package/dist/{search-summary-B1x1Vmzh.js → search-summary-CYOHZAAy.js} +4 -4
- package/dist/{search-summary-B1x1Vmzh.js.map → search-summary-CYOHZAAy.js.map} +1 -1
- package/dist/{define-agent-eval-B6uE3gNu.js → self-improve-CIFqccHV.js} +8 -97
- package/dist/self-improve-CIFqccHV.js.map +1 -0
- package/dist/{define-agent-eval-Cjc0wWnO.d.ts → self-improve-DY8ZY4lY.d.ts} +8 -54
- package/dist/self-improve-DY8ZY4lY.d.ts.map +1 -0
- package/dist/{sequential-BhbTSxpt.d.ts → sequential-B9iROM1S.d.ts} +2 -2
- package/dist/{sequential-BhbTSxpt.d.ts.map → sequential-B9iROM1S.d.ts.map} +1 -1
- package/dist/{sequential-ux_XrjBf.js → sequential-tZjGysXY.js} +3 -3
- package/dist/{sequential-ux_XrjBf.js.map → sequential-tZjGysXY.js.map} +1 -1
- package/dist/{skillopt-optimization-method-D_swD0Cy.js → skillopt-optimization-method-CbHBkopM.js} +9 -8
- package/dist/{skillopt-optimization-method-D_swD0Cy.js.map → skillopt-optimization-method-CbHBkopM.js.map} +1 -1
- package/dist/{statistical-heldout-CaS4T-43.js → statistical-heldout-C7Jjo5nP.js} +3 -3
- package/dist/{statistical-heldout-CaS4T-43.js.map → statistical-heldout-C7Jjo5nP.js.map} +1 -1
- package/dist/{statistics-DSidA5I2.js → statistics-BPl13X3G.js} +208 -700
- package/dist/statistics-BPl13X3G.js.map +1 -0
- package/dist/statistics.d.ts +3 -3
- package/dist/statistics.js +3 -2
- package/dist/{store-tool-spans-DniaFwjM.d.ts → store-tool-spans-Dq8r0PbJ.d.ts} +4 -4
- package/dist/{store-tool-spans-DniaFwjM.d.ts.map → store-tool-spans-Dq8r0PbJ.d.ts.map} +1 -1
- package/dist/{summary-report-CI4J6gxU.js → summary-report-DzbnK81K.js} +15 -7
- package/dist/summary-report-DzbnK81K.js.map +1 -0
- package/dist/summary-report-figures-CJHygLgw.d.ts.map +1 -1
- package/dist/supervisor-run/index.d.ts +1 -1
- package/dist/supervisor-run/index.js +1 -1
- package/dist/{systemone-DzY-2Zri.d.ts → systemone-BuSZTI88.d.ts} +8 -7
- package/dist/systemone-BuSZTI88.d.ts.map +1 -0
- package/dist/{systemone-review-CXecR_m-.d.ts → systemone-review-mlfxWdLz.d.ts} +2 -2
- package/dist/{systemone-review-CXecR_m-.d.ts.map → systemone-review-mlfxWdLz.d.ts.map} +1 -1
- package/dist/systemone.d.ts +3 -3
- package/dist/systemone.js +1 -1
- package/dist/{tool-groups-DF6OqhoG.d.ts → tool-groups-PNDX8fd-.d.ts} +2 -2
- package/dist/tool-groups-PNDX8fd-.d.ts.map +1 -0
- package/dist/{tool-waste-u7JJ_BlE.js → tool-waste-783VCo1y.js} +3 -2
- package/dist/{tool-waste-u7JJ_BlE.js.map → tool-waste-783VCo1y.js.map} +1 -1
- package/dist/tool-waste-B01AMpID.d.ts +121 -0
- package/dist/tool-waste-B01AMpID.d.ts.map +1 -0
- package/dist/{trace-questions-DO8y3J-E.d.ts → trace-questions-DBtr4jWi.d.ts} +2 -2
- package/dist/{trace-questions-DO8y3J-E.d.ts.map → trace-questions-DBtr4jWi.d.ts.map} +1 -1
- package/dist/trace-repair/index.d.ts +1 -1
- package/dist/trace-repair/index.js +1 -1
- package/dist/traces.d.ts +4 -4
- package/dist/traces.js +1 -1
- package/dist/trajectory-B3o6Ald_.d.ts +100 -0
- package/dist/trajectory-B3o6Ald_.d.ts.map +1 -0
- package/dist/trajectory-replay/index.js +1 -1
- package/dist/{tree-DQMlcNFI.js → tree-CtlQQL1w.js} +6 -4
- package/dist/{tree-DQMlcNFI.js.map → tree-CtlQQL1w.js.map} +1 -1
- package/dist/{types-BMSDkS8l.d.ts → types-BO948H-U.d.ts} +7 -4
- package/dist/{types-BMSDkS8l.d.ts.map → types-BO948H-U.d.ts.map} +1 -1
- package/dist/{types-fuOwNq1C.d.ts → types-CKNAzCSA.d.ts} +3 -2
- package/dist/types-CKNAzCSA.d.ts.map +1 -0
- package/dist/{types-BLv2Ngla.d.ts → types-D-WF1KM3.d.ts} +2 -2
- package/dist/{types-BLv2Ngla.d.ts.map → types-D-WF1KM3.d.ts.map} +1 -1
- package/dist/types-DK4vNv5q.js.map +1 -1
- package/dist/{types-D_PfKC59.d.ts → types-DbeIGi73.d.ts} +2 -2
- package/dist/{types-D_PfKC59.d.ts.map → types-DbeIGi73.d.ts.map} +1 -1
- package/dist/wire/index.d.ts +4 -4
- package/dist/world/index.d.ts +529 -0
- package/dist/world/index.d.ts.map +1 -0
- package/dist/world/index.js +1356 -0
- package/dist/world/index.js.map +1 -0
- package/docs/campaign-proposers.md +7 -0
- package/docs/concepts.md +2 -0
- package/docs/design/statistics-decisions.md +31 -0
- package/docs/eval-surface-map.md +4 -1
- package/docs/feature-guide.md +2 -0
- package/docs/multi-turn-optimization.md +80 -0
- package/docs/outcome-validity.md +69 -0
- package/docs/public-api.md +86 -31
- package/docs/world.md +104 -0
- package/package.json +6 -1
- package/dist/analyze-runs-xjKBBqIB.d.ts.map +0 -1
- package/dist/benchmark-command-DkBMUDwy.js.map +0 -1
- package/dist/campaign-DfSWSreo.js.map +0 -1
- package/dist/cluster-Bj90LK-1.d.ts.map +0 -1
- package/dist/define-agent-eval-B6uE3gNu.js.map +0 -1
- package/dist/define-agent-eval-Cjc0wWnO.d.ts.map +0 -1
- package/dist/external-optimizer-subprocess-BW0ZWUUr.js.map +0 -1
- package/dist/index-C6TG1LwA.d.ts.map +0 -1
- package/dist/index-CKjqN9_U.d.ts.map +0 -1
- package/dist/index-DAFZRMlF.d.ts.map +0 -1
- package/dist/index-xEM_SoCl.d.ts.map +0 -1
- package/dist/interval-CWyxqDpE.d.ts +0 -43
- package/dist/interval-CWyxqDpE.d.ts.map +0 -1
- package/dist/llm-judge-DQJTQx01.js.map +0 -1
- package/dist/matrix-CqZSpwgN.d.ts.map +0 -1
- package/dist/outcome-observations-DL3CC8w1.js.map +0 -1
- package/dist/pareto-Bg75Gajo.js.map +0 -1
- package/dist/rubric-predictive-validity--6z0q8s6.js.map +0 -1
- package/dist/rubric-predictive-validity-C9wc7f_D.d.ts.map +0 -1
- package/dist/run-improvement-loop-BfwOUudy.d.ts.map +0 -1
- package/dist/run-record-Bqg0NZ_e.js.map +0 -1
- package/dist/sequential-BphITa5b.js.map +0 -1
- package/dist/statistics-DSidA5I2.js.map +0 -1
- package/dist/summary-report-CI4J6gxU.js.map +0 -1
- package/dist/systemone-DzY-2Zri.d.ts.map +0 -1
- package/dist/tool-groups-DF6OqhoG.d.ts.map +0 -1
- package/dist/tool-waste-CIhtU1ad.d.ts +0 -217
- package/dist/tool-waste-CIhtU1ad.d.ts.map +0 -1
- package/dist/types-fuOwNq1C.d.ts.map +0 -1
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
import { a as findingTreatmentSchema, c as findingEvidenceRefSchema, i as findingConditionsSchema, s as findingCalibrationSchema } from "./finding-composition-CyWSTcAY.js";
|
|
2
|
+
import { t as CostLedger } from "./cost-ledger-C5CCidPm.js";
|
|
3
|
+
import { n as appendSearchLedgerLine, r as tryWithSearchLedgerFileLock } from "./search-ledger-file-QuIbgz6b.js";
|
|
4
|
+
import { n as FINDING_SCOPE_FIELDS, t as ANALYST_SEVERITIES } from "./types-_tlhWGUq.js";
|
|
5
|
+
import { createRequire } from "node:module";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
// src/campaign/storage.ts
|
|
9
|
+
/** Node-filesystem storage — the default. Lazily requires `node:fs` so the
|
|
10
|
+
* module imports cleanly in non-Node runtimes (where the caller passes
|
|
11
|
+
* `inMemoryCampaignStorage` instead and never constructs this).
|
|
12
|
+
*
|
|
13
|
+
* `createRequire(import.meta.url)` is the ESM-native lazy require — a bare
|
|
14
|
+
* `require` is a ReferenceError under `"type": "module"`, which is exactly
|
|
15
|
+
* the shape this package publishes. */
|
|
16
|
+
function fsCampaignStorage() {
|
|
17
|
+
const { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } = createRequire(import.meta.url)("node:fs");
|
|
18
|
+
return {
|
|
19
|
+
kind: "filesystem",
|
|
20
|
+
ensureDir(dir) {
|
|
21
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
22
|
+
},
|
|
23
|
+
exists(path) {
|
|
24
|
+
return existsSync(path);
|
|
25
|
+
},
|
|
26
|
+
read(path) {
|
|
27
|
+
try {
|
|
28
|
+
return readFileSync(path, "utf8");
|
|
29
|
+
} catch {
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
write(path, content) {
|
|
34
|
+
writeFileSync(path, content);
|
|
35
|
+
},
|
|
36
|
+
append(path, content, expectedBytes) {
|
|
37
|
+
const result = tryWithSearchLedgerFileLock(path, () => {
|
|
38
|
+
let actualBytes = 0;
|
|
39
|
+
try {
|
|
40
|
+
actualBytes = statSync(path).size;
|
|
41
|
+
} catch (error) {
|
|
42
|
+
if (error.code !== "ENOENT") throw error;
|
|
43
|
+
}
|
|
44
|
+
if (actualBytes !== expectedBytes) return void 0;
|
|
45
|
+
appendSearchLedgerLine(path, content);
|
|
46
|
+
return expectedBytes + Buffer.byteLength(content);
|
|
47
|
+
});
|
|
48
|
+
return result.acquired ? result.value : void 0;
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
/** In-memory storage for filesystem-less runtimes. Artifacts + trace spans
|
|
53
|
+
* live in a `Map` for the duration of the run; the `CampaignResult` is
|
|
54
|
+
* fully populated, but nothing is persisted to disk. */
|
|
55
|
+
function inMemoryCampaignStorage() {
|
|
56
|
+
const files = /* @__PURE__ */ new Map();
|
|
57
|
+
const dirs = /* @__PURE__ */ new Set();
|
|
58
|
+
return {
|
|
59
|
+
kind: "memory",
|
|
60
|
+
ensureDir(dir) {
|
|
61
|
+
dirs.add(dir);
|
|
62
|
+
},
|
|
63
|
+
exists(path) {
|
|
64
|
+
return files.has(path) || dirs.has(path);
|
|
65
|
+
},
|
|
66
|
+
read(path) {
|
|
67
|
+
const value = files.get(path);
|
|
68
|
+
if (value === void 0) return void 0;
|
|
69
|
+
return typeof value === "string" ? value : new TextDecoder().decode(value);
|
|
70
|
+
},
|
|
71
|
+
write(path, content) {
|
|
72
|
+
files.set(path, content);
|
|
73
|
+
},
|
|
74
|
+
append(path, content, expectedBytes) {
|
|
75
|
+
const current = files.get(path);
|
|
76
|
+
const currentText = current === void 0 ? "" : typeof current === "string" ? current : new TextDecoder().decode(current);
|
|
77
|
+
const currentBytes = new TextEncoder().encode(currentText).byteLength;
|
|
78
|
+
if (currentBytes !== expectedBytes) return void 0;
|
|
79
|
+
files.set(path, `${currentText}${content}`);
|
|
80
|
+
return currentBytes + new TextEncoder().encode(content).byteLength;
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
/** Open the durable spend account stored beside a logical run. */
|
|
85
|
+
function createRunCostLedger(input) {
|
|
86
|
+
const path = join(input.runDir, "cost-ledger.jsonl");
|
|
87
|
+
if (input.ensureRunDir ?? true) input.storage.ensureDir(input.runDir);
|
|
88
|
+
return new CostLedger({
|
|
89
|
+
costCeilingUsd: input.costCeilingUsd,
|
|
90
|
+
persistence: {
|
|
91
|
+
read: () => {
|
|
92
|
+
const stored = input.storage.read(path);
|
|
93
|
+
if (stored === void 0 && input.storage.exists(path)) throw new Error(`CostLedger: cannot read existing event log '${path}'`);
|
|
94
|
+
const events = stored ?? "";
|
|
95
|
+
return {
|
|
96
|
+
revision: String(new TextEncoder().encode(events).byteLength),
|
|
97
|
+
events
|
|
98
|
+
};
|
|
99
|
+
},
|
|
100
|
+
append: (expectedRevision, event) => {
|
|
101
|
+
const expectedBytes = Number(expectedRevision);
|
|
102
|
+
if (!Number.isSafeInteger(expectedBytes) || expectedBytes < 0) throw new Error(`CostLedger: invalid storage revision '${expectedRevision}'`);
|
|
103
|
+
const next = input.storage.append(path, event, expectedBytes);
|
|
104
|
+
return next === void 0 ? void 0 : String(next);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
// src/analyst/finding-scope.ts
|
|
110
|
+
/**
|
|
111
|
+
* What a finding is about and what it was measured on — AnalystFinding 1.1.0.
|
|
112
|
+
*
|
|
113
|
+
* A 1.0.0 finding states a claim with no layer and no population, so "a flat
|
|
114
|
+
* team beat a deep hierarchy", measured on 4 runs of one play where run 2
|
|
115
|
+
* inherited run 1's code, reads exactly like a lab-wide rule. Schema 1.1.0
|
|
116
|
+
* makes the population part of the record:
|
|
117
|
+
*
|
|
118
|
+
* - `layer` names the level the claim is about, on one ladder from a single
|
|
119
|
+
* event up to the whole lab, plus `meta` for findings about the measurement
|
|
120
|
+
* itself (a judge, a ruler, an analyst).
|
|
121
|
+
* - `scope` names the measured population, its size and time window, and the
|
|
122
|
+
* domain path it was drawn from.
|
|
123
|
+
* - `method` says whether the claim was computed, measured or judged; a
|
|
124
|
+
* judged claim without calibration reads as uncalibrated.
|
|
125
|
+
* - `evidence_units` lists the measured units with their lineage. When it is
|
|
126
|
+
* present the stored `scope.n` and `scope.population` must equal it, so the
|
|
127
|
+
* declared population cannot drift from the evidence.
|
|
128
|
+
*
|
|
129
|
+
* A claim moves above the layer it was measured at only through `promote`.
|
|
130
|
+
*/
|
|
131
|
+
/**
|
|
132
|
+
* The layer ladder, lowest first. `problem` is what discovery-lab calls a
|
|
133
|
+
* theatre. `meta` sits outside the ladder: it is about the instrument, not the
|
|
134
|
+
* agents, so it never promotes and never bounds another layer.
|
|
135
|
+
*/
|
|
136
|
+
const FINDING_LAYERS = [
|
|
137
|
+
"event",
|
|
138
|
+
"turn",
|
|
139
|
+
"agent",
|
|
140
|
+
"team",
|
|
141
|
+
"run",
|
|
142
|
+
"play",
|
|
143
|
+
"problem",
|
|
144
|
+
"domain",
|
|
145
|
+
"lab",
|
|
146
|
+
"meta"
|
|
147
|
+
];
|
|
148
|
+
/** Rank on the ladder; `meta` has none. */
|
|
149
|
+
function findingLayerRank(layer) {
|
|
150
|
+
return layer === "meta" ? null : FINDING_LAYERS.indexOf(layer);
|
|
151
|
+
}
|
|
152
|
+
const nonEmpty = z.string().refine((value) => value.trim().length > 0, { message: "must be a non-empty string" });
|
|
153
|
+
const timestamp = z.string().refine((value) => Number.isFinite(Date.parse(value)), { message: "must be a valid timestamp" });
|
|
154
|
+
const finite = z.number().refine(Number.isFinite, { message: "must be finite" });
|
|
155
|
+
const unitRate = finite.refine((value) => value >= 0 && value <= 1, { message: "must be in [0,1]" });
|
|
156
|
+
const layerSchema = z.enum(FINDING_LAYERS);
|
|
157
|
+
const scopeSchema = z.object({
|
|
158
|
+
population: z.array(nonEmpty),
|
|
159
|
+
n: z.number().int().nonnegative(),
|
|
160
|
+
window: z.object({
|
|
161
|
+
from: timestamp,
|
|
162
|
+
to: timestamp
|
|
163
|
+
}).strict(),
|
|
164
|
+
domain_path: z.array(nonEmpty).min(1).optional()
|
|
165
|
+
}).strict();
|
|
166
|
+
const methodSchema = z.object({
|
|
167
|
+
kind: z.enum([
|
|
168
|
+
"computed",
|
|
169
|
+
"measured",
|
|
170
|
+
"judged"
|
|
171
|
+
]),
|
|
172
|
+
name: nonEmpty,
|
|
173
|
+
version: nonEmpty,
|
|
174
|
+
calibration: findingCalibrationSchema.optional()
|
|
175
|
+
}).strict();
|
|
176
|
+
const measureSchema = z.object({
|
|
177
|
+
name: nonEmpty,
|
|
178
|
+
value: finite,
|
|
179
|
+
unit: z.string(),
|
|
180
|
+
interval: z.tuple([finite, finite]).optional(),
|
|
181
|
+
level: finite.refine((value) => value > 0 && value < 1, { message: "must be in (0,1)" }).optional()
|
|
182
|
+
}).strict();
|
|
183
|
+
const evidenceUnitSchema = z.object({
|
|
184
|
+
id: nonEmpty,
|
|
185
|
+
layer: layerSchema,
|
|
186
|
+
derived_from: nonEmpty.nullable().optional()
|
|
187
|
+
}).strict();
|
|
188
|
+
const findingObject = z.object({
|
|
189
|
+
schema_version: z.enum(["1.0.0", "1.1.0"]),
|
|
190
|
+
finding_id: nonEmpty,
|
|
191
|
+
analyst_id: nonEmpty,
|
|
192
|
+
produced_at: timestamp,
|
|
193
|
+
severity: z.enum(ANALYST_SEVERITIES),
|
|
194
|
+
area: nonEmpty,
|
|
195
|
+
claim: nonEmpty,
|
|
196
|
+
rationale: z.string().optional(),
|
|
197
|
+
evidence_refs: z.array(findingEvidenceRefSchema),
|
|
198
|
+
recommended_action: z.string().optional(),
|
|
199
|
+
validation_plan: z.string().optional(),
|
|
200
|
+
confidence: unitRate,
|
|
201
|
+
subject: z.string().optional(),
|
|
202
|
+
derived_from_judge: z.boolean().optional(),
|
|
203
|
+
metadata: z.record(z.string(), z.unknown()).optional(),
|
|
204
|
+
layer: layerSchema.optional(),
|
|
205
|
+
scope: scopeSchema.optional(),
|
|
206
|
+
method: methodSchema.optional(),
|
|
207
|
+
measure: measureSchema.optional(),
|
|
208
|
+
confounders: z.array(nonEmpty).optional(),
|
|
209
|
+
valid_for: nonEmpty.optional(),
|
|
210
|
+
claim_id: nonEmpty.optional(),
|
|
211
|
+
evidence_units: z.array(evidenceUnitSchema).min(1).optional(),
|
|
212
|
+
treatment: z.array(findingTreatmentSchema).optional(),
|
|
213
|
+
conditions: z.array(findingConditionsSchema).optional()
|
|
214
|
+
}).strict();
|
|
215
|
+
function checkFinding(finding, context) {
|
|
216
|
+
const issue = (path, message) => context.addIssue({
|
|
217
|
+
code: "custom",
|
|
218
|
+
path,
|
|
219
|
+
message
|
|
220
|
+
});
|
|
221
|
+
if (finding.schema_version === "1.0.0") {
|
|
222
|
+
for (const field of FINDING_SCOPE_FIELDS) if (finding[field] !== void 0) issue([field], `${field} requires schema_version 1.1.0`);
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
if (finding.layer === void 0) issue(["layer"], "1.1.0 findings require a layer");
|
|
226
|
+
if (finding.scope === void 0) issue(["scope"], "1.1.0 findings require a scope");
|
|
227
|
+
if (finding.method === void 0) issue(["method"], "1.1.0 findings require a method");
|
|
228
|
+
const { scope, measure, evidence_units: units } = finding;
|
|
229
|
+
if (scope) {
|
|
230
|
+
if (Date.parse(scope.window.from) > Date.parse(scope.window.to)) issue(["scope", "window"], "window.from must not be after window.to");
|
|
231
|
+
if (new Set(scope.population).size !== scope.population.length) issue(["scope", "population"], "population ids must be unique");
|
|
232
|
+
if (scope.population.length > 0 && scope.population.length !== scope.n) issue(["scope", "n"], `n ${scope.n} does not match ${scope.population.length} population ids`);
|
|
233
|
+
}
|
|
234
|
+
if (measure?.interval && measure.interval[0] > measure.interval[1]) issue(["measure", "interval"], "interval lower bound exceeds its upper bound");
|
|
235
|
+
if (measure?.level !== void 0 && measure.interval === void 0) issue(["measure", "level"], "level describes an interval; none is present");
|
|
236
|
+
if (finding.method?.kind !== "judged" && finding.method?.calibration !== void 0) issue(["method", "calibration"], "only judged findings carry a calibration");
|
|
237
|
+
for (const field of ["treatment", "conditions"]) {
|
|
238
|
+
const values = finding[field];
|
|
239
|
+
if (values && new Set(values.map((value) => value.id)).size !== values.length) issue([field], "composition ids must be unique");
|
|
240
|
+
}
|
|
241
|
+
if (!units) return;
|
|
242
|
+
const ids = units.map((unit) => unit.id);
|
|
243
|
+
if (new Set(ids).size !== ids.length) issue(["evidence_units"], "unit ids must be unique");
|
|
244
|
+
if (scope) {
|
|
245
|
+
if (scope.n !== ids.length) issue(["scope", "n"], `n ${scope.n} does not match ${ids.length} evidence units`);
|
|
246
|
+
const population = [...scope.population].sort();
|
|
247
|
+
const unitIds = [...ids].sort();
|
|
248
|
+
if (population.length !== unitIds.length || population.some((id, index) => id !== unitIds[index])) issue(["scope", "population"], "population must name exactly the evidence units");
|
|
249
|
+
}
|
|
250
|
+
const findingRank = finding.layer === void 0 ? null : findingLayerRank(finding.layer);
|
|
251
|
+
if (findingRank === null) return;
|
|
252
|
+
for (const [index, unit] of units.entries()) {
|
|
253
|
+
const unitRank = findingLayerRank(unit.layer);
|
|
254
|
+
if (unitRank !== null && unitRank > findingRank) issue([
|
|
255
|
+
"evidence_units",
|
|
256
|
+
index,
|
|
257
|
+
"layer"
|
|
258
|
+
], `a ${finding.layer} finding cannot rest on a ${unit.layer} unit`);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
/** The one validator for stored findings of either schema version. Unknown fields fail. */
|
|
262
|
+
const AnalystFindingSchema = findingObject.superRefine(checkFinding);
|
|
263
|
+
/** A finding admitted as candidate-generation input; same rules plus its origin. */
|
|
264
|
+
const ProposalFindingSchema = findingObject.extend({ proposal_origin: z.enum(["search", "production"]) }).strict().superRefine(checkFinding);
|
|
265
|
+
/** Validate one stored finding of schema 1.0.0 or 1.1.0. */
|
|
266
|
+
function parseAnalystFinding(value) {
|
|
267
|
+
const parsed = AnalystFindingSchema.safeParse(value);
|
|
268
|
+
if (parsed.success) return {
|
|
269
|
+
succeeded: true,
|
|
270
|
+
value: parsed.data
|
|
271
|
+
};
|
|
272
|
+
const issue = parsed.error.issues[0];
|
|
273
|
+
return {
|
|
274
|
+
succeeded: false,
|
|
275
|
+
error: {
|
|
276
|
+
path: (issue?.path ?? []).map(String).join("."),
|
|
277
|
+
message: issue?.message ?? "finding does not match the schema"
|
|
278
|
+
}
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
function readFindingScope(finding) {
|
|
282
|
+
if (finding.schema_version === "1.0.0" || !finding.scope || !finding.layer) return {
|
|
283
|
+
layer: "unknown",
|
|
284
|
+
n: "unknown",
|
|
285
|
+
independent_n: "unknown",
|
|
286
|
+
domain_path: null,
|
|
287
|
+
labels: ["unscoped"]
|
|
288
|
+
};
|
|
289
|
+
const labels = [];
|
|
290
|
+
if (finding.scope.n < 2) labels.push("anecdote");
|
|
291
|
+
if (finding.method?.kind === "judged" && finding.method.calibration === void 0) labels.push("uncalibrated");
|
|
292
|
+
const units = finding.evidence_units;
|
|
293
|
+
if (units?.some((unit) => unit.derived_from === void 0)) labels.push("lineage-unknown");
|
|
294
|
+
return {
|
|
295
|
+
layer: finding.layer,
|
|
296
|
+
n: finding.scope.n,
|
|
297
|
+
independent_n: units ? independentUnitCount(units) : "unknown",
|
|
298
|
+
domain_path: finding.scope.domain_path ?? null,
|
|
299
|
+
labels
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
/** Root token shared by every unit whose lineage was not recorded. */
|
|
303
|
+
const UNKNOWN_LINEAGE = "?unknown-lineage";
|
|
304
|
+
/**
|
|
305
|
+
* Lineage root of each unit, keyed by unit id. A unit derived from another
|
|
306
|
+
* unit in the list shares that unit's root; a unit derived from an id outside
|
|
307
|
+
* the list takes that id as its root; unknown lineage maps to one shared root.
|
|
308
|
+
*/
|
|
309
|
+
function lineageRoots(units) {
|
|
310
|
+
const byId = new Map(units.map((unit) => [unit.id, unit]));
|
|
311
|
+
const roots = /* @__PURE__ */ new Map();
|
|
312
|
+
for (const unit of units) {
|
|
313
|
+
let current = unit;
|
|
314
|
+
let root = unit.id;
|
|
315
|
+
const seen = /* @__PURE__ */ new Set();
|
|
316
|
+
while (current && !seen.has(current.id)) {
|
|
317
|
+
seen.add(current.id);
|
|
318
|
+
if (current.derived_from === void 0) {
|
|
319
|
+
root = UNKNOWN_LINEAGE;
|
|
320
|
+
break;
|
|
321
|
+
}
|
|
322
|
+
if (current.derived_from === null) {
|
|
323
|
+
root = current.id;
|
|
324
|
+
break;
|
|
325
|
+
}
|
|
326
|
+
root = current.derived_from;
|
|
327
|
+
current = byId.get(current.derived_from);
|
|
328
|
+
}
|
|
329
|
+
roots.set(unit.id, root);
|
|
330
|
+
}
|
|
331
|
+
return roots;
|
|
332
|
+
}
|
|
333
|
+
/** Units with distinct lineage roots. */
|
|
334
|
+
function independentUnitCount(units) {
|
|
335
|
+
return new Set(lineageRoots(units).values()).size;
|
|
336
|
+
}
|
|
337
|
+
/** One entry per unit id, sorted; a later copy that records lineage fills an earlier unknown. */
|
|
338
|
+
function mergeEvidenceUnits(units) {
|
|
339
|
+
const byId = /* @__PURE__ */ new Map();
|
|
340
|
+
for (const unit of units) {
|
|
341
|
+
const existing = byId.get(unit.id);
|
|
342
|
+
if (!existing || existing.derived_from === void 0 && unit.derived_from !== void 0) byId.set(unit.id, { ...unit });
|
|
343
|
+
}
|
|
344
|
+
return [...byId.values()].sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
|
|
345
|
+
}
|
|
346
|
+
/** The window spanning every finding's scope window. */
|
|
347
|
+
function spanningWindow(findings) {
|
|
348
|
+
const windows = findings.map((finding) => finding.scope.window);
|
|
349
|
+
return {
|
|
350
|
+
from: windows.map((w) => w.from).reduce((a, b) => Date.parse(b) < Date.parse(a) ? b : a),
|
|
351
|
+
to: windows.map((w) => w.to).reduce((a, b) => Date.parse(b) > Date.parse(a) ? b : a)
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
function mostSevere(findings) {
|
|
355
|
+
return ANALYST_SEVERITIES[Math.min(...findings.map((finding) => ANALYST_SEVERITIES.indexOf(finding.severity)))];
|
|
356
|
+
}
|
|
357
|
+
export { independentUnitCount as a, mostSevere as c, spanningWindow as d, createRunCostLedger as f, UNKNOWN_LINEAGE as i, parseAnalystFinding as l, inMemoryCampaignStorage as m, FINDING_LAYERS as n, lineageRoots as o, fsCampaignStorage as p, ProposalFindingSchema as r, mergeEvidenceUnits as s, AnalystFindingSchema as t, readFindingScope as u };
|
|
358
|
+
|
|
359
|
+
//# sourceMappingURL=finding-scope-B_As3F_v.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"finding-scope-B_As3F_v.js","names":[],"sources":["../src/campaign/storage.ts","../src/analyst/finding-scope.ts"],"sourcesContent":["import { createRequire } from 'node:module'\nimport { join } from 'node:path'\nimport { CostLedger } from '../cost-ledger'\nimport { appendSearchLedgerLine, tryWithSearchLedgerFileLock } from './search-ledger-file'\n\n/**\n * `CampaignStorage` — the filesystem seam `runCampaign` writes through\n * (run/cell dirs, the resumability cache, per-cell artifacts, trace spans).\n *\n * The default (`fsCampaignStorage`) is the Node filesystem — identical\n * behavior to the inline `node:fs` calls it replaces, so existing CLI\n * consumers are unaffected. `inMemoryCampaignStorage` keeps everything in a\n * `Map`, so the substrate runs in environments WITHOUT a filesystem\n * (Cloudflare Workers, Deno Deploy, other edge runtimes) — the campaign\n * still produces its `CampaignResult` (cells + aggregates) in memory;\n * artifacts/traces simply aren't persisted to disk.\n *\n * Paths are opaque keys to the in-memory adapter — it does not parse them,\n * so the same `join(...)`-built paths work unchanged across both adapters.\n */\nexport interface CampaignStorage {\n /** `filesystem` for the Node filesystem, whose paths durable journals such\n * as the search ledger may open directly; any other storage keeps those\n * journals in itself. */\n readonly kind?: 'filesystem' | 'memory'\n /** Ensure a directory exists (recursive). No-op for in-memory. */\n ensureDir(dir: string): void\n /** Does this path exist (as a written file or an ensured dir)? */\n exists(path: string): boolean\n /** Read a UTF-8 file; `undefined` when missing or unreadable. */\n read(path: string): string | undefined\n /** Write a file (string or bytes). Parent dir is assumed ensured. */\n write(path: string, content: string | Uint8Array): void\n /** Append only when the current UTF-8 byte length matches `expectedBytes`.\n * Returns the new length, or undefined when another writer won. */\n append(path: string, content: string, expectedBytes: number): number | undefined\n}\n\n/** Node-filesystem storage — the default. Lazily requires `node:fs` so the\n * module imports cleanly in non-Node runtimes (where the caller passes\n * `inMemoryCampaignStorage` instead and never constructs this).\n *\n * `createRequire(import.meta.url)` is the ESM-native lazy require — a bare\n * `require` is a ReferenceError under `\"type\": \"module\"`, which is exactly\n * the shape this package publishes. */\nexport function fsCampaignStorage(): CampaignStorage {\n const nodeRequire = createRequire(import.meta.url)\n const { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } = nodeRequire(\n 'node:fs',\n ) as typeof import('node:fs')\n return {\n kind: 'filesystem',\n ensureDir(dir) {\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true })\n },\n exists(path) {\n return existsSync(path)\n },\n read(path) {\n try {\n return readFileSync(path, 'utf8')\n } catch {\n return undefined\n }\n },\n write(path, content) {\n writeFileSync(path, content as Uint8Array)\n },\n append(path, content, expectedBytes) {\n const result = tryWithSearchLedgerFileLock(path, () => {\n let actualBytes = 0\n try {\n actualBytes = statSync(path).size\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n }\n if (actualBytes !== expectedBytes) return undefined\n appendSearchLedgerLine(path, content)\n return expectedBytes + Buffer.byteLength(content)\n })\n return result.acquired ? result.value : undefined\n },\n }\n}\n\n/** In-memory storage for filesystem-less runtimes. Artifacts + trace spans\n * live in a `Map` for the duration of the run; the `CampaignResult` is\n * fully populated, but nothing is persisted to disk. */\nexport function inMemoryCampaignStorage(): CampaignStorage {\n const files = new Map<string, string | Uint8Array>()\n const dirs = new Set<string>()\n return {\n kind: 'memory',\n ensureDir(dir) {\n dirs.add(dir)\n },\n exists(path) {\n return files.has(path) || dirs.has(path)\n },\n read(path) {\n const value = files.get(path)\n if (value === undefined) return undefined\n return typeof value === 'string' ? value : new TextDecoder().decode(value)\n },\n write(path, content) {\n files.set(path, content)\n },\n append(path, content, expectedBytes) {\n const current = files.get(path)\n const currentText =\n current === undefined\n ? ''\n : typeof current === 'string'\n ? current\n : new TextDecoder().decode(current)\n const currentBytes = new TextEncoder().encode(currentText).byteLength\n if (currentBytes !== expectedBytes) return undefined\n files.set(path, `${currentText}${content}`)\n return currentBytes + new TextEncoder().encode(content).byteLength\n },\n }\n}\n\n/** Open the durable spend account stored beside a logical run. */\nexport function createRunCostLedger(input: {\n storage: CampaignStorage\n runDir: string\n costCeilingUsd?: number\n /** Set false for read-only inspection that must not create the run directory. */\n ensureRunDir?: boolean\n}): CostLedger {\n const path = join(input.runDir, 'cost-ledger.jsonl')\n if (input.ensureRunDir ?? true) input.storage.ensureDir(input.runDir)\n return new CostLedger({\n costCeilingUsd: input.costCeilingUsd,\n persistence: {\n read: () => {\n const stored = input.storage.read(path)\n if (stored === undefined && input.storage.exists(path)) {\n throw new Error(`CostLedger: cannot read existing event log '${path}'`)\n }\n const events = stored ?? ''\n return {\n revision: String(new TextEncoder().encode(events).byteLength),\n events,\n }\n },\n append: (expectedRevision, event) => {\n const expectedBytes = Number(expectedRevision)\n if (!Number.isSafeInteger(expectedBytes) || expectedBytes < 0) {\n throw new Error(`CostLedger: invalid storage revision '${expectedRevision}'`)\n }\n const next = input.storage.append(path, event, expectedBytes)\n return next === undefined ? undefined : String(next)\n },\n },\n })\n}\n","/**\n * What a finding is about and what it was measured on — AnalystFinding 1.1.0.\n *\n * A 1.0.0 finding states a claim with no layer and no population, so \"a flat\n * team beat a deep hierarchy\", measured on 4 runs of one play where run 2\n * inherited run 1's code, reads exactly like a lab-wide rule. Schema 1.1.0\n * makes the population part of the record:\n *\n * - `layer` names the level the claim is about, on one ladder from a single\n * event up to the whole lab, plus `meta` for findings about the measurement\n * itself (a judge, a ruler, an analyst).\n * - `scope` names the measured population, its size and time window, and the\n * domain path it was drawn from.\n * - `method` says whether the claim was computed, measured or judged; a\n * judged claim without calibration reads as uncalibrated.\n * - `evidence_units` lists the measured units with their lineage. When it is\n * present the stored `scope.n` and `scope.population` must equal it, so the\n * declared population cannot drift from the evidence.\n *\n * A claim moves above the layer it was measured at only through `promote`.\n */\n\nimport { z } from 'zod'\nimport type { BootstrapInterval } from '../statistics/internal'\nimport { findingConditionsSchema, findingTreatmentSchema } from './finding-composition'\nimport { findingCalibrationSchema, findingEvidenceRefSchema } from './finding-primitives'\nimport {\n ANALYST_SEVERITIES,\n type AnalystFinding,\n type AnalystSeverity,\n FINDING_SCOPE_FIELDS,\n type ProposalFinding,\n} from './types'\n\n/**\n * The layer ladder, lowest first. `problem` is what discovery-lab calls a\n * theatre. `meta` sits outside the ladder: it is about the instrument, not the\n * agents, so it never promotes and never bounds another layer.\n */\nexport const FINDING_LAYERS = [\n 'event',\n 'turn',\n 'agent',\n 'team',\n 'run',\n 'play',\n 'problem',\n 'domain',\n 'lab',\n 'meta',\n] as const\n\nexport type FindingLayer = (typeof FINDING_LAYERS)[number]\n\n/** Rank on the ladder; `meta` has none. */\nfunction findingLayerRank(layer: FindingLayer): number | null {\n return layer === 'meta' ? null : FINDING_LAYERS.indexOf(layer)\n}\n\nexport interface FindingScope {\n /**\n * Ids of the measured units. A population is stored resolved, never as a\n * query: the ids are what `n`, `evidence_units` and promotion's lineage\n * check are compared against, and a query re-run later can select a\n * different set. Select populations with `queryFindings` (layer, subject,\n * domain path, analyst) and store the ids it returned.\n */\n population: string[]\n /** Units measured. Below 2, readers label the finding an anecdote. */\n n: number\n /** ISO-8601 bounds of the measured activity. */\n window: { from: string; to: string }\n /** Domain taxonomy path of any depth, broadest first. */\n domain_path?: string[]\n}\n\n/** A bootstrap interval with the key its clusters were drawn by (a window subject, a trace, ...). */\nexport interface CalibrationInterval extends BootstrapInterval {\n cluster: string\n}\n\nexport interface FindingCalibration {\n /** Gold items the judge was scored against. */\n gold_n: number\n /** Share of gold items where the judge matched the gold label. */\n agreement: number\n /** Chance-corrected agreement (Cohen's κ). */\n kappa: number\n /** Rank statistic of the positive class's probability against gold, when the judge supplied one. */\n auc?: number | null\n /** Seeded percentile cluster bootstrap of `auc`. */\n ci?: CalibrationInterval | null\n}\n\nexport interface FindingMethod {\n kind: 'computed' | 'measured' | 'judged'\n name: string\n version: string\n calibration?: FindingCalibration\n}\n\nexport interface FindingMeasure {\n name: string\n value: number\n unit: string\n interval?: [number, number]\n /** Confidence level of `interval`, in (0, 1). */\n level?: number\n}\n\n/**\n * One measured unit. `derived_from` is the unit this one inherited state from\n * (run 2 built on run 1's code): `null` records an independent start, and an\n * absent field records lineage nobody captured. Unknown lineage counts as\n * shared, so it can never manufacture independent support for a claim.\n */\nexport interface FindingEvidenceUnit {\n id: string\n layer: FindingLayer\n derived_from?: string | null\n}\n\nconst nonEmpty = z.string().refine((value) => value.trim().length > 0, {\n message: 'must be a non-empty string',\n})\nconst timestamp = z.string().refine((value) => Number.isFinite(Date.parse(value)), {\n message: 'must be a valid timestamp',\n})\nconst finite = z.number().refine(Number.isFinite, { message: 'must be finite' })\nconst unitRate = finite.refine((value) => value >= 0 && value <= 1, { message: 'must be in [0,1]' })\n\nconst layerSchema = z.enum(FINDING_LAYERS)\n\nconst scopeSchema = z\n .object({\n population: z.array(nonEmpty),\n n: z.number().int().nonnegative(),\n window: z.object({ from: timestamp, to: timestamp }).strict(),\n domain_path: z.array(nonEmpty).min(1).optional(),\n })\n .strict()\n\nconst methodSchema = z\n .object({\n kind: z.enum(['computed', 'measured', 'judged']),\n name: nonEmpty,\n version: nonEmpty,\n calibration: findingCalibrationSchema.optional(),\n })\n .strict()\n\nconst measureSchema = z\n .object({\n name: nonEmpty,\n value: finite,\n unit: z.string(),\n interval: z.tuple([finite, finite]).optional(),\n level: finite\n .refine((value) => value > 0 && value < 1, { message: 'must be in (0,1)' })\n .optional(),\n })\n .strict()\n\nconst evidenceUnitSchema = z\n .object({\n id: nonEmpty,\n layer: layerSchema,\n derived_from: nonEmpty.nullable().optional(),\n })\n .strict()\n\nconst findingObject = z\n .object({\n schema_version: z.enum(['1.0.0', '1.1.0']),\n finding_id: nonEmpty,\n analyst_id: nonEmpty,\n produced_at: timestamp,\n severity: z.enum(ANALYST_SEVERITIES),\n area: nonEmpty,\n claim: nonEmpty,\n rationale: z.string().optional(),\n evidence_refs: z.array(findingEvidenceRefSchema),\n recommended_action: z.string().optional(),\n validation_plan: z.string().optional(),\n confidence: unitRate,\n subject: z.string().optional(),\n derived_from_judge: z.boolean().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n layer: layerSchema.optional(),\n scope: scopeSchema.optional(),\n method: methodSchema.optional(),\n measure: measureSchema.optional(),\n confounders: z.array(nonEmpty).optional(),\n valid_for: nonEmpty.optional(),\n claim_id: nonEmpty.optional(),\n evidence_units: z.array(evidenceUnitSchema).min(1).optional(),\n treatment: z.array(findingTreatmentSchema).optional(),\n conditions: z.array(findingConditionsSchema).optional(),\n })\n .strict()\n\ntype FindingShape = z.infer<typeof findingObject>\n\nfunction checkFinding(finding: FindingShape, context: z.RefinementCtx): void {\n const issue = (path: PropertyKey[], message: string): void =>\n context.addIssue({ code: 'custom', path, message })\n if (finding.schema_version === '1.0.0') {\n for (const field of FINDING_SCOPE_FIELDS) {\n if (finding[field] !== undefined) issue([field], `${field} requires schema_version 1.1.0`)\n }\n return\n }\n // A 1.1.0 finding exists to state its layer and population; one without\n // them is a 1.0.0 finding with a misleading version.\n if (finding.layer === undefined) issue(['layer'], '1.1.0 findings require a layer')\n if (finding.scope === undefined) issue(['scope'], '1.1.0 findings require a scope')\n if (finding.method === undefined) issue(['method'], '1.1.0 findings require a method')\n const { scope, measure, evidence_units: units } = finding\n if (scope) {\n if (Date.parse(scope.window.from) > Date.parse(scope.window.to)) {\n issue(['scope', 'window'], 'window.from must not be after window.to')\n }\n if (new Set(scope.population).size !== scope.population.length) {\n issue(['scope', 'population'], 'population ids must be unique')\n }\n if (scope.population.length > 0 && scope.population.length !== scope.n) {\n issue(['scope', 'n'], `n ${scope.n} does not match ${scope.population.length} population ids`)\n }\n }\n if (measure?.interval && measure.interval[0] > measure.interval[1]) {\n issue(['measure', 'interval'], 'interval lower bound exceeds its upper bound')\n }\n if (measure?.level !== undefined && measure.interval === undefined) {\n issue(['measure', 'level'], 'level describes an interval; none is present')\n }\n if (finding.method?.kind !== 'judged' && finding.method?.calibration !== undefined) {\n issue(['method', 'calibration'], 'only judged findings carry a calibration')\n }\n for (const field of ['treatment', 'conditions'] as const) {\n const values = finding[field]\n if (values && new Set(values.map((value) => value.id)).size !== values.length)\n issue([field], 'composition ids must be unique')\n }\n if (!units) return\n const ids = units.map((unit) => unit.id)\n if (new Set(ids).size !== ids.length) issue(['evidence_units'], 'unit ids must be unique')\n if (scope) {\n if (scope.n !== ids.length) {\n issue(['scope', 'n'], `n ${scope.n} does not match ${ids.length} evidence units`)\n }\n const population = [...scope.population].sort()\n const unitIds = [...ids].sort()\n if (\n population.length !== unitIds.length ||\n population.some((id, index) => id !== unitIds[index])\n ) {\n issue(['scope', 'population'], 'population must name exactly the evidence units')\n }\n }\n const findingRank = finding.layer === undefined ? null : findingLayerRank(finding.layer)\n if (findingRank === null) return\n for (const [index, unit] of units.entries()) {\n const unitRank = findingLayerRank(unit.layer)\n if (unitRank !== null && unitRank > findingRank) {\n issue(\n ['evidence_units', index, 'layer'],\n `a ${finding.layer} finding cannot rest on a ${unit.layer} unit`,\n )\n }\n }\n}\n\n/** The one validator for stored findings of either schema version. Unknown fields fail. */\nexport const AnalystFindingSchema = findingObject.superRefine(checkFinding)\n\n/** A finding admitted as candidate-generation input; same rules plus its origin. */\nexport const ProposalFindingSchema = findingObject\n .extend({ proposal_origin: z.enum(['search', 'production']) })\n .strict()\n .superRefine(checkFinding)\n\n// Compile-time proof that the schemas and the hand-written types agree.\nconst _findingType: z.ZodType<AnalystFinding> = AnalystFindingSchema\nconst _proposalType: z.ZodType<ProposalFinding> = ProposalFindingSchema\nvoid _findingType\nvoid _proposalType\n\nexport type FindingParseOutcome =\n | { succeeded: true; value: AnalystFinding }\n | { succeeded: false; error: { path: string; message: string } }\n\n/** Validate one stored finding of schema 1.0.0 or 1.1.0. */\nexport function parseAnalystFinding(value: unknown): FindingParseOutcome {\n const parsed = AnalystFindingSchema.safeParse(value)\n if (parsed.success) return { succeeded: true, value: parsed.data as AnalystFinding }\n const issue = parsed.error.issues[0]\n return {\n succeeded: false,\n error: {\n path: (issue?.path ?? []).map(String).join('.'),\n message: issue?.message ?? 'finding does not match the schema',\n },\n }\n}\n\n/**\n * A finding's scope as a reader sees it. A 1.0.0 finding states neither layer\n * nor population, so both read `unknown` — never a guessed value.\n */\nexport interface FindingScopeReading {\n layer: FindingLayer | 'unknown'\n n: number | 'unknown'\n /** Units with distinct lineage roots; unknown lineage counts as one shared root. */\n independent_n: number | 'unknown'\n domain_path: readonly string[] | null\n labels: FindingReaderLabel[]\n}\n\n/**\n * - `unscoped`: a 1.0.0 finding with no layer or population.\n * - `anecdote`: measured on fewer than two units.\n * - `uncalibrated`: judged, with no calibration against gold labels.\n * - `lineage-unknown`: at least one unit has no recorded lineage.\n */\nexport type FindingReaderLabel = 'unscoped' | 'anecdote' | 'uncalibrated' | 'lineage-unknown'\n\nexport function readFindingScope(finding: AnalystFinding): FindingScopeReading {\n if (finding.schema_version === '1.0.0' || !finding.scope || !finding.layer) {\n return {\n layer: 'unknown',\n n: 'unknown',\n independent_n: 'unknown',\n domain_path: null,\n labels: ['unscoped'],\n }\n }\n const labels: FindingReaderLabel[] = []\n if (finding.scope.n < 2) labels.push('anecdote')\n if (finding.method?.kind === 'judged' && finding.method.calibration === undefined) {\n labels.push('uncalibrated')\n }\n const units = finding.evidence_units\n if (units?.some((unit) => unit.derived_from === undefined)) labels.push('lineage-unknown')\n return {\n layer: finding.layer,\n n: finding.scope.n,\n independent_n: units ? independentUnitCount(units) : 'unknown',\n domain_path: finding.scope.domain_path ?? null,\n labels,\n }\n}\n\n/** Root token shared by every unit whose lineage was not recorded. */\nexport const UNKNOWN_LINEAGE = '?unknown-lineage'\n\n/**\n * Lineage root of each unit, keyed by unit id. A unit derived from another\n * unit in the list shares that unit's root; a unit derived from an id outside\n * the list takes that id as its root; unknown lineage maps to one shared root.\n */\nexport function lineageRoots(units: ReadonlyArray<FindingEvidenceUnit>): Map<string, string> {\n const byId = new Map(units.map((unit) => [unit.id, unit]))\n const roots = new Map<string, string>()\n for (const unit of units) {\n let current: FindingEvidenceUnit | undefined = unit\n let root = unit.id\n const seen = new Set<string>()\n while (current && !seen.has(current.id)) {\n seen.add(current.id)\n if (current.derived_from === undefined) {\n root = UNKNOWN_LINEAGE\n break\n }\n if (current.derived_from === null) {\n root = current.id\n break\n }\n root = current.derived_from\n current = byId.get(current.derived_from)\n }\n roots.set(unit.id, root)\n }\n return roots\n}\n\n/** Units with distinct lineage roots. */\nexport function independentUnitCount(units: ReadonlyArray<FindingEvidenceUnit>): number {\n return new Set(lineageRoots(units).values()).size\n}\n\n/** One entry per unit id, sorted; a later copy that records lineage fills an earlier unknown. */\nexport function mergeEvidenceUnits(units: readonly FindingEvidenceUnit[]): FindingEvidenceUnit[] {\n const byId = new Map<string, FindingEvidenceUnit>()\n for (const unit of units) {\n const existing = byId.get(unit.id)\n if (!existing || (existing.derived_from === undefined && unit.derived_from !== undefined)) {\n byId.set(unit.id, { ...unit })\n }\n }\n return [...byId.values()].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))\n}\n\n/** The window spanning every finding's scope window. */\nexport function spanningWindow(findings: readonly AnalystFinding[]): FindingScope['window'] {\n const windows = findings.map((finding) => finding.scope!.window)\n return {\n from: windows.map((w) => w.from).reduce((a, b) => (Date.parse(b) < Date.parse(a) ? b : a)),\n to: windows.map((w) => w.to).reduce((a, b) => (Date.parse(b) > Date.parse(a) ? b : a)),\n }\n}\n\nexport function mostSevere(findings: readonly AnalystFinding[]): AnalystSeverity {\n return ANALYST_SEVERITIES[\n Math.min(...findings.map((finding) => ANALYST_SEVERITIES.indexOf(finding.severity)))\n ]!\n}\n"],"mappings":";;;;;;;;;;;;;;;AA6CA,SAAgB,oBAAqC;CAEnD,MAAM,EAAE,YAAY,WAAW,cAAc,UAAU,kBADnC,cAAc,YAAY,GACqC,CAAC,CAClF,SACF;CACA,OAAO;EACL,MAAM;EACN,UAAU,KAAK;GACb,IAAI,CAAC,WAAW,GAAG,GAAG,UAAU,KAAK,EAAE,WAAW,KAAK,CAAC;EAC1D;EACA,OAAO,MAAM;GACX,OAAO,WAAW,IAAI;EACxB;EACA,KAAK,MAAM;GACT,IAAI;IACF,OAAO,aAAa,MAAM,MAAM;GAClC,QAAQ;IACN;GACF;EACF;EACA,MAAM,MAAM,SAAS;GACnB,cAAc,MAAM,OAAqB;EAC3C;EACA,OAAO,MAAM,SAAS,eAAe;GACnC,MAAM,SAAS,4BAA4B,YAAY;IACrD,IAAI,cAAc;IAClB,IAAI;KACF,cAAc,SAAS,IAAI,CAAC,CAAC;IAC/B,SAAS,OAAO;KACd,IAAK,MAAgC,SAAS,UAAU,MAAM;IAChE;IACA,IAAI,gBAAgB,eAAe,OAAO,KAAA;IAC1C,uBAAuB,MAAM,OAAO;IACpC,OAAO,gBAAgB,O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AG,KAAK,OAAO,CAAC,CAAC,CAAC,MAAM,GAAG,MAAO,EAAE,KAAK,EAAE,KAAK,KAAK,EAAE,KAAK,EAAE,KAAK,IAAI,CAAE;AACnF;;AAGA,SAAgB,eAAe,UAA6D;CAC1F,MAAM,UAAU,SAAS,KAAK,YAAY,QAAQ,MAAO,MAAM;CAC/D,OAAO;EACL,MAAM,QAAQ,KAAK,MAAM,EAAE,IAAI,CAAC,CAAC,QAAQ,GAAG,MAAO,KAAK,MAAM,CAAC,IAAI,KAAK,MAAM,CAAC,IAAI,IAAI,CAAE;EACzF,IAAI,QAAQ,KAAK,MAAM,EAAE,EAAE,CAAC,CAAC,QAAQ,GAAG,MAAO,KAAK,MAAM,CAAC,IAAI,KAAK,MAAM,CAAC,IAAI,IAAI,CAAE;CACvF;AACF;AAEA,SAAgB,WAAW,UAAsD;CAC/E,OAAO,mBACL,KAAK,IAAI,GAAG,SAAS,KAAK,YAAY,mBAAmB,QAAQ,QAAQ,QAAQ,CAAC,CAAC;AAEvF"}
|
|
@@ -4,7 +4,7 @@ import { t as extractJsonPayload } from "./json-DtvZNAU9.js";
|
|
|
4
4
|
import { A as RawAnalystFindingSchema } from "./kind-factory-B-xCxG7p.js";
|
|
5
5
|
import "./llm-client-Dw4x6EdE.js";
|
|
6
6
|
import { t as paidChat } from "./chat-json-call-DMrwmB-k.js";
|
|
7
|
-
import { n as decodeRawFindingArray } from "./dspy-rlm-engine-
|
|
7
|
+
import { n as decodeRawFindingArray } from "./dspy-rlm-engine-DQbPdT_o.js";
|
|
8
8
|
import { z } from "zod";
|
|
9
9
|
import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
10
10
|
import { dirname } from "node:path";
|
|
@@ -539,4 +539,4 @@ function diffFindings(previous, current, policy = {}) {
|
|
|
539
539
|
}
|
|
540
540
|
export { diffFindings as n, createChatTraceEngine as r, FindingsStore as t };
|
|
541
541
|
|
|
542
|
-
//# sourceMappingURL=findings-store-
|
|
542
|
+
//# sourceMappingURL=findings-store-CZy5kUDo.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"findings-store-DV8WA5nD.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 TraceAnalysisActivity,\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.1'\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 async analyze(request) {\n const activity = { modelCalls: 0, toolCalls: 0 }\n try {\n return await analyze(\n request,\n { ...options, model, maxOutputTokens, reportFormat },\n activity,\n )\n } finally {\n request.recordActivity?.(activity)\n }\n },\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 activity: TraceAnalysisActivity,\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 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 activity.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 (activity.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 activity.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 activity.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 ...activity,\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,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,o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AAK,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"}
|
|
1
|
+
{"version":3,"file":"findings-store-CZy5kUDo.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 TraceAnalysisActivity,\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.1'\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 async analyze(request) {\n const activity = { modelCalls: 0, toolCalls: 0 }\n try {\n return await analyze(\n request,\n { ...options, model, maxOutputTokens, reportFormat },\n activity,\n )\n } finally {\n request.recordActivity?.(activity)\n }\n },\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 activity: TraceAnalysisActivity,\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 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 activity.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 (activity.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 activity.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 activity.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 ...activity,\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,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;GAC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|
package/dist/fuzz.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { s as ValidationError } from "./errors-DeEEV9Vx.js";
|
|
2
|
-
import {
|
|
2
|
+
import { m as summarizeNumberSeries } from "./paired-tests-CXcD_B80.js";
|
|
3
3
|
import { t as mulberry32 } from "./random-DrzcgC7F.js";
|
|
4
4
|
import { o as CostReceiptCaptureError, t as CostLedger } from "./cost-ledger-C5CCidPm.js";
|
|
5
5
|
// src/fuzz/cube.ts
|