@tangle-network/agent-eval 2.0.5 → 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 +24 -0
- package/dist/adapters/http.d.ts +2 -2
- package/dist/{agent-profile-CcOq7bOO.d.ts → agent-profile-ORN4aArD.d.ts} +5 -5
- package/dist/{agent-profile-CcOq7bOO.d.ts.map → agent-profile-ORN4aArD.d.ts.map} +1 -1
- package/dist/analyst/index.d.ts +15 -15
- package/dist/analyst/index.js +18 -14
- package/dist/analyst/index.js.map +1 -1
- 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-MfXRocwZ.js → benchmark-command-DLg8E4y8.js} +16 -9
- 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-BmMs8YJt.d.ts → campaign-evidence-CM4FBOkX.d.ts} +5 -5
- package/dist/{campaign-evidence-BmMs8YJt.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 +6 -6
- 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-CUuorCWZ.d.ts → default-registry-Bskl2HzV.d.ts} +6 -7
- package/dist/default-registry-Bskl2HzV.d.ts.map +1 -0
- package/dist/{default-registry-IkE3byrA.js → default-registry-kps1SOaD.js} +27 -15
- package/dist/default-registry-kps1SOaD.js.map +1 -0
- 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-DE11iBcC.js → dspy-rlm-engine-DQbPdT_o.js} +8 -4
- package/dist/{dspy-rlm-engine-DE11iBcC.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-DfyLPVL1.d.ts → evaluation-C4-tf3Z_.d.ts} +4 -4
- package/dist/{evaluation-DfyLPVL1.d.ts.map → evaluation-C4-tf3Z_.d.ts.map} +1 -1
- package/dist/evaluation.d.ts +1 -1
- package/dist/{exact-types-CiCXYhNK.d.ts → exact-types-CUsSMW3n.d.ts} +2 -2
- package/dist/{exact-types-CiCXYhNK.d.ts.map → exact-types-CUsSMW3n.d.ts.map} +1 -1
- package/dist/{execution-insight-wUNXxo5Y.d.ts → execution-insight-YihQrSqd.d.ts} +2 -2
- package/dist/{execution-insight-wUNXxo5Y.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-HJticMDz.d.ts → feedback-trajectory-D7hgL6y5.d.ts} +3 -3
- package/dist/{feedback-trajectory-HJticMDz.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-BxpV-hfH.js → findings-store-CZy5kUDo.js} +26 -19
- package/dist/findings-store-CZy5kUDo.js.map +1 -0
- package/dist/fuzz.js +1 -1
- package/dist/{harness-session-lines-CSxKR6no.js → harness-session-lines-CTh1-uOb.js} +21 -19
- package/dist/harness-session-lines-CTh1-uOb.js.map +1 -0
- package/dist/{index-Ucp54Pcl.d.ts → index--vDCtdaj.d.ts} +7 -8
- package/dist/index--vDCtdaj.d.ts.map +1 -0
- 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-CR-guIiZ.d.ts → index-DmMHTDjT.d.ts} +10 -8
- package/dist/index-DmMHTDjT.d.ts.map +1 -0
- package/dist/{index-oX0TuJFv.d.ts → index-Er8TKQ3q.d.ts} +4 -4
- package/dist/{index-oX0TuJFv.d.ts.map → index-Er8TKQ3q.d.ts.map} +1 -1
- package/dist/{index-B_k8aY9k.d.ts → index-moZnazVj.d.ts} +22 -21
- package/dist/index-moZnazVj.d.ts.map +1 -0
- package/dist/index.d.ts +33 -30
- package/dist/index.js +27 -24
- package/dist/index.js.map +1 -1
- package/dist/{analyze-runs-Ke0WbAf6.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/{kind-factory-BDd4rhML.js → kind-factory-B-xCxG7p.js} +33 -5
- package/dist/kind-factory-B-xCxG7p.js.map +1 -0
- package/dist/llm-judge-DFoSy4Qn.js +476 -0
- package/dist/llm-judge-DFoSy4Qn.js.map +1 -0
- package/dist/{matrix-DlSrRl_v.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-iEaSEGZB.d.ts → prime-protocol-Jm2pWh--.d.ts} +2 -2
- package/dist/{prime-protocol-iEaSEGZB.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-V8o2kZtn.d.ts → registry-DEZDECdr.d.ts} +4 -4
- package/dist/{registry-V8o2kZtn.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/rollout/index.js +2 -2
- package/dist/{rollout-DVwpCHBC.js → rollout-B_lrpd9a.js} +2 -2
- package/dist/{rollout-DVwpCHBC.js.map → rollout-B_lrpd9a.js.map} +1 -1
- 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-CtLyPb5-.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-DdUijr_t.js → runtime-rollouts-Vv-BAqmq.js} +3 -3
- package/dist/{runtime-rollouts-DdUijr_t.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-DXA1EhnN.d.ts → search-kernel-BzTeb89p.d.ts} +3 -3
- package/dist/{search-kernel-DXA1EhnN.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-D17XsdAt.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-otlp-CR9fWum6.js → store-otlp-CdeW7NWq.js} +2 -2
- package/dist/{store-otlp-CR9fWum6.js.map → store-otlp-CdeW7NWq.js.map} +1 -1
- package/dist/{store-tool-spans-tkdUJWup.js → store-tool-spans-CVX-jfkk.js} +3 -3
- package/dist/{store-tool-spans-tkdUJWup.js.map → store-tool-spans-CVX-jfkk.js.map} +1 -1
- package/dist/{store-tool-spans-C47hUUVM.d.ts → store-tool-spans-Dq8r0PbJ.d.ts} +4 -5
- package/dist/store-tool-spans-Dq8r0PbJ.d.ts.map +1 -0
- 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-MXhFSYdy.d.ts → systemone-BuSZTI88.d.ts} +8 -7
- package/dist/systemone-BuSZTI88.d.ts.map +1 -0
- package/dist/{systemone-review-C9kbs3zD.d.ts → systemone-review-mlfxWdLz.d.ts} +2 -2
- package/dist/{systemone-review-C9kbs3zD.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-BSd08M7B.d.ts → tool-groups-PNDX8fd-.d.ts} +2 -3
- 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-CJANeK9P.d.ts → trace-questions-DBtr4jWi.d.ts} +2 -3
- package/dist/trace-questions-DBtr4jWi.d.ts.map +1 -0
- package/dist/trace-repair/index.d.ts +1 -1
- package/dist/trace-repair/index.js +1 -1
- package/dist/traces.d.ts +4 -5
- package/dist/traces.d.ts.map +1 -1
- package/dist/traces.js +4 -4
- 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-DD1eUTLn.d.ts → types-BO948H-U.d.ts} +7 -4
- package/dist/{types-DD1eUTLn.d.ts.map → types-BO948H-U.d.ts.map} +1 -1
- package/dist/{types-AGUuvnae.d.ts → types-CKNAzCSA.d.ts} +158 -3
- 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-CE9JMZhk.d.ts → types-DbeIGi73.d.ts} +2 -2
- package/dist/{types-CE9JMZhk.d.ts.map → types-DbeIGi73.d.ts.map} +1 -1
- package/dist/types-_tlhWGUq.js.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/trace-analysis.md +1 -0
- package/docs/world.md +104 -0
- package/package.json +7 -2
- package/dist/analyze-runs-Ke0WbAf6.d.ts.map +0 -1
- package/dist/benchmark-command-MfXRocwZ.js.map +0 -1
- package/dist/campaign-DfSWSreo.js.map +0 -1
- package/dist/cluster-Bj90LK-1.d.ts.map +0 -1
- package/dist/default-registry-CUuorCWZ.d.ts.map +0 -1
- package/dist/default-registry-IkE3byrA.js.map +0 -1
- package/dist/define-agent-eval-B6uE3gNu.js.map +0 -1
- package/dist/define-agent-eval-D17XsdAt.d.ts.map +0 -1
- package/dist/engine-BZVXOc6n.d.ts +0 -152
- package/dist/engine-BZVXOc6n.d.ts.map +0 -1
- package/dist/external-optimizer-subprocess-BW0ZWUUr.js.map +0 -1
- package/dist/findings-store-BxpV-hfH.js.map +0 -1
- package/dist/harness-session-lines-CSxKR6no.js.map +0 -1
- package/dist/index-B_k8aY9k.d.ts.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-CR-guIiZ.d.ts.map +0 -1
- package/dist/index-Ucp54Pcl.d.ts.map +0 -1
- package/dist/interval-CWyxqDpE.d.ts +0 -43
- package/dist/interval-CWyxqDpE.d.ts.map +0 -1
- package/dist/kind-factory-BDd4rhML.js.map +0 -1
- package/dist/llm-judge-DQJTQx01.js.map +0 -1
- package/dist/matrix-DlSrRl_v.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-CtLyPb5-.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/store-tool-spans-C47hUUVM.d.ts.map +0 -1
- package/dist/summary-report-CI4J6gxU.js.map +0 -1
- package/dist/systemone-MXhFSYdy.d.ts.map +0 -1
- package/dist/tool-groups-BSd08M7B.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/trace-questions-CJANeK9P.d.ts.map +0 -1
- package/dist/types-AGUuvnae.d.ts.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/world/chat-agent.ts","../../src/world/world.ts","../../src/world/score.ts","../../src/world/tools.ts","../../src/world/episode.ts","../../src/world/compare.ts","../../src/world/launch-quarter.ts","../../src/world/policies.ts"],"sourcesContent":["// A model-backed agent for the world: one chat-completions tool loop per\n// session. The system prompt is the agent under test's own; the first user\n// message is the scenario brief, the date and the notes the agent saved.\n// Nothing from an earlier session's conversation is replayed.\n\nimport type { ChatClient } from '../analyst/chat-client'\nimport { ValidationError } from '../errors'\nimport type { LlmMessage, LlmToolDefinition } from '../llm-client'\nimport type { WorldAgent, WorldSession } from './types'\n\n/** What one model call returned, without its text. */\nexport interface ChatWorldResponse {\n /** Model id the provider echoed; null when it echoed none. */\n servedModel: string | null\n finishReason: string | null\n toolCalls: number\n contentChars: number\n completionTokens: number\n reasoningTokens: number | null\n}\n\nexport interface ChatWorldSessionTranscript {\n session: number\n day: number\n /** Every message of the session, the system prompt included. */\n messages: LlmMessage[]\n /** One entry per model call, empty completions included. */\n responses: ChatWorldResponse[]\n /** `answered`: the model replied in words without a tool call. `turn_limit`:\n * it was cut off. `empty`: it kept returning neither words nor a tool call.\n * `failed`: a model call threw, and the driver records the session's error. */\n ended: 'answered' | 'turn_limit' | 'empty' | 'failed'\n}\n\nexport interface ChatWorldAgentOptions {\n client: ChatClient\n /** Default: the client's default model. */\n model?: string\n /** System prompt of the agent under test. */\n systemPrompt: string\n /** The first user message of a session. Default: `worldSessionPrompt`. A\n * binding that adds its product's own per-turn context wraps that. */\n sessionPrompt?: (session: WorldSession) => string\n /** Model calls one session may make. Default 16. */\n maxTurnsPerSession?: number\n /** Times in a row an empty completion, neither words nor a tool call, is\n * asked again before the session ends as `empty`. Default 2. */\n emptyRetries?: number\n maxTokens?: number\n temperature?: number\n /** Called with each finished session's transcript. */\n onSession?: (transcript: ChatWorldSessionTranscript) => Promise<void> | void\n}\n\n/** The first user message of a session: all the agent is given. */\nexport function worldSessionPrompt(session: WorldSession): string {\n const notes = Object.entries(session.notes)\n return [\n session.brief,\n '',\n `Today is ${session.date}: day ${session.day}, review ${session.index + 1}. ${session.daysLeft} days are left.`,\n notes.length === 0\n ? 'You have saved no notes.'\n : `Notes you saved earlier:\\n${notes.map(([key, text]) => `[${key}]\\n${text}`).join('\\n\\n')}`,\n '',\n 'Read the state with the tools, act if the evidence supports it, and save what you will need next time. When you are done for this review, reply in plain text with what you did and why.',\n ].join('\\n')\n}\n\n/** An agent that plays each session as a tool loop against a chat model. */\nexport function chatWorldAgent(opts: ChatWorldAgentOptions): WorldAgent {\n const maxTurns = opts.maxTurnsPerSession ?? 16\n const emptyRetries = opts.emptyRetries ?? 2\n if (!Number.isSafeInteger(maxTurns) || maxTurns < 1) {\n throw new ValidationError('chatWorldAgent: maxTurnsPerSession must be a positive integer')\n }\n if (!Number.isSafeInteger(emptyRetries) || emptyRetries < 0) {\n throw new ValidationError('chatWorldAgent: emptyRetries must be a non-negative integer')\n }\n return async (session) => {\n const tools: LlmToolDefinition[] = session.tools.map((tool) => ({\n type: 'function',\n function: { name: tool.name, description: tool.description, parameters: tool.inputSchema },\n }))\n const messages: LlmMessage[] = [\n { role: 'system', content: opts.systemPrompt },\n { role: 'user', content: (opts.sessionPrompt ?? worldSessionPrompt)(session) },\n ]\n const transcript: ChatWorldSessionTranscript = {\n session: session.index,\n day: session.day,\n messages,\n responses: [],\n ended: 'turn_limit',\n }\n let emptyInARow = 0\n try {\n while (transcript.responses.length < maxTurns) {\n const response = await opts.client.chat({\n ...(opts.model ? { model: opts.model } : {}),\n messages,\n tools,\n toolChoice: 'auto',\n ...(opts.maxTokens !== undefined ? { maxTokens: opts.maxTokens } : {}),\n ...(opts.temperature !== undefined ? { temperature: opts.temperature } : {}),\n })\n const calls = response.toolCalls ?? []\n transcript.responses.push({\n servedModel: response.servedModel ?? null,\n finishReason: response.finishReason ?? null,\n toolCalls: calls.length,\n contentChars: response.content.length,\n completionTokens: response.usage.completionTokens,\n reasoningTokens: response.usage.reasoningTokens ?? null,\n })\n if (calls.length === 0 && response.content.trim() === '') {\n // Neither an answer nor an action. Ending the session here would\n // score a provider hiccup as the agent choosing to do nothing.\n emptyInARow += 1\n if (emptyInARow > emptyRetries) {\n transcript.ended = 'empty'\n break\n }\n continue\n }\n emptyInARow = 0\n messages.push({\n role: 'assistant',\n content: response.content,\n ...(calls.length > 0 ? { toolCalls: calls } : {}),\n })\n if (calls.length === 0) {\n transcript.ended = 'answered'\n break\n }\n for (const call of calls) {\n let input: unknown\n try {\n input = call.argumentsJson.trim() === '' ? {} : JSON.parse(call.argumentsJson)\n } catch {\n // Passed through as text, so the world refuses it and logs the attempt.\n input = call.argumentsJson\n }\n const result = session.call(call.name, input)\n messages.push({ role: 'tool', toolCallId: call.id, content: JSON.stringify(result) })\n }\n }\n } catch (error) {\n transcript.ended = 'failed'\n throw error\n } finally {\n await opts.onSession?.(transcript)\n }\n }\n}\n","// The world: a clock only the caller advances, a budget, and levers whose\n// spend turns into outcomes days later. Every random draw comes from a stream\n// named by (seed, lever, day), so what a day of spend returns never depends on\n// when or how often anyone looked, and two policies run on one seed meet the\n// same luck.\n\nimport { ValidationError } from '../errors'\nimport { hashCanonical } from '../ledger-core/canonical'\nimport { makeRng, seedFromData } from '../statistics/internal'\nimport type {\n WorldAction,\n WorldApproval,\n WorldDecisionEvidence,\n WorldEndState,\n WorldLever,\n WorldLeverKey,\n WorldRefusal,\n WorldScenario,\n} from './types'\n\nconst DAY_MS = 86_400_000\nconst WEEK_DAYS = 7\n/** Stream slots at or above this belong to weekly shocks, below it to days. */\nconst WEEK_STREAM_OFFSET = 1_000_000\nconst MAX_NOTES = 32\nconst MAX_NOTE_CHARS = 8_000\nconst MAX_REASON_CHARS = 500\nconst NOTE_KEY = /^[A-Za-z0-9][A-Za-z0-9 _.-]{0,79}$/\n\ninterface LeverState {\n rate: number\n /** The standing rate when today began, before anything this session changed. */\n rateAtDayStart: number\n /** Consecutive days with spend, today included once it has run. */\n age: number\n health: number\n spent: number\n produced: number\n landed: number\n approvedMaxRate: number\n overdriveDays: number\n spendByDay: number[]\n landedByDay: number[]\n /** Outcomes scheduled to land, by day; runs past the horizon. */\n landing: number[]\n /** One-off spend added to the rate, by day. */\n onceByDay: Record<string, number>\n}\n\ninterface WorldState {\n day: number\n budget: number\n levers: Record<string, LeverState>\n approvals: WorldApproval[]\n notes: Record<string, string>\n}\n\n/** A world's whole state as plain data, for a driver whose sessions run in\n * separate processes. */\nexport interface WorldSnapshot {\n scenarioDigest: string\n seed: number\n state: unknown\n}\n\nexport type WorldActionOutcome =\n | { ok: true; message: string; action: WorldAction; evidence?: WorldDecisionEvidence }\n | { ok: false; refused: WorldRefusal; message: string }\n\nexport interface WorldStatusLever extends WorldLever {\n dailyRate: number\n /** Highest daily rate a granted approval covers; absent when none is needed. */\n approvedMaxRate?: number\n spent: number\n outcomes: number\n}\n\nexport interface WorldStatus {\n day: number\n date: string\n daysLeft: number\n horizonDays: number\n sessionEveryDays: number\n budgetLeft: number\n spent: number\n outcomes: number\n outcomeUnit: string\n outcomeValue: number\n currency: string\n approvalDelayDays: number\n levers: WorldStatusLever[]\n approvals: WorldApproval[]\n}\n\nexport interface WorldResultRow {\n lever: string\n fromDay: number\n /** Last day of the period, inclusive. */\n toDay: number\n fromDate: string\n spend: number\n /** Outcomes that landed in the period, whenever their spend was made. */\n outcomes: number\n}\n\n/** Digest of the whole scenario, key included: two episodes compare only when\n * this matches. */\nfunction worldScenarioDigest(scenario: WorldScenario): string {\n return hashCanonical(scenario)\n}\n\nfunction finite(name: string, value: number, min: number, max = Number.POSITIVE_INFINITY): void {\n if (!Number.isFinite(value) || value < min || value > max) {\n throw new ValidationError(`world scenario: ${name} must be within [${min}, ${max}]`)\n }\n}\n\n/** Refuse a scenario the simulation cannot run as written. */\nfunction validateWorldScenario(scenario: WorldScenario): void {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(scenario.startDate) || Number.isNaN(dateMs(scenario.startDate))) {\n throw new ValidationError('world scenario: startDate must be a YYYY-MM-DD date')\n }\n for (const name of ['horizonDays', 'sessionEveryDays'] as const) {\n if (!Number.isSafeInteger(scenario[name]) || scenario[name] < 1) {\n throw new ValidationError(`world scenario: ${name} must be a positive integer`)\n }\n }\n if (!Number.isSafeInteger(scenario.approvalDelayDays) || scenario.approvalDelayDays < 0) {\n throw new ValidationError('world scenario: approvalDelayDays must be a non-negative integer')\n }\n finite('budget', scenario.budget, 0)\n finite('outcome.value', scenario.outcome.value, 0)\n if (scenario.levers.length === 0) {\n throw new ValidationError('world scenario: at least one lever is required')\n }\n const ids = new Set<string>()\n for (const lever of scenario.levers) {\n if (!/^[a-z][a-z0-9_]*$/.test(lever.id) || ids.has(lever.id)) {\n throw new ValidationError(`world scenario: lever id '${lever.id}' is invalid or repeated`)\n }\n ids.add(lever.id)\n finite(`${lever.id}.maxRate`, lever.maxRate, 0)\n finite(`${lever.id}.guidelineRate`, lever.guidelineRate, 0, lever.maxRate)\n finite(`${lever.id}.startRate`, lever.startRate, 0, lever.maxRate)\n finite(`${lever.id}.resultLagDays.from`, lever.resultLagDays.from, 0)\n finite(`${lever.id}.resultLagDays.to`, lever.resultLagDays.to, lever.resultLagDays.from)\n const key = scenario.key.levers[lever.id]\n if (!key) throw new ValidationError(`world scenario: the key has no lever '${lever.id}'`)\n finite(`${lever.id}.yield`, key.yield, 0)\n finite(`${lever.id}.weeklyNoise`, key.weeklyNoise, 0, 3)\n finite(`${lever.id}.rampDays`, key.rampDays, 1)\n finite(`${lever.id}.saturationRate`, key.saturationRate, 0)\n finite(`${lever.id}.marginalYield`, key.marginalYield, 0, 1)\n finite(`${lever.id}.delayDays.min`, key.delayDays.min, 1)\n finite(`${lever.id}.delayDays.median`, key.delayDays.median, key.delayDays.min)\n finite(`${lever.id}.delayDays.max`, key.delayDays.max, key.delayDays.median)\n // Outcomes land on whole days; a fractional bound would schedule one between days, where it never lands.\n if (!Number.isSafeInteger(key.delayDays.min) || !Number.isSafeInteger(key.delayDays.max)) {\n throw new ValidationError(\n `world scenario: ${lever.id}.delayDays min and max must be whole days`,\n )\n }\n // A day's outcomes are drawn one by one; keep the largest possible day small.\n finite(`${lever.id} daily outcomes at maxRate`, lever.maxRate * key.yield, 0, 10_000)\n if (key.wear) {\n finite(`${lever.id}.wear.weeklyLoad`, key.wear.weeklyLoad, Number.MIN_VALUE)\n finite(`${lever.id}.wear.damagePerDay`, key.wear.damagePerDay, 0, 1)\n finite(`${lever.id}.wear.recoveryPerDay`, key.wear.recoveryPerDay, 0, 1)\n finite(`${lever.id}.wear.floor`, key.wear.floor, 0, 1)\n }\n }\n for (const id of Object.keys(scenario.key.levers)) {\n if (!ids.has(id)) throw new ValidationError(`world scenario: the key names no lever '${id}'`)\n }\n finite('key.evidence.minOutcomes', scenario.key.evidence.minOutcomes, 0)\n finite('key.evidence.scaleFactor', scenario.key.evidence.scaleFactor, 1)\n}\n\nfunction dateMs(date: string): number {\n return Date.parse(`${date}T00:00:00.000Z`)\n}\n\nfunction standardNormal(rng: () => number): number {\n // Box-Muller; 1 - u keeps the log argument above zero.\n return Math.sqrt(-2 * Math.log(1 - rng())) * Math.cos(2 * Math.PI * rng())\n}\n\nfunction poisson(mean: number, rng: () => number): number {\n if (mean <= 0) return 0\n if (mean >= 30) return Math.max(0, Math.round(mean + Math.sqrt(mean) * standardNormal(rng)))\n const limit = Math.exp(-mean)\n let count = 0\n let product = rng()\n while (product > limit) {\n count += 1\n product *= rng()\n }\n return count\n}\n\nfunction round2(value: number): number {\n return Math.round(value * 100) / 100\n}\n\nexport class World {\n readonly scenario: WorldScenario\n readonly seed: number\n readonly scenarioDigest: string\n private state: WorldState\n\n constructor(scenario: WorldScenario, seed: number) {\n validateWorldScenario(scenario)\n if (!Number.isSafeInteger(seed)) {\n throw new ValidationError(`world: seed must be a safe integer, got ${seed}`)\n }\n this.scenario = scenario\n this.seed = seed\n this.scenarioDigest = worldScenarioDigest(scenario)\n const levers: Record<string, LeverState> = {}\n for (const lever of scenario.levers) {\n levers[lever.id] = {\n rate: 0,\n rateAtDayStart: 0,\n age: 0,\n health: 1,\n spent: 0,\n produced: 0,\n landed: 0,\n approvedMaxRate: 0,\n overdriveDays: 0,\n spendByDay: [],\n landedByDay: [],\n landing: [],\n onceByDay: {},\n }\n }\n this.state = { day: 0, budget: scenario.budget, levers, approvals: [], notes: {} }\n }\n\n /** Rebuild a world from `snapshot()`. The scenario and seed must be the ones it was taken from. */\n static restore(scenario: WorldScenario, snapshot: WorldSnapshot): World {\n const world = new World(scenario, snapshot.seed)\n if (snapshot.scenarioDigest !== world.scenarioDigest) {\n throw new ValidationError('world: the snapshot was taken from a different scenario')\n }\n world.state = structuredClone(snapshot.state) as WorldState\n return world\n }\n\n snapshot(): WorldSnapshot {\n return {\n scenarioDigest: this.scenarioDigest,\n seed: this.seed,\n state: structuredClone(this.state),\n }\n }\n\n // ── The clock ────────────────────────────────────────────────────────\n\n get day(): number {\n return this.state.day\n }\n\n get daysLeft(): number {\n return this.scenario.horizonDays - this.state.day\n }\n\n get over(): boolean {\n return this.state.day >= this.scenario.horizonDays\n }\n\n /** Calendar date of a day, by default today. */\n date(day = this.state.day): string {\n return new Date(dateMs(this.scenario.startDate) + day * DAY_MS).toISOString().slice(0, 10)\n }\n\n /** The simulated instant: midnight UTC at the start of today. */\n now(): Date {\n return new Date(dateMs(this.scenario.startDate) + this.state.day * DAY_MS)\n }\n\n /** Run the world forward. Time moves only here, and stops at the horizon. */\n advance(days: number): void {\n if (!Number.isSafeInteger(days) || days < 0) {\n throw new ValidationError(`world: advance takes a non-negative integer, got ${days}`)\n }\n for (let i = 0; i < days && !this.over; i++) {\n this.simulateDay(this.state.day)\n this.state.day += 1\n this.decideApprovals()\n }\n }\n\n // ── What the agent may read ──────────────────────────────────────────\n\n get notes(): Readonly<Record<string, string>> {\n return { ...this.state.notes }\n }\n\n status(): WorldStatus {\n const { scenario, state } = this\n let spent = 0\n let outcomes = 0\n const levers = scenario.levers.map((lever): WorldStatusLever => {\n const s = state.levers[lever.id]!\n spent += s.spent\n outcomes += s.landed\n return {\n ...lever,\n resultLagDays: { ...lever.resultLagDays },\n dailyRate: s.rate,\n ...(lever.requiresApproval ? { approvedMaxRate: s.approvedMaxRate } : {}),\n spent: round2(s.spent),\n outcomes: s.landed,\n }\n })\n return {\n day: state.day,\n date: this.date(),\n daysLeft: this.daysLeft,\n horizonDays: scenario.horizonDays,\n sessionEveryDays: scenario.sessionEveryDays,\n budgetLeft: round2(state.budget),\n spent: round2(spent),\n outcomes,\n outcomeUnit: scenario.outcome.unit,\n outcomeValue: scenario.outcome.value,\n currency: scenario.currency,\n approvalDelayDays: scenario.approvalDelayDays,\n levers,\n approvals: state.approvals.map((approval) => ({ ...approval })),\n }\n }\n\n /** Spend and landed outcomes for every finished day, by week or by day. */\n results(opts: { lever?: string; by?: 'week' | 'day' } = {}): WorldResultRow[] {\n const span = opts.by === 'day' ? 1 : WEEK_DAYS\n const rows: WorldResultRow[] = []\n for (const lever of this.scenario.levers) {\n if (opts.lever !== undefined && opts.lever !== lever.id) continue\n const s = this.state.levers[lever.id]!\n for (let from = 0; from < this.state.day; from += span) {\n const to = Math.min(from + span, this.state.day)\n let spend = 0\n let outcomes = 0\n for (let day = from; day < to; day++) {\n spend += s.spendByDay[day] ?? 0\n outcomes += s.landedByDay[day] ?? 0\n }\n rows.push({\n lever: lever.id,\n fromDay: from,\n toDay: to - 1,\n fromDate: this.date(from),\n spend: round2(spend),\n outcomes,\n })\n }\n }\n return rows\n }\n\n // ── What the agent may do ────────────────────────────────────────────\n\n /** Set a lever's standing daily spend, from today on. */\n setRate(leverId: string, dailyRate: number): WorldActionOutcome {\n const planned = dailyRate + this.onceToday(leverId)\n const raises = dailyRate > (this.state.levers[leverId]?.rate ?? 0)\n const checked = this.spendCheck(leverId, dailyRate, planned, raises)\n if (!checked.ok) return checked\n const s = checked.state\n const evidence = this.evidence(leverId)\n s.rate = dailyRate\n return {\n ok: true,\n message: `${leverId} runs at ${dailyRate} ${this.scenario.currency} a day from ${this.date()}.`,\n action: { kind: 'set_rate', day: this.state.day, lever: leverId, dailyRate },\n evidence,\n }\n }\n\n /** Add a one-off spend to today, on top of the lever's standing rate. */\n spendOnce(leverId: string, amount: number): WorldActionOutcome {\n const planned = (this.state.levers[leverId]?.rate ?? 0) + this.onceToday(leverId) + amount\n const checked = this.spendCheck(leverId, amount, planned, true)\n if (!checked.ok) return checked\n if (!(amount > 0)) {\n return { ok: false, refused: 'invalid_input', message: 'amount must be above zero.' }\n }\n // One-offs already placed today, on any lever, are spoken for.\n let placed = 0\n for (const lever of this.scenario.levers) placed += this.onceToday(lever.id)\n if (placed + amount > this.state.budget) {\n return {\n ok: false,\n refused: 'insufficient_budget',\n message: `The budget has ${round2(this.state.budget - placed)} ${this.scenario.currency} not already placed today.`,\n }\n }\n const today = String(this.state.day)\n checked.state.onceByDay[today] = this.onceToday(leverId) + amount\n return {\n ok: true,\n message: `${leverId} spends an extra ${amount} ${this.scenario.currency} on ${this.date()}.`,\n action: { kind: 'spend_once', day: this.state.day, lever: leverId, amount },\n }\n }\n\n /** Ask for approval to run a gated lever up to a daily rate. The decision\n * lands `approvalDelayDays` later. */\n requestApproval(leverId: string, maxDailyRate: number, reason: string): WorldActionOutcome {\n if (this.over) return { ok: false, refused: 'episode_over', message: 'The episode is over.' }\n const lever = this.scenario.levers.find((candidate) => candidate.id === leverId)\n if (!lever) {\n return { ok: false, refused: 'unknown_lever', message: `No lever '${leverId}'.` }\n }\n if (!Number.isFinite(maxDailyRate) || maxDailyRate <= 0) {\n return { ok: false, refused: 'invalid_input', message: 'maxDailyRate must be above zero.' }\n }\n if (reason.length > MAX_REASON_CHARS) {\n return {\n ok: false,\n refused: 'invalid_input',\n message: `reason holds at most ${MAX_REASON_CHARS} characters.`,\n }\n }\n if (maxDailyRate > lever.maxRate) {\n return {\n ok: false,\n refused: 'over_max_rate',\n message: `${leverId} cannot run above ${lever.maxRate} ${this.scenario.currency} a day.`,\n }\n }\n const approval: WorldApproval = {\n id: `approval-${this.state.approvals.length + 1}`,\n lever: leverId,\n maxDailyRate,\n reason,\n requestedDay: this.state.day,\n decisionDay: this.state.day + this.scenario.approvalDelayDays,\n status: 'pending',\n }\n this.state.approvals.push(approval)\n this.decideApprovals()\n return {\n ok: true,\n message:\n approval.status === 'granted'\n ? `${approval.id} is granted.`\n : `${approval.id} is pending; the decision lands on ${this.date(approval.decisionDay)}.`,\n action: {\n kind: 'request_approval',\n day: this.state.day,\n lever: leverId,\n maxDailyRate,\n reason,\n },\n }\n }\n\n /** Keep a note for later sessions. Notes are the only memory the world carries. */\n saveNote(key: string, text: string): { ok: true } | { ok: false; message: string } {\n if (!NOTE_KEY.test(key)) {\n return {\n ok: false,\n message:\n 'key must be 1 to 80 letters, digits, spaces, dots, dashes or underscores, starting with a letter or digit.',\n }\n }\n if (text.length > MAX_NOTE_CHARS) {\n return { ok: false, message: `A note holds at most ${MAX_NOTE_CHARS} characters.` }\n }\n if (\n !Object.hasOwn(this.state.notes, key) &&\n Object.keys(this.state.notes).length >= MAX_NOTES\n ) {\n return { ok: false, message: `At most ${MAX_NOTES} notes are kept.` }\n }\n if (text === '') delete this.state.notes[key]\n else this.state.notes[key] = text\n return { ok: true }\n }\n\n /** Apply a recorded action. Used to replay an episode. */\n apply(action: WorldAction): WorldActionOutcome {\n if (action.kind === 'set_rate') return this.setRate(action.lever, action.dailyRate)\n if (action.kind === 'spend_once') return this.spendOnce(action.lever, action.amount)\n return this.requestApproval(action.lever, action.maxDailyRate, action.reason)\n }\n\n // ── What only the scorer may read ────────────────────────────────────\n\n /** How much a lever's results can say so far. Hidden from the agent. */\n evidence(leverId: string): WorldDecisionEvidence {\n const s = this.state.levers[leverId]\n const key = this.scenario.key.levers[leverId]\n if (!s || !key) throw new ValidationError(`world: no lever '${leverId}'`)\n let maturedSpend = 0\n for (let day = 0; day + key.delayDays.max < this.state.day; day++) {\n maturedSpend += s.spendByDay[day] ?? 0\n }\n return { lever: leverId, rateAtDayStart: s.rateAtDayStart, landed: s.landed, maturedSpend }\n }\n\n end(): WorldEndState {\n const levers: WorldEndState['levers'] = {}\n let spent = 0\n let outcomes = 0\n for (const lever of this.scenario.levers) {\n const s = this.state.levers[lever.id]!\n spent += s.spent\n outcomes += s.landed\n levers[lever.id] = {\n rate: s.rate,\n health: s.health,\n spent: s.spent,\n landed: s.landed,\n inFlight: s.produced - s.landed,\n overdriveDays: s.overdriveDays,\n }\n }\n return {\n day: this.state.day,\n budgetLeft: this.state.budget,\n spent,\n outcomes,\n value: this.state.budget + outcomes * this.scenario.outcome.value,\n levers,\n approvals: this.state.approvals.map((approval) => ({ ...approval })),\n }\n }\n\n // ── Simulation ───────────────────────────────────────────────────────\n\n private onceToday(leverId: string): number {\n return this.state.levers[leverId]?.onceByDay[String(this.state.day)] ?? 0\n }\n\n /** `plannedDailySpend` is everything the lever would spend today: its\n * standing rate and its one-offs. A change that only lowers spend passes\n * the cap and the approval check. */\n private spendCheck(\n leverId: string,\n amount: number,\n plannedDailySpend: number,\n raises: boolean,\n ): { ok: true; state: LeverState } | Extract<WorldActionOutcome, { ok: false }> {\n if (this.over) return { ok: false, refused: 'episode_over', message: 'The episode is over.' }\n const lever = this.scenario.levers.find((candidate) => candidate.id === leverId)\n const state = this.state.levers[leverId]\n if (!lever || !state) {\n return { ok: false, refused: 'unknown_lever', message: `No lever '${leverId}'.` }\n }\n if (!Number.isFinite(amount) || amount < 0) {\n return { ok: false, refused: 'invalid_input', message: 'Spend must be zero or more.' }\n }\n if (!raises) return { ok: true, state }\n if (plannedDailySpend > lever.maxRate) {\n return {\n ok: false,\n refused: 'over_max_rate',\n message: `${leverId} cannot spend more than ${lever.maxRate} ${this.scenario.currency} in a day.`,\n }\n }\n if (lever.requiresApproval && plannedDailySpend > state.approvedMaxRate) {\n return {\n ok: false,\n refused: 'approval_missing',\n message:\n state.approvedMaxRate > 0\n ? `${leverId} is approved up to ${state.approvedMaxRate} ${this.scenario.currency} a day. Request approval for more first.`\n : `${leverId} needs a granted approval before it can spend. Request one first.`,\n }\n }\n return { ok: true, state }\n }\n\n private decideApprovals(): void {\n for (const approval of this.state.approvals) {\n if (approval.status !== 'pending' || approval.decisionDay > this.state.day) continue\n approval.status = 'granted'\n const s = this.state.levers[approval.lever]!\n s.approvedMaxRate = Math.max(s.approvedMaxRate, approval.maxDailyRate)\n }\n }\n\n private stream(leverIndex: number, slot: number): () => number {\n return makeRng(seedFromData([[this.seed, leverIndex, slot]]))\n }\n\n private weekShock(leverIndex: number, key: WorldLeverKey, day: number): number {\n if (key.weeklyNoise === 0) return 1\n const week = Math.floor(day / WEEK_DAYS)\n const z = standardNormal(this.stream(leverIndex, WEEK_STREAM_OFFSET + week))\n // Mean-one lognormal, so noise moves a week's yield without moving its expectation.\n return Math.exp(key.weeklyNoise * z - key.weeklyNoise ** 2 / 2)\n }\n\n private simulateDay(day: number): void {\n const { scenario, state } = this\n scenario.levers.forEach((lever, leverIndex) => {\n const s = state.levers[lever.id]!\n const key = scenario.key.levers[lever.id]!\n\n const landedToday = s.landing[day] ?? 0\n s.landedByDay[day] = landedToday\n s.landed += landedToday\n\n const planned = s.rate + (s.onceByDay[String(day)] ?? 0)\n const spend = Math.min(planned, state.budget)\n state.budget -= spend\n s.spent += spend\n s.spendByDay[day] = spend\n s.age = spend > 0 ? s.age + 1 : 0\n\n if (spend > 0) {\n const effective =\n spend <= key.saturationRate\n ? spend\n : key.saturationRate + (spend - key.saturationRate) * key.marginalYield\n const ramp = Math.min(1, s.age / key.rampDays)\n const mean = effective * key.yield * ramp * s.health * this.weekShock(leverIndex, key, day)\n const rng = this.stream(leverIndex, day)\n const count = poisson(mean, rng)\n const { min, median, max } = key.delayDays\n const spread = max > median ? Math.log(max / median) / 2 : 0\n for (let i = 0; i < count; i++) {\n const delay = Math.round(median * Math.exp(spread * standardNormal(rng)))\n const lands = day + Math.min(max, Math.max(min, delay))\n s.landing[lands] = (s.landing[lands] ?? 0) + 1\n }\n s.produced += count\n }\n\n s.rateAtDayStart = s.rate\n\n if (key.wear) {\n let load = 0\n for (let back = 0; back < WEEK_DAYS; back++) load += s.spendByDay[day - back] ?? 0\n if (load > key.wear.weeklyLoad) {\n s.overdriveDays += 1\n const excess = load / key.wear.weeklyLoad - 1\n s.health = Math.max(key.wear.floor, s.health - key.wear.damagePerDay * excess)\n } else {\n s.health = Math.min(1, s.health + key.wear.recoveryPerDay)\n }\n }\n })\n }\n}\n","// Scoring reads two things: the end state, and the decision log. The end\n// state says how the episode came out. The log says which calls the world\n// refused, which deep cuts and scale-ups came before the evidence could support\n// them. `worldDecisionCosts` then prices each accepted action by replaying the\n// episode without it.\n\nimport { ValidationError } from '../errors'\nimport { seedFromData } from '../statistics/internal'\nimport type {\n WorldAction,\n WorldDecisionCost,\n WorldEndState,\n WorldEpisode,\n WorldLogEntry,\n WorldPrematureDecision,\n WorldRefusal,\n WorldScenario,\n WorldScore,\n WorldSessionRecord,\n} from './types'\nimport { World } from './world'\n\n/** The accepted actions of a log, in the order they were taken. */\nexport function worldActions(log: readonly WorldLogEntry[]): WorldAction[] {\n return log.flatMap((entry) => (entry.action ? [entry.action] : []))\n}\n\n/** Re-run a scenario and seed under a list of actions. An action the world\n * refuses on replay is skipped, as it would have been live. */\nexport function replayWorld(\n scenario: WorldScenario,\n seed: number,\n actions: readonly WorldAction[],\n): WorldEndState {\n const world = new World(scenario, seed)\n for (const action of actions) {\n if (action.day > world.day) world.advance(action.day - world.day)\n world.apply(action)\n }\n world.advance(world.daysLeft)\n return world.end()\n}\n\nfunction prematureDecisions(\n scenario: WorldScenario,\n log: readonly WorldLogEntry[],\n): WorldPrematureDecision[] {\n const rule = scenario.key.evidence\n // A day's decision on a lever is its net change: the last rate set that day\n // against the rate the day began with. Three small raises in one session\n // are one large raise.\n const net = new Map<string, WorldLogEntry>()\n for (const entry of log) {\n if (entry.action?.kind === 'set_rate' && entry.evidence) {\n net.set(`${entry.action.day}:${entry.action.lever}`, entry)\n }\n }\n const found: WorldPrematureDecision[] = []\n for (const entry of net.values()) {\n if (entry.action?.kind !== 'set_rate' || !entry.evidence) continue\n const { rateAtDayStart, landed, maturedSpend } = entry.evidence\n if (rateAtDayStart <= 0) continue\n const next = entry.action.dailyRate\n const kind =\n next <= rateAtDayStart / rule.scaleFactor\n ? 'cut'\n : next >= rateAtDayStart * rule.scaleFactor\n ? 'scale'\n : null\n if (!kind) continue\n const exposure = maturedSpend / scenario.outcome.value\n if (landed >= rule.minOutcomes || exposure >= rule.minOutcomes) continue\n found.push({\n seq: entry.seq,\n day: entry.day,\n lever: entry.action.lever,\n kind,\n landed,\n maturedSpend,\n })\n }\n return found.sort((a, b) => a.seq - b.seq)\n}\n\nexport interface WorldDecisionCostOptions {\n /** Fresh noise seeds the expected cost is averaged over. Default 20. */\n noiseSeeds?: number\n}\n\n/** Price every accepted action of an episode by replaying the episode without\n * it, costliest in expectation first. The other actions stay as recorded, so\n * a removed rate change leaves the lever at its previous rate until the next\n * recorded change. */\nexport function worldDecisionCosts(\n scenario: WorldScenario,\n episode: Pick<WorldEpisode, 'seed' | 'log'>,\n opts: WorldDecisionCostOptions = {},\n): WorldDecisionCost[] {\n const noiseSeeds = opts.noiseSeeds ?? 20\n if (!Number.isSafeInteger(noiseSeeds) || noiseSeeds < 1) {\n throw new ValidationError('worldDecisionCosts: noiseSeeds must be a positive integer')\n }\n const taken = episode.log.filter((entry) => entry.action !== undefined)\n const all = taken.map((entry) => entry.action!)\n const fresh = Array.from({ length: noiseSeeds }, (_, index) =>\n seedFromData([[episode.seed, index + 1]]),\n )\n const realizedBase = replayWorld(scenario, episode.seed, all).value\n const freshBase = fresh.map((seed) => replayWorld(scenario, seed, all).value)\n const costs = taken.map((entry, index): WorldDecisionCost => {\n const without = all.filter((_, at) => at !== index)\n const expected = fresh.map(\n (seed, at) => replayWorld(scenario, seed, without).value - freshBase[at]!,\n )\n return {\n seq: entry.seq,\n day: entry.day,\n action: entry.action!,\n realizedCost: replayWorld(scenario, episode.seed, without).value - realizedBase,\n expectedCost: expected.reduce((sum, cost) => sum + cost, 0) / expected.length,\n }\n })\n return costs.sort((x, y) => y.expectedCost - x.expectedCost || x.seq - y.seq)\n}\n\n/** Score an episode from its end state and its decision log. */\nexport function scoreWorldEpisode(\n scenario: WorldScenario,\n sessions: readonly WorldSessionRecord[],\n log: readonly WorldLogEntry[],\n end: WorldEndState,\n): WorldScore {\n const refused: Partial<Record<WorldRefusal, number>> = {}\n for (const entry of log) {\n const reason = entry.result.refused\n if (reason) refused[reason] = (refused[reason] ?? 0) + 1\n }\n let overdriveDays = 0\n let inFlight = 0\n for (const lever of Object.values(end.levers)) {\n overdriveDays += lever.overdriveDays\n inFlight += lever.inFlight\n }\n return {\n value: end.value,\n gain: end.value - scenario.budget,\n refused,\n prematureDecisions: prematureDecisions(scenario, log),\n overdriveDays,\n lateValue: inFlight * scenario.outcome.value,\n failedSessions: sessions.filter((session) => session.error !== undefined).length,\n }\n}\n","// The tools an agent reads and acts on the world with. A binding may rename\n// them or wrap them in a product's own tools; whatever reaches the world goes\n// through `callWorldTool`, so every call lands in one log.\n\nimport type {\n WorldAction,\n WorldDecisionEvidence,\n WorldScenario,\n WorldToolDefinition,\n WorldToolResult,\n} from './types'\nimport type { World, WorldActionOutcome } from './world'\n\nexport interface WorldToolCall {\n result: WorldToolResult\n action?: WorldAction\n evidence?: WorldDecisionEvidence\n}\n\n/** Tool definitions for a scenario. Built from its public half only. */\nexport function worldTools(scenario: WorldScenario): WorldToolDefinition[] {\n const leverIds = scenario.levers.map((lever) => lever.id)\n const lever = { type: 'string', enum: leverIds, description: 'Lever id.' }\n return [\n {\n name: 'status',\n description:\n \"Today's date, days left, budget left, every lever with its current daily rate, guideline and approval state, and every approval request.\",\n inputSchema: { type: 'object', properties: {}, additionalProperties: false },\n },\n {\n name: 'results',\n description: `Spend and landed ${scenario.outcome.unit} for each finished period. Outcomes are counted in the period they landed in, which is later than the spend that caused them.`,\n inputSchema: {\n type: 'object',\n properties: {\n lever: { ...lever, description: 'Limit to one lever. Default: all.' },\n by: {\n type: 'string',\n enum: ['week', 'day'],\n description: 'Period length. Default: week.',\n },\n },\n additionalProperties: false,\n },\n },\n {\n name: 'set_rate',\n description: `Set a lever's standing daily spend in ${scenario.currency}, from today on. Zero stops it.`,\n inputSchema: {\n type: 'object',\n properties: { lever, dailyRate: { type: 'number', minimum: 0 } },\n required: ['lever', 'dailyRate'],\n additionalProperties: false,\n },\n },\n {\n name: 'spend_once',\n description: `Spend an extra amount in ${scenario.currency} on a lever today only, on top of its standing rate.`,\n inputSchema: {\n type: 'object',\n properties: { lever, amount: { type: 'number', exclusiveMinimum: 0 } },\n required: ['lever', 'amount'],\n additionalProperties: false,\n },\n },\n {\n name: 'request_approval',\n description: `Ask for approval to run a lever up to a daily rate. Levers marked requiresApproval refuse spend that no granted approval covers. A decision takes ${scenario.approvalDelayDays} day(s).`,\n inputSchema: {\n type: 'object',\n properties: {\n lever,\n maxDailyRate: { type: 'number', exclusiveMinimum: 0 },\n reason: { type: 'string' },\n },\n required: ['lever', 'maxDailyRate', 'reason'],\n additionalProperties: false,\n },\n },\n {\n name: 'save_note',\n description:\n 'Save a note under a key. Notes are the only thing carried into later sessions; saving an empty text deletes the key.',\n inputSchema: {\n type: 'object',\n properties: { key: { type: 'string' }, text: { type: 'string' } },\n required: ['key', 'text'],\n additionalProperties: false,\n },\n },\n ]\n}\n\nfunction refusedInput(message: string): WorldToolCall {\n return { result: { ok: false, refused: 'invalid_input', message } }\n}\n\nfunction fromOutcome(outcome: WorldActionOutcome): WorldToolCall {\n if (!outcome.ok) {\n return { result: { ok: false, refused: outcome.refused, message: outcome.message } }\n }\n return {\n result: { ok: true, message: outcome.message },\n action: outcome.action,\n ...(outcome.evidence ? { evidence: outcome.evidence } : {}),\n }\n}\n\n/** Run one tool call against the world. Never throws on agent input. */\nexport function callWorldTool(world: World, name: string, input: unknown): WorldToolCall {\n const args = (input ?? {}) as Record<string, unknown>\n if (typeof args !== 'object' || Array.isArray(args)) {\n return refusedInput('Tool input must be an object.')\n }\n switch (name) {\n case 'status':\n return { result: { ok: true, message: 'Current state.', data: world.status() } }\n case 'results': {\n if (args.lever !== undefined && typeof args.lever !== 'string') {\n return refusedInput('lever must be a lever id.')\n }\n if (args.by !== undefined && args.by !== 'week' && args.by !== 'day') {\n return refusedInput(\"by must be 'week' or 'day'.\")\n }\n const rows = world.results({ lever: args.lever, by: args.by })\n return { result: { ok: true, message: `${rows.length} period(s).`, data: rows } }\n }\n case 'set_rate':\n if (typeof args.lever !== 'string' || typeof args.dailyRate !== 'number') {\n return refusedInput('set_rate takes { lever, dailyRate }.')\n }\n return fromOutcome(world.setRate(args.lever, args.dailyRate))\n case 'spend_once':\n if (typeof args.lever !== 'string' || typeof args.amount !== 'number') {\n return refusedInput('spend_once takes { lever, amount }.')\n }\n return fromOutcome(world.spendOnce(args.lever, args.amount))\n case 'request_approval':\n if (typeof args.lever !== 'string' || typeof args.maxDailyRate !== 'number') {\n return refusedInput('request_approval takes { lever, maxDailyRate, reason }.')\n }\n return fromOutcome(\n world.requestApproval(\n args.lever,\n args.maxDailyRate,\n typeof args.reason === 'string' ? args.reason : '',\n ),\n )\n case 'save_note': {\n if (typeof args.key !== 'string' || typeof args.text !== 'string') {\n return refusedInput('save_note takes { key, text }.')\n }\n const saved = world.saveNote(args.key, args.text)\n return saved.ok\n ? { result: { ok: true, message: `Saved '${args.key}'.` } }\n : refusedInput(saved.message)\n }\n default:\n return { result: { ok: false, refused: 'unknown_tool', message: `No tool '${name}'.` } }\n }\n}\n","// The multi-session driver. It opens one session per `sessionEveryDays`, hands\n// the agent the brief, the tools and the notes the agent saved earlier, then\n// advances the clock. The driver carries nothing else between sessions: no\n// transcript, no tool results, no summary. What an agent wants to remember, it\n// saves.\n\nimport { ValidationError } from '../errors'\nimport { scoreWorldEpisode } from './score'\nimport { callWorldTool, type WorldToolCall, worldTools } from './tools'\nimport type {\n WorldAgent,\n WorldEpisode,\n WorldLogEntry,\n WorldScenario,\n WorldSession,\n WorldSessionRecord,\n} from './types'\nimport { World } from './world'\n\nexport interface RunWorldEpisodeOptions {\n scenario: WorldScenario\n seed: number\n agent: WorldAgent\n /** Tool calls one session may make before the world refuses more. Default 64. */\n maxCallsPerSession?: number\n /** Called after each session, before the clock moves. */\n onSession?: (record: WorldSessionRecord, world: World) => Promise<void> | void\n}\n\nfunction loggable(input: unknown): unknown {\n try {\n return JSON.parse(JSON.stringify(input ?? {}))\n } catch {\n return '[unserializable input]'\n }\n}\n\n/** Run one agent through one episode of a scenario. */\nexport async function runWorldEpisode(opts: RunWorldEpisodeOptions): Promise<WorldEpisode> {\n const { scenario, seed } = opts\n const maxCalls = opts.maxCallsPerSession ?? 64\n if (!Number.isSafeInteger(maxCalls) || maxCalls < 1) {\n throw new ValidationError('runWorldEpisode: maxCallsPerSession must be a positive integer')\n }\n const world = new World(scenario, seed)\n const tools = worldTools(scenario)\n const log: WorldLogEntry[] = []\n const sessions: WorldSessionRecord[] = []\n\n for (let index = 0; !world.over; index++) {\n const record: WorldSessionRecord = { index, day: world.day, calls: 0 }\n let open = true\n const session: WorldSession = {\n index,\n day: world.day,\n date: world.date(),\n daysLeft: world.daysLeft,\n brief: scenario.brief,\n notes: world.notes,\n tools,\n call(name, input) {\n let call: WorldToolCall\n if (!open) {\n call = {\n result: { ok: false, refused: 'session_closed', message: 'This session has ended.' },\n }\n } else if (record.calls >= maxCalls) {\n call = {\n result: {\n ok: false,\n refused: 'call_limit',\n message: `A session allows ${maxCalls} tool calls.`,\n },\n }\n } else {\n call = callWorldTool(world, name, input)\n }\n // A call on a closed session belongs to no session's count, and is\n // stamped with the day it was made on.\n if (open) record.calls += 1\n log.push({\n seq: log.length,\n session: index,\n day: world.day,\n tool: name,\n input: loggable(input),\n result: call.result,\n ...(call.action ? { action: call.action } : {}),\n ...(call.evidence ? { evidence: call.evidence } : {}),\n })\n // The agent gets a copy: the log's record is not the agent's to edit.\n return structuredClone(call.result)\n },\n }\n try {\n await opts.agent(session)\n } catch (error) {\n // The agent's failure is recorded and the quarter goes on without it:\n // a missed session is a consequence, and the caller can see which\n // sessions failed.\n record.error = error instanceof Error ? error.message : String(error)\n }\n open = false\n sessions.push(record)\n await opts.onSession?.(record, world)\n world.advance(scenario.sessionEveryDays)\n }\n\n const end = world.end()\n return {\n scenarioId: scenario.id,\n scenarioDigest: world.scenarioDigest,\n seed,\n sessions,\n log,\n notes: { ...world.notes },\n end,\n score: scoreWorldEpisode(scenario, sessions, log, end),\n }\n}\n","// Policies compared on the same seeds. One seed gives every policy the same\n// luck, so a contrast is read on per-seed differences, and \"beats\" has to\n// clear the spread seeds alone produce.\n\nimport { ValidationError } from '../errors'\nimport { meanConfidenceInterval } from '../statistics/descriptive'\nimport { pairedSignTest } from '../statistics/paired-tests'\nimport { runWorldEpisode } from './episode'\nimport type { WorldAgent, WorldEpisode, WorldScenario } from './types'\n\nexport interface WorldPolicyRow {\n policy: string\n /** End value per seed, in seed order. */\n values: number[]\n mean: number\n /** Sample standard deviation across seeds. */\n stddev: number\n min: number\n max: number\n /** Mean end value minus the starting budget. */\n meanGain: number\n /** Refused spends with no recorded approval, summed over seeds. */\n unapprovedSpendAttempts: number\n /** Deep cuts and scale-ups made before the evidence rule was met, summed over seeds. */\n prematureDecisions: number\n /** Sessions in which the policy threw, summed over seeds. */\n failedSessions: number\n}\n\nexport interface WorldPolicyContrast {\n better: string\n worse: string\n /** `better - worse` end value per seed. */\n differences: number[]\n meanDifference: number\n minDifference: number\n /** Seeds on which `better` ended higher. */\n wins: number\n /** The larger of the two policies' standard deviations across seeds. */\n seedNoise: number\n /** Exact one-sided sign test on the per-seed differences. */\n signTestP: number\n /** `better` ended higher on every seed, by more than twice the seed noise on\n * average, and neither policy had a failed session. */\n beyondNoise: boolean\n}\n\nexport interface CompareWorldPoliciesOptions {\n scenario: WorldScenario\n /** At least two distinct seeds; every policy runs every seed. */\n seeds: readonly number[]\n /** Policy name to a factory called once per episode with its seed. */\n policies: Readonly<Record<string, (seed: number) => WorldAgent>>\n /** `[better, worse]` pairs to test. */\n contrasts?: ReadonlyArray<readonly [string, string]>\n}\n\nexport interface WorldPolicyComparison {\n scenarioId: string\n scenarioDigest: string\n seeds: number[]\n rows: WorldPolicyRow[]\n contrasts: WorldPolicyContrast[]\n episodes: Record<string, WorldEpisode[]>\n}\n\n/** Run every policy on every seed and report each row and each contrast. */\nexport async function compareWorldPolicies(\n opts: CompareWorldPoliciesOptions,\n): Promise<WorldPolicyComparison> {\n const seeds = [...opts.seeds]\n if (seeds.length < 2 || new Set(seeds).size !== seeds.length) {\n throw new ValidationError('compareWorldPolicies: at least two distinct seeds are required')\n }\n // Checked before anything runs: a typo must not discard paid episodes.\n const names = Object.keys(opts.policies)\n if (names.length === 0) {\n throw new ValidationError('compareWorldPolicies: at least one policy is required')\n }\n for (const name of (opts.contrasts ?? []).flat()) {\n if (!names.includes(name)) {\n throw new ValidationError(`compareWorldPolicies: no policy '${name}'`)\n }\n }\n const episodes: Record<string, WorldEpisode[]> = {}\n for (const [policy, make] of Object.entries(opts.policies)) {\n const runs: WorldEpisode[] = []\n for (const seed of seeds) {\n runs.push(await runWorldEpisode({ scenario: opts.scenario, seed, agent: make(seed) }))\n }\n episodes[policy] = runs\n }\n\n const rows = Object.entries(episodes).map(([policy, runs]): WorldPolicyRow => {\n const values = runs.map((run) => run.end.value)\n const summary = meanConfidenceInterval(values)\n return {\n policy,\n values,\n mean: summary.mean!,\n stddev: summary.stdev!,\n min: Math.min(...values),\n max: Math.max(...values),\n meanGain: summary.mean! - opts.scenario.budget,\n unapprovedSpendAttempts: runs.reduce(\n (sum, run) => sum + (run.score.refused.approval_missing ?? 0),\n 0,\n ),\n prematureDecisions: runs.reduce((sum, run) => sum + run.score.prematureDecisions.length, 0),\n failedSessions: runs.reduce((sum, run) => sum + run.score.failedSessions, 0),\n }\n })\n\n const contrasts = (opts.contrasts ?? []).map(([better, worse]): WorldPolicyContrast => {\n const high = rows.find((row) => row.policy === better)!\n const low = rows.find((row) => row.policy === worse)!\n const differences = high.values.map((value, index) => value - low.values[index]!)\n const meanDifference = differences.reduce((sum, d) => sum + d, 0) / differences.length\n const minDifference = Math.min(...differences)\n const seedNoise = Math.max(high.stddev, low.stddev)\n return {\n better,\n worse,\n differences,\n meanDifference,\n minDifference,\n wins: differences.filter((d) => d > 0).length,\n seedNoise,\n signTestP: pairedSignTest(differences, 'greater').pValue,\n beyondNoise:\n minDifference > 0 &&\n meanDifference > 2 * seedNoise &&\n high.failedSessions + low.failedSessions === 0,\n }\n })\n\n return {\n scenarioId: opts.scenario.id,\n scenarioDigest: episodes[names[0]!]![0]!.scenarioDigest,\n seeds,\n rows,\n contrasts,\n episodes,\n }\n}\n","// The first reference scenario: a product launch quarter. It is data. The\n// public half reads like a marketing lead's brief; the key states what each\n// channel really does. Change a number here and the digest changes, so results\n// from two versions never compare by accident.\n//\n// What the scenario is built to punish:\n// - judging a channel before its results have landed (content and community\n// show nothing for weeks and are the two best channels over the quarter),\n// - scaling a channel on a lucky week (paid social loses money on average\n// and has the noisiest weeks),\n// - driving a channel past what it can take (email pays best per dollar and\n// its list wears out, slowly and lastingly, above the stated guideline),\n// - spending late on results that cannot land before the quarter ends,\n// - sending without a recorded approval.\n\nimport type { WorldScenario } from './types'\n\nexport const launchQuarterScenario: WorldScenario = {\n id: 'launch-quarter-v1',\n title: 'Launch quarter',\n brief: [\n 'You run go-to-market for a product launch. The quarter is 91 days and you review it once a week.',\n 'You have a budget and five channels. Set a daily spend on each channel; it keeps running at that rate until you change it.',\n 'Your result is the budget you have left at the end of the quarter plus the value of every qualified signup that has landed by then. Signups that land after day 91 count for nothing, and unspent budget keeps its full value.',\n 'Results land days or weeks after the spend that caused them, and a single week of numbers is noisy. Each channel states when its results usually land.',\n 'Email and content go out under your name: they need an approval on record before they can spend, and an approval takes two days.',\n 'Between reviews you remember only what you saved with save_note.',\n ].join('\\n'),\n startDate: '2027-01-04',\n horizonDays: 91,\n sessionEveryDays: 7,\n budget: 60_000,\n currency: 'USD',\n outcome: { unit: 'qualified signups', value: 100 },\n approvalDelayDays: 2,\n levers: [\n {\n id: 'email',\n label: 'Email to the house list',\n description:\n 'Campaigns to the existing subscriber list. Results land within days. The deliverability team asks for at most about two full sends a week, which is the guideline rate; mailing harder than that risks spam complaints, and a damaged sender reputation takes months to repair.',\n startRate: 40,\n guidelineRate: 60,\n maxRate: 400,\n requiresApproval: true,\n resultLagDays: { from: 1, to: 4 },\n },\n {\n id: 'paid_search',\n label: 'Paid search',\n description:\n 'Search ads on buying-intent keywords. Results land within a week. The ad platform needs about a week of steady spend to finish learning, and pausing a campaign starts that over. Keyword volume is limited, so spend above the guideline buys weaker clicks.',\n startRate: 150,\n guidelineRate: 300,\n maxRate: 1_500,\n requiresApproval: false,\n resultLagDays: { from: 1, to: 6 },\n },\n {\n id: 'paid_social',\n label: 'Paid social',\n description:\n 'Promoted posts to a cold audience. Results land within days and swing widely from week to week: one post can carry a week.',\n startRate: 150,\n guidelineRate: 300,\n maxRate: 1_500,\n requiresApproval: false,\n resultLagDays: { from: 1, to: 4 },\n },\n {\n id: 'content',\n label: 'Content and search',\n description:\n 'Articles and guides published under the company name. A piece starts to rank and bring signups two to five weeks after it is paid for, and a steady publishing cadence compounds; stopping resets it.',\n startRate: 150,\n guidelineRate: 250,\n maxRate: 800,\n requiresApproval: true,\n resultLagDays: { from: 14, to: 35 },\n },\n {\n id: 'community',\n label: 'Community sponsorships',\n description:\n 'Sponsored newsletters, meetups and podcasts. Signups arrive one to three weeks after a placement runs, in clumps.',\n startRate: 100,\n guidelineRate: 200,\n maxRate: 800,\n requiresApproval: false,\n resultLagDays: { from: 7, to: 21 },\n },\n ],\n key: {\n levers: {\n email: {\n yield: 0.06,\n delayDays: { min: 1, median: 2, max: 4 },\n weeklyNoise: 0.25,\n rampDays: 1,\n saturationRate: 120,\n marginalYield: 0.5,\n wear: { weeklyLoad: 450, damagePerDay: 0.06, recoveryPerDay: 0.004, floor: 0.15 },\n },\n paid_search: {\n yield: 0.016,\n delayDays: { min: 1, median: 3, max: 6 },\n weeklyNoise: 0.2,\n rampDays: 7,\n saturationRate: 300,\n marginalYield: 0.25,\n },\n paid_social: {\n yield: 0.007,\n delayDays: { min: 1, median: 2, max: 4 },\n weeklyNoise: 0.9,\n rampDays: 1,\n saturationRate: 300,\n marginalYield: 0.5,\n },\n content: {\n yield: 0.035,\n delayDays: { min: 14, median: 21, max: 35 },\n weeklyNoise: 0.3,\n rampDays: 28,\n saturationRate: 250,\n marginalYield: 0.3,\n },\n community: {\n yield: 0.022,\n delayDays: { min: 7, median: 12, max: 21 },\n weeklyNoise: 0.6,\n rampDays: 1,\n saturationRate: 200,\n marginalYield: 0.3,\n },\n },\n evidence: { minOutcomes: 20, scaleFactor: 1.5 },\n },\n}\n","// Scripted policies. They act through the same tools and the same notes as a\n// model-backed agent, so a scenario can be checked before any model is paid\n// for: a policy that waits for evidence must beat one that acts on the latest\n// number, and both must clear the floors. When they do not rank that way the\n// scenario is wrong.\n\nimport { ValidationError } from '../errors'\nimport { makeRng, seedFromData, zQuantile } from '../statistics/internal'\nimport type { WorldAgent, WorldScenario, WorldSession } from './types'\nimport type { WorldResultRow, WorldStatus, WorldStatusLever } from './world'\n\nexport interface EvidencePolicyOptions {\n /** `matured` sets every landed outcome against the spend old enough to have\n * landed, by the lever's public lag. `latest` sets the last period's landed\n * outcomes against the last period's spend. */\n evidence: 'matured' | 'latest'\n /** Days of counted spend a lever needs before it is judged. */\n minEvidenceDays: number\n /** Standard errors the return must clear break-even by, in either\n * direction, before the lever is killed or scaled. Zero acts on the point\n * estimate. */\n confidence: number\n /** Factor a winning lever's rate is raised by. */\n scaleStep: number\n /** The rate a lever is never raised above. */\n ceiling: 'guideline' | 'max'\n /** Stop a lever once its results would land after the horizon, and never\n * plan more spend than the budget left. */\n planAhead: boolean\n}\n\ninterface PolicyMemory {\n killed: string[]\n}\n\nconst MEMORY_NOTE = 'policy'\n\nfunction statusOf(session: WorldSession): WorldStatus {\n return session.call('status').data as WorldStatus\n}\n\nfunction approvalCovers(lever: WorldStatusLever, rate: number): boolean {\n return !lever.requiresApproval || (lever.approvedMaxRate ?? 0) >= rate\n}\n\nfunction requestApprovalOnce(\n session: WorldSession,\n status: WorldStatus,\n lever: WorldStatusLever,\n rate: number,\n): void {\n if (approvalCovers(lever, rate)) return\n const asked = status.approvals.some(\n (approval) => approval.lever === lever.id && approval.maxDailyRate >= rate,\n )\n if (!asked) {\n session.call('request_approval', {\n lever: lever.id,\n maxDailyRate: rate,\n reason: `Run ${lever.label} at up to ${rate} a day.`,\n })\n }\n}\n\n/** Never acts. Its end value is the starting budget: the floor every policy is read against. */\nexport const doNothingPolicy: WorldAgent = () => {}\n\n/** Sets random rates across the whole allowed range each session. */\nexport function randomPolicy(seed: number): WorldAgent {\n return (session) => {\n const rng = makeRng(seedFromData([[seed, session.index]]))\n const status = statusOf(session)\n for (const lever of status.levers) {\n if (rng() < 0.5) continue\n const rate = Math.round(rng() * lever.maxRate)\n if (lever.requiresApproval && rng() < 0.5) {\n session.call('request_approval', { lever: lever.id, maxDailyRate: rate, reason: 'random' })\n }\n session.call('set_rate', { lever: lever.id, dailyRate: rate })\n }\n }\n}\n\n/** Starts every lever at its suggested rate, then kills and scales on the\n * evidence rule its options state. */\nexport function evidencePolicy(opts: EvidencePolicyOptions): WorldAgent {\n if (!(opts.scaleStep >= 1) || !(opts.confidence >= 0) || !(opts.minEvidenceDays >= 0)) {\n throw new ValidationError(\n 'evidencePolicy: scaleStep must be 1 or more; confidence and minEvidenceDays zero or more',\n )\n }\n return (session) => {\n const status = statusOf(session)\n const rows = session.call('results', { by: 'day' }).data as WorldResultRow[]\n const memory: PolicyMemory = session.notes[MEMORY_NOTE]\n ? (JSON.parse(session.notes[MEMORY_NOTE]) as PolicyMemory)\n : { killed: [] }\n const rates = new Map(status.levers.map((lever) => [lever.id, lever.dailyRate]))\n const returns = new Map<string, number>()\n const setRate = (lever: string, dailyRate: number) => {\n if (session.call('set_rate', { lever, dailyRate }).ok) rates.set(lever, dailyRate)\n }\n\n for (const lever of status.levers) {\n const ceiling = opts.ceiling === 'guideline' ? lever.guidelineRate : lever.maxRate\n requestApprovalOnce(session, status, lever, ceiling)\n if (memory.killed.includes(lever.id)) continue\n\n const lag = (lever.resultLagDays.from + lever.resultLagDays.to) / 2\n const tooLate = opts.planAhead && status.daysLeft <= lag\n if (lever.dailyRate === 0) {\n if (!tooLate && lever.spent === 0 && approvalCovers(lever, lever.startRate)) {\n setRate(lever.id, lever.startRate)\n }\n continue\n }\n if (tooLate) {\n setRate(lever.id, 0)\n continue\n }\n\n // Spend is counted up to the day whose results should have landed by\n // now; outcomes are counted over the same window shifted by the lag.\n const mine = rows.filter((row) => row.lever === lever.id)\n const window = opts.evidence === 'latest' ? status.sessionEveryDays : Number.POSITIVE_INFINITY\n const shift = opts.evidence === 'matured' ? lag : 0\n let spend = 0\n let days = 0\n let outcomes = 0\n for (const row of mine) {\n if (row.fromDay < status.day - window) continue\n outcomes += row.outcomes\n if (row.fromDay < status.day - shift && row.spend > 0) {\n spend += row.spend\n days += 1\n }\n }\n if (spend === 0 || days < opts.minEvidenceDays) continue\n const error = opts.confidence * Math.sqrt(Math.max(outcomes, 1))\n const low = ((outcomes - error) * status.outcomeValue) / spend\n const high = ((outcomes + error) * status.outcomeValue) / spend\n returns.set(lever.id, (outcomes * status.outcomeValue) / spend)\n if (high < 1) {\n setRate(lever.id, 0)\n memory.killed.push(lever.id)\n } else if (low > 1 && lever.dailyRate < ceiling) {\n const next = Math.min(ceiling, Math.round(lever.dailyRate * opts.scaleStep))\n if (approvalCovers(lever, next)) setRate(lever.id, next)\n }\n }\n\n if (opts.planAhead) {\n // Fit the plan to the money: lower the weakest lever until the standing\n // rates can be paid to the horizon.\n const weakestFirst = [...rates.keys()].sort(\n (a, b) => (returns.get(a) ?? 1) - (returns.get(b) ?? 1),\n )\n for (const lever of weakestFirst) {\n const planned = [...rates.values()].reduce((sum, rate) => sum + rate, 0) * status.daysLeft\n const over = planned - status.budgetLeft\n if (over <= 0) break\n const rate = rates.get(lever) ?? 0\n if (rate > 0) setRate(lever, Math.max(0, Math.floor(rate - over / status.daysLeft)))\n }\n }\n session.call('save_note', { key: MEMORY_NOTE, text: JSON.stringify(memory) })\n }\n}\n\n/** Waits for a lever's matured results to clear break-even by two standard\n * errors, moves in small steps, stays inside the guidelines and plans to the\n * horizon. */\nexport const patientPolicy: WorldAgent = evidencePolicy({\n evidence: 'matured',\n minEvidenceDays: 14,\n confidence: 2,\n scaleStep: 1.25,\n ceiling: 'guideline',\n planAhead: true,\n})\n\n/** Acts on last period's number at the first review: kills what is under\n * break-even, doubles what is over it, up to the hard cap. */\nexport const impulsivePolicy: WorldAgent = evidencePolicy({\n evidence: 'latest',\n minEvidenceDays: 1,\n confidence: 0,\n scaleStep: 2,\n ceiling: 'max',\n planAhead: false,\n})\n\n/** Starts every lever at its suggested rate and never changes it. Patience\n * has to beat this too, or the scenario only rewards sitting still. */\nexport const setAndHoldPolicy: WorldAgent = evidencePolicy({\n evidence: 'matured',\n minEvidenceDays: Number.POSITIVE_INFINITY,\n confidence: 0,\n scaleStep: 1,\n ceiling: 'guideline',\n planAhead: false,\n})\n\n/** A reference that reads the key. Each lever is two tiers of spend, up to\n * its saturation or wear limit and above it; tiers are funded best return\n * first until the budget is planned, and a tier stops once its results would\n * land too late to pay. It is a strong informed plan, not a proven optimum. */\nexport function informedPolicy(scenario: WorldScenario): WorldAgent {\n const value = scenario.outcome.value\n const tiers = scenario.levers\n .flatMap((lever) => {\n const key = scenario.key.levers[lever.id]!\n const cap = Math.min(lever.maxRate, key.wear ? key.wear.weeklyLoad / 7 : lever.maxRate)\n const base = Math.floor(Math.min(cap, key.saturationRate))\n const spread =\n key.delayDays.max > key.delayDays.median\n ? Math.log(key.delayDays.max / key.delayDays.median) / 2\n : 0\n return [\n { rate: base, perUnit: key.yield * value },\n { rate: Math.floor(cap) - base, perUnit: key.yield * value * key.marginalYield },\n ].map((tier) => ({\n ...tier,\n lever: lever.id,\n // Spend stops paying when the share of its outcomes landing in time\n // falls under 1 / perUnit.\n stopDaysLeft:\n tier.perUnit > 1\n ? Math.ceil(key.delayDays.median * Math.exp(spread * zQuantile(1 / tier.perUnit)))\n : 0,\n }))\n })\n .filter((tier) => tier.rate > 0 && tier.perUnit > 1)\n .sort((a, b) => b.perUnit - a.perUnit)\n return (session) => {\n const status = statusOf(session)\n const target = new Map<string, number>()\n const wanted = new Map<string, number>()\n let unplanned = status.budgetLeft\n for (const tier of tiers) {\n wanted.set(tier.lever, (wanted.get(tier.lever) ?? 0) + tier.rate)\n const days = Math.max(0, status.daysLeft - tier.stopDaysLeft)\n const affordable = days > 0 ? Math.min(tier.rate, Math.floor(unplanned / days)) : 0\n unplanned -= affordable * days\n target.set(tier.lever, (target.get(tier.lever) ?? 0) + affordable)\n }\n for (const lever of status.levers) {\n const rate = target.get(lever.id)\n if (rate === undefined) continue\n requestApprovalOnce(session, status, lever, wanted.get(lever.id) ?? rate)\n if (rate !== lever.dailyRate && approvalCovers(lever, rate)) {\n session.call('set_rate', { lever: lever.id, dailyRate: rate })\n }\n }\n }\n}\n"],"mappings":";;;;;AAuDA,SAAgB,mBAAmB,SAA+B;CAChE,MAAM,QAAQ,OAAO,QAAQ,QAAQ,KAAK;CAC1C,OAAO;EACL,QAAQ;EACR;EACA,YAAY,QAAQ,KAAK,QAAQ,QAAQ,IAAI,WAAW,QAAQ,QAAQ,EAAE,IAAI,QAAQ,SAAS;EAC/F,MAAM,WAAW,IACb,6BACA,6BAA6B,MAAM,KAAK,CAAC,KAAK,UAAU,IAAI,IAAI,KAAK,MAAM,CAAC,CAAC,KAAK,MAAM;EAC5F;EACA;CACF,CAAC,CAAC,KAAK,IAAI;AACb;;AAGA,SAAgB,eAAe,MAAyC;CACtE,MAAM,WAAW,KAAK,sBAAsB;CAC5C,MAAM,eAAe,KAAK,gBAAgB;CAC1C,IAAI,CAAC,OAAO,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AAU,IAAI,KAAK,OAAO,CAAC,CAAC,IAC/E;EACR,EAAE;CACJ,CAAC,CAAC,CACD,QAAQ,SAAS,KAAK,OAAO,KAAK,KAAK,UAAU,CAAC,CAAC,CACnD,MAAM,GAAG,MAAM,EAAE,UAAU,EAAE,OAAO;CACvC,QAAQ,YAAY;EAClB,MAAM,SAAS,SAAS,OAAO;EAC/B,MAAM,yBAAS,IAAI,IAAoB;EACvC,MAAM,yBAAS,IAAI,IAAoB;EACvC,IAAI,YAAY,OAAO;EACvB,KAAK,MAAM,QAAQ,OAAO;GACxB,OAAO,IAAI,KAAK,QAAQ,OAAO,IAAI,KAAK,KAAK,KAAK,KAAK,KAAK,IAAI;GAChE,MAAM,OAAO,KAAK,IAAI,GAAG,OAAO,WAAW,KAAK,YAAY;GAC5D,MAAM,aAAa,OAAO,IAAI,KAAK,IAAI,KAAK,MAAM,KAAK,MAAM,YAAY,IAAI,CAAC,IAAI;GAClF,aAAa,aAAa;GAC1B,OAAO,IAAI,KAAK,QAAQ,OAAO,IAAI,KAAK,KAAK,KAAK,KAAK,UAAU;EACnE;EACA,KAAK,MAAM,SAAS,OAAO,QAAQ;GACjC,MAAM,OAAO,OAAO,IAAI,MAAM,EAAE;GAChC,IAAI,SAAS,KAAA,GAAW;GACxB,oBAAoB,SAAS,QAAQ,OAAO,OAAO,IAAI,MAAM,EAAE,KAAK,IAAI;GACxE,IAAI,SAAS,MAAM,aAAa,eAAe,OAAO,IAAI,GACxD,QAAQ,KAAK,YAAY;IAAE,OAAO,MAAM;IAAI,WAAW;GAAK,CAAC;EAEjE;CACF;AACF"}
|
|
@@ -20,6 +20,13 @@ Use it to search for a better surface and inspect the final decision.
|
|
|
20
20
|
Use it to compare selected surfaces under declared resource limits.
|
|
21
21
|
Runnable versions: [`examples/self-improve-optimizer`](../examples/self-improve-optimizer/) and [`examples/compare-optimization-methods`](../examples/compare-optimization-methods/).
|
|
22
22
|
|
|
23
|
+
Both entry points take the same per-cell dispatch, so the target decides what to pass them:
|
|
24
|
+
|
|
25
|
+
| Target | Dispatch | Judge and gate | Optimizer evidence |
|
|
26
|
+
|---|---|---|---|
|
|
27
|
+
| One artifact per case | Your `agent(surface, scenario, ctx)` | Your judge; `defaultProductionGate` | `describeArtifact`, or the artifact text |
|
|
28
|
+
| A multi-turn conversation with a simulated user | `multishotRollout(...).agent` and its `dispatchRef` | `conversationJudge()`; `conversationGate()` refuses arms that met a different user or seed | `describeConversation` ([multi-turn optimization](./multi-turn-optimization.md)) |
|
|
29
|
+
|
|
23
30
|
## Compose searches over a candidate
|
|
24
31
|
|
|
25
32
|
Use `scopedOptimizationMethod()` to change one projection while scoring the complete candidate.
|
package/docs/concepts.md
CHANGED
|
@@ -214,6 +214,8 @@ Keep raw usage and its source identity beside the projection.
|
|
|
214
214
|
| **Train cases** | Evidence the optimizer reads to write candidates. |
|
|
215
215
|
| **Selection cases** | Evidence the optimizer reads to choose among its candidates. |
|
|
216
216
|
| **Final cases** | Held back from the optimizer entirely. They produce the reported lift. |
|
|
217
|
+
| **Rollout** | One conversation between the candidate agent and a simulated user, scored by a code check of its outcome. See [multi-turn optimization](./multi-turn-optimization.md). |
|
|
218
|
+
| **pass^k** | Success in all k repeats of a case. Reported beside mean success, which hides a case that passes on some seeds only. |
|
|
217
219
|
|
|
218
220
|
Keep scenario identifiers disjoint across the three partitions.
|
|
219
221
|
For new-unit claims or fresh final evidence, also keep source units separate between development and final cases.
|
|
@@ -62,3 +62,34 @@ It returns after-minus-before `delta`, `lower`, `upper`, confidence and both cou
|
|
|
62
62
|
either empty arm gives a null delta and full difference support. This interval assumes
|
|
63
63
|
independent binomial observations; repeated attempts do not become independent trials.
|
|
64
64
|
Reference: [Newcombe (1998), method 10 and Table II](https://doi.org/10.1002/(SICI)1097-0258(19980430)17:8%3C873::AID-SIM779%3E3.0.CO;2-I).
|
|
65
|
+
|
|
66
|
+
## Association across many measures
|
|
67
|
+
|
|
68
|
+
`clusteredAssociation` tests whether a score predicts an outcome when rows share independent units:
|
|
69
|
+
AUC for a 0/1 outcome (null 0.5, through `rocAuc`) and Spearman for a continuous one (null 0, through `spearmanR`).
|
|
70
|
+
Its standard error is the standard deviation of the statistic over `clusterBootstrap` resamples of whole units,
|
|
71
|
+
and its p-value is a Wald test on Student-t with `units - 1` degrees of freedom, two-sided or `greater`.
|
|
72
|
+
The percentile interval from the same resamples is reported beside it.
|
|
73
|
+
|
|
74
|
+
Why a Wald test on the whole-unit standard error, not a bootstrap tail count:
|
|
75
|
+
a study that corrects across hundreds of measures needs p-values below `level / m`, and a bootstrap tail
|
|
76
|
+
count cannot go below `1 / resamples`. A row resample would understate the standard error whenever rows of
|
|
77
|
+
one unit share what makes that unit differ; the planted test in `tests/meta-eval/measure-validity.test.ts`
|
|
78
|
+
(24 units, a unit-level rank correlation near 0.25 and none in the population) admits under row resampling
|
|
79
|
+
and not under unit resampling. When every defined resample gives the same value, the standard error is zero
|
|
80
|
+
and the p-value falls back to `1 / (definedResamples + 1)` on the tested side of the null, or 1.
|
|
81
|
+
|
|
82
|
+
`scope: 'within-unit'` compares rows only inside each unit: AUC per unit weighted by its positive-negative
|
|
83
|
+
pairs, which is the Mann-Whitney count restricted to same-unit pairs, or Spearman per unit weighted by its row
|
|
84
|
+
pairs, with a score constant inside a unit counted as no association there. Units are summarized once and the
|
|
85
|
+
summaries are resampled, so a unit drawn twice stays two units. A pooled statistic can be carried entirely by
|
|
86
|
+
differences between units, such as larger repositories failing more; the within-unit statistic cannot.
|
|
87
|
+
|
|
88
|
+
`measureValidityStudy` fixes each measure's direction before the cut, so its tests are one-sided in that
|
|
89
|
+
direction and Benjamini-Hochberg runs on those p-values. A two-sided test would admit a measure whose direction
|
|
90
|
+
reversed. The one-sided test has a known weakness: when the same units appear on both sides of the cut, a
|
|
91
|
+
coincidence among those units can choose the direction and then confirm it, raising the pooled error rate up to
|
|
92
|
+
twice the level. The within-unit test is immune to that, because unit-level coincidences cancel inside a unit,
|
|
93
|
+
and `predicts` requires it wherever it can be estimated; a pooled-only pass is labelled `predicts-pooled-only`.
|
|
94
|
+
Movement agreement is the AUC of a movement's sign for the better outcome, which equals balanced accuracy and
|
|
95
|
+
stays 0.5 under no relation whatever the outcome's base rate; it is tested one-sided as its own family.
|
package/docs/eval-surface-map.md
CHANGED
|
@@ -11,6 +11,8 @@ This reference covers direct execution controls and specialist modules.
|
|
|
11
11
|
| [`runCampaign()`](../examples/plan-before-you-spend/) | `/campaign` | Execute and judge a scenarios × repetitions grid through caller-owned dispatch. | `CampaignResult` |
|
|
12
12
|
| [`runEval()`](../src/campaign/presets/run-eval.ts) | `/contract` or `/campaign` | Score one surface with campaign defaults. | `CampaignResult` |
|
|
13
13
|
| [`runProfileMatrix()`](../examples/profile-matrix/) | `/campaign` | Run the same cases across named agent profiles with provenance and backend checks. | `RunProfileMatrixResult`, including `.records`. |
|
|
14
|
+
| [`raceProfileMatrix()`](../examples/profile-matrix-report/) | `/campaign` | Run a profile-matrix plan in doubling batches and stop paying for profiles clearly worse than the leader. | Elimination log, survivors, the final paired comparison, and the selection-bias warning. |
|
|
15
|
+
| [`renderProfileMatrixReport()`](../examples/profile-matrix-report/) | `/campaign` | Turn profile-matrix records into one decision page: frontiers, paired differences, factor effects, slices, error overlap, difficulty, calibration and power, with cells that ran fewer cases kept in a partial-coverage table. | A self-contained HTML string; `analyzeProfileMatrix()` returns the numbers, the panel and its common cases. |
|
|
14
16
|
| [`runOptimization()`](./campaign-proposers.md#write-a-custom-candidate-generator) | `/campaign` | Generate, measure, and select candidates on development cases. | Generations and a winner surface. |
|
|
15
17
|
| [`runImprovementLoop()`](./multi-shot-optimization.md) | `/contract` or `/campaign` | Search, compare on final cases, and apply a release gate. | Final comparison, winner, and gate decision. |
|
|
16
18
|
| [`compareOptimizationMethods()`](../examples/compare-optimization-methods/) | `/campaign` | Compare selected surfaces from several methods under declared budgets. | Final paired contrasts, uncertainty, and costs. |
|
|
@@ -50,6 +52,7 @@ Coverage reports missing, failed, and zero-score rows separately.
|
|
|
50
52
|
| Test a grader with known incorrect items | `/meta-eval` | [`definePlant()`, `seedPlants()`, `catchRate()`](./plants.md) |
|
|
51
53
|
| Measure agreement and known bias patterns | `/meta-eval` | `calibrateJudgeContinuous()`, `continuousAgreement()`, `positionalBias()`, `verbosityBias()`, `selfPreference()` |
|
|
52
54
|
| Relate scores to declared deployment outcomes | `/meta-eval` | `rubricPredictiveValidity()`, `correlationStudy()`, `calibrationFromPairs()`, `calibrationCurve()` |
|
|
55
|
+
| Choose which recorded measures to climb from later outcomes, held out by time | `/meta-eval`, `/experiment` | `measureValidityStudy()`, `guardDrift()`, `sealMeasureValidityPlan()` |
|
|
53
56
|
|
|
54
57
|
The top-level `claim` declares the independent unit for ordinary reusable comparisons.
|
|
55
58
|
Include `minimumEffect` when the decision concerns a practical improvement.
|
|
@@ -80,7 +83,7 @@ Use the decision diagnostics and intervals to distinguish insufficient evidence
|
|
|
80
83
|
| `/supervisor-run` | Read recursive run directories and their evidence coverage. |
|
|
81
84
|
| `/trace-repair`, `/trajectory-replay` | Execute proposed repairs or replay recorded shell trajectories. |
|
|
82
85
|
| `/benchmarks`, `/fuzz` | Adapt benchmark data and explore a declared behavior space. |
|
|
83
|
-
| `/builder-eval`, `/multishot`, [`/multishot/golden`](./multishot-golden-records.md) | Evaluate generated applications and multi-turn conversations. |
|
|
86
|
+
| `/builder-eval`, `/multishot`, [`/multishot/golden`](./multishot-golden-records.md) | Evaluate generated applications and multi-turn conversations; [optimize an agent over conversations](./multi-turn-optimization.md). |
|
|
84
87
|
| `/matrix` | Schedule Cartesian experiment grids. |
|
|
85
88
|
| `/rl` | Build reward, preference, and supervised datasets from eligible evidence. |
|
|
86
89
|
| `/profile-cell` | Create and validate portable agent-profile identities. |
|
package/docs/feature-guide.md
CHANGED
|
@@ -34,6 +34,8 @@ Evaluation measures whether the result met its requirements, whether another att
|
|
|
34
34
|
| “I need train/dev/test/holdout examples.” | `Dataset` plus feedback trajectory conversion | Stable splits and contamination control. |
|
|
35
35
|
| “Which optimization procedure wins?” | `compareOptimizationMethods` | Runs complete methods on shared train and selection cases, then compares them on separate final cases. |
|
|
36
36
|
| “Improve a multi-turn agent with candidates from my runtime.” | `runImprovementLoop` | Evaluates caller-generated candidates and applies a separate release rule. |
|
|
37
|
+
| “Improve an agent over conversations with a simulated user.” | `multishotRollout` with `selfImprove`, `conversationJudge`, `conversationGate` | Each cell is one conversation under a fixed simulated user; see [multi-turn optimization](./multi-turn-optimization.md). |
|
|
38
|
+
| “Is my simulated user realistic?” | `measureSimulatorRealism` | A calibrated judge picks the real user's message at recorded turns; 50% is indistinguishable. |
|
|
37
39
|
| “Improve prompts, then code if prompts plateau.” | `gepaOptimizationMethod` or `externalTextOptimizationMethod` for the prompt; agent-runtime's worktree path for the code | Text search stays here; executable code changes belong to the runtime. |
|
|
38
40
|
| “Find why a regression happened.” | bisector, traces, run records | Narrows changes and preserves evidence. |
|
|
39
41
|
| “Expose evals to another language.” | Wire protocol and Python client | HTTP/RPC boundary for non-TypeScript apps. |
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# Optimize A Multi-Turn Agent
|
|
2
|
+
|
|
3
|
+
A conversation between a simulated user and an agent is an optimization and comparison target like any other surface.
|
|
4
|
+
`multishotRollout()` from `/multishot` runs one conversation per campaign cell on the existing conversation engine, so `selfImprove()` and `compareOptimizationMethods()` search and gate the agent side over multi-turn rollouts.
|
|
5
|
+
The simulated user is part of the measurement: it is held fixed across candidates, and it can be measured against real users.
|
|
6
|
+
Runnable version: [`examples/multi-turn-optimization`](../examples/multi-turn-optimization/).
|
|
7
|
+
|
|
8
|
+
## Run a conversation as the dispatch
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
import {
|
|
12
|
+
conversationGate,
|
|
13
|
+
conversationJudge,
|
|
14
|
+
describeConversation,
|
|
15
|
+
multishotRollout,
|
|
16
|
+
} from '@tangle-network/agent-eval/multishot'
|
|
17
|
+
import { selfImprove } from '@tangle-network/agent-eval/contract'
|
|
18
|
+
|
|
19
|
+
const conversation = multishotRollout<RefundScenario>({
|
|
20
|
+
agent: { model: AGENT_MODEL, transport: agentTransport },
|
|
21
|
+
user: { model: USER_MODEL, transport: userTransport, rigor: 'demanding' },
|
|
22
|
+
maxTurns: 6,
|
|
23
|
+
outcome: (record, scenario) => refundOutcome(record.transcript, scenario.persona),
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
const result = await selfImprove({
|
|
27
|
+
agent: conversation.agent,
|
|
28
|
+
dispatchRef: conversation.dispatchRef,
|
|
29
|
+
scenarios,
|
|
30
|
+
judge: conversationJudge(),
|
|
31
|
+
gate: conversationGate(),
|
|
32
|
+
describeArtifact: describeConversation,
|
|
33
|
+
baselineSurface: 'You are the support desk.',
|
|
34
|
+
method: gepa,
|
|
35
|
+
budget: { holdoutScenarios },
|
|
36
|
+
})
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
| Piece | What it does |
|
|
40
|
+
|---|---|
|
|
41
|
+
| `agent` | The candidate surface becomes the agent's profile (a text surface is its system prompt; pass `profile` for other surfaces). Every leg is a paid call through the cell's `ctx.cost`: the agent on the `agent` channel, the simulated user on `driver`, and each call carries the cell seed. |
|
|
42
|
+
| `outcome` | Code decides whether the conversation reached its goal. It is the objective part of the score. |
|
|
43
|
+
| Ending | The simulated user ends with `[[signed-off]]` or `[[gave-up]]` (`DEFAULT_USER_ENDING`), or the conversation reaches `maxTurns`. The marker is removed from the transcript. |
|
|
44
|
+
| `ConversationArtifact` | Transcript, tool artifacts, ending, outcome, the first pushback turn, the simulated-user identity and the seed. |
|
|
45
|
+
| `conversationJudge()` | Composite 0 when the outcome failed, else 1, or a semantic judge's [0, 1] composite. |
|
|
46
|
+
| `describeConversation` | The one evidence object both the native proposer and GEPA receive: outcome, ending, agent turns, first pushback turn, and the transcript's head and tail. Its JSON stays within the evidence bound, so neither path cuts it. |
|
|
47
|
+
|
|
48
|
+
## Compare under the same simulated user
|
|
49
|
+
|
|
50
|
+
Agent success moves with the user model as well as the agent, so a comparison holds the user fixed.
|
|
51
|
+
|
|
52
|
+
- The simulated user is built from the scenario and the rollout's fixed options only. The candidate surface never reaches its prompt, opener or description of the agent.
|
|
53
|
+
- `SimulatedUserIdentity` digests the user model, fallbacks, rigor, persona, prompt, opener and ending protocol. `dispatchRef` hashes the same options, so caches and premeasured baselines never cross users.
|
|
54
|
+
- `conversationGate()` refuses with `SimulatedUserMismatchError` when any paired held-out conversation met a different user, ran on a different seed, or carries no identity. Outside the gate, call `assertSameSimulatedUser(baselineCells, candidateCells)`.
|
|
55
|
+
|
|
56
|
+
## Report reliability across repeats
|
|
57
|
+
|
|
58
|
+
Mean success hides a conversation that resolves the user's problem on some seeds only.
|
|
59
|
+
Run the scenarios with `reps: k` and read `repeatReliability(cells, { k, success })` from `/campaign`: per scenario and overall, pass^k (success in all k repeats, `passHatK` from `/statistics`) beside mean success, with each independent unit weighted equally.
|
|
60
|
+
A dispatch or judge failure is counted in `failedCells`, never as an agent failure.
|
|
61
|
+
|
|
62
|
+
## Measure the simulated user against real users
|
|
63
|
+
|
|
64
|
+
`measureSimulatorRealism()` asks how often a judge tells the simulator's message from a real user's at the same point of a real conversation.
|
|
65
|
+
|
|
66
|
+
1. `recordedUserTurns(trajectory, run)` reads each real user turn and the visible context before it from a recorded trace. A run whose scenario id names its task gets a `contextDigest` over the task and context; one without a task identity gets none.
|
|
67
|
+
2. The driver writes the next message from that context. `simulatedUserDriver()` runs the exact prompt, point of view and model rotation a rollout uses.
|
|
68
|
+
3. `simulatorRealismJudge()` is a System One decision point at the turn layer. It sees the context and both messages, in both orders, and picks the one the real user wrote. Its calibration must reach `DECISION_POINT_MIN_KAPPA` and carry the `questionDigest` of this exact question and served model; otherwise every judgment is recorded as uncalibrated. Build that digest with `decisionQuestionDigest` from `/systemone` over `SIMULATOR_REALISM_QUESTIONS.real`, the text the judge asks, so a calibration set labelled under other wording cannot certify it.
|
|
69
|
+
|
|
70
|
+
Accuracy is reported per independent conversation with a cluster bootstrap interval. 50% means the judge cannot tell the simulator from real users.
|
|
71
|
+
A row without a context digest, or with a digest its context does not match, is refused with `SharedContextIdentityError` before any driver call.
|
|
72
|
+
|
|
73
|
+
## Optimize the user side
|
|
74
|
+
|
|
75
|
+
`improveAdversarialUser()` searches for a simulated-user plan that makes a fixed agent fail.
|
|
76
|
+
|
|
77
|
+
- Its objective is the agent's failure rate. It builds that judge itself and refuses a caller `judge` or `gate`; `conversationJudge()` refuses every conversation whose user side was the candidate, both with `UserSideObjectiveError`.
|
|
78
|
+
- A plan is admitted only when a calibrated realism judge's accuracy, at the upper end of its interval, stays at or below `realism.maxJudgeAccuracy`.
|
|
79
|
+
- An admitted plan's failing held-out conversations become `trainScenarios` with the plan as `userPlan` and `origin.kind: 'adversarial-user'`. `conversationGate()` refuses them in a held-out split with `AdversarialScenarioInHeldOutError`; for other comparisons call `assertHeldOutExcludesAdversarial()`.
|
|
80
|
+
- Scenarios that share an id or persona with the agent's held-out split are refused with `AdversarialSplitError`.
|
package/docs/outcome-validity.md
CHANGED
|
@@ -92,6 +92,75 @@ This ordering is exploratory and can conceal conflicts among outcomes.
|
|
|
92
92
|
Inspect all `pairs` and use a target chosen before analysis for an automated recommendation.
|
|
93
93
|
Confirm any proposed change with fresh evidence and fixed scoring rules.
|
|
94
94
|
|
|
95
|
+
## Choose which measures to climb
|
|
96
|
+
|
|
97
|
+
`rubricPredictiveValidity()` and `correlationStudy()` describe one association over all the data.
|
|
98
|
+
`measureValidityStudy()` asks the question a climb needs: which of many recorded numbers predict an outcome decided later, on changes they were not chosen on, and which few to climb.
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
import { sealMeasureValidityPlan } from '@tangle-network/agent-eval/experiment'
|
|
102
|
+
import { measureValidityStudy, type MeasuredChange } from '@tangle-network/agent-eval/meta-eval'
|
|
103
|
+
|
|
104
|
+
const plan = sealMeasureValidityPlan({
|
|
105
|
+
id: 'which-numbers-predict-kept-changes',
|
|
106
|
+
cut: Date.parse('2026-10-01T00:00:00Z'),
|
|
107
|
+
level: 0.05,
|
|
108
|
+
outcomes: [{ id: 'kept', direction: 'higher-is-better', kind: 'binary' }],
|
|
109
|
+
measures: [{ id: 'review_depth' }, { id: 'test_delta', noise: 0.1, cost: 1 }],
|
|
110
|
+
})
|
|
111
|
+
|
|
112
|
+
const change: MeasuredChange = {
|
|
113
|
+
id: 'change-1842', // the outcome store joins it through DeploymentOutcome.runId
|
|
114
|
+
at: Date.parse('2026-10-03T12:00:00Z'),
|
|
115
|
+
unit: 'repository-17', // the independent unit; intervals resample whole units
|
|
116
|
+
measures: { review_depth: 3, test_delta: 0.4 }, // an absent key is unmeasured
|
|
117
|
+
movements: { test_delta: { before: 0.1, after: 0.5 } }, // optional
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const report = await measureValidityStudy({ plan, changes: [change /* , ... */], outcomes })
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Seal the plan before reading changes made after the cut, and keep its digest where an independent reader can see it.
|
|
124
|
+
The study refuses a plan whose seal does not verify; the seal proves identity, not when it was made.
|
|
125
|
+
[`examples/measure-validity`](../examples/measure-validity/) runs the whole path on generated history.
|
|
126
|
+
|
|
127
|
+
The cut splits the changes.
|
|
128
|
+
A change made before the cut fixes each measure's direction, its standardization and the selected subset, reading only outcomes captured by the cut.
|
|
129
|
+
Every reported statistic comes from changes made at or after the cut, with those choices fixed.
|
|
130
|
+
`excludedObservations` counts outcomes captured before their change, beyond `maxCaptureLagMs`, or after the cut for a change made before it.
|
|
131
|
+
|
|
132
|
+
| Field | Meaning |
|
|
133
|
+
|---|---|
|
|
134
|
+
| `coverage` | Per measure: changes, measured changes and share, before and after the cut. An absent value is unmeasured, never zero. |
|
|
135
|
+
| `pairs[].label` | `predicts`: the pooled test passes and so does the within-unit test where it can be estimated. `predicts-pooled-only`: the pooled test passes and the within-unit test does not, so the ranking may come from differences between units rather than between changes. `not-shown`: tested and not admitted. `insufficient`: not tested. |
|
|
136
|
+
| `pairs[].reason` | Why a pair is not `predicts`: `below-minimum-count` (fewer than `minJoined`, default 100, joined changes after the cut), `too-few-units` (fewer than `minUnits`, default 20), `too-little-variation` (fewer than `minMinority`, default 20, joined changes after the cut differ from the measure's most common value: the smaller class of a two-valued measure), `no-pre-cut-direction`, `constant-after-cut`, `not-significant`, `direction-reversed` (the interval lies wholly past the null), `within-unit-not-shown`. |
|
|
137
|
+
| `pairs[].postCut.association` | The pooled statistic: AUC for a binary outcome, Spearman for a continuous one, aligned so above the null favors the better outcome; whole-unit standard error, percentile interval and one-sided p-value from `clusteredAssociation()`. |
|
|
138
|
+
| `pairs[].postCut.withinUnit` | The same statistic computed inside each unit and weighted by its comparable pairs; null when fewer than `minUnits` units hold a pair of changes with different outcomes. |
|
|
139
|
+
| `hypothesis` | Every p-value is one-sided in the direction fixed before the cut. |
|
|
140
|
+
| `tested`, `withinUnitTested` | Pairs in the pooled and within-unit false-discovery families. |
|
|
141
|
+
| `pairs[].leadTimeMs` | Outcome capture time minus change time over the joined changes after the cut. |
|
|
142
|
+
| `pairs[].movement` | With before and after values: `sensitivity` (share of changes that moved beyond the measure's declared `noise`) and `agreement` (balanced agreement between the movement's direction and the better outcome, 0.5 under no relation), each with a whole-unit interval. `insensitive` marks a measure that predicts across items but does not move under change. |
|
|
143
|
+
| `selections[]` | Per outcome: `climb`, a subset chosen before the cut by greedy forward selection on the equal-weight composite; `guards`, admitted measures not climbed (`redundant`, `no-gain`, `size-limit`); `excluded`, measures that are insensitive, move against the outcome, or predict only across units (`pooled-only`); `composite`, the subset's statistic before and after the cut. |
|
|
144
|
+
|
|
145
|
+
The selection reads only changes before the cut.
|
|
146
|
+
A candidate whose absolute rank correlation with a climbed measure reaches `maxRedundancy` (default 0.9) is a redundant guard; another must add at least `minGain` (default 0.01) to the composite's statistic.
|
|
147
|
+
The composite's post-cut score reads the changes admission read, so it describes the chosen subset; the next batch is its independent check.
|
|
148
|
+
|
|
149
|
+
Keep guards unoptimized.
|
|
150
|
+
`guardDrift({ report, outcome, batch, tolerance })` reads a later batch against the before-cut references: a climbed measure whose rise over the mean of its guards has a lower bound above `tolerance`, in before-cut scale units, is `drift`.
|
|
151
|
+
Guards are measured at change time, so the check runs before the outcome arrives; pass the outcome store to also report the outcome's shift.
|
|
152
|
+
|
|
153
|
+
Each test is one-sided in the direction fixed before the cut, so a measure whose direction reversed is never admitted.
|
|
154
|
+
When the same units appear on both sides of the cut, a coincidence among those units can choose the direction and then confirm it on the pooled statistic; the within-unit statistic cannot be moved by such a coincidence, which is why `predicts` requires it where it can be estimated.
|
|
155
|
+
|
|
156
|
+
Known limit: an outcome defined by overlap with the change's own content, such as "a later fix touched the same lines", grows with the change's size, so a size measure predicts it by exposure rather than by quality.
|
|
157
|
+
Record a stricter outcome that does not depend on size, such as a later fix that names the change, and report it beside the overlap outcome; a measure that predicts only the overlap outcome is predicting exposure.
|
|
158
|
+
|
|
159
|
+
Prediction is not causation.
|
|
160
|
+
An admitted measure forecasts the outcome of changes like these; it does not show that raising the measure raises the outcome, and a climbed measure can be moved without the work it used to reflect.
|
|
161
|
+
Records that show cause assign changes at random or interleave them, so the measure moves for reasons unrelated to the outcome.
|
|
162
|
+
The report carries this in `claim`.
|
|
163
|
+
|
|
95
164
|
## Propose an experiment against one target
|
|
96
165
|
|
|
97
166
|
```ts
|