@tangle-network/agent-eval 1.0.40 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (372) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/dist/adapters/http.d.ts +2 -2
  3. package/dist/{agent-profile-hytrwAnN.d.ts → agent-profile-BSgtn-k-.d.ts} +83 -4
  4. package/dist/agent-profile-BSgtn-k-.d.ts.map +1 -0
  5. package/dist/{agent-profile-DgbRJpSi.js → agent-profile-CCw6EXWW.js} +2 -2
  6. package/dist/{agent-profile-DgbRJpSi.js.map → agent-profile-CCw6EXWW.js.map} +1 -1
  7. package/dist/{agent-profile-cell-7Mt0wBkl.js → agent-profile-cell-CUthydZB.js} +2 -2
  8. package/dist/{agent-profile-cell-7Mt0wBkl.js.map → agent-profile-cell-CUthydZB.js.map} +1 -1
  9. package/dist/analyst/index.d.ts +13 -13
  10. package/dist/analyst/index.d.ts.map +1 -1
  11. package/dist/analyst/index.js +15 -15
  12. package/dist/analyst/index.js.map +1 -1
  13. package/dist/{analyze-runs-DqHx3Q_g.js → analyze-runs-C_9cXPZn.js} +9 -9
  14. package/dist/{analyze-runs-DqHx3Q_g.js.map → analyze-runs-C_9cXPZn.js.map} +1 -1
  15. package/dist/{analyze-runs-Ctuz-dd3.d.ts → analyze-runs-zEI7yAH_.d.ts} +2 -2
  16. package/dist/{analyze-runs-Ctuz-dd3.d.ts.map → analyze-runs-zEI7yAH_.d.ts.map} +1 -1
  17. package/dist/app-grade/index.d.ts +3 -3
  18. package/dist/app-grade/index.js +3 -3
  19. package/dist/authenticity/index.d.ts.map +1 -1
  20. package/dist/authenticity/index.js.map +1 -1
  21. package/dist/{benchmark-command-CJw3ijDV.js → benchmark-command-XLXa7I98.js} +14 -13
  22. package/dist/benchmark-command-XLXa7I98.js.map +1 -0
  23. package/dist/benchmarks/index.d.ts +8 -4
  24. package/dist/benchmarks/index.d.ts.map +1 -1
  25. package/dist/benchmarks/index.js +11 -6
  26. package/dist/benchmarks/index.js.map +1 -1
  27. package/dist/builder-eval/index.d.ts +1 -1
  28. package/dist/builder-eval/index.js +3 -3
  29. package/dist/{calibration-BBhY1QM6.js → calibration-Cfoup0xz.js} +3 -3
  30. package/dist/{calibration-BBhY1QM6.js.map → calibration-Cfoup0xz.js.map} +1 -1
  31. package/dist/campaign/index.d.ts +9 -9
  32. package/dist/campaign/index.js +16 -15
  33. package/dist/{campaign-DawSkDag.js → campaign-BlmkAwFD.js} +23 -23
  34. package/dist/campaign-BlmkAwFD.js.map +1 -0
  35. package/dist/{campaign-evidence-C1c6uihA.d.ts → campaign-evidence-BVKG5o32.d.ts} +6 -6
  36. package/dist/{campaign-evidence-C1c6uihA.d.ts.map → campaign-evidence-BVKG5o32.d.ts.map} +1 -1
  37. package/dist/{campaign-evidence-BX8OveG5.js → campaign-evidence-CsUE_lwc.js} +79 -26
  38. package/dist/campaign-evidence-CsUE_lwc.js.map +1 -0
  39. package/dist/{canonical-gLeHiqzd.d.ts → canonical-CGXS21f_.d.ts} +8 -5
  40. package/dist/{canonical-gLeHiqzd.d.ts.map → canonical-CGXS21f_.d.ts.map} +1 -1
  41. package/dist/{canonical-BANK6NOj.js → canonical-DKgL_Wby.js} +30 -8
  42. package/dist/canonical-DKgL_Wby.js.map +1 -0
  43. package/dist/{chat-client-DmPB31_2.js → chat-client-DqAXFLi-.js} +2 -2
  44. package/dist/{chat-client-DmPB31_2.js.map → chat-client-DqAXFLi-.js.map} +1 -1
  45. package/dist/{chat-json-call-Rfhu7JbJ.js → chat-json-call-CB6sQ6sv.js} +2 -2
  46. package/dist/{chat-json-call-Rfhu7JbJ.js.map → chat-json-call-CB6sQ6sv.js.map} +1 -1
  47. package/dist/{claim-C6LRiwz1.js → claim-BWEXwwBk.js} +2 -2
  48. package/dist/{claim-C6LRiwz1.js.map → claim-BWEXwwBk.js.map} +1 -1
  49. package/dist/cli.js +11 -11
  50. package/dist/{client-BIFwUg7I.d.ts → client-DUMIaMob.d.ts} +2 -2
  51. package/dist/{client-BIFwUg7I.d.ts.map → client-DUMIaMob.d.ts.map} +1 -1
  52. package/dist/cluster-CSd0LE_M.d.ts.map +1 -1
  53. package/dist/{cluster-bootstrap-ClPYIWoX.js → cluster-bootstrap-DPzVy3_K.js} +2 -2
  54. package/dist/{cluster-bootstrap-ClPYIWoX.js.map → cluster-bootstrap-DPzVy3_K.js.map} +1 -1
  55. package/dist/{completion-verifier-C3q1T96h.js → completion-verifier-DiG3y43g.js} +6 -6
  56. package/dist/{completion-verifier-C3q1T96h.js.map → completion-verifier-DiG3y43g.js.map} +1 -1
  57. package/dist/containment-order-GCJ-y_FV.js +56 -0
  58. package/dist/containment-order-GCJ-y_FV.js.map +1 -0
  59. package/dist/contract/index.d.ts +11 -11
  60. package/dist/contract/index.js +16 -16
  61. package/dist/contract/index.js.map +1 -1
  62. package/dist/cost-ledger-1CwUnVOd.js.map +1 -1
  63. package/dist/{decision-point-BN1YQNqk.js → decision-point-gt5JgqZ0.js} +8 -8
  64. package/dist/{decision-point-BN1YQNqk.js.map → decision-point-gt5JgqZ0.js.map} +1 -1
  65. package/dist/{default-registry-C5x2jyD6.d.ts → default-registry-DH_tl-V1.d.ts} +7 -7
  66. package/dist/{default-registry-C5x2jyD6.d.ts.map → default-registry-DH_tl-V1.d.ts.map} +1 -1
  67. package/dist/{default-registry-BE5Rj9ba.js → default-registry-Y9AaKLmG.js} +8 -8
  68. package/dist/default-registry-Y9AaKLmG.js.map +1 -0
  69. package/dist/{define-agent-eval-C4yoCqkc.d.ts → define-agent-eval-BDxV_ONM.d.ts} +18 -9
  70. package/dist/define-agent-eval-BDxV_ONM.d.ts.map +1 -0
  71. package/dist/{define-agent-eval-CyU7eAzj.js → define-agent-eval-Cq-bdF4O.js} +13 -11
  72. package/dist/define-agent-eval-Cq-bdF4O.js.map +1 -0
  73. package/dist/diagnosis/index.d.ts +3 -3
  74. package/dist/diagnosis/index.d.ts.map +1 -1
  75. package/dist/diagnosis/index.js +1 -1
  76. package/dist/diagnosis/index.js.map +1 -1
  77. package/dist/{dspy-rlm-engine-aM1RWOUT.js → dspy-rlm-engine-CHpTzYvZ.js} +4 -3
  78. package/dist/dspy-rlm-engine-CHpTzYvZ.js.map +1 -0
  79. package/dist/{emitter-DhQ65mza.js → emitter-BjW3NnX-.js} +15 -6
  80. package/dist/emitter-BjW3NnX-.js.map +1 -0
  81. package/dist/{emitter-mAXC5PSN.d.ts → emitter-Cw8ijO3v.d.ts} +4 -4
  82. package/dist/{emitter-mAXC5PSN.d.ts.map → emitter-Cw8ijO3v.d.ts.map} +1 -1
  83. package/dist/{engine-B2w3ARpj.d.ts → engine-3y87jnX0.d.ts} +2 -2
  84. package/dist/{engine-B2w3ARpj.d.ts.map → engine-3y87jnX0.d.ts.map} +1 -1
  85. package/dist/errors-DeEEV9Vx.js.map +1 -1
  86. package/dist/{eval-campaign-CWWh-1p1.js → eval-campaign-Cyk-tkLh.js} +5 -5
  87. package/dist/{eval-campaign-CWWh-1p1.js.map → eval-campaign-Cyk-tkLh.js.map} +1 -1
  88. package/dist/{evaluation-CQ-uAbqF.d.ts → evaluation-RODuDmCe.d.ts} +4 -4
  89. package/dist/{evaluation-CQ-uAbqF.d.ts.map → evaluation-RODuDmCe.d.ts.map} +1 -1
  90. package/dist/evaluation.d.ts +1 -1
  91. package/dist/{exact-types-B0_jA3V7.d.ts → exact-types-C4Rug7fG.d.ts} +2 -2
  92. package/dist/{exact-types-B0_jA3V7.d.ts.map → exact-types-C4Rug7fG.d.ts.map} +1 -1
  93. package/dist/{execution-insight-9No6Si55.d.ts → execution-insight-iOsr1Zi8.d.ts} +2 -2
  94. package/dist/{execution-insight-9No6Si55.d.ts.map → execution-insight-iOsr1Zi8.d.ts.map} +1 -1
  95. package/dist/experiment/index.d.ts +4 -4
  96. package/dist/experiment/index.d.ts.map +1 -1
  97. package/dist/experiment/index.js +10 -10
  98. package/dist/experiment/index.js.map +1 -1
  99. package/dist/{exporters-C9AwGDDK.js → exporters-CKFtnWmX.js} +2 -2
  100. package/dist/{exporters-C9AwGDDK.js.map → exporters-CKFtnWmX.js.map} +1 -1
  101. package/dist/external-optimizer-contracts-eKQTutGZ.js +123 -0
  102. package/dist/external-optimizer-contracts-eKQTutGZ.js.map +1 -0
  103. package/dist/{external-optimizer-process-DFEPdWJY.js → external-optimizer-process-CkAc1xBa.js} +22 -26
  104. package/dist/external-optimizer-process-CkAc1xBa.js.map +1 -0
  105. package/dist/{external-optimizer-subprocess-BspZ0bZb.js → external-optimizer-subprocess-B48Ie4qQ.js} +10 -124
  106. package/dist/external-optimizer-subprocess-B48Ie4qQ.js.map +1 -0
  107. package/dist/extract-usage-ISFqhfDz.js.map +1 -1
  108. package/dist/{feedback-trajectory-CCWiFzeE.d.ts → feedback-trajectory-B5hTr9w5.d.ts} +4 -4
  109. package/dist/{feedback-trajectory-CCWiFzeE.d.ts.map → feedback-trajectory-B5hTr9w5.d.ts.map} +1 -1
  110. package/dist/{finding-composition-BMgspnVI.js → finding-composition-CyWSTcAY.js} +2 -2
  111. package/dist/{finding-composition-BMgspnVI.js.map → finding-composition-CyWSTcAY.js.map} +1 -1
  112. package/dist/{findings-store-B8pq8Rhr.js → findings-store-Rx9ZJgHV.js} +6 -6
  113. package/dist/{findings-store-B8pq8Rhr.js.map → findings-store-Rx9ZJgHV.js.map} +1 -1
  114. package/dist/fuzz.d.ts.map +1 -1
  115. package/dist/fuzz.js +1 -1
  116. package/dist/fuzz.js.map +1 -1
  117. package/dist/{harness-session-lines-Fd5aeSDV.js → harness-session-lines-CSxKR6no.js} +3 -3
  118. package/dist/{harness-session-lines-Fd5aeSDV.js.map → harness-session-lines-CSxKR6no.js.map} +1 -1
  119. package/dist/{hf-dataset-kthWy7xl.js → hf-dataset-B0s2ZAhQ.js} +4 -4
  120. package/dist/{hf-dataset-kthWy7xl.js.map → hf-dataset-B0s2ZAhQ.js.map} +1 -1
  121. package/dist/hosted/index.d.ts +2 -2
  122. package/dist/hosted/index.js +1 -1
  123. package/dist/{index-BuuUhU_V.d.ts → index-BJTUL2Ff.d.ts} +41 -29
  124. package/dist/index-BJTUL2Ff.d.ts.map +1 -0
  125. package/dist/{index-Bhc7H9e0.d.ts → index-CX8_WfqS.d.ts} +5 -5
  126. package/dist/{index-Bhc7H9e0.d.ts.map → index-CX8_WfqS.d.ts.map} +1 -1
  127. package/dist/{index-DtW7KhyE.d.ts → index-D-nKkzsI.d.ts} +3 -3
  128. package/dist/{index-DtW7KhyE.d.ts.map → index-D-nKkzsI.d.ts.map} +1 -1
  129. package/dist/{index-HdlzN11G.d.ts → index-D1NRaf5U.d.ts} +7 -7
  130. package/dist/{index-HdlzN11G.d.ts.map → index-D1NRaf5U.d.ts.map} +1 -1
  131. package/dist/{index-Bcy00QoN.d.ts → index-DcGHcBpR.d.ts} +86 -86
  132. package/dist/index-DcGHcBpR.d.ts.map +1 -0
  133. package/dist/{index-CXoFLNKI.d.ts → index-FLyheOVA.d.ts} +9 -9
  134. package/dist/index-FLyheOVA.d.ts.map +1 -0
  135. package/dist/{index-lRKqfyg4.d.ts → index-qy6buL6y.d.ts} +2 -2
  136. package/dist/{index-lRKqfyg4.d.ts.map → index-qy6buL6y.d.ts.map} +1 -1
  137. package/dist/index.d.ts +29 -29
  138. package/dist/index.js +41 -41
  139. package/dist/index.js.map +1 -1
  140. package/dist/{integrity-BSs9dgKW.js → integrity-BF0tJK21.js} +3 -3
  141. package/dist/{integrity-BSs9dgKW.js.map → integrity-BF0tJK21.js.map} +1 -1
  142. package/dist/{journal-DQsbHGjX.js → journal-3y-btqaP.js} +2 -2
  143. package/dist/{journal-DQsbHGjX.js.map → journal-3y-btqaP.js.map} +1 -1
  144. package/dist/journal-file-AekB57Er.js.map +1 -1
  145. package/dist/{json-recovery-b7O9WVTF.js → json-recovery-BRUCeQxo.js} +2 -2
  146. package/dist/{json-recovery-b7O9WVTF.js.map → json-recovery-BRUCeQxo.js.map} +1 -1
  147. package/dist/{judge-gate-LbmZU-pA.js → judge-gate-TBv2jeO0.js} +3 -3
  148. package/dist/{judge-gate-LbmZU-pA.js.map → judge-gate-TBv2jeO0.js.map} +1 -1
  149. package/dist/{kind-factory-B5FfFE5G.js → kind-factory-DfNsTe-q.js} +3 -3
  150. package/dist/kind-factory-DfNsTe-q.js.map +1 -0
  151. package/dist/ledger-core/index.d.ts +2 -2
  152. package/dist/ledger-core/index.js +3 -3
  153. package/dist/{ledger-core-7e6sXmhV.js → ledger-core-auznoaD7.js} +3 -3
  154. package/dist/ledger-core-auznoaD7.js.map +1 -0
  155. package/dist/{llm-client-CdHo3SH0.js → llm-client-gRPgIJyz.js} +2 -2
  156. package/dist/{llm-client-CdHo3SH0.js.map → llm-client-gRPgIJyz.js.map} +1 -1
  157. package/dist/{llm-judge-DHgx29ro.js → llm-judge-CThv1Rog.js} +140 -44
  158. package/dist/llm-judge-CThv1Rog.js.map +1 -0
  159. package/dist/{matrix-BKzNwIWb.d.ts → matrix-CfJ5vhfq.d.ts} +2 -2
  160. package/dist/{matrix-BKzNwIWb.d.ts.map → matrix-CfJ5vhfq.d.ts.map} +1 -1
  161. package/dist/meta-eval/index.d.ts +1 -1
  162. package/dist/meta-eval/index.js +9 -9
  163. package/dist/{mint-VN-qtJTc.js → mint-B4n1pRRd.js} +12 -6
  164. package/dist/mint-B4n1pRRd.js.map +1 -0
  165. package/dist/{model-comparison-BZr_Hu00.js → model-comparison-CgnVh4Ph.js} +3 -3
  166. package/dist/{model-comparison-BZr_Hu00.js.map → model-comparison-CgnVh4Ph.js.map} +1 -1
  167. package/dist/multishot/golden/index.d.ts +1 -1
  168. package/dist/multishot/index.d.ts +2 -2
  169. package/dist/multishot/index.js +1 -1
  170. package/dist/multishot/index.js.map +1 -1
  171. package/dist/openapi.json +1 -1
  172. package/dist/{outcome-observations-YFFmdGGW.js → outcome-observations-DL3CC8w1.js} +2 -2
  173. package/dist/{outcome-observations-YFFmdGGW.js.map → outcome-observations-DL3CC8w1.js.map} +1 -1
  174. package/dist/{paired-arms-DH376s4-.js → paired-arms-DZhH3FGu.js} +3 -3
  175. package/dist/{paired-arms-DH376s4-.js.map → paired-arms-DZhH3FGu.js.map} +1 -1
  176. package/dist/{paired-promotion-decision-BoWHWL1i.js → paired-promotion-decision-Dn3-jaq4.js} +2 -2
  177. package/dist/{paired-promotion-decision-BoWHWL1i.js.map → paired-promotion-decision-Dn3-jaq4.js.map} +1 -1
  178. package/dist/{paired-promotion-decision-BBSxTo-h.d.ts → paired-promotion-decision-Il-Nv-n4.d.ts} +2 -2
  179. package/dist/{paired-promotion-decision-BBSxTo-h.d.ts.map → paired-promotion-decision-Il-Nv-n4.d.ts.map} +1 -1
  180. package/dist/{paired-promotion-power-BXH3gzvs.js → paired-promotion-power-BlzXdgMD.js} +3 -3
  181. package/dist/{paired-promotion-power-BXH3gzvs.js.map → paired-promotion-power-BlzXdgMD.js.map} +1 -1
  182. package/dist/{pareto-BNWWbLNl.js → pareto-Bg75Gajo.js} +7 -7
  183. package/dist/{pareto-BNWWbLNl.js.map → pareto-Bg75Gajo.js.map} +1 -1
  184. package/dist/pipelines/index.d.ts +3 -3
  185. package/dist/pipelines/index.d.ts.map +1 -1
  186. package/dist/pipelines/index.js +19 -33
  187. package/dist/pipelines/index.js.map +1 -1
  188. package/dist/{prime-protocol-BR0xy0cF.d.ts → prime-protocol-CdNaCQy5.d.ts} +2 -2
  189. package/dist/{prime-protocol-BR0xy0cF.d.ts.map → prime-protocol-CdNaCQy5.d.ts.map} +1 -1
  190. package/dist/profile-cell.js +1 -1
  191. package/dist/{promotion-gate-XiTqW22r.d.ts → promotion-gate-DKAvMFlS.d.ts} +2 -2
  192. package/dist/{promotion-gate-XiTqW22r.d.ts.map → promotion-gate-DKAvMFlS.d.ts.map} +1 -1
  193. package/dist/{promotion-policy-CfgRPGx0.js → promotion-policy-CxDIh-9p.js} +4 -4
  194. package/dist/{promotion-policy-CfgRPGx0.js.map → promotion-policy-CxDIh-9p.js.map} +1 -1
  195. package/dist/{proposal-findings-DFQvA-k5.js → proposal-findings-DnR7zdUc.js} +2 -2
  196. package/dist/{proposal-findings-DFQvA-k5.js.map → proposal-findings-DnR7zdUc.js.map} +1 -1
  197. package/dist/{query-Ck6KhcDo.js → query-Dhjkwqyx.js} +2 -2
  198. package/dist/{query-Ck6KhcDo.js.map → query-Dhjkwqyx.js.map} +1 -1
  199. package/dist/{registry-D23oO0_f.d.ts → registry-LqAf_laP.d.ts} +3 -3
  200. package/dist/{registry-D23oO0_f.d.ts.map → registry-LqAf_laP.d.ts.map} +1 -1
  201. package/dist/{release-confidence-BdidB0mG.js → release-confidence-BLHOMK5Q.js} +3 -3
  202. package/dist/{release-confidence-BdidB0mG.js.map → release-confidence-BLHOMK5Q.js.map} +1 -1
  203. package/dist/reporting.d.ts +4 -4
  204. package/dist/reporting.js +5 -5
  205. package/dist/{research-report-BGKsOqkF.d.ts → research-report-BauFJiqu.d.ts} +2 -2
  206. package/dist/{research-report-BGKsOqkF.d.ts.map → research-report-BauFJiqu.d.ts.map} +1 -1
  207. package/dist/{researcher-DvFDa1o1.d.ts → researcher-B4e2Z92k.d.ts} +3 -3
  208. package/dist/{researcher-DvFDa1o1.d.ts.map → researcher-B4e2Z92k.d.ts.map} +1 -1
  209. package/dist/{reward-hacking-DNiHskry.js → reward-hacking-DKAflk2c.js} +2 -2
  210. package/dist/{reward-hacking-DNiHskry.js.map → reward-hacking-DKAflk2c.js.map} +1 -1
  211. package/dist/rl.d.ts +155 -39
  212. package/dist/rl.d.ts.map +1 -1
  213. package/dist/rl.js +420 -76
  214. package/dist/rl.js.map +1 -1
  215. package/dist/rollout/index.d.ts +4 -4
  216. package/dist/rollout/index.js +6 -6
  217. package/dist/{rollout-DDMkK_Lw.js → rollout-B6LlGRSq.js} +9 -9
  218. package/dist/rollout-B6LlGRSq.js.map +1 -0
  219. package/dist/{rollout-nodes-DzmHlPAC.js → rollout-nodes-Vas6OSxX.js} +2 -2
  220. package/dist/{rollout-nodes-DzmHlPAC.js.map → rollout-nodes-Vas6OSxX.js.map} +1 -1
  221. package/dist/{rubric-predictive-validity-Cln7r56F.js → rubric-predictive-validity--6z0q8s6.js} +2 -2
  222. package/dist/{rubric-predictive-validity-Cln7r56F.js.map → rubric-predictive-validity--6z0q8s6.js.map} +1 -1
  223. package/dist/{run-improvement-loop-BAxDnaPI.d.ts → run-improvement-loop-B1OKCm2D.d.ts} +112 -70
  224. package/dist/run-improvement-loop-B1OKCm2D.d.ts.map +1 -0
  225. package/dist/{run-record-c860wUR8.js → run-record-Bqg0NZ_e.js} +19 -4
  226. package/dist/run-record-Bqg0NZ_e.js.map +1 -0
  227. package/dist/{run-record-Dx64nPcX.js → run-record-CqUft6Yf.js} +2 -2
  228. package/dist/{run-record-Dx64nPcX.js.map → run-record-CqUft6Yf.js.map} +1 -1
  229. package/dist/{runtime-rollouts-CALol_Y4.js → runtime-rollouts-DdUijr_t.js} +7 -7
  230. package/dist/runtime-rollouts-DdUijr_t.js.map +1 -0
  231. package/dist/{schema-BTTzvMnn.d.ts → schema-BfSoJjD-.d.ts} +5 -1
  232. package/dist/schema-BfSoJjD-.d.ts.map +1 -0
  233. package/dist/{schema-b18jtzZw.js → schema-Bh9CfSZT.js} +3 -1
  234. package/dist/schema-Bh9CfSZT.js.map +1 -0
  235. package/dist/schema-CkIvnmLU.d.ts.map +1 -1
  236. package/dist/schema-D-xu3MU_.js.map +1 -1
  237. package/dist/search/index.d.ts +3 -3
  238. package/dist/search/index.d.ts.map +1 -1
  239. package/dist/search/index.js +3 -3
  240. package/dist/{search-kernel-DRHWY35J.d.ts → search-kernel-CuTvZlPS.d.ts} +5 -5
  241. package/dist/{search-kernel-DRHWY35J.d.ts.map → search-kernel-CuTvZlPS.d.ts.map} +1 -1
  242. package/dist/{search-ledger-oyqxZhry.js → search-ledger-C7t68cmy.js} +7 -7
  243. package/dist/{search-ledger-oyqxZhry.js.map → search-ledger-C7t68cmy.js.map} +1 -1
  244. package/dist/{search-ledger-file-DoHCYYLt.js → search-ledger-file-QuIbgz6b.js} +2 -2
  245. package/dist/search-ledger-file-QuIbgz6b.js.map +1 -0
  246. package/dist/{search-ledger-types-qiYRUo_N.d.ts → search-ledger-types-BhZE848w.d.ts} +2 -2
  247. package/dist/{search-ledger-types-qiYRUo_N.d.ts.map → search-ledger-types-BhZE848w.d.ts.map} +1 -1
  248. package/dist/{search-shipper-BwqeQ61l.js → search-shipper-CmDW9dU6.js} +3 -3
  249. package/dist/{search-shipper-BwqeQ61l.js.map → search-shipper-CmDW9dU6.js.map} +1 -1
  250. package/dist/{search-summary-CNHpHFfw.js → search-summary-B1x1Vmzh.js} +5 -5
  251. package/dist/{search-summary-CNHpHFfw.js.map → search-summary-B1x1Vmzh.js.map} +1 -1
  252. package/dist/{sequential-93xxuiiG.js → sequential-BphITa5b.js} +4 -4
  253. package/dist/{sequential-93xxuiiG.js.map → sequential-BphITa5b.js.map} +1 -1
  254. package/dist/{sequential-B-zx24n_.d.ts → sequential-DqOJZO2V.d.ts} +2 -2
  255. package/dist/{sequential-B-zx24n_.d.ts.map → sequential-DqOJZO2V.d.ts.map} +1 -1
  256. package/dist/{sequential-C6k0Wrb7.js → sequential-ux_XrjBf.js} +3 -3
  257. package/dist/{sequential-C6k0Wrb7.js.map → sequential-ux_XrjBf.js.map} +1 -1
  258. package/dist/{served-model-qhLmbutL.js → served-model-BXmeKm7D.js} +2 -2
  259. package/dist/{served-model-qhLmbutL.js.map → served-model-BXmeKm7D.js.map} +1 -1
  260. package/dist/{server-DnoEi4Sb.js → server-BxHJyclG.js} +4 -4
  261. package/dist/{server-DnoEi4Sb.js.map → server-BxHJyclG.js.map} +1 -1
  262. package/dist/{skillopt-optimization-method-Du3GbReg.js → skillopt-optimization-method-CHW9mphc.js} +389 -68
  263. package/dist/skillopt-optimization-method-CHW9mphc.js.map +1 -0
  264. package/dist/{statistical-heldout-BvcAVtof.js → statistical-heldout-CaS4T-43.js} +3 -3
  265. package/dist/{statistical-heldout-BvcAVtof.js.map → statistical-heldout-CaS4T-43.js.map} +1 -1
  266. package/dist/{statistics-CHs0jlsY.js → statistics-DSidA5I2.js} +184 -184
  267. package/dist/statistics-DSidA5I2.js.map +1 -0
  268. package/dist/statistics.d.ts +1 -1
  269. package/dist/statistics.js +1 -1
  270. package/dist/{store-otlp-DHc_E78m.js → store-otlp-DCQTz9lS.js} +2 -2
  271. package/dist/{store-otlp-DHc_E78m.js.map → store-otlp-DCQTz9lS.js.map} +1 -1
  272. package/dist/{store-tool-spans-C1lZKvvl.d.ts → store-tool-spans-B0UYrcl7.d.ts} +5 -5
  273. package/dist/{store-tool-spans-C1lZKvvl.d.ts.map → store-tool-spans-B0UYrcl7.d.ts.map} +1 -1
  274. package/dist/{store-tool-spans-BR4IhZYZ.js → store-tool-spans-D2-S3OdE.js} +4 -4
  275. package/dist/{store-tool-spans-BR4IhZYZ.js.map → store-tool-spans-D2-S3OdE.js.map} +1 -1
  276. package/dist/storyboard/index.d.ts.map +1 -1
  277. package/dist/storyboard/index.js.map +1 -1
  278. package/dist/{summary-report-CXiE1UrA.js → summary-report-CI4J6gxU.js} +4 -4
  279. package/dist/{summary-report-CXiE1UrA.js.map → summary-report-CI4J6gxU.js.map} +1 -1
  280. package/dist/supervisor-run/index.d.ts +2 -2
  281. package/dist/supervisor-run/index.d.ts.map +1 -1
  282. package/dist/supervisor-run/index.js +3 -3
  283. package/dist/{systemone-B_3Vd395.d.ts → systemone-nAN8fBy9.d.ts} +8 -8
  284. package/dist/{systemone-B_3Vd395.d.ts.map → systemone-nAN8fBy9.d.ts.map} +1 -1
  285. package/dist/systemone-protocol.js +1 -1
  286. package/dist/{systemone-review-ZAN-5m_2.d.ts → systemone-review-e2ElIpD_.d.ts} +3 -3
  287. package/dist/{systemone-review-ZAN-5m_2.d.ts.map → systemone-review-e2ElIpD_.d.ts.map} +1 -1
  288. package/dist/{systemone-review-CqNNZMiD.js → systemone-review-ir3Cbejl.js} +3 -3
  289. package/dist/{systemone-review-CqNNZMiD.js.map → systemone-review-ir3Cbejl.js.map} +1 -1
  290. package/dist/systemone.d.ts +3 -3
  291. package/dist/systemone.js +2 -2
  292. package/dist/{tool-groups-BOH1E-E4.d.ts → tool-groups-sRVCeevR.d.ts} +3 -3
  293. package/dist/tool-groups-sRVCeevR.d.ts.map +1 -0
  294. package/dist/tool-waste-CIhtU1ad.d.ts +217 -0
  295. package/dist/tool-waste-CIhtU1ad.d.ts.map +1 -0
  296. package/dist/{tool-waste-DzLI-JJg.js → tool-waste-u7JJ_BlE.js} +3 -3
  297. package/dist/{tool-waste-DzLI-JJg.js.map → tool-waste-u7JJ_BlE.js.map} +1 -1
  298. package/dist/{trace-questions-DBsrgY_H.d.ts → trace-questions-BN-LSfkA.d.ts} +3 -3
  299. package/dist/{trace-questions-DBsrgY_H.d.ts.map → trace-questions-BN-LSfkA.d.ts.map} +1 -1
  300. package/dist/trace-repair/index.d.ts +1 -1
  301. package/dist/trace-repair/index.d.ts.map +1 -1
  302. package/dist/trace-repair/index.js +4 -4
  303. package/dist/trace-repair/index.js.map +1 -1
  304. package/dist/traces.d.ts +4 -4
  305. package/dist/traces.js +6 -6
  306. package/dist/{training-admission-xaDOlQ_U.d.ts → training-admission-DGZCyntI.d.ts} +2 -2
  307. package/dist/{training-admission-xaDOlQ_U.d.ts.map → training-admission-DGZCyntI.d.ts.map} +1 -1
  308. package/dist/trajectory-CKVZaQoQ.js +144 -0
  309. package/dist/trajectory-CKVZaQoQ.js.map +1 -0
  310. package/dist/trajectory-replay/index.d.ts.map +1 -1
  311. package/dist/trajectory-replay/index.js +24 -11
  312. package/dist/trajectory-replay/index.js.map +1 -1
  313. package/dist/{tree-0r6gPODs.js → tree-DQMlcNFI.js} +18 -6
  314. package/dist/tree-DQMlcNFI.js.map +1 -0
  315. package/dist/{types-DmYd2Igl.d.ts → types-BJ27EWAS.d.ts} +8 -8
  316. package/dist/{types-DmYd2Igl.d.ts.map → types-BJ27EWAS.d.ts.map} +1 -1
  317. package/dist/{types-ClDpBoLt.d.ts → types-CDWfUYOq.d.ts} +2 -2
  318. package/dist/{types-ClDpBoLt.d.ts.map → types-CDWfUYOq.d.ts.map} +1 -1
  319. package/dist/{types-_dfu6Ox2.d.ts → types-DI7YKvDI.d.ts} +3 -3
  320. package/dist/{types-_dfu6Ox2.d.ts.map → types-DI7YKvDI.d.ts.map} +1 -1
  321. package/dist/{types-C8AyaiFi.js → types-_tlhWGUq.js} +2 -2
  322. package/dist/{types-C8AyaiFi.js.map → types-_tlhWGUq.js.map} +1 -1
  323. package/dist/{types-DGqGbNY4.d.ts → types-pMk2rgP9.d.ts} +20 -6
  324. package/dist/{types-DGqGbNY4.d.ts.map → types-pMk2rgP9.d.ts.map} +1 -1
  325. package/dist/{verdict-CKo1iZkI.js → verdict-5PVtsWT_.js} +2 -2
  326. package/dist/{verdict-CKo1iZkI.js.map → verdict-5PVtsWT_.js.map} +1 -1
  327. package/dist/{verdict-cache-DfzlHLdf.js → verdict-cache-BPaYxfG8.js} +2 -2
  328. package/dist/verdict-cache-BPaYxfG8.js.map +1 -0
  329. package/dist/wire/index.d.ts +1 -1
  330. package/dist/wire/index.js +1 -1
  331. package/docs/campaign-proposers.md +14 -1
  332. package/docs/public-api.md +323 -85
  333. package/docs/rollout.md +2 -2
  334. package/docs/search-ledger.md +14 -2
  335. package/docs/statistical-evidence.md +9 -3
  336. package/docs/trajectory-replay.md +4 -0
  337. package/package.json +1 -1
  338. package/dist/agent-profile-hytrwAnN.d.ts.map +0 -1
  339. package/dist/benchmark-command-CJw3ijDV.js.map +0 -1
  340. package/dist/campaign-DawSkDag.js.map +0 -1
  341. package/dist/campaign-evidence-BX8OveG5.js.map +0 -1
  342. package/dist/canonical-BANK6NOj.js.map +0 -1
  343. package/dist/default-registry-BE5Rj9ba.js.map +0 -1
  344. package/dist/define-agent-eval-C4yoCqkc.d.ts.map +0 -1
  345. package/dist/define-agent-eval-CyU7eAzj.js.map +0 -1
  346. package/dist/dspy-rlm-engine-aM1RWOUT.js.map +0 -1
  347. package/dist/emitter-DhQ65mza.js.map +0 -1
  348. package/dist/external-optimizer-process-DFEPdWJY.js.map +0 -1
  349. package/dist/external-optimizer-subprocess-BspZ0bZb.js.map +0 -1
  350. package/dist/index-Bcy00QoN.d.ts.map +0 -1
  351. package/dist/index-BuuUhU_V.d.ts.map +0 -1
  352. package/dist/index-CXoFLNKI.d.ts.map +0 -1
  353. package/dist/kind-factory-B5FfFE5G.js.map +0 -1
  354. package/dist/ledger-core-7e6sXmhV.js.map +0 -1
  355. package/dist/llm-judge-DHgx29ro.js.map +0 -1
  356. package/dist/mint-VN-qtJTc.js.map +0 -1
  357. package/dist/rollout-DDMkK_Lw.js.map +0 -1
  358. package/dist/run-improvement-loop-BAxDnaPI.d.ts.map +0 -1
  359. package/dist/run-record-c860wUR8.js.map +0 -1
  360. package/dist/runtime-rollouts-CALol_Y4.js.map +0 -1
  361. package/dist/schema-BTTzvMnn.d.ts.map +0 -1
  362. package/dist/schema-b18jtzZw.js.map +0 -1
  363. package/dist/search-ledger-file-DoHCYYLt.js.map +0 -1
  364. package/dist/skillopt-optimization-method-Du3GbReg.js.map +0 -1
  365. package/dist/statistics-CHs0jlsY.js.map +0 -1
  366. package/dist/tool-groups-BOH1E-E4.d.ts.map +0 -1
  367. package/dist/tool-waste-CUASoTtk.d.ts +0 -139
  368. package/dist/tool-waste-CUASoTtk.d.ts.map +0 -1
  369. package/dist/trajectory-O3GDHmev.js +0 -55
  370. package/dist/trajectory-O3GDHmev.js.map +0 -1
  371. package/dist/tree-0r6gPODs.js.map +0 -1
  372. package/dist/verdict-cache-DfzlHLdf.js.map +0 -1
@@ -45,17 +45,39 @@ function hashCanonical(value) {
45
45
  * undefined-valued key, and the reader cannot verify the writer.
46
46
  *
47
47
  * Only that one rule is applied. Every other non-canonical value — `NaN`, a
48
- * class instance, an `undefined` array item, a cycle — reaches
49
- * {@link canonicalString} unchanged and is refused there, so this form never
50
- * turns an ambiguous value into a valid-looking digest the way
51
- * `JSON.stringify` turns `NaN` into `null`.
48
+ * class instance, an `undefined` array item — reaches {@link canonicalString}
49
+ * unchanged and is refused there, so this form never turns an ambiguous value
50
+ * into a valid-looking digest the way `JSON.stringify` turns `NaN` into `null`.
51
+ *
52
+ * A reference cycle is refused here with {@link LedgerCanonicalizationError},
53
+ * because walking it would never end. Only the objects on the current path
54
+ * count, so a value reached twice without a cycle still encodes.
52
55
  */
53
56
  function jsonDocument(value) {
57
+ return documentForm(value, /* @__PURE__ */ new Set(), []);
58
+ }
59
+ /** `ancestors` holds the arrays and plain objects from the root down to `value`. */
60
+ function documentForm(value, ancestors, path) {
54
61
  if (value === null || typeof value !== "object") return value;
55
- if (Array.isArray(value)) return value.map(jsonDocument);
56
62
  const prototype = Object.getPrototypeOf(value);
57
- if (prototype !== Object.prototype && prototype !== null) return value;
58
- return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== void 0).map(([key, entry]) => [key, jsonDocument(entry)]));
63
+ const isArray = Array.isArray(value);
64
+ if (!isArray && prototype !== Object.prototype && prototype !== null) return value;
65
+ if (ancestors.has(value)) throw new LedgerCanonicalizationError(`value has no canonical JSON form: $${path.map((key) => typeof key === "number" ? `[${key}]` : `.${key}`).join("")} closes a reference cycle`);
66
+ const descend = (entry, key) => {
67
+ path.push(key);
68
+ try {
69
+ return documentForm(entry, ancestors, path);
70
+ } finally {
71
+ path.pop();
72
+ }
73
+ };
74
+ ancestors.add(value);
75
+ try {
76
+ if (isArray) return value.map((entry, index) => descend(entry, index));
77
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== void 0).map(([key, entry]) => [key, descend(entry, key)]));
78
+ } finally {
79
+ ancestors.delete(value);
80
+ }
59
81
  }
60
82
  /** Name the offending value and path so a refusal is actionable. The RFC 8785
61
83
  * encoder above is the sole authority on acceptance; this walk only explains a
@@ -124,4 +146,4 @@ function compareCodeUnits(left, right) {
124
146
  }
125
147
  export { hashCanonical as a, compareCodeUnits as i, LedgerCanonicalizationError as n, jsonDocument as o, canonicalString as r, LEDGER_HASH_PATTERN as t };
126
148
 
127
- //# sourceMappingURL=canonical-BANK6NOj.js.map
149
+ //# sourceMappingURL=canonical-DKgL_Wby.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"canonical-DKgL_Wby.js","names":[],"sources":["../src/ledger-core/canonical.ts"],"sourcesContent":["/**\n * Canonical bytes and digests for durable journal rows.\n *\n * Serialization is RFC 8785 through `@tangle-network/agent-interface` — the\n * stack's single identity scheme — so a value carries the same digest in every\n * package that produces or verifies one.\n *\n * Values canonical JSON cannot represent faithfully are refused, never coerced.\n * `NaN`, `Infinity`, `undefined`, class instances, cycles, and unpaired\n * surrogates each have a lossy encoding that maps distinct records onto one\n * digest, and in a hash chain the digest IS the record's identity: a coercion\n * there is a collision, not a convenience.\n */\n\nimport { canonicalCandidateDigest, canonicalCandidateJson } from '@tangle-network/agent-interface'\nimport { ValidationError } from '../errors'\n\nexport type LedgerHash = `sha256:${string}`\n\n/** Shape of every ledger digest: `sha256:` followed by 64 lowercase hex chars. */\nexport const LEDGER_HASH_PATTERN = /^sha256:[a-f0-9]{64}$/\n\n/** A value has no faithful canonical-JSON form, so it cannot be stored or hashed. */\nexport class LedgerCanonicalizationError extends ValidationError {}\n\n/** Canonical JSON encoding (RFC 8785): object keys sorted by UTF-16 code unit,\n * recursively. This is the byte form that is hashed and stored, so equal values\n * always encode identically. */\nexport function canonicalString(value: unknown): string {\n try {\n return canonicalCandidateJson(value)\n } catch (error) {\n throw canonicalizationError(value, error)\n }\n}\n\nexport function hashCanonical(value: unknown): LedgerHash {\n try {\n return canonicalCandidateDigest(value)\n } catch (error) {\n throw canonicalizationError(value, error)\n }\n}\n\n/**\n * The JSON document form of `value` — the value as a JSON file carries it.\n *\n * A JSON document has no `undefined`, so an undefined-valued key is absent\n * from the document and absent from its digest. Use this, and say so, when a\n * record is digested BEFORE being written and re-digested AFTER being read\n * back: without it the two digests disagree for a record carrying an\n * undefined-valued key, and the reader cannot verify the writer.\n *\n * Only that one rule is applied. Every other non-canonical value — `NaN`, a\n * class instance, an `undefined` array item — reaches {@link canonicalString}\n * unchanged and is refused there, so this form never turns an ambiguous value\n * into a valid-looking digest the way `JSON.stringify` turns `NaN` into `null`.\n *\n * A reference cycle is refused here with {@link LedgerCanonicalizationError},\n * because walking it would never end. Only the objects on the current path\n * count, so a value reached twice without a cycle still encodes.\n */\nexport function jsonDocument(value: unknown): unknown {\n return documentForm(value, new Set(), [])\n}\n\n/** `ancestors` holds the arrays and plain objects from the root down to `value`. */\nfunction documentForm(\n value: unknown,\n ancestors: Set<object>,\n path: Array<string | number>,\n): unknown {\n if (value === null || typeof value !== 'object') return value\n const prototype = Object.getPrototypeOf(value)\n const isArray = Array.isArray(value)\n if (!isArray && prototype !== Object.prototype && prototype !== null) return value\n if (ancestors.has(value)) {\n const at = path.map((key) => (typeof key === 'number' ? `[${key}]` : `.${key}`)).join('')\n throw new LedgerCanonicalizationError(\n `value has no canonical JSON form: $${at} closes a reference cycle`,\n )\n }\n const descend = (entry: unknown, key: string | number): unknown => {\n path.push(key)\n try {\n return documentForm(entry, ancestors, path)\n } finally {\n path.pop()\n }\n }\n ancestors.add(value)\n try {\n if (isArray) return (value as unknown[]).map((entry, index) => descend(entry, index))\n // fromEntries creates own properties, including a caller's __proto__ key.\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .filter(([, entry]) => entry !== undefined)\n .map(([key, entry]) => [key, descend(entry, key)]),\n )\n } finally {\n ancestors.delete(value)\n }\n}\n\n/** Name the offending value and path so a refusal is actionable. The RFC 8785\n * encoder above is the sole authority on acceptance; this walk only explains a\n * rejection it already made. */\nfunction canonicalizationError(value: unknown, cause: unknown): LedgerCanonicalizationError {\n const defect = firstNonCanonicalDefect(value, '$', new Set())\n const reason = defect !== '' ? defect : cause instanceof Error ? cause.message : String(cause)\n return new LedgerCanonicalizationError(`value has no canonical JSON form: ${reason}`, {\n cause,\n })\n}\n\nfunction firstNonCanonicalDefect(value: unknown, path: string, ancestors: Set<object>): string {\n if (value === null) return ''\n if (value === undefined) return `${path} is undefined`\n const type = typeof value\n if (type === 'number') {\n return Number.isFinite(value) ? '' : `${path} is ${String(value)}`\n }\n if (type === 'string') {\n return isWellFormedUtf16(value as string) ? '' : `${path} contains an unpaired surrogate`\n }\n if (type === 'boolean') return ''\n if (type !== 'object') return `${path} is a ${type}`\n const object = value as object\n if (ancestors.has(object)) return `${path} closes a reference cycle`\n const prototype = Object.getPrototypeOf(object)\n if (!Array.isArray(object) && prototype !== Object.prototype && prototype !== null) {\n return `${path} is a ${object.constructor?.name ?? 'non-plain'} instance, not plain JSON data`\n }\n const nested = new Set(ancestors).add(object)\n if (Array.isArray(object)) {\n for (let index = 0; index < object.length; index += 1) {\n const defect = firstNonCanonicalDefect(object[index], `${path}[${index}]`, nested)\n if (defect !== '') return defect\n }\n return ''\n }\n for (const [key, entry] of Object.entries(object)) {\n if (!isWellFormedUtf16(key)) return `${path}.${key} has a key with an unpaired surrogate`\n const defect = firstNonCanonicalDefect(entry, `${path}.${key}`, nested)\n if (defect !== '') return defect\n }\n return ''\n}\n\nfunction isWellFormedUtf16(value: string): boolean {\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index)\n if (code >= 0xd800 && code <= 0xdbff) {\n const next = value.charCodeAt(index + 1)\n if (!(next >= 0xdc00 && next <= 0xdfff)) return false\n index += 1\n } else if (code >= 0xdc00 && code <= 0xdfff) {\n return false\n }\n }\n return true\n}\n\n/**\n * Compare two strings by UTF-16 code unit — the order RFC 8785 uses for object\n * keys, and the order any array must be sorted into before it is canonicalized.\n *\n * `String.prototype.localeCompare` reads the host's collation, so it is a\n * property of the machine rather than of the value. RFC 8785 canonicalizes an\n * array BY POSITION, so a `localeCompare` sort in front of `canonicalString` or\n * `hashCanonical` lets the collation decide the digest bytes: the ids\n * `Accuracy, brevity, Clarity` order as `Accuracy,brevity,Clarity` under an\n * en-US collation and as `Accuracy,Clarity,brevity` by code unit, and the two\n * produce different digests for the same data.\n *\n * Use this for any ordering whose result reaches a digest, a stable\n * serialization, or a stored identity. A comparator for a report a human reads\n * is free to keep `localeCompare`.\n */\nexport function compareCodeUnits(left: string, right: string): number {\n if (left < right) return -1\n return left > right ? 1 : 0\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAoBA,MAAa,sBAAsB;;AAGnC,IAAa,8BAAb,cAAiD,gBAAgB,CAAC;;;;AAKlE,SAAgB,gBAAgB,OAAwB;CACtD,IAAI;EACF,OAAO,uBAAuB,KAAK;CACrC,SAAS,OAAO;EACd,MAAM,sBAAsB,OAAO,KAAK;CAC1C;AACF;AAEA,SAAgB,cAAc,OAA4B;CACxD,IAAI;EACF,OAAO,yBAAyB,KAAK;CACvC,SAAS,OAAO;EACd,MAAM,sBAAsB,OAAO,KAAK;CAC1C;AACF;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,aAAa,OAAyB;CACpD,OAAO,aAAa,uBAAO,IAAI,IAAI,GAAG,CAAC,CAAC;AAC1C;;AAGA,SAAS,aACP,OACA,WACA,MACS;CACT,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CACxD,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,MAAM,UAAU,MAAM,QAAQ,KAAK;CACnC,IAAI,CAAC,WAAW,cAAc,OAAO,aAAa,cAAc,MAAM,OAAO;CAC7E,IAAI,UAAU,IAAI,KAAK,GAErB,MAAM,IAAI,4BACR,sCAFS,KAAK,KAAK,QAAS,OAAO,QAAQ,WAAW,IAAI,IAAI,KAAK,IAAI,KAAM,CAAC,CAAC,KAAK,EAE9C,EAAG,0BAC3C;CAEF,MAAM,WAAW,OAAgB,QAAkC;EACjE,KAAK,KAAK,GAAG;EACb,IAAI;GACF,OAAO,aAAa,OAAO,WAAW,IAAI;EAC5C,UAAU;GACR,KAAK,IAAI;EACX;CACF;CACA,UAAU,IAAI,KAAK;CACnB,IAAI;EACF,IAAI,SAAS,OAAQ,MAAoB,KAAK,OAAO,UAAU,QAAQ,OAAO,KAAK,CAAC;EAEpF,OAAO,OAAO,YACZ,OAAO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AAQ,GAAG,KAAK,GAAG,MAAM,IAAI,MAAM;GACjF,IAAI,WAAW,IAAI,OAAO;EAC5B;EACA,OAAO;CACT;CACA,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,GAAG;EACjD,IAAI,CAAC,kBAAkB,GAAG,GAAG,OAAO,GAAG,KAAK,GAAG,IAAI;EACnD,MAAM,SAAS,wBAAwB,OAAO,GAAG,KAAK,GAAG,OAAO,MAAM;EACtE,IAAI,WAAW,IAAI,OAAO;CAC5B;CACA,OAAO;AACT;AAEA,SAAS,kBAAkB,OAAwB;CACjD,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS,GAAG;EACpD,MAAM,OAAO,MAAM,WAAW,KAAK;EACnC,IAAI,QAAQ,SAAU,QAAQ,OAAQ;GACpC,MAAM,OAAO,MAAM,WAAW,QAAQ,CAAC;GACvC,IAAI,EAAE,QAAQ,SAAU,QAAQ,QAAS,OAAO;GAChD,SAAS;EACX,OAAO,IAAI,QAAQ,SAAU,QAAQ,OACnC,OAAO;CAEX;CACA,OAAO;AACT;;;;;;;;;;;;;;;;;AAkBA,SAAgB,iBAAiB,MAAc,OAAuB;CACpE,IAAI,OAAO,OAAO,OAAO;CACzB,OAAO,OAAO,QAAQ,IAAI;AAC5B"}
@@ -1,4 +1,4 @@
1
- import { t as LlmClient } from "./llm-client-CdHo3SH0.js";
1
+ import { t as LlmClient } from "./llm-client-gRPgIJyz.js";
2
2
  // src/analyst/chat-client.ts
3
3
  /**
4
4
  * Provider-neutral chat contract for every model call made by agent-eval.
@@ -115,4 +115,4 @@ function openAiCompatibleClient(opts) {
115
115
  }
116
116
  export { createChatClient as n, DEFAULT_JUDGE_MODEL as t };
117
117
 
118
- //# sourceMappingURL=chat-client-DmPB31_2.js.map
118
+ //# sourceMappingURL=chat-client-DqAXFLi-.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"chat-client-DmPB31_2.js","names":[],"sources":["../src/analyst/chat-client.ts"],"sourcesContent":["/**\n * Provider-neutral chat contract for every model call made by agent-eval.\n *\n * The caller owns model execution. Evaluation code receives canonical requests\n * and results without importing a provider SDK, and agent-eval reads no\n * environment variable to find a provider credential: every transport is bound\n * at the call site.\n *\n * Two ways to bind one. `custom` and `sandbox-sdk` take a `chat` function the\n * caller wrote. `openai-compatible` takes an endpoint and a credential the\n * caller passes as values, and agent-eval issues the HTTP request itself.\n *\n * WHY THE THIRD ONE EXISTS. Every consumer that wanted a plain OpenAI-style\n * endpoint had to hand-write the same fetch loop — retry on 429 and 5xx,\n * `json_schema` degrade, fenced-JSON stripping, and, load-bearing here, the\n * `servedModel` echo that `assertServedModel` and `assertCrossFamilyServed`\n * read. A hand-written transport that omits `servedModel` makes both identity\n * checks read `unreported`, so the two-vendor judge rule they enforce silently\n * measures nothing. Measured motive: agent-eval 0.172.1 exported no such\n * transport, so a two-model judge panel in discovery-lab reached\n * `createChatClient({ transport: 'custom', baseUrl, apiKey })` — fields that\n * exist on no transport option — and every call threw\n * `TypeError: opts.chat is not a function`, which surfaced as\n * `aggregateJudgeVerdicts: all 2 judges failed`.\n *\n * The credential still never comes from agent-eval's environment. `baseUrl`\n * and the bearer are required arguments with no default and no fallback, so a\n * misconfigured caller gets a refusal at construction, never a call to an\n * endpoint it did not name.\n */\n\nimport {\n type LlmCallRequest,\n type LlmCallResult,\n LlmClient,\n type LlmClientOptions,\n} from '../llm-client'\n\n/**\n * Unified chat interface using the package's canonical LLM request and result.\n */\nexport interface ChatClient {\n /** Display name of the bound transport, included in telemetry. */\n readonly transport: ChatTransport\n /** Default model when the caller omits one. */\n readonly defaultModel?: string\n /** Total provider attempts this transport can make for one chat call. */\n readonly maximumAttempts?: number\n\n /** Implementations must enforce `req.maxTokens` when it is present. */\n chat(req: ChatRequest, opts?: ChatCallOpts): Promise<ChatResponse>\n}\n\n/** Judge model when neither caller nor client names one: one every model-restricted Router key may call. */\nexport const DEFAULT_JUDGE_MODEL = 'zai/glm-5.3'\n\nexport type ChatTransport =\n | 'sandbox-sdk' // box.streamPrompt() — chat completion via sandbox SDK\n | 'custom' // caller-adapted SDK or transport\n | 'openai-compatible' // caller-named /v1 endpoint, driven by this package\n | 'mock' // test-time injection\n\nexport interface ChatRequest extends Omit<LlmCallRequest, 'model'> {\n /** Optional — falls back to ChatClient.defaultModel. */\n model?: string\n}\n\nexport type ChatResponse = LlmCallResult\n\nexport interface ChatCallOpts {\n /** Cancel the in-flight request. */\n signal?: AbortSignal\n /** Hard USD ceiling for this single call (informational; the underlying transport may not enforce). */\n maxCostUsd?: number\n /** Correlation tag carried into request headers when the transport allows. */\n correlationId?: string\n /** Stable provider idempotency key for retries/redrives of one paid call. */\n idempotencyKey?: string\n}\n\n// ── Factory ─────────────────────────────────────────────────────────\n\nexport type CreateChatClientOpts =\n | SandboxSdkTransportOpts\n | CustomTransportOpts\n | OpenAiCompatibleTransportOpts\n | MockTransportOpts\n\ninterface BaseTransportOpts {\n defaultModel?: string\n /** Total provider attempts. Required for opaque transports used in capped runs. */\n maximumAttempts?: number\n}\n\n/**\n * Sandbox-SDK transport. The caller supplies a canonical chat function for an\n * already-configured Sandbox handle, so agent-eval does not import the SDK.\n */\nexport interface SandboxSdkTransportOpts extends BaseTransportOpts {\n transport: 'sandbox-sdk'\n chat: (req: ChatRequest, opts?: ChatCallOpts) => Promise<ChatResponse>\n}\n\n/** Caller-adapted SDK or transport returning the canonical ChatResponse shape. */\nexport interface CustomTransportOpts extends BaseTransportOpts {\n transport: 'custom'\n chat: (req: ChatRequest, opts?: ChatCallOpts) => Promise<ChatResponse>\n}\n\n/**\n * OpenAI-compatible HTTP transport: the caller names a `/v1` endpoint and\n * hands over a bearer, and this package drives `POST {baseUrl}/chat/completions`.\n *\n * Use this instead of hand-rolling a `custom` transport around `fetch`. The\n * result carries `servedModel` — the model id the provider echoed, verbatim —\n * which is the only field `assertServedModel` and `assertCrossFamilyServed`\n * can read to witness a gateway answering from a different model than the one\n * requested.\n *\n * `baseUrl` ends at the `/v1` prefix; the `/chat/completions` path is this\n * package's to append. A `baseUrl` that already carries the path is a\n * construction error, not a request to a doubled URL.\n *\n * Exactly one credential form is required — `apiKey`, `bearer`, or\n * `authHeader`. There is no environment fallback: agent-eval never goes\n * looking for a key.\n */\nexport interface OpenAiCompatibleTransportOpts\n extends BaseTransportOpts,\n Pick<\n LlmClientOptions,\n | 'assertServedModel'\n | 'customTokenPricing'\n | 'deadlineMs'\n | 'defaultTimeoutMs'\n | 'fetch'\n | 'jsonPayloadMode'\n | 'jsonSchemaTransport'\n | 'minIntervalMs'\n | 'provider'\n | 'rawSink'\n | 'signal'\n | 'thinking'\n > {\n transport: 'openai-compatible'\n /** Endpoint ending at the `/v1` prefix. Required — there is no default endpoint. */\n baseUrl: string\n /** Bearer credential. One of `apiKey`, `bearer`, or `authHeader` is required. */\n apiKey?: string\n /** Bearer credential, alternate spelling. */\n bearer?: string\n /** Non-bearer authorization header, for endpoints that want their own scheme. */\n authHeader?: { name: string; value: string }\n}\n\n/**\n * Mock transport for tests. The handler receives the request and returns\n * whatever the test wants. No retries, no JSON-schema degrade.\n */\nexport interface MockTransportOpts extends BaseTransportOpts {\n transport: 'mock'\n handler: (req: ChatRequest, opts?: ChatCallOpts) => Promise<ChatResponse>\n}\n\n/**\n * Build a ChatClient bound to a specific transport. The returned client\n * is safe to share across analysts in a single registry run.\n */\nexport function createChatClient(opts: CreateChatClientOpts): ChatClient {\n switch (opts.transport) {\n case 'sandbox-sdk':\n return {\n transport: 'sandbox-sdk',\n defaultModel: opts.defaultModel,\n maximumAttempts: opts.maximumAttempts,\n chat: async (req, callOpts) => opts.chat(resolveModel(req, opts.defaultModel), callOpts),\n }\n case 'custom':\n return {\n transport: 'custom',\n defaultModel: opts.defaultModel,\n maximumAttempts: opts.maximumAttempts,\n chat: async (req, callOpts) => opts.chat(resolveModel(req, opts.defaultModel), callOpts),\n }\n case 'openai-compatible':\n return openAiCompatibleClient(opts)\n case 'mock':\n return {\n transport: 'mock',\n defaultModel: opts.defaultModel,\n maximumAttempts: 1,\n chat: async (req, callOpts) => opts.handler(resolveModel(req, opts.defaultModel), callOpts),\n }\n }\n}\n\nfunction resolveModel(req: ChatRequest, defaultModel: string | undefined): ChatRequest {\n if (req.model) return req\n if (!defaultModel) {\n throw new Error(\n 'ChatClient.chat: no model on request and no defaultModel on the client. ' +\n 'Either pass req.model or bind defaultModel at createChatClient().',\n )\n }\n return { ...req, model: defaultModel }\n}\n\n/**\n * Build the OpenAI-compatible client, refusing a half-configured one first.\n *\n * Both refusals are construction-time on purpose. A missing credential or a\n * doubled path is a caller mistake that a request would turn into a 401 or a\n * 404 from an endpoint the caller did not intend to reach — the failure then\n * reads as a provider problem instead of a configuration one.\n */\nfunction openAiCompatibleClient(opts: OpenAiCompatibleTransportOpts): ChatClient {\n const baseUrl = opts.baseUrl?.trim().replace(/\\/+$/, '') ?? ''\n if (!baseUrl) {\n throw new Error(\n \"createChatClient({ transport: 'openai-compatible' }): baseUrl is required and has no default.\",\n )\n }\n if (/\\/chat\\/completions$/.test(baseUrl)) {\n throw new Error(\n \"createChatClient({ transport: 'openai-compatible' }): baseUrl ends at the /v1 prefix; \" +\n `this package appends /chat/completions. Got ${baseUrl}`,\n )\n }\n if (!opts.apiKey?.trim() && !opts.bearer?.trim() && !opts.authHeader) {\n throw new Error(\n \"createChatClient({ transport: 'openai-compatible' }): one of apiKey, bearer, or authHeader \" +\n 'is required. agent-eval reads no environment variable for a credential.',\n )\n }\n\n const clientOptions: LlmClientOptions = {\n baseUrl,\n ...(opts.apiKey ? { apiKey: opts.apiKey } : {}),\n ...(opts.bearer ? { bearer: opts.bearer } : {}),\n ...(opts.authHeader ? { authHeader: opts.authHeader } : {}),\n ...(opts.maximumAttempts === undefined ? {} : { maximumAttempts: opts.maximumAttempts }),\n ...(opts.assertServedModel === undefined ? {} : { assertServedModel: opts.assertServedModel }),\n ...(opts.customTokenPricing === undefined\n ? {}\n : { customTokenPricing: opts.customTokenPricing }),\n ...(opts.deadlineMs === undefined ? {} : { deadlineMs: opts.deadlineMs }),\n ...(opts.defaultTimeoutMs === undefined ? {} : { defaultTimeoutMs: opts.defaultTimeoutMs }),\n ...(opts.fetch === undefined ? {} : { fetch: opts.fetch }),\n ...(opts.jsonPayloadMode === undefined ? {} : { jsonPayloadMode: opts.jsonPayloadMode }),\n ...(opts.jsonSchemaTransport === undefined\n ? {}\n : { jsonSchemaTransport: opts.jsonSchemaTransport }),\n ...(opts.minIntervalMs === undefined ? {} : { minIntervalMs: opts.minIntervalMs }),\n ...(opts.provider === undefined ? {} : { provider: opts.provider }),\n ...(opts.rawSink === undefined ? {} : { rawSink: opts.rawSink }),\n ...(opts.signal === undefined ? {} : { signal: opts.signal }),\n ...(opts.thinking === undefined ? {} : { thinking: opts.thinking }),\n }\n const client = new LlmClient(clientOptions)\n\n return {\n transport: 'openai-compatible',\n ...(opts.defaultModel ? { defaultModel: opts.defaultModel } : {}),\n maximumAttempts: client.maximumAttempts,\n chat: async (req, callOpts) => {\n const resolved = resolveModel(req, opts.defaultModel)\n return client.call(resolved as LlmCallRequest, {\n ...(callOpts?.signal ? { signal: callOpts.signal } : {}),\n ...(callOpts?.idempotencyKey ? { idempotencyKey: callOpts.idempotencyKey } : {}),\n })\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,MAAa,sBAAsB;;;;;AAkHnC,SAAgB,iBAAiB,MAAwC;CACvE,QAAQ,KAAK,WAAb;EACE,KAAK,eACH,OAAO;GACL,WAAW;GACX,cAAc,KAAK;GACnB,iBAAiB,KAAK;GACtB,MAAM,OAAO,KAAK,aAAa,KAAK,KAAK,aAAa,KAAK,KAAK,YAAY,GAAG,QAAQ;EACzF;EACF,KAAK,UACH,OAAO;GACL,WAAW;GACX,cAAc,KAAK;GACnB,iBAAiB,KAAK;GACtB,MAAM,OAAO,KAAK,aAAa,KAAK,KAAK,aAAa,KAAK,KAAK,YAAY,GAAG,QAAQ;EACzF;EACF,KAAK,qBACH,OA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,KAAA,IAAY,CAAC,IAAI,EAAE,kBAAkB,KAAK,iBAAiB;EACzF,GAAI,KAAK,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,KAAK,MAAM;EACxD,GAAI,KAAK,oBAAoB,KAAA,IAAY,CAAC,IAAI,EAAE,iBAAiB,KAAK,gBAAgB;EACtF,GAAI,KAAK,wBAAwB,KAAA,IAC7B,CAAC,IACD,EAAE,qBAAqB,KAAK,oBAAoB;EACpD,GAAI,KAAK,kBAAkB,KAAA,IAAY,CAAC,IAAI,EAAE,eAAe,KAAK,cAAc;EAChF,GAAI,KAAK,aAAa,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU,KAAK,SAAS;EACjE,GAAI,KAAK,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,KAAK,QAAQ;EAC9D,GAAI,KAAK,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,KAAK,OAAO;EAC3D,GAAI,KAAK,aAAa,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU,KAAK,SAAS;CACnE;CACA,MAAM,SAAS,IAAI,UAAU,aAAa;CAE1C,OAAO;EACL,WAAW;EACX,GAAI,KAAK,eAAe,EAAE,cAAc,KAAK,aAAa,IAAI,CAAC;EAC/D,iBAAiB,OAAO;EACxB,MAAM,OAAO,KAAK,aAAa;GAC7B,MAAM,WAAW,aAAa,KAAK,KAAK,YAAY;GACpD,OAAO,OAAO,KAAK,UAA4B;IAC7C,GAAI,UAAU,SAAS,EAAE,QAAQ,SAAS,OAAO,IAAI,CAAC;IACtD,GAAI,UAAU,iBAAiB,EAAE,gBAAgB,SAAS,eAAe,IAAI,CAAC;GAChF,CAAC;EACH;CACF;AACF"}
1
+ {"version":3,"file":"chat-client-DqAXFLi-.js","names":[],"sources":["../src/analyst/chat-client.ts"],"sourcesContent":["/**\n * Provider-neutral chat contract for every model call made by agent-eval.\n *\n * The caller owns model execution. Evaluation code receives canonical requests\n * and results without importing a provider SDK, and agent-eval reads no\n * environment variable to find a provider credential: every transport is bound\n * at the call site.\n *\n * Two ways to bind one. `custom` and `sandbox-sdk` take a `chat` function the\n * caller wrote. `openai-compatible` takes an endpoint and a credential the\n * caller passes as values, and agent-eval issues the HTTP request itself.\n *\n * WHY THE THIRD ONE EXISTS. Every consumer that wanted a plain OpenAI-style\n * endpoint had to hand-write the same fetch loop — retry on 429 and 5xx,\n * `json_schema` degrade, fenced-JSON stripping, and, load-bearing here, the\n * `servedModel` echo that `assertServedModel` and `assertCrossFamilyServed`\n * read. A hand-written transport that omits `servedModel` makes both identity\n * checks read `unreported`, so the two-vendor judge rule they enforce silently\n * measures nothing. Measured motive: agent-eval 0.172.1 exported no such\n * transport, so a two-model judge panel in discovery-lab reached\n * `createChatClient({ transport: 'custom', baseUrl, apiKey })` — fields that\n * exist on no transport option — and every call threw\n * `TypeError: opts.chat is not a function`, which surfaced as\n * `aggregateJudgeVerdicts: all 2 judges failed`.\n *\n * The credential still never comes from agent-eval's environment. `baseUrl`\n * and the bearer are required arguments with no default and no fallback, so a\n * misconfigured caller gets a refusal at construction, never a call to an\n * endpoint it did not name.\n */\n\nimport {\n type LlmCallRequest,\n type LlmCallResult,\n LlmClient,\n type LlmClientOptions,\n} from '../llm-client'\n\n/**\n * Unified chat interface using the package's canonical LLM request and result.\n */\nexport interface ChatClient {\n /** Display name of the bound transport, included in telemetry. */\n readonly transport: ChatTransport\n /** Default model when the caller omits one. */\n readonly defaultModel?: string\n /** Total provider attempts this transport can make for one chat call. */\n readonly maximumAttempts?: number\n\n /** Implementations must enforce `req.maxTokens` when it is present. */\n chat(req: ChatRequest, opts?: ChatCallOpts): Promise<ChatResponse>\n}\n\n/** Judge model when neither caller nor client names one: one every model-restricted Router key may call. */\nexport const DEFAULT_JUDGE_MODEL = 'zai/glm-5.3'\n\nexport type ChatTransport =\n | 'sandbox-sdk' // box.streamPrompt() — chat completion via sandbox SDK\n | 'custom' // caller-adapted SDK or transport\n | 'openai-compatible' // caller-named /v1 endpoint, driven by this package\n | 'mock' // test-time injection\n\nexport interface ChatRequest extends Omit<LlmCallRequest, 'model'> {\n /** Optional — falls back to ChatClient.defaultModel. */\n model?: string\n}\n\nexport type ChatResponse = LlmCallResult\n\nexport interface ChatCallOpts {\n /** Cancel the in-flight request. */\n signal?: AbortSignal\n /** Hard USD ceiling for this single call (informational; the underlying transport may not enforce). */\n maxCostUsd?: number\n /** Correlation tag carried into request headers when the transport allows. */\n correlationId?: string\n /** Stable provider idempotency key for retries/redrives of one paid call. */\n idempotencyKey?: string\n}\n\n// ── Factory ─────────────────────────────────────────────────────────\n\nexport type CreateChatClientOpts =\n | SandboxSdkTransportOpts\n | CustomTransportOpts\n | OpenAiCompatibleTransportOpts\n | MockTransportOpts\n\ninterface BaseTransportOpts {\n defaultModel?: string\n /** Total provider attempts. Required for opaque transports used in capped runs. */\n maximumAttempts?: number\n}\n\n/**\n * Sandbox-SDK transport. The caller supplies a canonical chat function for an\n * already-configured Sandbox handle, so agent-eval does not import the SDK.\n */\nexport interface SandboxSdkTransportOpts extends BaseTransportOpts {\n transport: 'sandbox-sdk'\n chat: (req: ChatRequest, opts?: ChatCallOpts) => Promise<ChatResponse>\n}\n\n/** Caller-adapted SDK or transport returning the canonical ChatResponse shape. */\nexport interface CustomTransportOpts extends BaseTransportOpts {\n transport: 'custom'\n chat: (req: ChatRequest, opts?: ChatCallOpts) => Promise<ChatResponse>\n}\n\n/**\n * OpenAI-compatible HTTP transport: the caller names a `/v1` endpoint and\n * hands over a bearer, and this package drives `POST {baseUrl}/chat/completions`.\n *\n * Use this instead of hand-rolling a `custom` transport around `fetch`. The\n * result carries `servedModel` — the model id the provider echoed, verbatim —\n * which is the only field `assertServedModel` and `assertCrossFamilyServed`\n * can read to witness a gateway answering from a different model than the one\n * requested.\n *\n * `baseUrl` ends at the `/v1` prefix; the `/chat/completions` path is this\n * package's to append. A `baseUrl` that already carries the path is a\n * construction error, not a request to a doubled URL.\n *\n * Exactly one credential form is required — `apiKey`, `bearer`, or\n * `authHeader`. There is no environment fallback: agent-eval never goes\n * looking for a key.\n */\nexport interface OpenAiCompatibleTransportOpts\n extends BaseTransportOpts,\n Pick<\n LlmClientOptions,\n | 'assertServedModel'\n | 'customTokenPricing'\n | 'deadlineMs'\n | 'defaultTimeoutMs'\n | 'fetch'\n | 'jsonPayloadMode'\n | 'jsonSchemaTransport'\n | 'minIntervalMs'\n | 'provider'\n | 'rawSink'\n | 'signal'\n | 'thinking'\n > {\n transport: 'openai-compatible'\n /** Endpoint ending at the `/v1` prefix. Required — there is no default endpoint. */\n baseUrl: string\n /** Bearer credential. One of `apiKey`, `bearer`, or `authHeader` is required. */\n apiKey?: string\n /** Bearer credential, alternate spelling. */\n bearer?: string\n /** Non-bearer authorization header, for endpoints that want their own scheme. */\n authHeader?: { name: string; value: string }\n}\n\n/**\n * Mock transport for tests. The handler receives the request and returns\n * whatever the test wants. No retries, no JSON-schema degrade.\n */\nexport interface MockTransportOpts extends BaseTransportOpts {\n transport: 'mock'\n handler: (req: ChatRequest, opts?: ChatCallOpts) => Promise<ChatResponse>\n}\n\n/**\n * Build a ChatClient bound to a specific transport. The returned client\n * is safe to share across analysts in a single registry run.\n */\nexport function createChatClient(opts: CreateChatClientOpts): ChatClient {\n switch (opts.transport) {\n case 'sandbox-sdk':\n return {\n transport: 'sandbox-sdk',\n defaultModel: opts.defaultModel,\n maximumAttempts: opts.maximumAttempts,\n chat: async (req, callOpts) => opts.chat(resolveModel(req, opts.defaultModel), callOpts),\n }\n case 'custom':\n return {\n transport: 'custom',\n defaultModel: opts.defaultModel,\n maximumAttempts: opts.maximumAttempts,\n chat: async (req, callOpts) => opts.chat(resolveModel(req, opts.defaultModel), callOpts),\n }\n case 'openai-compatible':\n return openAiCompatibleClient(opts)\n case 'mock':\n return {\n transport: 'mock',\n defaultModel: opts.defaultModel,\n maximumAttempts: 1,\n chat: async (req, callOpts) => opts.handler(resolveModel(req, opts.defaultModel), callOpts),\n }\n }\n}\n\nfunction resolveModel(req: ChatRequest, defaultModel: string | undefined): ChatRequest {\n if (req.model) return req\n if (!defaultModel) {\n throw new Error(\n 'ChatClient.chat: no model on request and no defaultModel on the client. ' +\n 'Either pass req.model or bind defaultModel at createChatClient().',\n )\n }\n return { ...req, model: defaultModel }\n}\n\n/**\n * Build the OpenAI-compatible client, refusing a half-configured one first.\n *\n * Both refusals are construction-time on purpose. A missing credential or a\n * doubled path is a caller mistake that a request would turn into a 401 or a\n * 404 from an endpoint the caller did not intend to reach — the failure then\n * reads as a provider problem instead of a configuration one.\n */\nfunction openAiCompatibleClient(opts: OpenAiCompatibleTransportOpts): ChatClient {\n const baseUrl = opts.baseUrl?.trim().replace(/\\/+$/, '') ?? ''\n if (!baseUrl) {\n throw new Error(\n \"createChatClient({ transport: 'openai-compatible' }): baseUrl is required and has no default.\",\n )\n }\n if (/\\/chat\\/completions$/.test(baseUrl)) {\n throw new Error(\n \"createChatClient({ transport: 'openai-compatible' }): baseUrl ends at the /v1 prefix; \" +\n `this package appends /chat/completions. Got ${baseUrl}`,\n )\n }\n if (!opts.apiKey?.trim() && !opts.bearer?.trim() && !opts.authHeader) {\n throw new Error(\n \"createChatClient({ transport: 'openai-compatible' }): one of apiKey, bearer, or authHeader \" +\n 'is required. agent-eval reads no environment variable for a credential.',\n )\n }\n\n const clientOptions: LlmClientOptions = {\n baseUrl,\n ...(opts.apiKey ? { apiKey: opts.apiKey } : {}),\n ...(opts.bearer ? { bearer: opts.bearer } : {}),\n ...(opts.authHeader ? { authHeader: opts.authHeader } : {}),\n ...(opts.maximumAttempts === undefined ? {} : { maximumAttempts: opts.maximumAttempts }),\n ...(opts.assertServedModel === undefined ? {} : { assertServedModel: opts.assertServedModel }),\n ...(opts.customTokenPricing === undefined\n ? {}\n : { customTokenPricing: opts.customTokenPricing }),\n ...(opts.deadlineMs === undefined ? {} : { deadlineMs: opts.deadlineMs }),\n ...(opts.defaultTimeoutMs === undefined ? {} : { defaultTimeoutMs: opts.defaultTimeoutMs }),\n ...(opts.fetch === undefined ? {} : { fetch: opts.fetch }),\n ...(opts.jsonPayloadMode === undefined ? {} : { jsonPayloadMode: opts.jsonPayloadMode }),\n ...(opts.jsonSchemaTransport === undefined\n ? {}\n : { jsonSchemaTransport: opts.jsonSchemaTransport }),\n ...(opts.minIntervalMs === undefined ? {} : { minIntervalMs: opts.minIntervalMs }),\n ...(opts.provider === undefined ? {} : { provider: opts.provider }),\n ...(opts.rawSink === undefined ? {} : { rawSink: opts.rawSink }),\n ...(opts.signal === undefined ? {} : { signal: opts.signal }),\n ...(opts.thinking === undefined ? {} : { thinking: opts.thinking }),\n }\n const client = new LlmClient(clientOptions)\n\n return {\n transport: 'openai-compatible',\n ...(opts.defaultModel ? { defaultModel: opts.defaultModel } : {}),\n maximumAttempts: client.maximumAttempts,\n chat: async (req, callOpts) => {\n const resolved = resolveModel(req, opts.defaultModel)\n return client.call(resolved as LlmCallRequest, {\n ...(callOpts?.signal ? { signal: callOpts.signal } : {}),\n ...(callOpts?.idempotencyKey ? { idempotencyKey: callOpts.idempotencyKey } : {}),\n })\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,MAAa,sBAAsB;;;;;AAkHnC,SAAgB,iBAAiB,MAAwC;CACvE,QAAQ,KAAK,WAAb;EACE,KAAK,eACH,OAAO;GACL,WAAW;GACX,cAAc,KAAK;GACnB,iBAAiB,KAAK;GACtB,MAAM,OAAO,KAAK,aAAa,KAAK,KAAK,aAAa,KAAK,KAAK,YAAY,GAAG,QAAQ;EACzF;EACF,KAAK,UACH,OAAO;GACL,WAAW;GACX,cAAc,KAAK;GACnB,iBAAiB,KAAK;GACtB,MAAM,OAAO,KAAK,aAAa,KAAK,KAAK,aAAa,KAAK,KAAK,YAAY,GAAG,QAAQ;EACzF;EACF,KAAK,qBACH,OAAO,uBAAuB,IAAI;EACpC,KAAK,QACH,OAAO;GACL,WAAW;GACX,cAAc,KAAK;GACnB,iBAAiB;GACjB,MAAM,OAAO,KAAK,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,OAAO,KAAK,MAAM;EACxD,GAAI,KAAK,oBAAoB,KAAA,IAAY,CAAC,IAAI,EAAE,iBAAiB,KAAK,gBAAgB;EACtF,GAAI,KAAK,wBAAwB,KAAA,IAC7B,CAAC,IACD,EAAE,qBAAqB,KAAK,oBAAoB;EACpD,GAAI,KAAK,kBAAkB,KAAA,IAAY,CAAC,IAAI,EAAE,eAAe,KAAK,cAAc;EAChF,GAAI,KAAK,aAAa,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU,KAAK,SAAS;EACjE,GAAI,KAAK,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,KAAK,QAAQ;EAC9D,GAAI,KAAK,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,KAAK,OAAO;EAC3D,GAAI,KAAK,aAAa,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU,KAAK,SAAS;CACnE;CACA,MAAM,SAAS,IAAI,UAAU,aAAa;CAE1C,OAAO;EACL,WAAW;EACX,GAAI,KAAK,eAAe,EAAE,cAAc,KAAK,aAAa,IAAI,CAAC;EAC/D,iBAAiB,OAAO;EACxB,MAAM,OAAO,KAAK,aAAa;GAC7B,MAAM,WAAW,aAAa,KAAK,KAAK,YAAY;GACpD,OAAO,OAAO,KAAK,UAA4B;IAC7C,GAAI,UAAU,SAAS,EAAE,QAAQ,SAAS,OAAO,IAAI,CAAC;IACtD,GAAI,UAAU,iBAAiB,EAAE,gBAAgB,SAAS,eAAe,IAAI,CAAC;GAChF,CAAC;EACH;CACF;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { t as extractJsonPayload } from "./json-DtvZNAU9.js";
2
- import { a as maximumChargeForLlmRequest, i as costReceiptFromLlmError, r as costReceiptFromLlm } from "./llm-client-CdHo3SH0.js";
2
+ import { a as maximumChargeForLlmRequest, i as costReceiptFromLlmError, r as costReceiptFromLlm } from "./llm-client-gRPgIJyz.js";
3
3
  // src/chat-json-call.ts
4
4
  /** Parse a JSON answer out of a model response. The transport may fence it. */
5
5
  function parseJsonAnswer(response, actor) {
@@ -60,4 +60,4 @@ async function paidJsonChat(input) {
60
60
  }
61
61
  export { paidJsonChat as n, paidChat as t };
62
62
 
63
- //# sourceMappingURL=chat-json-call-Rfhu7JbJ.js.map
63
+ //# sourceMappingURL=chat-json-call-CB6sQ6sv.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"chat-json-call-Rfhu7JbJ.js","names":[],"sources":["../src/chat-json-call.ts"],"sourcesContent":["/**\n * One paid model call through a caller-owned `ChatClient`, metered by the\n * cost ledger.\n *\n * agent-eval executes no paid model: the transport is supplied by the caller\n * and the credential never enters this package. What stays here is the\n * accounting around the call — the priced maximum reserved before it runs, the\n * stable call id forwarded as the provider idempotency key, the receipt\n * settled from the response, and an honest unknown-usage receipt when the\n * transport failed.\n *\n * The judges, the wire judge endpoint, and the in-process trace-analysis\n * engine all make the same call in the same order; this is the one copy of\n * that sequence. `paidChat` is the sequence; `paidJsonChat` adds the JSON\n * answer parse that a structured caller needs.\n */\n\nimport type { ChatClient, ChatResponse } from './analyst/chat-client'\nimport type { CostChannel, CostLedgerHandle, CostReceipt, CustomTokenPricing } from './cost-ledger'\nimport {\n costReceiptFromLlm,\n costReceiptFromLlmError,\n extractJsonPayload,\n type LlmCallRequest,\n maximumChargeForLlmRequest,\n} from './llm-client'\n\ninterface PaidChatInput {\n /** Caller-owned transport. One `chat()` call. */\n chat: ChatClient\n /** The exact canonical request, including its JSON-mode or schema fields. */\n request: LlmCallRequest\n ledger: CostLedgerHandle\n channel: CostChannel\n phase: string\n actor: string\n tags?: Record<string, string>\n signal?: AbortSignal\n /** Endpoint rates used when the transport reports no billed amount. */\n pricing?: CustomTokenPricing\n}\n\ntype PaidJsonChatInput = PaidChatInput\n\ntype PaidChatResult =\n | { succeeded: true; response: ChatResponse; receipt: CostReceipt }\n | { succeeded: false; error: Error; receipt?: CostReceipt }\n\ntype PaidJsonChatResult<T> =\n | { succeeded: true; value: T; response: ChatResponse; receipt: CostReceipt }\n | { succeeded: false; error: Error; receipt?: CostReceipt }\n\n/** Parse a JSON answer out of a model response. The transport may fence it. */\nfunction parseJsonAnswer<T>(response: ChatResponse, actor: string): T {\n try {\n return JSON.parse(extractJsonPayload(response.content)) as T\n } catch (error) {\n throw new Error(\n `${actor}: model answer was not JSON — ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n}\n\n/** Reserve, execute, and settle one caller-owned chat call. */\nexport async function paidChat(input: PaidChatInput): Promise<PaidChatResult> {\n const paid = await input.ledger.runPaidCall({\n channel: input.channel,\n phase: input.phase,\n actor: input.actor,\n model: input.request.model,\n ...(input.tags && Object.keys(input.tags).length > 0 ? { tags: input.tags } : {}),\n maximumCharge: maximumChargeForLlmRequest(input.request, {\n ...(input.chat.maximumAttempts === undefined\n ? {}\n : { maximumAttempts: input.chat.maximumAttempts }),\n ...(input.pricing ? { customTokenPricing: input.pricing } : {}),\n }),\n ...(input.signal ? { signal: input.signal } : {}),\n execute: (signal, callId) => input.chat.chat(input.request, { signal, idempotencyKey: callId }),\n receipt: (response) => costReceiptFromLlm(response, input.pricing),\n receiptFromError: (error) => costReceiptFromLlmError(error, input.pricing),\n })\n if (!paid.succeeded) {\n return {\n succeeded: false,\n error: paid.error,\n ...(paid.receipt ? { receipt: paid.receipt } : {}),\n }\n }\n return { succeeded: true, response: paid.value, receipt: paid.receipt }\n}\n\nexport async function paidJsonChat<T>(input: PaidJsonChatInput): Promise<PaidJsonChatResult<T>> {\n const paid = await paidChat(input)\n if (!paid.succeeded) return paid\n // The call completed and was billed. A malformed answer is a contract\n // failure AFTER the money was spent, so it keeps the settled receipt instead\n // of reporting the spend as unknown.\n try {\n return {\n succeeded: true,\n value: parseJsonAnswer<T>(paid.response, input.actor),\n response: paid.response,\n receipt: paid.receipt,\n }\n } catch (error) {\n return {\n succeeded: false,\n error: error instanceof Error ? error : new Error(String(error)),\n receipt: paid.receipt,\n }\n }\n}\n"],"mappings":";;;;AAqDA,SAAS,gBAAmB,UAAwB,OAA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W;GACX,OAAO,gBAAmB,KAAK,UAAU,MAAM,KAAK;GACpD,UAAU,KAAK;GACf,SAAS,KAAK;EAChB;CACF,SAAS,OAAO;EACd,OAAO;GACL,WAAW;GACX,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;GAC/D,SAAS,KAAK;EAChB;CACF;AACF"}
1
+ {"version":3,"file":"chat-json-call-CB6sQ6sv.js","names":[],"sources":["../src/chat-json-call.ts"],"sourcesContent":["/**\n * One paid model call through a caller-owned `ChatClient`, metered by the\n * cost ledger.\n *\n * agent-eval executes no paid model: the transport is supplied by the caller\n * and the credential never enters this package. What stays here is the\n * accounting around the call — the priced maximum reserved before it runs, the\n * stable call id forwarded as the provider idempotency key, the receipt\n * settled from the response, and an honest unknown-usage receipt when the\n * transport failed.\n *\n * The judges, the wire judge endpoint, and the in-process trace-analysis\n * engine all make the same call in the same order; this is the one copy of\n * that sequence. `paidChat` is the sequence; `paidJsonChat` adds the JSON\n * answer parse that a structured caller needs.\n */\n\nimport type { ChatClient, ChatResponse } from './analyst/chat-client'\nimport type { CostChannel, CostLedgerHandle, CostReceipt, CustomTokenPricing } from './cost-ledger'\nimport {\n costReceiptFromLlm,\n costReceiptFromLlmError,\n extractJsonPayload,\n type LlmCallRequest,\n maximumChargeForLlmRequest,\n} from './llm-client'\n\ninterface PaidChatInput {\n /** Caller-owned transport. One `chat()` call. */\n chat: ChatClient\n /** The exact canonical request, including its JSON-mode or schema fields. */\n request: LlmCallRequest\n ledger: CostLedgerHandle\n channel: CostChannel\n phase: string\n actor: string\n tags?: Record<string, string>\n signal?: AbortSignal\n /** Endpoint rates used when the transport reports no billed amount. */\n pricing?: CustomTokenPricing\n}\n\ntype PaidJsonChatInput = PaidChatInput\n\ntype PaidChatResult =\n | { succeeded: true; response: ChatResponse; receipt: CostReceipt }\n | { succeeded: false; error: Error; receipt?: CostReceipt }\n\ntype PaidJsonChatResult<T> =\n | { succeeded: true; value: T; response: ChatResponse; receipt: CostReceipt }\n | { succeeded: false; error: Error; receipt?: CostReceipt }\n\n/** Parse a JSON answer out of a model response. The transport may fence it. */\nfunction parseJsonAnswer<T>(response: ChatResponse, actor: string): T {\n try {\n return JSON.parse(extractJsonPayload(response.content)) as T\n } catch (error) {\n throw new Error(\n `${actor}: model answer was not JSON — ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n}\n\n/** Reserve, execute, and settle one caller-owned chat call. */\nexport async function paidChat(input: PaidChatInput): Promise<PaidChatResult> {\n const paid = await input.ledger.runPaidCall({\n channel: input.channel,\n phase: input.phase,\n actor: input.actor,\n model: input.request.model,\n ...(input.tags && Object.keys(input.tags).length > 0 ? { tags: input.tags } : {}),\n maximumCharge: maximumChargeForLlmRequest(input.request, {\n ...(input.chat.maximumAttempts === undefined\n ? {}\n : { maximumAttempts: input.chat.maximumAttempts }),\n ...(input.pricing ? { customTokenPricing: input.pricing } : {}),\n }),\n ...(input.signal ? { signal: input.signal } : {}),\n execute: (signal, callId) => input.chat.chat(input.request, { signal, idempotencyKey: callId }),\n receipt: (response) => costReceiptFromLlm(response, input.pricing),\n receiptFromError: (error) => costReceiptFromLlmError(error, input.pricing),\n })\n if (!paid.succeeded) {\n return {\n succeeded: false,\n error: paid.error,\n ...(paid.receipt ? { receipt: paid.receipt } : {}),\n }\n }\n return { succeeded: true, response: paid.value, receipt: paid.receipt }\n}\n\nexport async function paidJsonChat<T>(input: PaidJsonChatInput): Promise<PaidJsonChatResult<T>> {\n const paid = await paidChat(input)\n if (!paid.succeeded) return paid\n // The call completed and was billed. A malformed answer is a contract\n // failure AFTER the money was spent, so it keeps the settled receipt instead\n // of reporting the spend as unknown.\n try {\n return {\n succeeded: true,\n value: parseJsonAnswer<T>(paid.response, input.actor),\n response: paid.response,\n receipt: paid.receipt,\n }\n } catch (error) {\n return {\n succeeded: false,\n error: error instanceof Error ? error : new Error(String(error)),\n receipt: paid.receipt,\n }\n }\n}\n"],"mappings":";;;;AAqDA,SAAS,gBAAmB,UA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GACL,WAAW;GACX,OAAO,gBAAmB,KAAK,UAAU,MAAM,KAAK;GACpD,UAAU,KAAK;GACf,SAAS,KAAK;EAChB;CACF,SAAS,OAAO;EACd,OAAO;GACL,WAAW;GACX,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;GAC/D,SAAS,KAAK;EAChB;CACF;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { s as ValidationError } from "./errors-DeEEV9Vx.js";
2
- import { i as compareCodeUnits } from "./canonical-BANK6NOj.js";
2
+ import { i as compareCodeUnits } from "./canonical-DKgL_Wby.js";
3
3
  import { r as readField } from "./predicate-BYHA4MBn.js";
4
4
  import { z } from "zod";
5
5
  // src/experiment/claim.ts
@@ -50,4 +50,4 @@ function summarizeEvaluationUnits(claim, rows) {
50
50
  }
51
51
  export { evaluationClaimSchema as n, summarizeEvaluationUnits as r, defineEvaluationClaim as t };
52
52
 
53
- //# sourceMappingURL=claim-C6LRiwz1.js.map
53
+ //# sourceMappingURL=claim-BWEXwwBk.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"claim-C6LRiwz1.js","names":[],"sources":["../src/experiment/claim.ts"],"sourcesContent":["import { z } from 'zod'\nimport { ValidationError } from '../errors'\nimport { compareCodeUnits } from '../ledger-core/canonical'\nimport type { EvidenceRecord } from './ast/evidence'\nimport { readField } from './ast/predicate'\n\nconst nonEmpty = z\n .string()\n .min(1)\n .refine((value) => value.trim() === value)\n\n/** The claim's schema, shared by every record that binds a claim. */\nexport const evaluationClaimSchema = z\n .object({\n use: z.enum(['development', 'comparison', 'certification']),\n population: z.object({ id: nonEmpty, description: nonEmpty }).strict(),\n samplingFrame: nonEmpty,\n independentUnit: nonEmpty,\n generalization: z.enum(['fixed-roster', 'new-units']),\n minimumEffect: z.number().finite().positive().optional(),\n })\n .strict()\n\n/** The population and independent observations a measured result can describe. */\nexport type EvaluationClaim = z.infer<typeof evaluationClaimSchema>\n\n/** Validate a claim before binding it to a sealed experiment or final evidence. */\nexport function defineEvaluationClaim(input: EvaluationClaim): EvaluationClaim {\n const parsed = evaluationClaimSchema.safeParse(input)\n if (!parsed.success)\n throw new ValidationError(`invalid evaluation claim: ${parsed.error.message}`)\n return Object.freeze({ ...parsed.data, population: Object.freeze(parsed.data.population) })\n}\n\nexport interface EvaluationUnitSummary {\n observations: number\n independentUnits: number\n units: Array<{ id: string; observations: number }>\n}\n\n/** Repetitions retain their denominator without becoming additional independent units. */\nexport function summarizeEvaluationUnits(\n claim: EvaluationClaim,\n rows: readonly object[],\n): EvaluationUnitSummary {\n const validated = defineEvaluationClaim(claim)\n const counts = new Map<string, number>()\n for (const [index, row] of rows.entries()) {\n if (row === null || typeof row !== 'object' || Array.isArray(row)) {\n throw new ValidationError(`evaluation claim: row ${index} must be an object`)\n }\n const value = readField(row as EvidenceRecord, validated.independentUnit)\n if (typeof value !== 'string' || !value.trim() || value.trim() !== value) {\n throw new ValidationError(\n `evaluation claim: row ${index} needs a nonempty string at '${validated.independentUnit}'`,\n )\n }\n counts.set(value, (counts.get(value) ?? 0) + 1)\n }\n return {\n observations: rows.length,\n independentUnits: counts.size,\n units: [...counts]\n .sort(([left], [right]) => compareCodeUnits(left, right))\n .map(([id, observations]) => ({ id, observations })),\n }\n}\n"],"mappings":";;;;;AAMA,MAAM,WAAW,EACd,OAAO,CAAC,CACR,IAAI,CAAC,CAAC,CACN,QAAQ,UAAU,MAAM,KAAK,MAAM,KAAK;;AAG3C,MAAa,wBAAwB,EAClC,OAAO;CACN,KAAK,EAAE,KAAK;EAAC;EAAe;EAAc;CAAe,CAAC;CAC1D,YAAY,EAAE,OAAO;EAAE,IAAI;EAAU,aAAa;CAAS,CAAC,CAAC,CAAC,OAAO;CACrE,eAAe;CACf,iBAAiB;CACjB,gBAAgB,EAAE,KAAK,CAAC,gBAAgB,WAAW,CAAC;CACpD,eAAe,EAAE,OAAO,CAAC,CAAC,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS;AACzD,CAAC,CAAC,CACD,OAAO;;AAMV,SAAgB,sBAAsB,OAAyC;CAC7E,MAAM,SAAS,sBAAsB,UAAU,KAAK;CACpD,IAAI,CAAC,OAAO,SACV,MAAM,IAAI,gBAAgB,6BAA6B,OAAO,MAAM,SAAS;CAC/E,OAAO,OAAO,OAAO;EAAE,GAAG,OAAO;EAAM,YAAY,OAAO,OAAO,OAAO,KAAK,UAAU;CAAE,CAAC;AAC5F;;AASA,SAAgB,yBACd,OACA,MACuB;CACvB,MAAM,YAAY,sBAAsB,KAAK;CAC7C,MAAM,yBAAS,IAAI,IAAoB;CACvC,KAAK,MAAM,CAAC,OAAO,QAAQ,KAAK,QAAQ,GAAG;EACzC,IAAI,QAAQ,QAAQ,OAAO,QAAQ,YAAY,MAAM,QAAQ,GAAG,GAC9D,MAAM,IAAI,gBAAgB,yBAAyB,MAAM,mBAAmB;EAE9E,MAAM,QAAQ,UAAU,KAAuB,UAAU,eAAe;EACxE,IAAI,OAAO,UAAU,YAAY,CAAC,MAAM,KAAK,KAAK,MAAM,KAAK,MAAM,OACjE,MAAM,IAAI,gBACR,yBAAyB,MAAM,+BAA+B,UAAU,gBAAgB,EAC1F;EAEF,OAAO,IAAI,QAAQ,OAAO,IAAI,KAAK,KAAK,KAAK,CAAC;CAChD;CACA,OAAO;EACL,cAAc,KAAK;EACnB,kBAAkB,OAAO;EACzB,OAAO,CAAC,GAAG,MAAM,CAAC,CACf,MAAM,CAAC,OAAO,CAAC,WAAW,iBAAiB,MAAM,KAAK,CAAC,CAAC,CACxD,KAAK,CAAC,IAAI,mBAAmB;GAAE;GAAI;EAAa,EAAE;CACvD;AACF"}
1
+ {"version":3,"file":"claim-BWEXwwBk.js","names":[],"sources":["../src/experiment/claim.ts"],"sourcesContent":["import { z } from 'zod'\nimport { ValidationError } from '../errors'\nimport { compareCodeUnits } from '../ledger-core/canonical'\nimport type { EvidenceRecord } from './ast/evidence'\nimport { readField } from './ast/predicate'\n\nconst nonEmpty = z\n .string()\n .min(1)\n .refine((value) => value.trim() === value)\n\n/** The claim's schema, shared by every record that binds a claim. */\nexport const evaluationClaimSchema = z\n .object({\n use: z.enum(['development', 'comparison', 'certification']),\n population: z.object({ id: nonEmpty, description: nonEmpty }).strict(),\n samplingFrame: nonEmpty,\n independentUnit: nonEmpty,\n generalization: z.enum(['fixed-roster', 'new-units']),\n minimumEffect: z.number().finite().positive().optional(),\n })\n .strict()\n\n/** The population and independent observations a measured result can describe. */\nexport type EvaluationClaim = z.infer<typeof evaluationClaimSchema>\n\n/** Validate a claim before binding it to a sealed experiment or final evidence. */\nexport function defineEvaluationClaim(input: EvaluationClaim): EvaluationClaim {\n const parsed = evaluationClaimSchema.safeParse(input)\n if (!parsed.success)\n throw new ValidationError(`invalid evaluation claim: ${parsed.error.message}`)\n return Object.freeze({ ...parsed.data, population: Object.freeze(parsed.data.population) })\n}\n\nexport interface EvaluationUnitSummary {\n observations: number\n independentUnits: number\n units: Array<{ id: string; observations: number }>\n}\n\n/** Repetitions retain their denominator without becoming additional independent units. */\nexport function summarizeEvaluationUnits(\n claim: EvaluationClaim,\n rows: readonly object[],\n): EvaluationUnitSummary {\n const validated = defineEvaluationClaim(claim)\n const counts = new Map<string, number>()\n for (const [index, row] of rows.entries()) {\n if (row === null || typeof row !== 'object' || Array.isArray(row)) {\n throw new ValidationError(`evaluation claim: row ${index} must be an object`)\n }\n const value = readField(row as EvidenceRecord, validated.independentUnit)\n if (typeof value !== 'string' || !value.trim() || value.trim() !== value) {\n throw new ValidationError(\n `evaluation claim: row ${index} needs a nonempty string at '${validated.independentUnit}'`,\n )\n }\n counts.set(value, (counts.get(value) ?? 0) + 1)\n }\n return {\n observations: rows.length,\n independentUnits: counts.size,\n units: [...counts]\n .sort(([left], [right]) => compareCodeUnits(left, right))\n .map(([id, observations]) => ({ id, observations })),\n }\n}\n"],"mappings":";;;;;AAMA,MAAM,WAAW,EACd,OAAO,CAAC,CACR,IAAI,CAAC,CAAC,CACN,QAAQ,UAAU,MAAM,KAAK,MAAM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,OAAO,CAAC,WAAW,iBAAiB,MAAM,KAAK,CAAC,CAAC,CACxD,KAAK,CAAC,IAAI,mBAAmB;GAAE;GAAI;EAAa,EAAE;CACvD;AACF"}
package/dist/cli.js CHANGED
@@ -1,16 +1,16 @@
1
1
  #!/usr/bin/env node
2
2
  import { c as errorMessage } from "./errors-DeEEV9Vx.js";
3
- import { i as replaySearchLedgerText } from "./search-ledger-oyqxZhry.js";
4
- import { l as operatorYield, u as INSUFFICIENT_FROM } from "./pareto-BNWWbLNl.js";
5
- import { t as renderSearchSummary } from "./search-summary-CNHpHFfw.js";
6
- import { l as SEARCH_LEDGER_BATCH_MAX_BYTES, m as SearchRunKindSchema, r as shipSearchLedger, s as hostedTenantFromEnv, t as SearchShipConflictError } from "./search-shipper-BwqeQ61l.js";
7
- import { n as createChatClient } from "./chat-client-DmPB31_2.js";
8
- import { a as privacyHit, f as appendRolloutLines, n as runRolloutReleaseCli, r as PRIVACY_RULE_NAMES, u as gateReceiptRolloutLines } from "./hf-dataset-kthWy7xl.js";
9
- import { i as harnessSessionRolloutLines, n as harnessSessionRefs } from "./harness-session-lines-Fd5aeSDV.js";
10
- import { t as runAnalystBenchmarkCommand } from "./benchmark-command-CJw3ijDV.js";
11
- import { i as buildOpenApi, l as handleVersion, o as runRpcBatch, r as startServerAsync, s as runRpcOnce } from "./server-DnoEi4Sb.js";
12
- import { b as editCreditText, f as landscape, g as surfaceTextEdits, l as metaSearch, m as formatLandscape, n as taskMatrix, o as skillManifold, r as formatSkillManifold, s as renderMetaSearchText, t as tree, v as front, y as editCredit } from "./tree-0r6gPODs.js";
13
- import { a as analyzeSupervisorRun, i as renderSupervisorRunMarkdown, r as renderSupervisorRunHeadline, t as runtimeRunRolloutLines } from "./runtime-rollouts-CALol_Y4.js";
3
+ import { i as replaySearchLedgerText } from "./search-ledger-C7t68cmy.js";
4
+ import { l as operatorYield, u as INSUFFICIENT_FROM } from "./pareto-Bg75Gajo.js";
5
+ import { t as renderSearchSummary } from "./search-summary-B1x1Vmzh.js";
6
+ import { l as SEARCH_LEDGER_BATCH_MAX_BYTES, m as SearchRunKindSchema, r as shipSearchLedger, s as hostedTenantFromEnv, t as SearchShipConflictError } from "./search-shipper-CmDW9dU6.js";
7
+ import { n as createChatClient } from "./chat-client-DqAXFLi-.js";
8
+ import { a as privacyHit, f as appendRolloutLines, n as runRolloutReleaseCli, r as PRIVACY_RULE_NAMES, u as gateReceiptRolloutLines } from "./hf-dataset-B0s2ZAhQ.js";
9
+ import { i as harnessSessionRolloutLines, n as harnessSessionRefs } from "./harness-session-lines-CSxKR6no.js";
10
+ import { t as runAnalystBenchmarkCommand } from "./benchmark-command-XLXa7I98.js";
11
+ import { i as buildOpenApi, l as handleVersion, o as runRpcBatch, r as startServerAsync, s as runRpcOnce } from "./server-BxHJyclG.js";
12
+ import { b as editCreditText, f as landscape, g as surfaceTextEdits, l as metaSearch, m as formatLandscape, n as taskMatrix, o as skillManifold, r as formatSkillManifold, s as renderMetaSearchText, t as tree, v as front, y as editCredit } from "./tree-DQMlcNFI.js";
13
+ import { a as analyzeSupervisorRun, i as renderSupervisorRunMarkdown, r as renderSupervisorRunHeadline, t as runtimeRunRolloutLines } from "./runtime-rollouts-DdUijr_t.js";
14
14
  import { createHash } from "node:crypto";
15
15
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
16
16
  import { dirname, join, resolve } from "node:path";
@@ -1,4 +1,4 @@
1
- import { A as SearchLedgerHash, O as SearchLedgerEntry } from "./search-ledger-types-qiYRUo_N.js";
1
+ import { A as SearchLedgerHash, O as SearchLedgerEntry } from "./search-ledger-types-BhZE848w.js";
2
2
  import { z } from "zod";
3
3
  /** At most this many UTF-8 bytes across one request's lines. A single line
4
4
  * larger than this cannot be shipped. */
@@ -214,4 +214,4 @@ declare function hostedClientFromEnv(overrides?: Partial<HostedTenant> & {
214
214
  env?: Record<string, string | undefined>;
215
215
  }): HostedClient | undefined;
216
216
  export { SearchLedgerConflictSchema as C, admitSearchLedgerBatch as D, SearchRunKind as E, SearchLedgerConflict as S, SearchLedgerHeadSchema as T, SEARCH_LEDGER_BATCH_MAX_BYTES as _, hostedClientFromEnv as a, SearchBlobPutResponseSchema as b, HostedIngestHeaders as c, IngestTracesRequest as d, TraceSpanEvent as f, IngestSearchLedgerRequestSchema as g, IngestSearchLedgerRequest as h, createHostedClient as i, HostedWireVersion as l, AdmitSearchLedgerBatchInput as m, HostedTenant as n, hostedTenantFromEnv as o, UnixNanoTimestamp as p, SearchLedgerIngestOutcome as r, HOSTED_WIRE_VERSION as s, HostedClient as t, IngestResponse as u, SEARCH_LEDGER_INGEST_PATH as v, SearchLedgerHead as w, SearchLedgerBatchAdmission as x, SearchBlobPutResponse as y };
217
- //# sourceMappingURL=client-BIFwUg7I.d.ts.map
217
+ //# sourceMappingURL=client-DUMIaMob.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"client-BIFwUg7I.d.ts","names":[],"sources":["../src/hosted/search-ledger-wire.ts","../src/hosted/types.ts","../src/hosted/client.ts"],"mappings":";;;;cAqCa;cAEA;;cAsBA,qBAAmB,EAAA;;;;KACpB,gBAAgB,EAAE,aAAa;;;cAI9B,wBAAsB,EAAA;;;;GAM/B,EAAA,KAAA;KACQ,mBAAmB,EAAE,aAAa;cAEjC,iCAA+B,EAAA;;;;;;;;;GAkBxC,EAAA,KAAA;KACQ,4BAA4B,EAAE,aAAa;;cAG1C,4BAA0B,EAAA;;;;;;;;;;;GAM5B,EAAA,KAAA;KACC,uBAAuB,EAAE,aAAa;;;cAIrC,6BAA2B,EAAA;;;;;;;;GAM7B,EAAA,KAAA;KACC,wBAAwB,EAAE,aAAa;KA+BvC;EAEN;;EAEA,SAAS;EACT;;EAEA,MAAM;;EAEN;EAAoB,UAAU;;UAEnB;EACf,SAAS;;EAET,MAAM;;EAEN,gBAAgB,mBAAmB;;;;;;;;iBASrB,uBACd,OAAO,8BACN;;;;;;;;;;;;;;;;;;;;;;;cCtJU;KACD,2BAA2B;;UAKtB;;EAEf;;EAEA;;EAEA,yBAAyB;;EAEzB;;;;;;KASU;;;;;;UAOK;EACf;EACA;EACA;EACA;EACA,mBAAmB;EACnB,iBAAiB;EACjB,YAAY;EACZ,SAAS;IACP,cAAc;IACd;IACA,aAAa;;EAEf;IAAW;IAAgC;;;EAE3C;;EAEA;;EAEA;;EAEA;;UAKe;EACf,aAAa;EACb,OAAO;;UAGQ;;EAEf;;EAEA,UAAU;IAAQ;IAAe;;;UC7ClB;;EAEf;;EAEA;;EAEA;;EAEA,mBAAmB;;EAEnB;;EAEA;;;KAIU;EACN;EAAoB,MAAM;;EAC1B;EAAoB,UAAU;;UAEnB;EACf,aAAa,OAAO,kBAAkB,0BAA0B,QAAQ;;EAExE,iBAAiB,kBAAkB,SAAS,cAAc,QAAQ;EAClE,mBACE,SAAS,2BACT,SAAS,cACR,QAAQ;EACX,cACE,4BACA,OAAO,WAAW,cAClB,qBACA,SAAS,cACR,QAAQ;WACF,QAAQ;WACR,aAAa;;iBA8IR,mBAAmB,QAAQ,eAAe;;;;;;;;;;iBAqG1C,oBACd,YAAW,QAAQ;EAAkB,MAAM;IAC1C;;;iBAmBa,oBACd,YAAW,QAAQ;EAAkB,MAAM;IAC1C"}
1
+ {"version":3,"file":"client-DUMIaMob.d.ts","names":[],"sources":["../src/hosted/search-ledger-wire.ts","../src/hosted/types.ts","../src/hosted/client.ts"],"mappings":";;;;cAqCa;cAEA;;cAsBA,qBAAmB,EAAA;;;;KACpB,gBAAgB,EAAE,aAAa;;;cAI9B,wBAAsB,EAAA;;;;GAM/B,EAAA,KAAA;KACQ,mBAAmB,EAAE,aAAa;cAEjC,iCAA+B,EAAA;;;;;;;;;GAkBxC,EAAA,KAAA;KACQ,4BAA4B,EAAE,aAAa;;cAG1C,4BAA0B,EAAA;;;;;;;;;;;GAM5B,EAAA,KAAA;KACC,uBAAuB,EAAE,aAAa;;;cAIrC,6BAA2B,EAAA;;;;;;;;GAM7B,EAAA,KAAA;KACC,wBAAwB,EAAE,aAAa;KA+BvC;EAEN;;EAEA,SAAS;EACT;;EAEA,MAAM;;EAEN;EAAoB,UAAU;;UAEnB;EACf,SAAS;;EAET,MAAM;;EAEN,gBAAgB,mBAAmB;;;;;;;;iBASrB,uBACd,OAAO,8BACN;;;;;;;;;;;;;;;;;;;;;;;cCtJU;KACD,2BAA2B;;UAKtB;;EAEf;;EAEA;;EAEA,yBAAyB;;EAEzB;;;;;;KASU;;;;;;UAOK;EACf;EACA;EACA;EACA;EACA,mBAAmB;EACnB,iBAAiB;EACjB,YAAY;EACZ,SAAS;IACP,cAAc;IACd;IACA,aAAa;;EAEf;IAAW;IAAgC;;;EAE3C;;EAEA;;EAEA;;EAEA;;UAKe;EACf,aAAa;EACb,OAAO;;UAGQ;;EAEf;;EAEA,UAAU;IAAQ;IAAe;;;UC7ClB;;EAEf;;EAEA;;EAEA;;EAEA,mBAAmB;;EAEnB;;EAEA;;;KAIU;EACN;EAAoB,MAAM;;EAC1B;EAAoB,UAAU;;UAEnB;EACf,aAAa,OAAO,kBAAkB,0BAA0B,QAAQ;;EAExE,iBAAiB,kBAAkB,SAAS,cAAc,QAAQ;EAClE,mBACE,SAAS,2BACT,SAAS,cACR,QAAQ;EACX,cACE,4BACA,OAAO,WAAW,cAClB,qBACA,SAAS,cACR,QAAQ;WACF,QAAQ;WACR,aAAa;;iBA8IR,mBAAmB,QAAQ,eAAe;;;;;;;;;;iBAqG1C,oBACd,YAAW,QAAQ;EAAkB,MAAM;IAC1C;;;iBAmBa,oBACd,YAAW,QAAQ;EAAkB,MAAM;IAC1C"}
@@ -1 +1 @@
1
- {"version":3,"file":"cluster-CSd0LE_M.d.ts","names":[],"sources":["../src/judge-families.ts","../src/integrity/served-model.ts","../src/trace/raw-provider-sink.ts","../src/llm-client/contract.ts","../src/analyst/chat-client.ts","../src/types.ts","../src/statistics/cluster.ts"],"mappings":";;;;;;;;;;;;KAWY;;;;;;;iBAsEI,YAAY,kBAAkB;UAc7B;;EAEf;;;;EAIA;;cAGW,yBAAyB;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;;KAGC,WAAW,MAAM,YAAY,OAAO,eAAe,QAAQ;UAMtD;EACf;EACA;EACA;EACA;;cC5NW;KACD;EAAsB;EAAa;EAAc;EAAmB;;UAC/D,uBAAuB;EACtC;EACA;EACA;;EAEA,UAAU,MAAM,GAAG;;;iBAIL,iBAAiB,GAC/B,gBAAgB,KAChB,UAAU,MAAM,GAAG,0BACnB,YAAY,QAAQ,kBAElB,WACA,MACA,OACA,WACC,uBAAuB,KACzB;UA2Cc,mBAAmB;;EAElC,YAAY,KAAK;EACjB,UAAU,KAAK;;EAEf,YAAY,QAAQ,KAAK,OAAO;EAChC;EACA;;EAEA;;EAEA;;UAEe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;iBAGc,YAAY,GAC1B,kBAAkB,KAClB,SAAS,mBAAmB,KAC3B"}
1
+ {"version":3,"file":"cluster-CSd0LE_M.d.ts","names":[],"sources":["../src/judge-families.ts","../src/integrity/served-model.ts","../src/trace/raw-provider-sink.ts","../src/llm-client/contract.ts","../src/analyst/chat-client.ts","../src/types.ts","../src/statistics/cluster.ts"],"mappings":";;;;;;;;;;;;KAWY;;;;;;;iBAsEI,YAAY,kBAAkB;UAc7B;;EAEf;;;;EAIA;;cAGW,yBAAyB;WAGlB,UAAU;WACV;EAFhB,YAAA,iBACgB,UAAU,eACV;;;;;;;;;;;;;;;iBAoBJ,kBACd,kBACA,OAAM,2BACL;;KCtFS;;;;;;;;;;;UAYK;;EAEf;;EAEA;EACA,iBAAiB;;EAEjB,cAAc;EACd,SAAS;;EAET;;;;;;;;;;;;iBAuDc,iBACd,mBACA,oCACC;cAkDU,+BAA+B;WAGxB,QAAQ,cAAc;EADtC,YAAA,iBACgB,QAAQ,cAAc;;;;;;;;;KAc9B;UAWK;;;;;;EAMf;;;;;EAKA;;EAEA;;;iBA0Bc,yBAAyB,OAAO;;;;;;iBAchC,kBACd,mBACA,mCACA,OAAM,2BACL;;;;;iBAea,mBACd,OAAO;EAAgB;EAAmB;IA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iBAGc,YAAY,GAC1B,kBAAkB,KAClB,SAAS,mBAAmB,KAC3B"}
@@ -1,5 +1,5 @@
1
1
  import { s as ValidationError } from "./errors-DeEEV9Vx.js";
2
- import { vt as seedFromData, xt as clusterBootstrap } from "./statistics-CHs0jlsY.js";
2
+ import { vt as seedFromData, xt as clusterBootstrap } from "./statistics-DSidA5I2.js";
3
3
  // src/meta-eval/cluster-bootstrap.ts
4
4
  /** Observation-weighted mean through the shared stratified cluster bootstrap. */
5
5
  function clusterBootstrapMean(observations, options = {}) {
@@ -21,4 +21,4 @@ function clusterBootstrapMean(observations, options = {}) {
21
21
  }
22
22
  export { clusterBootstrapMean as t };
23
23
 
24
- //# sourceMappingURL=cluster-bootstrap-ClPYIWoX.js.map
24
+ //# sourceMappingURL=cluster-bootstrap-DPzVy3_K.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"cluster-bootstrap-ClPYIWoX.js","names":[],"sources":["../src/meta-eval/cluster-bootstrap.ts"],"sourcesContent":["import { ValidationError } from '../errors'\nimport { clusterBootstrap } from '../statistics/cluster'\nimport { seedFromData } from '../statistics/internal'\n\n/** One observation and the source cluster it belongs to. */\nexport interface ClusteredObservation {\n cluster: string\n value: number\n stratum?: string\n}\n\nexport interface ClusterBootstrapOptions {\n /** Confidence level. Default 0.95. */\n confidence?: number\n /** Bootstrap resample count. Default 2000. */\n resamples?: number\n /** Deterministic seed. If omitted, derived from the values for reproducible intervals. */\n seed?: number\n}\n\nexport interface ClusterBootstrapResult {\n n: number\n clusters: number\n /** Mean over observations, each observation weighted equally. */\n mean: number\n low: number\n high: number\n confidence: number\n resamples: number\n}\n\n/** Observation-weighted mean through the shared stratified cluster bootstrap. */\nexport function clusterBootstrapMean(\n observations: readonly ClusteredObservation[],\n options: ClusterBootstrapOptions = {},\n): ClusterBootstrapResult {\n if (\n !observations.length ||\n (options.resamples !== undefined &&\n (!Number.isSafeInteger(options.resamples) || options.resamples < 1))\n ) {\n throw new ValidationError('clusterBootstrapMean: requires observations and positive resamples')\n }\n if (observations.some((row) => !Number.isFinite(row.value))) {\n throw new ValidationError('clusterBootstrapMean: value must be finite')\n }\n const confidence = options.confidence ?? 0.95\n const mean = (rows: readonly ClusteredObservation[]) =>\n rows.reduce((sum, row) => sum + row.value, 0) / rows.length\n return {\n ...clusterBootstrap(observations, (row) => row.cluster, mean, {\n level: confidence,\n seed: options.seed ?? seedFromData([observations.map((row) => row.value)]),\n ...(options.resamples === undefined ? {} : { resamples: options.resamples }),\n strata: (row) => row.stratum ?? '',\n }),\n n: observations.length,\n mean: mean(observations),\n confidence,\n }\n}\n"],"mappings":";;;;AAgCA,SAAgB,qBACd,cACA,UAAmC,CAAC,GACZ;CACxB,IACE,CAAC,aAAa,UACb,QAAQ,cAAc,KAAA,MACpB,CAAC,OAAO,cAAc,QAAQ,SAAS,KAAK,QAAQ,YAAY,IAEnE,MAAM,IAAI,gBAAgB,oEAAoE;CAEhG,IAAI,aAAa,MAAM,QAAQ,CAAC,OAAO,SAAS,IAAI,KAAK,CAAC,GACxD,MAAM,IAAI,gBAAgB,4CAA4C;CAExE,MAAM,aAAa,QAAQ,cAAc;CACzC,MAAM,QAAQ,SACZ,KAAK,QAAQ,KAAK,QAAQ,MAAM,IAAI,OAAO,CAAC,IAAI,KAAK;CACvD,OAAO;EACL,GAAG,iBAAiB,eAAe,QAAQ,IAAI,SAAS,MAAM;GAC5D,OAAO;GACP,MAAM,QAAQ,QAAQ,aAAa,CAAC,aAAa,KAAK,QAAQ,IAAI,KAAK,CAAC,CAAC;GACzE,GAAI,QAAQ,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW,QAAQ,UAAU;GAC1E,SAAS,QAAQ,IAAI,WAAW;EAClC,CAAC;EACD,GAAG,aAAa;EAChB,MAAM,KAAK,YAAY;EACvB;CACF;AACF"}
1
+ {"version":3,"file":"cluster-bootstrap-DPzVy3_K.js","names":[],"sources":["../src/meta-eval/cluster-bootstrap.ts"],"sourcesContent":["import { ValidationError } from '../errors'\nimport { clusterBootstrap } from '../statistics/cluster'\nimport { seedFromData } from '../statistics/internal'\n\n/** One observation and the source cluster it belongs to. */\nexport interface ClusteredObservation {\n cluster: string\n value: number\n stratum?: string\n}\n\nexport interface ClusterBootstrapOptions {\n /** Confidence level. Default 0.95. */\n confidence?: number\n /** Bootstrap resample count. Default 2000. */\n resamples?: number\n /** Deterministic seed. If omitted, derived from the values for reproducible intervals. */\n seed?: number\n}\n\nexport interface ClusterBootstrapResult {\n n: number\n clusters: number\n /** Mean over observations, each observation weighted equally. */\n mean: number\n low: number\n high: number\n confidence: number\n resamples: number\n}\n\n/** Observation-weighted mean through the shared stratified cluster bootstrap. */\nexport function clusterBootstrapMean(\n observations: readonly ClusteredObservation[],\n options: ClusterBootstrapOptions = {},\n): ClusterBootstrapResult {\n if (\n !observations.length ||\n (options.resamples !== undefined &&\n (!Number.isSafeInteger(options.resamples) || options.resamples < 1))\n ) {\n throw new ValidationError('clusterBootstrapMean: requires observations and positive resamples')\n }\n if (observations.some((row) => !Number.isFinite(row.value))) {\n throw new ValidationError('clusterBootstrapMean: value must be finite')\n }\n const confidence = options.confidence ?? 0.95\n const mean = (rows: readonly ClusteredObservation[]) =>\n rows.reduce((sum, row) => sum + row.value, 0) / rows.length\n return {\n ...clusterBootstrap(observations, (row) => row.cluster, mean, {\n level: confidence,\n seed: options.seed ?? seedFromData([observations.map((row) => row.value)]),\n ...(options.resamples === undefined ? {} : { resamples: options.resamples }),\n strata: (row) => row.stratum ?? '',\n }),\n n: observations.length,\n mean: mean(observations),\n confidence,\n }\n}\n"],"mappings":";;;;AAgCA,SAAgB,qBACd,cACA,UAAmC,CAAC,GACZ;CACxB,IACE,CAAC,aAAa,UACb,QAAQ,cAAc,KAAA,MACpB,CAAC,OAAO,cAAc,QAAQ,SAAS,KAAK,QAAQ,YAAY,IAEnE,MAAM,IAAI,gBAAgB,oEAAoE;CAEhG,IAAI,aAAa,MAAM,QAAQ,CAAC,OAAO,SAAS,IAAI,KAAK,CAAC,GACxD,MAAM,IAAI,gBAAgB,4CAA4C;CAExE,MAAM,aAAa,QAAQ,cAAc;CACzC,MAAM,QAAQ,SACZ,KAAK,QAAQ,KAAK,QAAQ,MAAM,IAAI,OAAO,CAAC,IAAI,KAAK;CACvD,OAAO;EACL,GAAG,iBAAiB,eAAe,QAAQ,IAAI,SAAS,MAAM;GAC5D,OAAO;GACP,MAAM,QAAQ,QAAQ,aAAa,CAAC,aAAa,KAAK,QAAQ,IAAI,KAAK,CAAC,CAAC;GACzE,GAAI,QAAQ,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW,QAAQ,UAAU;GAC1E,SAAS,QAAQ,IAAI,WAAW;EAClC,CAAC;EACD,GAAG,aAAa;EAChB,MAAM,KAAK,YAAY;EACvB;CACF;AACF"}
@@ -1,9 +1,9 @@
1
- import { r as assertServedModel, t as ModelSubstitutionError } from "./served-model-qhLmbutL.js";
1
+ import { r as assertServedModel, t as ModelSubstitutionError } from "./served-model-BXmeKm7D.js";
2
2
  import { t as CostLedger } from "./cost-ledger-1CwUnVOd.js";
3
- import { n as recoverTruncatedJson } from "./json-recovery-b7O9WVTF.js";
4
- import { t as certificationEvidenceDigest } from "./verdict-CKo1iZkI.js";
5
- import { a as maximumChargeForLlmRequest, i as costReceiptFromLlmError, r as costReceiptFromLlm } from "./llm-client-CdHo3SH0.js";
6
- import "./chat-client-DmPB31_2.js";
3
+ import { n as recoverTruncatedJson } from "./json-recovery-BRUCeQxo.js";
4
+ import { t as certificationEvidenceDigest } from "./verdict-5PVtsWT_.js";
5
+ import { a as maximumChargeForLlmRequest, i as costReceiptFromLlmError, r as costReceiptFromLlm } from "./llm-client-gRPgIJyz.js";
6
+ import "./chat-client-DqAXFLi-.js";
7
7
  import { t as JudgeParseError } from "./judges-BLxg5p8E.js";
8
8
  import { randomUUID } from "node:crypto";
9
9
  // src/completion-verifier.ts
@@ -387,4 +387,4 @@ function createLlmCorrectnessChecker(chat, opts = {}) {
387
387
  }
388
388
  export { createLlmCorrectnessChecker as n, verifyCompletion as r, completionVerdict as t };
389
389
 
390
- //# sourceMappingURL=completion-verifier-C3q1T96h.js.map
390
+ //# sourceMappingURL=completion-verifier-DiG3y43g.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"completion-verifier-C3q1T96h.js","names":[],"sources":["../src/completion-verifier.ts"],"sourcesContent":["/**\n * Completion verifier — the task-completion oracle.\n *\n * Answers the only eval question that is not a proxy: did the agent actually\n * COMPLETE the task — produce every required deliverable, persisted and\n * correct — rather than describe what should be done. A fluent transcript\n * that never produces the artifact scores zero here.\n *\n * Per requirement, a two-stage check:\n * 1. Structural — a produced item (vault artifact / approved proposal /\n * tool call) of the right kind is matched against the requirement and\n * carries non-empty content. Deterministic; no LLM.\n * 2. Correctness — only if structurally present AND the matched item\n * carries content, one targeted check decides whether that item\n * actually fulfils the requirement. A hallucinated artifact fails here;\n * an absent one already failed stage 1.\n *\n * `completionRate` is satisfied / MEASURABLE requirements (unmeasured rows —\n * checker failures — are excluded from the denominator, never scored as\n * zeros). Quality dimensions are meaningless on an incomplete task — callers\n * gate on `fullyComplete` / `completionRate` before scoring quality.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { type ChatClient, type ChatRequest, DEFAULT_JUDGE_MODEL } from './analyst/chat-client'\nimport type { ValidatedArtifact } from './artifact-validator'\nimport { CostLedger, type CostLedgerHandle } from './cost-ledger'\nimport { assertServedModel, ModelSubstitutionError } from './integrity/served-model'\nimport { recoverTruncatedJson } from './json-recovery'\nimport { JudgeParseError } from './judges'\nimport {\n costReceiptFromLlm,\n costReceiptFromLlmError,\n maximumChargeForLlmRequest,\n} from './llm-client'\nimport type { RawProviderEvent, RawProviderSink } from './trace/raw-provider-sink'\nimport {\n certificationEvidenceDigest,\n type DefaultVerdict,\n type VerdictCertification,\n} from './verdict'\nimport type { CheckerIdentity, VerificationStrategySource } from './verification-strategy'\n\n/** What kind of produced state can satisfy a requirement structurally. */\nexport type SatisfiedBy = 'artifact' | 'proposal' | 'tool-call' | 'any'\n\nexport interface CompletionRequirement {\n /** Stable id from the task gold (e.g. a persona's `expected_requirements[].req_id`). */\n reqId: string\n /** Human-readable description of the required deliverable. */\n title: string\n /** Optional kind/category hint, matched against a produced item's kind. */\n category?: string\n /** What produced state satisfies this requirement. Defaults to 'any'. */\n satisfiedBy?: SatisfiedBy\n}\n\nexport interface TaskGold {\n taskId: string\n requirements: CompletionRequirement[]\n}\n\nexport interface ProducedProposal {\n id: string\n title: string\n status: 'pending' | 'approved' | 'rejected'\n /** Optional persisted body — when present, enables a correctness check. */\n content?: string\n}\n\n/** Everything observable about what a run actually produced. */\nexport interface ProducedState {\n /** Persisted vault artifacts. Reuses the shared `ValidatedArtifact` shape. */\n artifacts: ValidatedArtifact[]\n /** Proposals / filings the agent created. */\n proposals: ProducedProposal[]\n /** Names of tools the agent invoked. */\n toolCalls: string[]\n}\n\nexport interface RequirementCheck {\n reqId: string\n title: string\n /** A produced item of the right kind matched the requirement, non-empty. */\n structurallyPresent: boolean\n /**\n * Whether the matched item actually fulfils the requirement. `null` when\n * not structurally present, when the matched item carries no content\n * to assess, or when the correctness check itself failed (`unmeasured`).\n */\n correct: boolean | null\n /** structurallyPresent && !unmeasured && correct !== false. */\n satisfied: boolean\n /**\n * Set when the correctness check itself errored (LLM call failure or an\n * unparseable response after retry). The requirement's fulfilment is\n * UNKNOWN — `correct` stays null, `satisfied` is false, and\n * `completionVerdict` excludes the row from `completionRate`'s\n * denominator. Never folded into a zero: a synthetic zero is\n * indistinguishable from a real failure (see `JudgeParseError`).\n */\n unmeasured?: true\n /** Why the correctness check could not be measured (present iff `unmeasured`). */\n unmeasuredReason?: string\n /** Human-readable evidence for the verdict. */\n evidence: string[]\n}\n\n/** Extends the substrate verdict spine: `valid` = `fullyComplete` and\n * `score` = `completionRate` — derived in `completionVerdict()`, the one\n * place those equalities hold by construction. */\nexport interface CompletionVerdict extends DefaultVerdict {\n taskId: string\n requirements: RequirementCheck[]\n /** satisfied / MEASURABLE requirements (unmeasured rows leave the denominator). */\n completionRate: number\n /** Every measurable requirement satisfied (false when anything is unmeasured). */\n fullyComplete: boolean\n /** Requirements whose correctness check errored — reported, never scored as zero. */\n unmeasuredCount: number\n}\n\n/**\n * Construct a `CompletionVerdict` from the per-requirement checks, deriving\n * `completionRate` / `fullyComplete` and the spine fields (`valid` =\n * `fullyComplete`, `score` = `completionRate`) in one place. Throws on zero\n * requirements — a verdict over nothing is a misconfiguration, mirroring\n * `verifyCompletion`'s gold-spec guard.\n */\nexport function completionVerdict(input: {\n taskId: string\n requirements: RequirementCheck[]\n /** What certified the correctness stage, when anything did. Omitted =\n * an uncertified verdict — the honest default for a bare checker. */\n certification?: VerdictCertification\n}): CompletionVerdict {\n if (input.requirements.length === 0) {\n throw new Error(\n `completionVerdict: task '${input.taskId}' has no requirement checks — nothing to derive a verdict from`,\n )\n }\n const measurable = input.requirements.filter((r) => !r.unmeasured)\n const unmeasuredCount = input.requirements.length - measurable.length\n if (measurable.length === 0) {\n // Every check errored: this is an infrastructure failure, not a scored\n // run. A 0-rate verdict here would be a fabricated measurement.\n throw new Error(\n `completionVerdict: task '${input.taskId}' has no measurable requirements — all ${input.requirements.length} correctness checks failed (${input.requirements[0]?.unmeasuredReason ?? 'unknown reason'})`,\n )\n }\n const satisfiedCount = measurable.filter((r) => r.satisfied).length\n const completionRate = satisfiedCount / measurable.length\n // A run with unmeasured rows can still report a rate over what WAS\n // measured, but must not claim full completion.\n const fullyComplete = unmeasuredCount === 0 && satisfiedCount === measurable.length\n return {\n taskId: input.taskId,\n requirements: input.requirements,\n completionRate,\n fullyComplete,\n unmeasuredCount,\n valid: fullyComplete,\n score: completionRate,\n ...(input.certification === undefined ? {} : { certification: input.certification }),\n }\n}\n\n/**\n * What a correctness checker declares about itself so the completion\n * verdict can carry a certification: which strategy member it discharges,\n * its exact identity, and the steps its answers rest on unverified.\n */\nexport interface CorrectnessCheckerAttestation {\n strategy: VerificationStrategySource\n checker: CheckerIdentity\n assumptions: string[]\n}\n\n/**\n * Decides whether a produced item's content actually fulfils a requirement.\n * Injected so the structural verifier stays pure and unit-testable; the\n * production implementation is `createLlmCorrectnessChecker`.\n *\n * `attestation` is optional metadata on the function value: a checker that\n * carries one yields certified completion verdicts; a bare function yields\n * the same verdict uncertified. A plain arrow function remains a valid\n * checker.\n */\nexport interface CorrectnessChecker {\n (\n requirement: CompletionRequirement,\n content: string,\n ): Promise<{ correct: boolean; reason: string }>\n attestation?: CorrectnessCheckerAttestation\n}\n\nconst STOPWORDS = new Set([\n 'the',\n 'a',\n 'an',\n 'of',\n 'for',\n 'and',\n 'or',\n 'to',\n 'in',\n 'on',\n 'with',\n 'by',\n])\n\n// Deliverable-FORM vocabulary — words that name the SHAPE of an output, not its\n// domain content. A correct \"swap-comparison view persisted as a ui/** artifact\"\n// is an OpenUI JSON whose body says nothing about \"artifact\" / \"persisted\" /\n// \"view\"; the discriminative tokens are the domain nouns (swap, comparison).\n// Stripped from the REQUIREMENT side of structural recall so a deliverable is\n// matched on what it IS about, not on the boilerplate describing its form. The\n// correctness checker strips the same class via TITLE_STOPWORDS. Anti-game holds:\n// the distinctive domain tokens remain, so an off-topic item still fails.\nconst REQUIREMENT_FORM_STOPWORDS = new Set([\n 'generated',\n 'generate',\n 'view',\n 'render',\n 'rendered',\n 'persisted',\n 'persist',\n 'artifact',\n 'file',\n 'document',\n 'note',\n 'proposal',\n 'deliverable',\n 'output',\n 'created',\n 'create',\n 'produce',\n 'produced',\n 'flag',\n])\n\nconst MATCH_THRESHOLD = 0.5\nconst MIN_CONTENT_CHARS = 50\n\nfunction tokens(s: string, extraStop?: Set<string>): Set<string> {\n return new Set(\n s\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((t) => t.length > 1 && !STOPWORDS.has(t) && !extraStop?.has(t)),\n )\n}\n\n/**\n * Recall of the requirement's tokens within a candidate's identifying text.\n * Recall, not Jaccard — a candidate's path/id legitimately carries extra\n * tokens the requirement does not name. The requirement side drops\n * deliverable-FORM vocabulary so recall keys on the distinctive domain tokens.\n */\nfunction tokenRecall(requirementText: string, candidateText: string): number {\n const req = tokens(requirementText, REQUIREMENT_FORM_STOPWORDS)\n if (req.size === 0) return 0\n const cand = tokens(candidateText)\n let hit = 0\n for (const t of req) if (cand.has(t)) hit++\n return hit / req.size\n}\n\ninterface Candidate {\n reqIndex: number\n /** Unique key for a produced item — each item satisfies at most one requirement. */\n itemKey: string\n score: number\n evidence: string\n /** Content to correctness-check, or null when the matched item has none. */\n content: string | null\n}\n\nfunction artifactCandidates(\n req: CompletionRequirement,\n reqIndex: number,\n artifacts: ValidatedArtifact[],\n): Candidate[] {\n const reqText = `${req.title} ${req.category ?? ''}`\n const out: Candidate[] = []\n artifacts.forEach((a, i) => {\n if ((a.content ?? '').trim().length < MIN_CONTENT_CHARS) return\n // Match against the artifact CONTENT too, not just its path + kind — a\n // generated view / note whose path is generic still satisfies a requirement\n // when its body covers it (e.g. an OpenUI comparison grounded in the on-file\n // figures). Bounded slice keeps the recall text cheap; MATCH_THRESHOLD holds.\n let score = tokenRecall(\n reqText,\n `${a.path ?? ''} ${a.kind} ${(a.content ?? '').slice(0, 4000)}`,\n )\n if (req.category && a.kind && req.category.toLowerCase() === a.kind.toLowerCase()) {\n score = Math.max(score, 1)\n }\n if (score < MATCH_THRESHOLD) return\n out.push({\n reqIndex,\n itemKey: `artifact:${i}`,\n score,\n evidence: `artifact '${a.path ?? a.kind}' matched (token recall ${score.toFixed(2)})`,\n content: a.content ?? null,\n })\n })\n return out\n}\n\nfunction proposalCandidates(\n req: CompletionRequirement,\n reqIndex: number,\n proposals: ProducedProposal[],\n): Candidate[] {\n const reqText = `${req.title} ${req.category ?? ''}`\n const out: Candidate[] = []\n for (const p of proposals) {\n // Pending or rejected work is not a completed deliverable.\n if (p.status !== 'approved') continue\n // A proposal needs an assessable BODY to be a deliverable. A bare title is\n // not completion: correctness cannot be judged on it, so a title-only match\n // would auto-pass the oracle (structurallyPresent && correct===null →\n // satisfied) with no verifiable content. Tool calls are the only\n // legitimately content-less deliverable (`toolCallCandidates`).\n const body = (p.content ?? '').trim()\n if (body.length < MIN_CONTENT_CHARS) continue\n // Match against the body as well as the (often short) title — a refusal /\n // flag / analysis proposal whose title is a label still satisfies a\n // descriptively-worded requirement when its content covers it. MATCH_THRESHOLD\n // + the requirement's distinctive tokens keep an off-topic proposal out;\n // correctness (a SEMANTIC checker, NOT this lexical pass) then judges\n // polarity/fulfilment, so a negation that merely contains the tokens fails.\n // Structural and correctness must use different evidence or the two-stage\n // check collapses to one lexical gate.\n const score = tokenRecall(reqText, `${p.title} ${body}`)\n if (score < MATCH_THRESHOLD) continue\n out.push({\n reqIndex,\n itemKey: `proposal:${p.id}`,\n score,\n evidence: `approved proposal '${p.title}' matched (token recall ${score.toFixed(2)})`,\n content: body,\n })\n }\n return out\n}\n\nfunction toolCallCandidates(\n req: CompletionRequirement,\n reqIndex: number,\n toolCalls: string[],\n): Candidate[] {\n const out: Candidate[] = []\n toolCalls.forEach((name, i) => {\n const score = tokenRecall(req.title, name)\n if (score < MATCH_THRESHOLD) return\n out.push({\n reqIndex,\n itemKey: `tool:${i}`,\n score,\n evidence: `tool call '${name}' matched (token recall ${score.toFixed(2)})`,\n content: null,\n })\n })\n return out\n}\n\n/**\n * Verify whether a run completed the task. `checkCorrectness` is injected —\n * `createLlmCorrectnessChecker` for production, a deterministic stub in tests.\n *\n * Throws on a gold spec with no requirements: an eval task that requires\n * nothing is a misconfiguration, not a vacuously-complete task.\n */\nexport async function verifyCompletion(\n gold: TaskGold,\n state: ProducedState,\n checkCorrectness: CorrectnessChecker,\n): Promise<CompletionVerdict> {\n if (gold.requirements.length === 0) {\n throw new Error(\n `verifyCompletion: task '${gold.taskId}' has no requirements — malformed gold spec`,\n )\n }\n\n // Collect every above-threshold (requirement, produced-item) candidate, then\n // assign greedily by descending score: each requirement and each produced\n // item is used at most once. One deliverable fulfils one requirement.\n const candidates: Candidate[] = []\n gold.requirements.forEach((req, i) => {\n const by = req.satisfiedBy ?? 'any'\n if (by === 'artifact' || by === 'any') {\n candidates.push(...artifactCandidates(req, i, state.artifacts))\n }\n if (by === 'proposal' || by === 'any') {\n candidates.push(...proposalCandidates(req, i, state.proposals))\n }\n if (by === 'tool-call' || by === 'any') {\n candidates.push(...toolCallCandidates(req, i, state.toolCalls))\n }\n })\n candidates.sort((a, b) => b.score - a.score)\n\n const assigned = new Map<number, Candidate>()\n const itemTaken = new Set<string>()\n for (const c of candidates) {\n if (assigned.has(c.reqIndex) || itemTaken.has(c.itemKey)) continue\n assigned.set(c.reqIndex, c)\n itemTaken.add(c.itemKey)\n }\n\n const requirements: RequirementCheck[] = []\n for (let i = 0; i < gold.requirements.length; i++) {\n const req = gold.requirements[i]!\n const match = assigned.get(i)\n const evidence: string[] = []\n let correct: boolean | null = null\n let unmeasuredReason: string | undefined\n\n if (match) {\n evidence.push(match.evidence)\n if (match.content !== null) {\n try {\n const r = await checkCorrectness(req, match.content)\n correct = r.correct\n evidence.push(`correctness: ${r.correct ? 'pass' : 'fail'} — ${r.reason}`)\n } catch (err) {\n // The CHECKER failed, not the requirement. Recording this as a\n // zero would fabricate a model failure out of an infrastructure\n // one; the requirement is unmeasured and leaves the denominator.\n unmeasuredReason =\n err instanceof JudgeParseError\n ? `checker response unparseable after retry: ${err.raw.slice(0, 200)}`\n : `checker call failed: ${err instanceof Error ? err.message : String(err)}`\n evidence.push(`correctness: UNMEASURED — ${unmeasuredReason}`)\n }\n } else {\n evidence.push('correctness: not assessed — matched item carries no content')\n }\n } else {\n const by = req.satisfiedBy ?? 'any'\n const kind = by === 'any' ? 'artifact/proposal/tool-call' : by\n evidence.push(`no produced ${kind} matched this requirement`)\n }\n\n const structurallyPresent = match !== undefined\n const unmeasured = unmeasuredReason !== undefined\n const satisfied = structurallyPresent && !unmeasured && correct !== false\n requirements.push({\n reqId: req.reqId,\n title: req.title,\n structurallyPresent,\n correct,\n satisfied,\n ...(unmeasured ? { unmeasured: true as const, unmeasuredReason } : {}),\n evidence,\n })\n }\n\n // The verdict blends the deterministic structural stage with the injected\n // correctness stage, so the certification names the checker's own member\n // and carries the structural stage's lexical nature as an assumption. A\n // checker without an attestation yields an uncertified verdict.\n const attestation = checkCorrectness.attestation\n const certification: VerdictCertification | undefined = attestation\n ? {\n strategy: attestation.strategy,\n checker: attestation.checker,\n assumptions: [\n 'structural matching is lexical token recall over produced items — the correctness stage only sees items it matched',\n ...attestation.assumptions,\n ],\n evidenceDigest: certificationEvidenceDigest({ taskId: gold.taskId, requirements }),\n }\n : undefined\n\n return completionVerdict({\n taskId: gold.taskId,\n requirements,\n ...(certification === undefined ? {} : { certification }),\n })\n}\n\nexport interface LlmCorrectnessCheckerOpts {\n /** Judge model. Default `DEFAULT_JUDGE_MODEL`, never the client's default, which may be the user simulator or the agent under test. */\n model?: string\n /** Optional ledger for direct use. */\n costLedger?: CostLedgerHandle\n costPhase?: string\n costTags?: Record<string, string>\n signal?: AbortSignal\n /** Max chars of artifact content sent to the checker. */\n maxContentChars?: number\n /**\n * Checker LLM calls per requirement before giving up (parse failures and\n * call errors both consume attempts). The failure then surfaces as an\n * `unmeasured` requirement, never a zero.\n */\n maxAttempts?: number\n /**\n * Forensic capture of every checker request/response/error — without it a\n * checker failure is unauditable (the agent-turn raws never contain the\n * checker's own calls). Same sink contract as `LlmClient`.\n */\n rawSink?: RawProviderSink\n}\n\n/**\n * Parse the correctness checker's model response. Tolerates a response\n * truncated mid-JSON (max_tokens cap) by auto-closing the prefix — the\n * verdict boolean usually lands in the first few tokens, so a recovered\n * prefix with a boolean `correct` is a real measurement, not a guess.\n * Fails loud (JudgeParseError) when no boolean verdict is recoverable.\n */\nfunction parseCorrectnessResponse(raw: string): { correct: boolean; reason: string } {\n const readVerdict = (candidate: unknown): { correct: boolean; reason: string } | null => {\n if (candidate === null || typeof candidate !== 'object') return null\n const { correct, reason } = candidate as { correct?: unknown; reason?: unknown }\n if (typeof correct !== 'boolean') return null\n return { correct, reason: typeof reason === 'string' ? reason : '' }\n }\n\n const match = raw.match(/\\{[\\s\\S]*\\}/)\n if (match) {\n try {\n const strict = readVerdict(JSON.parse(match[0]))\n if (strict) return strict\n } catch {\n // fall through to truncation recovery\n }\n }\n // The strict path needs a closing `}`; a cap-hit response has none. Take\n // everything from the first `{` and auto-close it.\n const start = raw.indexOf('{')\n if (start !== -1) {\n const recovered = readVerdict(recoverTruncatedJson(raw.slice(start)))\n if (recovered) return recovered\n }\n throw new JudgeParseError('correctness-checker', raw)\n}\n\n/**\n * Production `CorrectnessChecker` — one LLM call per matched artifact,\n * deterministic (temperature 0), structured JSON out. Judges fulfilment\n * only: a plan, a gesture, or a description of what should be done does not\n * fulfil a requirement — the artifact must BE the deliverable.\n */\nexport function createLlmCorrectnessChecker(\n chat: ChatClient,\n opts: LlmCorrectnessCheckerOpts = {},\n): CorrectnessChecker {\n const model = opts.model ?? DEFAULT_JUDGE_MODEL\n const maxContentChars = opts.maxContentChars ?? 8000\n const maxAttempts = opts.maxAttempts ?? 2\n const costLedger = opts.costLedger ?? new CostLedger()\n const sink = opts.rawSink\n const record = async (event: RawProviderEvent): Promise<void> => {\n // Forensic capture is best-effort; the verdict is the system of record.\n try {\n await sink?.record(event)\n } catch {\n // Intentionally swallowed.\n }\n }\n const checker: CorrectnessChecker = async (requirement, content) => {\n const request = {\n model,\n messages: [\n {\n role: 'system' as const,\n content:\n 'You verify whether a produced work artifact actually fulfils a stated requirement. Judge fulfilment only — is the deliverable substantively present and on-point — not polish. A plan to do it later, a vague gesture, or a description of what should be done does NOT fulfil a requirement; the artifact must BE the deliverable. Respond with a single JSON object: {\"correct\": boolean, \"reason\": string (<= 30 words)}.',\n },\n {\n role: 'user' as const,\n content: `Requirement: ${requirement.title}\\n${\n requirement.category ? `Category: ${requirement.category}\\n` : ''\n }\\nProduced artifact:\\n${content.slice(0, maxContentChars)}`,\n },\n ],\n temperature: 0,\n maxTokens: 200,\n } satisfies ChatRequest\n let lastErr: unknown\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n const started = Date.now()\n await record({\n eventId: randomUUID(),\n provider: chat.transport,\n model,\n endpoint: '/chat',\n baseUrl: '',\n attemptIndex: attempt,\n direction: 'request',\n timestamp: started,\n requestBody: request,\n redactedFields: [],\n })\n try {\n const paid = await costLedger.runPaidCall({\n channel: 'verifier',\n phase: opts.costPhase ?? 'completion.correctness',\n actor: 'correctness-checker',\n model,\n maximumCharge:\n chat.maximumAttempts === undefined\n ? undefined\n : maximumChargeForLlmRequest(request, { maximumAttempts: chat.maximumAttempts }),\n tags: {\n ...opts.costTags,\n requirementId: requirement.reqId,\n attempt: String(attempt),\n },\n signal: opts.signal,\n execute: (signal, callId) => chat.chat(request, { signal, idempotencyKey: callId }),\n receipt: costReceiptFromLlm,\n receiptFromError: costReceiptFromLlmError,\n })\n if (!paid.succeeded) throw paid.error\n const resp = paid.value\n // Hold the transport to its own word: a verdict produced by a model\n // other than the one requested is not this model's verdict. A\n // transport that echoes no id cannot be made to prove identity here —\n // callers needing that proof enable it at the client\n // (`LlmClientOptions.assertServedModel`) or gate on `assertModelsServed`.\n assertServedModel(model, resp.servedModel, {\n allowUnreported: true,\n context: `correctness checker for requirement ${requirement.reqId}`,\n })\n const raw = resp.content\n await record({\n eventId: randomUUID(),\n provider: chat.transport,\n model,\n endpoint: '/chat',\n baseUrl: '',\n attemptIndex: attempt,\n direction: 'response',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n responseBody: resp,\n redactedFields: [],\n })\n return parseCorrectnessResponse(raw)\n } catch (err) {\n lastErr = err\n await record({\n eventId: randomUUID(),\n provider: chat.transport,\n model,\n endpoint: '/chat',\n baseUrl: '',\n attemptIndex: attempt,\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n errorMessage: err instanceof Error ? err.message : String(err),\n redactedFields: [],\n })\n // Substitution is a verdict about identity, not a transient fault:\n // another attempt reaches the same wrong model and spends more tokens.\n if (err instanceof ModelSubstitutionError) throw err\n }\n }\n throw lastErr instanceof Error ? lastErr : new Error(String(lastErr))\n }\n checker.attestation = {\n strategy: 'judge',\n checker: { name: 'llm-correctness-checker', version: model },\n assumptions: [\n 'served-model identity is accepted when the transport reports none (assertServedModel allowUnreported)',\n ],\n }\n return checker\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiIA,SAAgB,kBAAkB,OAMZ;CACpB,IAAI,MAAM,aAAa,WAAW,GAChC,MAAM,IAAI,MACR,4BAA4B,MAAM,OAAO,+DAC3C;CAEF,MAAM,aAAa,MAAM,aAAa,QAAQ,MAAM,CAAC,EAAE,UAAU;CACjE,MAAM,kBAAkB,MAAM,aAAa,SAAS,WAAW;CAC/D,IAAI,WAAW,WAAW,GAGxB,MAAM,IAAI,MACR,4BAA4B,MAAM,OAAO,yCAAyC,MAAM,aAAa,OAAO,8BAA8B,MAAM,aAAa,EAAE,EAAE,oBAAoB,iBAAiB,EACxM;CAEF,MAAM,iBAAiB,WAAW,QAAQ,MAAM,EAAE,SAAS,CAAC,CAAC;CAC7D,MAAM,iBAAiB,iBAAiB,WAAW;CAGnD,MAAM,gBAAgB,oBAAoB,KAAK,mBAAmB,WAAW;CAC7E,OAAO;EACL,QAAQ,MAAM;EACd,cAAc,MAAM;EACpB;EACA;EACA;EACA,OAAO;EACP,OAAO;EACP,GAAI,MAAM,kBAAkB,KAAA,IAAY,CAAC,IAAI,EAAE,eAAe,MAAM,cAAc;CACpF;AACF;AA+BA,MAAM,4BAAY,IAAI,IAAI;CACxB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAUD,MAAM,6CAA6B,IAAI,IAAI;CACzC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,kBAAkB;AACxB,MAAM,oBAAoB;AAE1B,SAAS,OAAO,GAAW,WAAsC;CAC/D,OAAO,IAAI,IACT,EACG,YAAY,CAAC,CACb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AAW,KAAK,IAAI;KACpB,YAAY,KAAK,IAAI,IAAI;KACzB,cAAc;KACd,gBAAgB,CAAC;IACnB,CAAC;IACD,OAAO,yBAAyB,GAAG;GACrC,SAAS,KAAK;IACZ,UAAU;IACV,MAAM,OAAO;KACX,SAAS,WAAW;KACpB,UAAU,KAAK;KACf;KACA,UAAU;KACV,SAAS;KACT,cAAc;KACd,WAAW;KACX,WAAW,KAAK,IAAI;KACpB,YAAY,KAAK,IAAI,IAAI;KACzB,cAAc,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;KAC7D,gBAAgB,CAAC;IACnB,CAAC;IAGD,IAAI,eAAe,wBAAwB,MAAM;GACnD;EACF;EACA,MAAM,mBAAmB,QAAQ,UAAU,IAAI,MAAM,OAAO,OAAO,CAAC;CACtE;CACA,QAAQ,cAAc;EACpB,UAAU;EACV,SAAS;GAAE,MAAM;GAA2B,SAAS;EAAM;EAC3D,aAAa,CACX,uGACF;CACF;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"completion-verifier-DiG3y43g.js","names":[],"sources":["../src/completion-verifier.ts"],"sourcesContent":["/**\n * Completion verifier — the task-completion oracle.\n *\n * Answers the only eval question that is not a proxy: did the agent actually\n * COMPLETE the task — produce every required deliverable, persisted and\n * correct — rather than describe what should be done. A fluent transcript\n * that never produces the artifact scores zero here.\n *\n * Per requirement, a two-stage check:\n * 1. Structural — a produced item (vault artifact / approved proposal /\n * tool call) of the right kind is matched against the requirement and\n * carries non-empty content. Deterministic; no LLM.\n * 2. Correctness — only if structurally present AND the matched item\n * carries content, one targeted check decides whether that item\n * actually fulfils the requirement. A hallucinated artifact fails here;\n * an absent one already failed stage 1.\n *\n * `completionRate` is satisfied / MEASURABLE requirements (unmeasured rows —\n * checker failures — are excluded from the denominator, never scored as\n * zeros). Quality dimensions are meaningless on an incomplete task — callers\n * gate on `fullyComplete` / `completionRate` before scoring quality.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { type ChatClient, type ChatRequest, DEFAULT_JUDGE_MODEL } from './analyst/chat-client'\nimport type { ValidatedArtifact } from './artifact-validator'\nimport { CostLedger, type CostLedgerHandle } from './cost-ledger'\nimport { assertServedModel, ModelSubstitutionError } from './integrity/served-model'\nimport { recoverTruncatedJson } from './json-recovery'\nimport { JudgeParseError } from './judges'\nimport {\n costReceiptFromLlm,\n costReceiptFromLlmError,\n maximumChargeForLlmRequest,\n} from './llm-client'\nimport type { RawProviderEvent, RawProviderSink } from './trace/raw-provider-sink'\nimport {\n certificationEvidenceDigest,\n type DefaultVerdict,\n type VerdictCertification,\n} from './verdict'\nimport type { CheckerIdentity, VerificationStrategySource } from './verification-strategy'\n\n/** What kind of produced state can satisfy a requirement structurally. */\nexport type SatisfiedBy = 'artifact' | 'proposal' | 'tool-call' | 'any'\n\nexport interface CompletionRequirement {\n /** Stable id from the task gold (e.g. a persona's `expected_requirements[].req_id`). */\n reqId: string\n /** Human-readable description of the required deliverable. */\n title: string\n /** Optional kind/category hint, matched against a produced item's kind. */\n category?: string\n /** What produced state satisfies this requirement. Defaults to 'any'. */\n satisfiedBy?: SatisfiedBy\n}\n\nexport interface TaskGold {\n taskId: string\n requirements: CompletionRequirement[]\n}\n\nexport interface ProducedProposal {\n id: string\n title: string\n status: 'pending' | 'approved' | 'rejected'\n /** Optional persisted body — when present, enables a correctness check. */\n content?: string\n}\n\n/** Everything observable about what a run actually produced. */\nexport interface ProducedState {\n /** Persisted vault artifacts. Reuses the shared `ValidatedArtifact` shape. */\n artifacts: ValidatedArtifact[]\n /** Proposals / filings the agent created. */\n proposals: ProducedProposal[]\n /** Names of tools the agent invoked. */\n toolCalls: string[]\n}\n\nexport interface RequirementCheck {\n reqId: string\n title: string\n /** A produced item of the right kind matched the requirement, non-empty. */\n structurallyPresent: boolean\n /**\n * Whether the matched item actually fulfils the requirement. `null` when\n * not structurally present, when the matched item carries no content\n * to assess, or when the correctness check itself failed (`unmeasured`).\n */\n correct: boolean | null\n /** structurallyPresent && !unmeasured && correct !== false. */\n satisfied: boolean\n /**\n * Set when the correctness check itself errored (LLM call failure or an\n * unparseable response after retry). The requirement's fulfilment is\n * UNKNOWN — `correct` stays null, `satisfied` is false, and\n * `completionVerdict` excludes the row from `completionRate`'s\n * denominator. Never folded into a zero: a synthetic zero is\n * indistinguishable from a real failure (see `JudgeParseError`).\n */\n unmeasured?: true\n /** Why the correctness check could not be measured (present iff `unmeasured`). */\n unmeasuredReason?: string\n /** Human-readable evidence for the verdict. */\n evidence: string[]\n}\n\n/** Extends the substrate verdict spine: `valid` = `fullyComplete` and\n * `score` = `completionRate` — derived in `completionVerdict()`, the one\n * place those equalities hold by construction. */\nexport interface CompletionVerdict extends DefaultVerdict {\n taskId: string\n requirements: RequirementCheck[]\n /** satisfied / MEASURABLE requirements (unmeasured rows leave the denominator). */\n completionRate: number\n /** Every measurable requirement satisfied (false when anything is unmeasured). */\n fullyComplete: boolean\n /** Requirements whose correctness check errored — reported, never scored as zero. */\n unmeasuredCount: number\n}\n\n/**\n * Construct a `CompletionVerdict` from the per-requirement checks, deriving\n * `completionRate` / `fullyComplete` and the spine fields (`valid` =\n * `fullyComplete`, `score` = `completionRate`) in one place. Throws on zero\n * requirements — a verdict over nothing is a misconfiguration, mirroring\n * `verifyCompletion`'s gold-spec guard.\n */\nexport function completionVerdict(input: {\n taskId: string\n requirements: RequirementCheck[]\n /** What certified the correctness stage, when anything did. Omitted =\n * an uncertified verdict — the honest default for a bare checker. */\n certification?: VerdictCertification\n}): CompletionVerdict {\n if (input.requirements.length === 0) {\n throw new Error(\n `completionVerdict: task '${input.taskId}' has no requirement checks — nothing to derive a verdict from`,\n )\n }\n const measurable = input.requirements.filter((r) => !r.unmeasured)\n const unmeasuredCount = input.requirements.length - measurable.length\n if (measurable.length === 0) {\n // Every check errored: this is an infrastructure failure, not a scored\n // run. A 0-rate verdict here would be a fabricated measurement.\n throw new Error(\n `completionVerdict: task '${input.taskId}' has no measurable requirements — all ${input.requirements.length} correctness checks failed (${input.requirements[0]?.unmeasuredReason ?? 'unknown reason'})`,\n )\n }\n const satisfiedCount = measurable.filter((r) => r.satisfied).length\n const completionRate = satisfiedCount / measurable.length\n // A run with unmeasured rows can still report a rate over what WAS\n // measured, but must not claim full completion.\n const fullyComplete = unmeasuredCount === 0 && satisfiedCount === measurable.length\n return {\n taskId: input.taskId,\n requirements: input.requirements,\n completionRate,\n fullyComplete,\n unmeasuredCount,\n valid: fullyComplete,\n score: completionRate,\n ...(input.certification === undefined ? {} : { certification: input.certification }),\n }\n}\n\n/**\n * What a correctness checker declares about itself so the completion\n * verdict can carry a certification: which strategy member it discharges,\n * its exact identity, and the steps its answers rest on unverified.\n */\nexport interface CorrectnessCheckerAttestation {\n strategy: VerificationStrategySource\n checker: CheckerIdentity\n assumptions: string[]\n}\n\n/**\n * Decides whether a produced item's content actually fulfils a requirement.\n * Injected so the structural verifier stays pure and unit-testable; the\n * production implementation is `createLlmCorrectnessChecker`.\n *\n * `attestation` is optional metadata on the function value: a checker that\n * carries one yields certified completion verdicts; a bare function yields\n * the same verdict uncertified. A plain arrow function remains a valid\n * checker.\n */\nexport interface CorrectnessChecker {\n (\n requirement: CompletionRequirement,\n content: string,\n ): Promise<{ correct: boolean; reason: string }>\n attestation?: CorrectnessCheckerAttestation\n}\n\nconst STOPWORDS = new Set([\n 'the',\n 'a',\n 'an',\n 'of',\n 'for',\n 'and',\n 'or',\n 'to',\n 'in',\n 'on',\n 'with',\n 'by',\n])\n\n// Deliverable-FORM vocabulary — words that name the SHAPE of an output, not its\n// domain content. A correct \"swap-comparison view persisted as a ui/** artifact\"\n// is an OpenUI JSON whose body says nothing about \"artifact\" / \"persisted\" /\n// \"view\"; the discriminative tokens are the domain nouns (swap, comparison).\n// Stripped from the REQUIREMENT side of structural recall so a deliverable is\n// matched on what it IS about, not on the boilerplate describing its form. The\n// correctness checker strips the same class via TITLE_STOPWORDS. Anti-game holds:\n// the distinctive domain tokens remain, so an off-topic item still fails.\nconst REQUIREMENT_FORM_STOPWORDS = new Set([\n 'generated',\n 'generate',\n 'view',\n 'render',\n 'rendered',\n 'persisted',\n 'persist',\n 'artifact',\n 'file',\n 'document',\n 'note',\n 'proposal',\n 'deliverable',\n 'output',\n 'created',\n 'create',\n 'produce',\n 'produced',\n 'flag',\n])\n\nconst MATCH_THRESHOLD = 0.5\nconst MIN_CONTENT_CHARS = 50\n\nfunction tokens(s: string, extraStop?: Set<string>): Set<string> {\n return new Set(\n s\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((t) => t.length > 1 && !STOPWORDS.has(t) && !extraStop?.has(t)),\n )\n}\n\n/**\n * Recall of the requirement's tokens within a candidate's identifying text.\n * Recall, not Jaccard — a candidate's path/id legitimately carries extra\n * tokens the requirement does not name. The requirement side drops\n * deliverable-FORM vocabulary so recall keys on the distinctive domain tokens.\n */\nfunction tokenRecall(requirementText: string, candidateText: string): number {\n const req = tokens(requirementText, REQUIREMENT_FORM_STOPWORDS)\n if (req.size === 0) return 0\n const cand = tokens(candidateText)\n let hit = 0\n for (const t of req) if (cand.has(t)) hit++\n return hit / req.size\n}\n\ninterface Candidate {\n reqIndex: number\n /** Unique key for a produced item — each item satisfies at most one requirement. */\n itemKey: string\n score: number\n evidence: string\n /** Content to correctness-check, or null when the matched item has none. */\n content: string | null\n}\n\nfunction artifactCandidates(\n req: CompletionRequirement,\n reqIndex: number,\n artifacts: ValidatedArtifact[],\n): Candidate[] {\n const reqText = `${req.title} ${req.category ?? ''}`\n const out: Candidate[] = []\n artifacts.forEach((a, i) => {\n if ((a.content ?? '').trim().length < MIN_CONTENT_CHARS) return\n // Match against the artifact CONTENT too, not just its path + kind — a\n // generated view / note whose path is generic still satisfies a requirement\n // when its body covers it (e.g. an OpenUI comparison grounded in the on-file\n // figures). Bounded slice keeps the recall text cheap; MATCH_THRESHOLD holds.\n let score = tokenRecall(\n reqText,\n `${a.path ?? ''} ${a.kind} ${(a.content ?? '').slice(0, 4000)}`,\n )\n if (req.category && a.kind && req.category.toLowerCase() === a.kind.toLowerCase()) {\n score = Math.max(score, 1)\n }\n if (score < MATCH_THRESHOLD) return\n out.push({\n reqIndex,\n itemKey: `artifact:${i}`,\n score,\n evidence: `artifact '${a.path ?? a.kind}' matched (token recall ${score.toFixed(2)})`,\n content: a.content ?? null,\n })\n })\n return out\n}\n\nfunction proposalCandidates(\n req: CompletionRequirement,\n reqIndex: number,\n proposals: ProducedProposal[],\n): Candidate[] {\n const reqText = `${req.title} ${req.category ?? ''}`\n const out: Candidate[] = []\n for (const p of proposals) {\n // Pending or rejected work is not a completed deliverable.\n if (p.status !== 'approved') continue\n // A proposal needs an assessable BODY to be a deliverable. A bare title is\n // not completion: correctness cannot be judged on it, so a title-only match\n // would auto-pass the oracle (structurallyPresent && correct===null →\n // satisfied) with no verifiable content. Tool calls are the only\n // legitimately content-less deliverable (`toolCallCandidates`).\n const body = (p.content ?? '').trim()\n if (body.length < MIN_CONTENT_CHARS) continue\n // Match against the body as well as the (often short) title — a refusal /\n // flag / analysis proposal whose title is a label still satisfies a\n // descriptively-worded requirement when its content covers it. MATCH_THRESHOLD\n // + the requirement's distinctive tokens keep an off-topic proposal out;\n // correctness (a SEMANTIC checker, NOT this lexical pass) then judges\n // polarity/fulfilment, so a negation that merely contains the tokens fails.\n // Structural and correctness must use different evidence or the two-stage\n // check collapses to one lexical gate.\n const score = tokenRecall(reqText, `${p.title} ${body}`)\n if (score < MATCH_THRESHOLD) continue\n out.push({\n reqIndex,\n itemKey: `proposal:${p.id}`,\n score,\n evidence: `approved proposal '${p.title}' matched (token recall ${score.toFixed(2)})`,\n content: body,\n })\n }\n return out\n}\n\nfunction toolCallCandidates(\n req: CompletionRequirement,\n reqIndex: number,\n toolCalls: string[],\n): Candidate[] {\n const out: Candidate[] = []\n toolCalls.forEach((name, i) => {\n const score = tokenRecall(req.title, name)\n if (score < MATCH_THRESHOLD) return\n out.push({\n reqIndex,\n itemKey: `tool:${i}`,\n score,\n evidence: `tool call '${name}' matched (token recall ${score.toFixed(2)})`,\n content: null,\n })\n })\n return out\n}\n\n/**\n * Verify whether a run completed the task. `checkCorrectness` is injected —\n * `createLlmCorrectnessChecker` for production, a deterministic stub in tests.\n *\n * Throws on a gold spec with no requirements: an eval task that requires\n * nothing is a misconfiguration, not a vacuously-complete task.\n */\nexport async function verifyCompletion(\n gold: TaskGold,\n state: ProducedState,\n checkCorrectness: CorrectnessChecker,\n): Promise<CompletionVerdict> {\n if (gold.requirements.length === 0) {\n throw new Error(\n `verifyCompletion: task '${gold.taskId}' has no requirements — malformed gold spec`,\n )\n }\n\n // Collect every above-threshold (requirement, produced-item) candidate, then\n // assign greedily by descending score: each requirement and each produced\n // item is used at most once. One deliverable fulfils one requirement.\n const candidates: Candidate[] = []\n gold.requirements.forEach((req, i) => {\n const by = req.satisfiedBy ?? 'any'\n if (by === 'artifact' || by === 'any') {\n candidates.push(...artifactCandidates(req, i, state.artifacts))\n }\n if (by === 'proposal' || by === 'any') {\n candidates.push(...proposalCandidates(req, i, state.proposals))\n }\n if (by === 'tool-call' || by === 'any') {\n candidates.push(...toolCallCandidates(req, i, state.toolCalls))\n }\n })\n candidates.sort((a, b) => b.score - a.score)\n\n const assigned = new Map<number, Candidate>()\n const itemTaken = new Set<string>()\n for (const c of candidates) {\n if (assigned.has(c.reqIndex) || itemTaken.has(c.itemKey)) continue\n assigned.set(c.reqIndex, c)\n itemTaken.add(c.itemKey)\n }\n\n const requirements: RequirementCheck[] = []\n for (let i = 0; i < gold.requirements.length; i++) {\n const req = gold.requirements[i]!\n const match = assigned.get(i)\n const evidence: string[] = []\n let correct: boolean | null = null\n let unmeasuredReason: string | undefined\n\n if (match) {\n evidence.push(match.evidence)\n if (match.content !== null) {\n try {\n const r = await checkCorrectness(req, match.content)\n correct = r.correct\n evidence.push(`correctness: ${r.correct ? 'pass' : 'fail'} — ${r.reason}`)\n } catch (err) {\n // The CHECKER failed, not the requirement. Recording this as a\n // zero would fabricate a model failure out of an infrastructure\n // one; the requirement is unmeasured and leaves the denominator.\n unmeasuredReason =\n err instanceof JudgeParseError\n ? `checker response unparseable after retry: ${err.raw.slice(0, 200)}`\n : `checker call failed: ${err instanceof Error ? err.message : String(err)}`\n evidence.push(`correctness: UNMEASURED — ${unmeasuredReason}`)\n }\n } else {\n evidence.push('correctness: not assessed — matched item carries no content')\n }\n } else {\n const by = req.satisfiedBy ?? 'any'\n const kind = by === 'any' ? 'artifact/proposal/tool-call' : by\n evidence.push(`no produced ${kind} matched this requirement`)\n }\n\n const structurallyPresent = match !== undefined\n const unmeasured = unmeasuredReason !== undefined\n const satisfied = structurallyPresent && !unmeasured && correct !== false\n requirements.push({\n reqId: req.reqId,\n title: req.title,\n structurallyPresent,\n correct,\n satisfied,\n ...(unmeasured ? { unmeasured: true as const, unmeasuredReason } : {}),\n evidence,\n })\n }\n\n // The verdict blends the deterministic structural stage with the injected\n // correctness stage, so the certification names the checker's own member\n // and carries the structural stage's lexical nature as an assumption. A\n // checker without an attestation yields an uncertified verdict.\n const attestation = checkCorrectness.attestation\n const certification: VerdictCertification | undefined = attestation\n ? {\n strategy: attestation.strategy,\n checker: attestation.checker,\n assumptions: [\n 'structural matching is lexical token recall over produced items — the correctness stage only sees items it matched',\n ...attestation.assumptions,\n ],\n evidenceDigest: certificationEvidenceDigest({ taskId: gold.taskId, requirements }),\n }\n : undefined\n\n return completionVerdict({\n taskId: gold.taskId,\n requirements,\n ...(certification === undefined ? {} : { certification }),\n })\n}\n\nexport interface LlmCorrectnessCheckerOpts {\n /** Judge model. Default `DEFAULT_JUDGE_MODEL`, never the client's default, which may be the user simulator or the agent under test. */\n model?: string\n /** Optional ledger for direct use. */\n costLedger?: CostLedgerHandle\n costPhase?: string\n costTags?: Record<string, string>\n signal?: AbortSignal\n /** Max chars of artifact content sent to the checker. */\n maxContentChars?: number\n /**\n * Checker LLM calls per requirement before giving up (parse failures and\n * call errors both consume attempts). The failure then surfaces as an\n * `unmeasured` requirement, never a zero.\n */\n maxAttempts?: number\n /**\n * Forensic capture of every checker request/response/error — without it a\n * checker failure is unauditable (the agent-turn raws never contain the\n * checker's own calls). Same sink contract as `LlmClient`.\n */\n rawSink?: RawProviderSink\n}\n\n/**\n * Parse the correctness checker's model response. Tolerates a response\n * truncated mid-JSON (max_tokens cap) by auto-closing the prefix — the\n * verdict boolean usually lands in the first few tokens, so a recovered\n * prefix with a boolean `correct` is a real measurement, not a guess.\n * Fails loud (JudgeParseError) when no boolean verdict is recoverable.\n */\nfunction parseCorrectnessResponse(raw: string): { correct: boolean; reason: string } {\n const readVerdict = (candidate: unknown): { correct: boolean; reason: string } | null => {\n if (candidate === null || typeof candidate !== 'object') return null\n const { correct, reason } = candidate as { correct?: unknown; reason?: unknown }\n if (typeof correct !== 'boolean') return null\n return { correct, reason: typeof reason === 'string' ? reason : '' }\n }\n\n const match = raw.match(/\\{[\\s\\S]*\\}/)\n if (match) {\n try {\n const strict = readVerdict(JSON.parse(match[0]))\n if (strict) return strict\n } catch {\n // fall through to truncation recovery\n }\n }\n // The strict path needs a closing `}`; a cap-hit response has none. Take\n // everything from the first `{` and auto-close it.\n const start = raw.indexOf('{')\n if (start !== -1) {\n const recovered = readVerdict(recoverTruncatedJson(raw.slice(start)))\n if (recovered) return recovered\n }\n throw new JudgeParseError('correctness-checker', raw)\n}\n\n/**\n * Production `CorrectnessChecker` — one LLM call per matched artifact,\n * deterministic (temperature 0), structured JSON out. Judges fulfilment\n * only: a plan, a gesture, or a description of what should be done does not\n * fulfil a requirement — the artifact must BE the deliverable.\n */\nexport function createLlmCorrectnessChecker(\n chat: ChatClient,\n opts: LlmCorrectnessCheckerOpts = {},\n): CorrectnessChecker {\n const model = opts.model ?? DEFAULT_JUDGE_MODEL\n const maxContentChars = opts.maxContentChars ?? 8000\n const maxAttempts = opts.maxAttempts ?? 2\n const costLedger = opts.costLedger ?? new CostLedger()\n const sink = opts.rawSink\n const record = async (event: RawProviderEvent): Promise<void> => {\n // Forensic capture is best-effort; the verdict is the system of record.\n try {\n await sink?.record(event)\n } catch {\n // Intentionally swallowed.\n }\n }\n const checker: CorrectnessChecker = async (requirement, content) => {\n const request = {\n model,\n messages: [\n {\n role: 'system' as const,\n content:\n 'You verify whether a produced work artifact actually fulfils a stated requirement. Judge fulfilment only — is the deliverable substantively present and on-point — not polish. A plan to do it later, a vague gesture, or a description of what should be done does NOT fulfil a requirement; the artifact must BE the deliverable. Respond with a single JSON object: {\"correct\": boolean, \"reason\": string (<= 30 words)}.',\n },\n {\n role: 'user' as const,\n content: `Requirement: ${requirement.title}\\n${\n requirement.category ? `Category: ${requirement.category}\\n` : ''\n }\\nProduced artifact:\\n${content.slice(0, maxContentChars)}`,\n },\n ],\n temperature: 0,\n maxTokens: 200,\n } satisfies ChatRequest\n let lastErr: unknown\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n const started = Date.now()\n await record({\n eventId: randomUUID(),\n provider: chat.transport,\n model,\n endpoint: '/chat',\n baseUrl: '',\n attemptIndex: attempt,\n direction: 'request',\n timestamp: started,\n requestBody: request,\n redactedFields: [],\n })\n try {\n const paid = await costLedger.runPaidCall({\n channel: 'verifier',\n phase: opts.costPhase ?? 'completion.correctness',\n actor: 'correctness-checker',\n model,\n maximumCharge:\n chat.maximumAttempts === undefined\n ? undefined\n : maximumChargeForLlmRequest(request, { maximumAttempts: chat.maximumAttempts }),\n tags: {\n ...opts.costTags,\n requirementId: requirement.reqId,\n attempt: String(attempt),\n },\n signal: opts.signal,\n execute: (signal, callId) => chat.chat(request, { signal, idempotencyKey: callId }),\n receipt: costReceiptFromLlm,\n receiptFromError: costReceiptFromLlmError,\n })\n if (!paid.succeeded) throw paid.error\n const resp = paid.value\n // Hold the transport to its own word: a verdict produced by a model\n // other than the one requested is not this model's verdict. A\n // transport that echoes no id cannot be made to prove identity here —\n // callers needing that proof enable it at the client\n // (`LlmClientOptions.assertServedModel`) or gate on `assertModelsServed`.\n assertServedModel(model, resp.servedModel, {\n allowUnreported: true,\n context: `correctness checker for requirement ${requirement.reqId}`,\n })\n const raw = resp.content\n await record({\n eventId: randomUUID(),\n provider: chat.transport,\n model,\n endpoint: '/chat',\n baseUrl: '',\n attemptIndex: attempt,\n direction: 'response',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n responseBody: resp,\n redactedFields: [],\n })\n return parseCorrectnessResponse(raw)\n } catch (err) {\n lastErr = err\n await record({\n eventId: randomUUID(),\n provider: chat.transport,\n model,\n endpoint: '/chat',\n baseUrl: '',\n attemptIndex: attempt,\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n errorMessage: err instanceof Error ? err.message : String(err),\n redactedFields: [],\n })\n // Substitution is a verdict about identity, not a transient fault:\n // another attempt reaches the same wrong model and spends more tokens.\n if (err instanceof ModelSubstitutionError) throw err\n }\n }\n throw lastErr instanceof Error ? lastErr : new Error(String(lastErr))\n }\n checker.attestation = {\n strategy: 'judge',\n checker: { name: 'llm-correctness-checker', version: model },\n assumptions: [\n 'served-model identity is accepted when the transport reports none (assertServedModel allowUnreported)',\n ],\n }\n return checker\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiIA,SAAgB,kBAAkB,OAMZ;CACpB,IAAI,MAAM,aAAa,WAAW,GAChC,MAAM,IAAI,MACR,4BAA4B,MAAM,OAAO,+DAC3C;CAEF,MAAM,aAAa,MAAM,aAAa,QAAQ,MAAM,CAAC,EAAE,UAAU;CACjE,MAAM,kBAAkB,MAAM,aAAa,SAAS,WAAW;CAC/D,IAAI,WAAW,WAAW,GAGxB,MAAM,IAAI,MACR,4BAA4B,MAAM,OAAO,yCAAyC,MAAM,aAAa,OAAO,8BAA8B,MAAM,aAAa,EAAE,EAAE,oBAAoB,iBAAiB,EACxM;CAEF,MAAM,iBAAiB,WAAW,QAAQ,MAAM,EAAE,SAAS,CAAC,CAAC;CAC7D,MAAM,iBAAiB,iBAAiB,WAAW;CAGnD,MAAM,gBAAgB,oBAAoB,KAAK,mBAAmB,WAAW;CAC7E,OAAO;EACL,QAAQ,MAAM;EACd,cAAc,MAAM;EACpB;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G,KAAK;MACR,eAAe,YAAY;MAC3B,SAAS,OAAO,OAAO;KACzB;KACA,QAAQ,KAAK;KACb,UAAU,QAAQ,WAAW,KAAK,KAAK,SAAS;MAAE;MAAQ,gBAAgB;KAAO,CAAC;KAClF,SAAS;KACT,kBAAkB;IACpB,CAAC;IACD,IAAI,CAAC,KAAK,WAAW,MAAM,KAAK;IAChC,MAAM,OAAO,KAAK;IAMlB,kBAAkB,OAAO,KAAK,aAAa;KACzC,iBAAiB;KACjB,SAAS,uCAAuC,YAAY;IAC9D,CAAC;IACD,MAAM,MAAM,KAAK;IACjB,MAAM,OAAO;KACX,SAAS,WAAW;KACpB,UAAU,KAAK;KACf;KACA,UAAU;KACV,SAAS;KACT,cAAc;KACd,WAAW;KACX,WAAW,KAAK,IAAI;KACpB,YAAY,KAAK,IAAI,IAAI;KACzB,cAAc;KACd,gBAAgB,CAAC;IACnB,CAAC;IACD,OAAO,yBAAyB,GAAG;GACrC,SAAS,KAAK;IACZ,UAAU;IACV,MAAM,OAAO;KACX,SAAS,WAAW;KACpB,UAAU,KAAK;KACf;KACA,UAAU;KACV,SAAS;KACT,cAAc;KACd,WAAW;KACX,WAAW,KAAK,IAAI;KACpB,YAAY,KAAK,IAAI,IAAI;KACzB,cAAc,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;KAC7D,gBAAgB,CAAC;IACnB,CAAC;IAGD,IAAI,eAAe,wBAAwB,MAAM;GACnD;EACF;EACA,MAAM,mBAAmB,QAAQ,UAAU,IAAI,MAAM,OAAO,OAAO,CAAC;CACtE;CACA,QAAQ,cAAc;EACpB,UAAU;EACV,SAAS;GAAE,MAAM;GAA2B,SAAS;EAAM;EAC3D,aAAa,CACX,uGACF;CACF;CACA,OAAO;AACT"}
@@ -0,0 +1,56 @@
1
+ // src/trace/containment-order.ts
2
+ function containmentOrder(items, keys) {
3
+ const ids = new Set(items.map(keys.id));
4
+ const roots = [];
5
+ const absent = /* @__PURE__ */ new Set();
6
+ const children = /* @__PURE__ */ new Map();
7
+ items.forEach((item, i) => {
8
+ const parent = keys.parentId(item);
9
+ if (parent === null || parent === void 0 || parent === "") roots.push(i);
10
+ else if (!ids.has(parent)) {
11
+ roots.push(i);
12
+ absent.add(i);
13
+ } else {
14
+ const list = children.get(parent);
15
+ if (list) list.push(i);
16
+ else children.set(parent, [i]);
17
+ }
18
+ });
19
+ const byKey = (x, y) => keys.compare(items[x], items[y]) || x - y;
20
+ roots.sort(byKey);
21
+ for (const list of children.values()) list.sort(byKey);
22
+ const ordered = [];
23
+ const visited = new Array(items.length).fill(false);
24
+ const walk = (start, detached) => {
25
+ const stack = [{
26
+ index: start,
27
+ depth: 0
28
+ }];
29
+ while (stack.length > 0) {
30
+ const { index, depth } = stack.pop();
31
+ if (visited[index]) continue;
32
+ visited[index] = true;
33
+ const item = items[index];
34
+ ordered.push(depth === 0 && detached ? {
35
+ item,
36
+ depth,
37
+ detached
38
+ } : {
39
+ item,
40
+ depth
41
+ });
42
+ const kids = children.get(keys.id(item)) ?? [];
43
+ for (let k = kids.length - 1; k >= 0; k -= 1) if (!visited[kids[k]]) stack.push({
44
+ index: kids[k],
45
+ depth: depth + 1
46
+ });
47
+ }
48
+ };
49
+ for (const root of roots) walk(root, absent.has(root) ? "absent" : void 0);
50
+ const rest = items.map((_, i) => i).filter((i) => !visited[i]);
51
+ for (const index of rest.sort(byKey)) walk(index, "cycle");
52
+ return ordered;
53
+ }
54
+ export { containmentOrder as t };
55
+
56
+ //# sourceMappingURL=containment-order-GCJ-y_FV.js.map