@tangle-network/agent-eval 1.0.29 → 1.0.32

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 (292) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +1 -0
  3. package/dist/adapters/http.d.ts +2 -2
  4. package/dist/{agent-profile-BF1WLMco.d.ts → agent-profile-BpLyM2kL.d.ts} +2 -2
  5. package/dist/{agent-profile-BF1WLMco.d.ts.map → agent-profile-BpLyM2kL.d.ts.map} +1 -1
  6. package/dist/{agent-profile-cell-3kYxUsK2.d.ts → agent-profile-cell-BTsrta0H.d.ts} +2 -9
  7. package/dist/agent-profile-cell-BTsrta0H.d.ts.map +1 -0
  8. package/dist/agent-profile-cell-CT5JYueM.js.map +1 -1
  9. package/dist/analyst/index.d.ts +13 -13
  10. package/dist/analyst/index.js +11 -11
  11. package/dist/{analyze-runs-BaziIw93.d.ts → analyze-runs-DfUDLaCk.d.ts} +6 -16
  12. package/dist/analyze-runs-DfUDLaCk.d.ts.map +1 -0
  13. package/dist/{analyze-runs-BCSHzqna.js → analyze-runs-YagfYgfx.js} +5 -5
  14. package/dist/{analyze-runs-BCSHzqna.js.map → analyze-runs-YagfYgfx.js.map} +1 -1
  15. package/dist/app-grade/index.d.ts +3 -5
  16. package/dist/app-grade/index.d.ts.map +1 -1
  17. package/dist/app-grade/index.js +2 -6
  18. package/dist/app-grade/index.js.map +1 -1
  19. package/dist/{benchmark-command-DRAHkn4D.js → benchmark-command-CTmr-oo4.js} +11 -10
  20. package/dist/benchmark-command-CTmr-oo4.js.map +1 -0
  21. package/dist/benchmarks/index.d.ts +7 -6
  22. package/dist/benchmarks/index.d.ts.map +1 -1
  23. package/dist/benchmarks/index.js +13 -5
  24. package/dist/benchmarks/index.js.map +1 -1
  25. package/dist/builder-eval/index.js +1 -1
  26. package/dist/{calibration-Cf-wpqqO.js → calibration-DE2WQmlX.js} +2 -2
  27. package/dist/{calibration-Cf-wpqqO.js.map → calibration-DE2WQmlX.js.map} +1 -1
  28. package/dist/campaign/index.d.ts +8 -8
  29. package/dist/campaign/index.js +14 -14
  30. package/dist/{campaign-Cqz2vk2p.js → campaign-CtdTo5em.js} +15 -15
  31. package/dist/{campaign-Cqz2vk2p.js.map → campaign-CtdTo5em.js.map} +1 -1
  32. package/dist/{campaign-evidence-CVNKiK0q.js → campaign-evidence-BS2-OSFN.js} +4 -4
  33. package/dist/{campaign-evidence-CVNKiK0q.js.map → campaign-evidence-BS2-OSFN.js.map} +1 -1
  34. package/dist/cli.js +9 -8
  35. package/dist/cli.js.map +1 -1
  36. package/dist/{cluster-bootstrap-B0MTOBRU.js → cluster-bootstrap-ClPYIWoX.js} +2 -2
  37. package/dist/{cluster-bootstrap-B0MTOBRU.js.map → cluster-bootstrap-ClPYIWoX.js.map} +1 -1
  38. package/dist/contract/index.d.ts +12 -11
  39. package/dist/contract/index.js +56 -34
  40. package/dist/contract/index.js.map +1 -1
  41. package/dist/{decision-point-CQOczIIH.js → decision-point-DvX1Z4Ue.js} +3 -3
  42. package/dist/{decision-point-CQOczIIH.js.map → decision-point-DvX1Z4Ue.js.map} +1 -1
  43. package/dist/{default-registry-DoIBhuS-.d.ts → default-registry-2Ziw-0sL.d.ts} +7 -7
  44. package/dist/{default-registry-DoIBhuS-.d.ts.map → default-registry-2Ziw-0sL.d.ts.map} +1 -1
  45. package/dist/{default-registry-D-xd7KxV.js → default-registry-DeiYGNKW.js} +3 -3
  46. package/dist/{default-registry-D-xd7KxV.js.map → default-registry-DeiYGNKW.js.map} +1 -1
  47. package/dist/{define-agent-eval-Be2Ser8j.d.ts → define-agent-eval-DmCV1TZo.d.ts} +7 -7
  48. package/dist/{define-agent-eval-Be2Ser8j.d.ts.map → define-agent-eval-DmCV1TZo.d.ts.map} +1 -1
  49. package/dist/{define-agent-eval-BLVewqJm.js → define-agent-eval-GgvRcpNL.js} +7 -7
  50. package/dist/{define-agent-eval-BLVewqJm.js.map → define-agent-eval-GgvRcpNL.js.map} +1 -1
  51. package/dist/diagnosis/index.d.ts +4 -3
  52. package/dist/diagnosis/index.d.ts.map +1 -1
  53. package/dist/diagnosis/index.js +1 -1
  54. package/dist/{dspy-rlm-engine-BS_jxE0P.js → dspy-rlm-engine-DJ_4E-PM.js} +3 -3
  55. package/dist/{dspy-rlm-engine-BS_jxE0P.js.map → dspy-rlm-engine-DJ_4E-PM.js.map} +1 -1
  56. package/dist/{engine-CPBhCLJR.d.ts → engine-yaSDTpEa.d.ts} +2 -2
  57. package/dist/{engine-CPBhCLJR.d.ts.map → engine-yaSDTpEa.d.ts.map} +1 -1
  58. package/dist/{eval-campaign-DpkToY_w.js → eval-campaign-bpSlwr6t.js} +2 -2
  59. package/dist/{eval-campaign-DpkToY_w.js.map → eval-campaign-bpSlwr6t.js.map} +1 -1
  60. package/dist/{evaluation-BjRgUyst.d.ts → evaluation-BQQ2ga5W.d.ts} +4 -4
  61. package/dist/{evaluation-BjRgUyst.d.ts.map → evaluation-BQQ2ga5W.d.ts.map} +1 -1
  62. package/dist/evaluation.d.ts +1 -1
  63. package/dist/{exact-types-DEnrf7NX.d.ts → exact-types-xrjBO9sb.d.ts} +2 -2
  64. package/dist/{exact-types-DEnrf7NX.d.ts.map → exact-types-xrjBO9sb.d.ts.map} +1 -1
  65. package/dist/execution-insight-B-My58JW.d.ts +14 -0
  66. package/dist/execution-insight-B-My58JW.d.ts.map +1 -0
  67. package/dist/experiment/index.d.ts +3 -3
  68. package/dist/experiment/index.js +7 -7
  69. package/dist/{exporters-BKZLt1Px.js → exporters-CfKvJlti.js} +70 -43
  70. package/dist/exporters-CfKvJlti.js.map +1 -0
  71. package/dist/{external-optimizer-process-m9xln7zN.js → external-optimizer-process-jiq4CZD0.js} +2 -2
  72. package/dist/{external-optimizer-process-m9xln7zN.js.map → external-optimizer-process-jiq4CZD0.js.map} +1 -1
  73. package/dist/{external-optimizer-subprocess-GO6s84Ov.js → external-optimizer-subprocess-DUOcOqly.js} +2 -2
  74. package/dist/{external-optimizer-subprocess-GO6s84Ov.js.map → external-optimizer-subprocess-DUOcOqly.js.map} +1 -1
  75. package/dist/failure-cluster-OvKQ0BTq.d.ts +32 -0
  76. package/dist/failure-cluster-OvKQ0BTq.d.ts.map +1 -0
  77. package/dist/{failure-cluster-DOoa7CBg.d.ts → failure-taxonomy-C_SQZ_SJ.d.ts} +2 -30
  78. package/dist/failure-taxonomy-C_SQZ_SJ.d.ts.map +1 -0
  79. package/dist/{feedback-trajectory-DxkG5EPi.d.ts → feedback-trajectory-BbwTH49m.d.ts} +3 -3
  80. package/dist/{feedback-trajectory-DxkG5EPi.d.ts.map → feedback-trajectory-BbwTH49m.d.ts.map} +1 -1
  81. package/dist/{findings-store-CTy71Lnr.js → findings-store-B7JpmgJx.js} +3 -3
  82. package/dist/{findings-store-CTy71Lnr.js.map → findings-store-B7JpmgJx.js.map} +1 -1
  83. package/dist/fuzz.js +1 -1
  84. package/dist/harness-session-lines-hAxOvmtP.js +205 -0
  85. package/dist/harness-session-lines-hAxOvmtP.js.map +1 -0
  86. package/dist/{hf-dataset-Bv114tzB.js → hf-dataset-Cc81I0vQ.js} +65 -141
  87. package/dist/hf-dataset-Cc81I0vQ.js.map +1 -0
  88. package/dist/hosted/index.js +1 -1
  89. package/dist/{index-BI9ecONy.d.ts → index-8hbrQwdR.d.ts} +26 -11
  90. package/dist/index-8hbrQwdR.d.ts.map +1 -0
  91. package/dist/{index-AjfEHHA8.d.ts → index-BFpDeCuS.d.ts} +7 -7
  92. package/dist/{index-AjfEHHA8.d.ts.map → index-BFpDeCuS.d.ts.map} +1 -1
  93. package/dist/{index-DHWFYUVW.d.ts → index-Bcy00QoN.d.ts} +87 -144
  94. package/dist/index-Bcy00QoN.d.ts.map +1 -0
  95. package/dist/{index-BriU7rfL.d.ts → index-BfxYoHGF.d.ts} +226 -6
  96. package/dist/index-BfxYoHGF.d.ts.map +1 -0
  97. package/dist/{index-D-0mg-eu.d.ts → index-BnqugnsM.d.ts} +31 -11
  98. package/dist/index-BnqugnsM.d.ts.map +1 -0
  99. package/dist/{index-C8a9Dyan.d.ts → index-BwJtNdaj.d.ts} +21 -24
  100. package/dist/index-BwJtNdaj.d.ts.map +1 -0
  101. package/dist/{index-VSN1IZQp.d.ts → index-Yec_iihg.d.ts} +4 -3
  102. package/dist/index-Yec_iihg.d.ts.map +1 -0
  103. package/dist/index.d.ts +34 -31
  104. package/dist/index.js +21 -21
  105. package/dist/{integrity-BHM4voOx.js → integrity-BSs9dgKW.js} +3 -3
  106. package/dist/{integrity-BHM4voOx.js.map → integrity-BSs9dgKW.js.map} +1 -1
  107. package/dist/{journal-CTX5uK-n.js → journal-F3msN9OD.js} +5 -399
  108. package/dist/journal-F3msN9OD.js.map +1 -0
  109. package/dist/journal-file-AekB57Er.js +400 -0
  110. package/dist/journal-file-AekB57Er.js.map +1 -0
  111. package/dist/judge-calibration-DnrbQaXI.d.ts +144 -0
  112. package/dist/judge-calibration-DnrbQaXI.d.ts.map +1 -0
  113. package/dist/{judge-gate-DsoI5tx7.js → judge-gate-MP1rHOB4.js} +2 -2
  114. package/dist/{judge-gate-DsoI5tx7.js.map → judge-gate-MP1rHOB4.js.map} +1 -1
  115. package/dist/ledger-core/index.js +3 -2
  116. package/dist/{ledger-core-24IxvmVY.js → ledger-core-COxrkkZi.js} +2 -2
  117. package/dist/{ledger-core-24IxvmVY.js.map → ledger-core-COxrkkZi.js.map} +1 -1
  118. package/dist/{llm-judge-DzAT7Wka.js → llm-judge-Cc33WVHX.js} +102 -27
  119. package/dist/llm-judge-Cc33WVHX.js.map +1 -0
  120. package/dist/{matrix-DdniPG_M.d.ts → matrix-D0fEU0fq.d.ts} +2 -2
  121. package/dist/{matrix-DdniPG_M.d.ts.map → matrix-D0fEU0fq.d.ts.map} +1 -1
  122. package/dist/meta-eval/index.d.ts +3 -3
  123. package/dist/meta-eval/index.js +6 -6
  124. package/dist/{mint-Ck92efNo.js → mint-g8elU5yW.js} +11 -35
  125. package/dist/mint-g8elU5yW.js.map +1 -0
  126. package/dist/multishot/golden/index.d.ts +1 -1
  127. package/dist/multishot/index.d.ts +2 -2
  128. package/dist/openapi.json +1 -1
  129. package/dist/{outcome-observations-DPkH-LHQ.js → outcome-observations-YFFmdGGW.js} +2 -2
  130. package/dist/{outcome-observations-DPkH-LHQ.js.map → outcome-observations-YFFmdGGW.js.map} +1 -1
  131. package/dist/{paired-arms-DjMEtYI9.js → paired-arms-CMSTbLqX.js} +2 -2
  132. package/dist/{paired-arms-DjMEtYI9.js.map → paired-arms-CMSTbLqX.js.map} +1 -1
  133. package/dist/{paired-promotion-decision-DawN2o0G.d.ts → paired-promotion-decision-BBSxTo-h.d.ts} +2 -2
  134. package/dist/{paired-promotion-decision-DawN2o0G.d.ts.map → paired-promotion-decision-BBSxTo-h.d.ts.map} +1 -1
  135. package/dist/{paired-promotion-decision-Bi9__RQS.js → paired-promotion-decision-BoWHWL1i.js} +2 -2
  136. package/dist/{paired-promotion-decision-Bi9__RQS.js.map → paired-promotion-decision-BoWHWL1i.js.map} +1 -1
  137. package/dist/{paired-promotion-power-D03cUj9E.js → paired-promotion-power-BXH3gzvs.js} +3 -3
  138. package/dist/{paired-promotion-power-D03cUj9E.js.map → paired-promotion-power-BXH3gzvs.js.map} +1 -1
  139. package/dist/{pareto-UzjB3ZBk.js → pareto-B226QGVD.js} +54 -47
  140. package/dist/pareto-B226QGVD.js.map +1 -0
  141. package/dist/pipelines/index.d.ts +1 -1
  142. package/dist/pipelines/index.js +1 -1
  143. package/dist/{prime-protocol-RUPtoYiI.d.ts → prime-protocol-3aHqoxSH.d.ts} +2 -2
  144. package/dist/{prime-protocol-RUPtoYiI.d.ts.map → prime-protocol-3aHqoxSH.d.ts.map} +1 -1
  145. package/dist/profile-cell.d.ts +2 -2
  146. package/dist/{promotion-gate-DG_PSJx_.d.ts → promotion-gate-D-ffRHFQ.d.ts} +3 -3
  147. package/dist/{promotion-gate-DG_PSJx_.d.ts.map → promotion-gate-D-ffRHFQ.d.ts.map} +1 -1
  148. package/dist/{promotion-policy-DCgftbnd.js → promotion-policy-CfgRPGx0.js} +4 -4
  149. package/dist/{promotion-policy-DCgftbnd.js.map → promotion-policy-CfgRPGx0.js.map} +1 -1
  150. package/dist/{proposal-findings-CS6LoGGp.js → proposal-findings-BFtn6Lcx.js} +2 -2
  151. package/dist/{proposal-findings-CS6LoGGp.js.map → proposal-findings-BFtn6Lcx.js.map} +1 -1
  152. package/dist/{registry-BqoX13FD.d.ts → registry-x5n4GeBx.d.ts} +3 -3
  153. package/dist/{registry-BqoX13FD.d.ts.map → registry-x5n4GeBx.d.ts.map} +1 -1
  154. package/dist/{release-confidence-B4Xxdpmn.js → release-confidence-baM0TqCx.js} +2 -2
  155. package/dist/{release-confidence-B4Xxdpmn.js.map → release-confidence-baM0TqCx.js.map} +1 -1
  156. package/dist/reporting.d.ts +13 -6
  157. package/dist/reporting.d.ts.map +1 -1
  158. package/dist/reporting.js +5 -5
  159. package/dist/{summary-report-9kwI6jFQ.d.ts → research-report-CUbXuGX-.d.ts} +6 -121
  160. package/dist/research-report-CUbXuGX-.d.ts.map +1 -0
  161. package/dist/{researcher-BuojS14L.d.ts → researcher-D6D7q9uQ.d.ts} +4 -4
  162. package/dist/{researcher-BuojS14L.d.ts.map → researcher-D6D7q9uQ.d.ts.map} +1 -1
  163. package/dist/{reward-hacking-BYiDFbIl.js → reward-hacking-DNiHskry.js} +2 -2
  164. package/dist/{reward-hacking-BYiDFbIl.js.map → reward-hacking-DNiHskry.js.map} +1 -1
  165. package/dist/{reward-hacking-CIdVwVe4.d.ts → reward-hacking-_CAip56v.d.ts} +2 -2
  166. package/dist/{reward-hacking-CIdVwVe4.d.ts.map → reward-hacking-_CAip56v.d.ts.map} +1 -1
  167. package/dist/rl.d.ts +35 -17
  168. package/dist/rl.d.ts.map +1 -1
  169. package/dist/rl.js +116 -24
  170. package/dist/rl.js.map +1 -1
  171. package/dist/rollout/index.d.ts +5 -6
  172. package/dist/rollout/index.js +7 -6
  173. package/dist/{rollout-B86tqluQ.js → rollout-CCh4eSB3.js} +6 -5
  174. package/dist/{rollout-B86tqluQ.js.map → rollout-CCh4eSB3.js.map} +1 -1
  175. package/dist/{rollout-nodes-DhSPJ2X7.js → rollout-nodes-DzmHlPAC.js} +2 -2
  176. package/dist/rollout-nodes-DzmHlPAC.js.map +1 -0
  177. package/dist/{rubric-predictive-validity-Bbi88Aut.d.ts → rubric-predictive-validity-BTN3nNhC.d.ts} +2 -2
  178. package/dist/{rubric-predictive-validity-Bbi88Aut.d.ts.map → rubric-predictive-validity-BTN3nNhC.d.ts.map} +1 -1
  179. package/dist/{rubric-predictive-validity-DL7gJ51F.js → rubric-predictive-validity-Cln7r56F.js} +2 -2
  180. package/dist/{rubric-predictive-validity-DL7gJ51F.js.map → rubric-predictive-validity-Cln7r56F.js.map} +1 -1
  181. package/dist/{run-record-DTTx9Ktr.js → run-record-CbrxTcCO.js} +2 -2
  182. package/dist/{run-record-DTTx9Ktr.js.map → run-record-CbrxTcCO.js.map} +1 -1
  183. package/dist/{run-record-pBlhZizT.d.ts → run-record-hti3ETmO.d.ts} +2 -2
  184. package/dist/{run-record-pBlhZizT.d.ts.map → run-record-hti3ETmO.d.ts.map} +1 -1
  185. package/dist/{runtime-rollouts-BNrm5nC_.js → runtime-rollouts-C_hBaYXe.js} +279 -55
  186. package/dist/{runtime-rollouts-BNrm5nC_.js.map → runtime-rollouts-C_hBaYXe.js.map} +1 -1
  187. package/dist/{schema-PDKQ_iNE.d.ts → schema-BTTzvMnn.d.ts} +24 -5
  188. package/dist/schema-BTTzvMnn.d.ts.map +1 -0
  189. package/dist/{schema-ChIZfnqY.js → schema-b18jtzZw.js} +56 -3
  190. package/dist/schema-b18jtzZw.js.map +1 -0
  191. package/dist/search/index.d.ts +2 -2
  192. package/dist/search/index.js +2 -2
  193. package/dist/{search-kernel-C4XnLKIW.d.ts → search-kernel-IpyhPDQd.d.ts} +287 -276
  194. package/dist/search-kernel-IpyhPDQd.d.ts.map +1 -0
  195. package/dist/{search-ledger-9liYyZf5.js → search-ledger-D_ENQh0d.js} +4 -4
  196. package/dist/{search-ledger-9liYyZf5.js.map → search-ledger-D_ENQh0d.js.map} +1 -1
  197. package/dist/{search-ledger-file-BhOdgYIt.js → search-ledger-file-J8Xh9pU_.js} +3 -3
  198. package/dist/{search-ledger-file-BhOdgYIt.js.map → search-ledger-file-J8Xh9pU_.js.map} +1 -1
  199. package/dist/{search-shipper-B6tMNx1I.js → search-shipper-BUf7s92U.js} +3 -3
  200. package/dist/{search-shipper-B6tMNx1I.js.map → search-shipper-BUf7s92U.js.map} +1 -1
  201. package/dist/{search-summary-CISbbxyr.js → search-summary-B2RpvkkQ.js} +5 -5
  202. package/dist/{search-summary-CISbbxyr.js.map → search-summary-B2RpvkkQ.js.map} +1 -1
  203. package/dist/{sequential-1-T2oi1_.d.ts → sequential-B-zx24n_.d.ts} +2 -2
  204. package/dist/{sequential-1-T2oi1_.d.ts.map → sequential-B-zx24n_.d.ts.map} +1 -1
  205. package/dist/{sequential-Ko7T-zvu.js → sequential-C6k0Wrb7.js} +3 -3
  206. package/dist/{sequential-Ko7T-zvu.js.map → sequential-C6k0Wrb7.js.map} +1 -1
  207. package/dist/{sequential-9TVb5Nu5.js → sequential-pLr7Ukad.js} +3 -3
  208. package/dist/{sequential-9TVb5Nu5.js.map → sequential-pLr7Ukad.js.map} +1 -1
  209. package/dist/{single-run-lock-CUj2tjxT.js → single-run-lock-BSKsoeQF.js} +2 -2
  210. package/dist/{single-run-lock-CUj2tjxT.js.map → single-run-lock-BSKsoeQF.js.map} +1 -1
  211. package/dist/{skillopt-optimization-method-BtX7xXDd.js → skillopt-optimization-method-BnR2yh-a.js} +11 -11
  212. package/dist/{skillopt-optimization-method-BtX7xXDd.js.map → skillopt-optimization-method-BnR2yh-a.js.map} +1 -1
  213. package/dist/{statistical-heldout-Bx1QUDNy.d.ts → statistical-heldout-AvgLVFp6.d.ts} +6 -6
  214. package/dist/{statistical-heldout-Bx1QUDNy.d.ts.map → statistical-heldout-AvgLVFp6.d.ts.map} +1 -1
  215. package/dist/{statistical-heldout-DLO4Ebos.js → statistical-heldout-BvcAVtof.js} +3 -3
  216. package/dist/{statistical-heldout-DLO4Ebos.js.map → statistical-heldout-BvcAVtof.js.map} +1 -1
  217. package/dist/{statistics-CvvC-MPv.js → statistics-CHs0jlsY.js} +184 -2
  218. package/dist/statistics-CHs0jlsY.js.map +1 -0
  219. package/dist/statistics.d.ts +2 -2
  220. package/dist/statistics.js +2 -2
  221. package/dist/{store-tool-spans-kCDPEwjL.d.ts → store-tool-spans-Bm0-YhHG.d.ts} +5 -5
  222. package/dist/{store-tool-spans-kCDPEwjL.d.ts.map → store-tool-spans-Bm0-YhHG.d.ts.map} +1 -1
  223. package/dist/{summary-report-BEhqoxrA.js → summary-report-BgdIlM_w.js} +3 -3
  224. package/dist/{summary-report-BEhqoxrA.js.map → summary-report-BgdIlM_w.js.map} +1 -1
  225. package/dist/summary-report-figures-BoFCoiOP.d.ts +112 -0
  226. package/dist/summary-report-figures-BoFCoiOP.d.ts.map +1 -0
  227. package/dist/supervisor-run/index.d.ts +32 -8
  228. package/dist/supervisor-run/index.d.ts.map +1 -1
  229. package/dist/supervisor-run/index.js +3 -3
  230. package/dist/{systemone-CSwi1hp-.d.ts → systemone-DPVj7a1g.d.ts} +7 -7
  231. package/dist/{systemone-CSwi1hp-.d.ts.map → systemone-DPVj7a1g.d.ts.map} +1 -1
  232. package/dist/{systemone-review-WpWosn3a.d.ts → systemone-review-CrnsTRav.d.ts} +2 -2
  233. package/dist/{systemone-review-WpWosn3a.d.ts.map → systemone-review-CrnsTRav.d.ts.map} +1 -1
  234. package/dist/systemone.d.ts +3 -3
  235. package/dist/systemone.js +1 -1
  236. package/dist/{tool-groups-Bcasvncd.d.ts → tool-groups-5pgmtTmE.d.ts} +3 -3
  237. package/dist/tool-groups-5pgmtTmE.d.ts.map +1 -0
  238. package/dist/{tool-waste-BqSmmPUz.js → tool-waste-DWSohyd3.js} +2 -2
  239. package/dist/{tool-waste-BqSmmPUz.js.map → tool-waste-DWSohyd3.js.map} +1 -1
  240. package/dist/{trace-questions-DI42jXPj.d.ts → trace-questions-ETZDn5ax.d.ts} +3 -3
  241. package/dist/{trace-questions-DI42jXPj.d.ts.map → trace-questions-ETZDn5ax.d.ts.map} +1 -1
  242. package/dist/trace-repair/index.d.ts +2 -2
  243. package/dist/trace-repair/index.js +1 -1
  244. package/dist/traces.d.ts +4 -4
  245. package/dist/training-admission-xaDOlQ_U.d.ts +31 -0
  246. package/dist/training-admission-xaDOlQ_U.d.ts.map +1 -0
  247. package/dist/{tree-D2cNtu9m.js → tree-DA_WI1aV.js} +5 -5
  248. package/dist/{tree-D2cNtu9m.js.map → tree-DA_WI1aV.js.map} +1 -1
  249. package/dist/{types-DbGSC2No.d.ts → types-Dtt11Ppr.d.ts} +2 -2
  250. package/dist/{types-DbGSC2No.d.ts.map → types-Dtt11Ppr.d.ts.map} +1 -1
  251. package/dist/{types-CLGrB4Sv.d.ts → types-_dfu6Ox2.d.ts} +4 -4
  252. package/dist/{types-CLGrB4Sv.d.ts.map → types-_dfu6Ox2.d.ts.map} +1 -1
  253. package/dist/{types-ByrbgALT.d.ts → types-qJwFZTqa.d.ts} +7 -6
  254. package/dist/types-qJwFZTqa.d.ts.map +1 -0
  255. package/dist/{types-CEgIBy0W.d.ts → types-rf0yhJmW.d.ts} +3 -3
  256. package/dist/{types-CEgIBy0W.d.ts.map → types-rf0yhJmW.d.ts.map} +1 -1
  257. package/dist/wire/index.d.ts +1 -1
  258. package/docs/adopt-stack.md +2 -0
  259. package/docs/concepts.md +4 -1
  260. package/docs/design/statistics-decisions.md +17 -0
  261. package/docs/rollout.md +124 -4
  262. package/docs/search-ledger.md +18 -1
  263. package/docs/trace-analysis.md +11 -3
  264. package/package.json +3 -3
  265. package/dist/agent-profile-cell-3kYxUsK2.d.ts.map +0 -1
  266. package/dist/analyze-runs-BaziIw93.d.ts.map +0 -1
  267. package/dist/benchmark-command-DRAHkn4D.js.map +0 -1
  268. package/dist/exporters-BKZLt1Px.js.map +0 -1
  269. package/dist/exporters-dQKYD_Zo.d.ts +0 -159
  270. package/dist/exporters-dQKYD_Zo.d.ts.map +0 -1
  271. package/dist/failure-cluster-DOoa7CBg.d.ts.map +0 -1
  272. package/dist/hf-dataset-Bv114tzB.js.map +0 -1
  273. package/dist/index-BI9ecONy.d.ts.map +0 -1
  274. package/dist/index-BriU7rfL.d.ts.map +0 -1
  275. package/dist/index-C8a9Dyan.d.ts.map +0 -1
  276. package/dist/index-D-0mg-eu.d.ts.map +0 -1
  277. package/dist/index-DHWFYUVW.d.ts.map +0 -1
  278. package/dist/index-VSN1IZQp.d.ts.map +0 -1
  279. package/dist/journal-CTX5uK-n.js.map +0 -1
  280. package/dist/llm-judge-DzAT7Wka.js.map +0 -1
  281. package/dist/mint-Ck92efNo.js.map +0 -1
  282. package/dist/pareto-UzjB3ZBk.js.map +0 -1
  283. package/dist/reward-ap_R9mCH.d.ts +0 -53
  284. package/dist/reward-ap_R9mCH.d.ts.map +0 -1
  285. package/dist/rollout-nodes-DhSPJ2X7.js.map +0 -1
  286. package/dist/schema-ChIZfnqY.js.map +0 -1
  287. package/dist/schema-PDKQ_iNE.d.ts.map +0 -1
  288. package/dist/search-kernel-C4XnLKIW.d.ts.map +0 -1
  289. package/dist/statistics-CvvC-MPv.js.map +0 -1
  290. package/dist/summary-report-9kwI6jFQ.d.ts.map +0 -1
  291. package/dist/tool-groups-Bcasvncd.d.ts.map +0 -1
  292. package/dist/types-ByrbgALT.d.ts.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"mint-Ck92efNo.js","names":[],"sources":["../src/rollout/mint.ts"],"sourcesContent":["/**\n * Rollout minting — `tangle.rollout.v1` lines joined from the records the\n * substrate ALREADY keeps. There is no separate rollout store: a rollout\n * is the JOIN of a RunRecord (identity, provenance, cost, outcome) with\n * its trace (spans share `runId`), projected into the canonical line.\n *\n * Composition, not duplication:\n * - identity/provenance → `RunRecord` (candidateId, splitTag, agentProfile, hashes)\n * - step structure → `buildTrajectory` over the shared TraceStore\n * - preference-pair export → `feedbackTrajectoryToOptimizerRow` (feedback-trajectory.ts)\n * - PRM / reward-model → `reward-model-export.ts`\n * - search lineage → `searchLineage`, read from the run's search ledger\n *\n * Anti-Goodhart invariant: a run whose `outcome.realness.gated` is true is\n * never exported with a positive reward OR with any of the numbers that reward\n * was computed from. The gate travels into the training data (`reward` forced\n * to 0, `realness_gated: true`) and the whole outcome is transformed by\n * `gateGamedOutcome` inside `assertMinted` below, which relocates `metrics` and\n * `verdict` to `provenance.gated_evidence`. Mint returns\n * `MintedRolloutLine[]`: the brand the training exporters require, which only\n * this function, `readRolloutLedger`, and an explicit `assertMinted` can mint.\n *\n * A record carrying NEITHER split score is REJECTED (`ValidationError`), never\n * minted at 0 — \"nobody graded this\" is not the same claim as \"graded a total\n * failure\", and a trainer reading 0 learns the second. Lines that already\n * carry `reward: null` (interchange imports, existing ledgers) remain valid on\n * the wire; only the RunRecord→line door refuses.\n *\n * Records without spans or an explicit full capture become labeled GAP LINES (messages: [],\n * provenance.gap) — present in the output AND surfaced in\n * `missingTraces`; a capture gap is a finding, never a silent omission.\n */\n\nimport { ValidationError } from '../errors'\nimport { type RunRecord, type RunSearchCoordinates, runTaskScore } from '../run-record'\nimport type { LlmSpan, Span, ToolSpan } from '../trace/schema'\nimport type { TraceStore } from '../trace/store'\nimport { buildTrajectory } from '../trajectory'\nimport { rolloutRewardFields, scoreOrigin } from './reward'\nimport {\n assertMinted,\n type ChatMessage,\n type MintedRolloutLine,\n ROLLOUT_SCHEMA,\n type RolloutEvidenceAttempt,\n type RolloutRole,\n type RolloutSplit,\n type RolloutStep,\n} from './schema'\n\n/** Redactor for transcript/step payload text (secrets, PII), not opaque identity. */\nexport type RolloutScrubber = (text: string) => string\n\n/** A search cell's place in its search tree, read from the search ledger. */\nexport interface RolloutSearchLineage {\n /** Edges between the cell's node and the search root; the root is 0. */\n depth: number\n /** Order in which the node registered in its search; the root is 0. */\n ordinal: number\n /** Repeat index of the cell on its task, from 0. */\n rep: number\n /** Run id of the cell whose execution contains this search; null for a\n * top-level search. */\n containingRunId: string | null\n}\n\nexport interface MintRolloutOptions {\n scrub?: RolloutScrubber\n /**\n * Full canonical capture, including turns no longer in the model's context.\n * When supplied, missing/empty capture is refused, never replaced with a\n * span summary. Use the execution owner's capture or the existing harness\n * readers; reviewer traces and compacted histories are not full capture.\n */\n messagesOf?: (\n runId: string,\n ) => readonly ChatMessage[] | undefined | Promise<readonly ChatMessage[] | undefined>\n /** Provider attempts from a retained receipt bound to the exact run. */\n evidenceOf?: (\n runId: string,\n ) =>\n | { runId: string; attempts: readonly RolloutEvidenceAttempt[] }\n | undefined\n | Promise<{ runId: string; attempts: readonly RolloutEvidenceAttempt[] } | undefined>\n /** Cap steps per line (longest runs first drop middle steps). Default: no cap. */\n maxSteps?: number\n /** Role recorded on every minted line. Default 'agent' (a solo eval run). */\n role?: RolloutRole\n /** Task suite label. Default: the record's `experimentId`. */\n suite?: string\n /** Injected clock for deterministic output. */\n now?: () => Date\n /**\n * Lineage of a search run, read from its search ledger. It fills the line's\n * `generation` (node depth), `candidate_index` (node order), `task.rep` and\n * `parent_rollout_id` (the containing cell's run). Mint refuses a record\n * that carries `search` when this is absent, because a null `generation`\n * states that the run is not part of a search.\n */\n searchLineage?: (\n search: RunSearchCoordinates,\n ) => RolloutSearchLineage | Promise<RolloutSearchLineage>\n}\n\nexport interface MintRolloutResult {\n rows: MintedRolloutLine[]\n /** runIds that had a RunRecord but no spans — emitted as gap lines AND listed here. */\n missingTraces: string[]\n}\n\nconst asText = (v: unknown, scrub: RolloutScrubber): string => {\n const s = typeof v === 'string' ? v : JSON.stringify(v)\n return scrub(s ?? '')\n}\n\nfunction projectStep(span: Span, scrub: RolloutScrubber): RolloutStep {\n const base: RolloutStep = {\n kind: span.kind,\n name: scrub(span.name),\n status: span.status,\n durationMs: span.endedAt !== undefined ? span.endedAt - span.startedAt : undefined,\n }\n if (span.kind === 'llm') {\n const llm = span as LlmSpan\n const last = llm.messages[llm.messages.length - 1]\n if (last && last.content !== null) base.input = scrub(last.content)\n if (llm.output !== undefined) base.output = scrub(llm.output)\n } else if (span.kind === 'tool') {\n const tool = span as ToolSpan\n base.input = asText(tool.args, scrub)\n if (tool.result !== undefined) base.output = asText(tool.result, scrub)\n }\n return base\n}\n\n/** Preserve captured fields; invocation ids are opaque linkage, not generated text. */\nfunction projectMessage(message: ChatMessage, scrub: RolloutScrubber): ChatMessage {\n return {\n role: message.role,\n content: message.content === null ? null : scrub(message.content),\n ...(message.reasoning_content !== undefined\n ? { reasoning_content: scrub(message.reasoning_content) }\n : {}),\n ...(message.tool_calls !== undefined\n ? {\n tool_calls: message.tool_calls.map((call) => ({\n id: call.id,\n type: call.type,\n function: {\n name: call.function.name,\n arguments: scrub(call.function.arguments),\n },\n })),\n }\n : {}),\n ...(message.tool_call_id !== undefined ? { tool_call_id: message.tool_call_id } : {}),\n ...(message.name !== undefined ? { name: message.name } : {}),\n ...(message.is_copied_context !== undefined\n ? { is_copied_context: message.is_copied_context }\n : {}),\n }\n}\n\n/** Never recover missing calls from tool names, span order or argument summaries. */\nfunction requireToolLinkage(messages: readonly ChatMessage[], runId: string): void {\n const seen = new Set<string>()\n const pending = new Map<string, string>()\n const refuse: (detail: string) => never = (detail) => {\n throw new ValidationError(`Cannot mint rollout for run ${runId}: ${detail}`)\n }\n for (const message of messages) {\n if (message.tool_calls !== undefined) {\n if (message.role !== 'assistant' || !Array.isArray(message.tool_calls)) {\n refuse('tool calls must be captured on an assistant message')\n }\n if (pending.size > 0) refuse('new tool calls precede the prior invocation results')\n for (const call of message.tool_calls) {\n if (\n !call ||\n typeof call.id !== 'string' ||\n call.id.length === 0 ||\n seen.has(call.id) ||\n call.type !== 'function' ||\n !call.function ||\n typeof call.function.name !== 'string' ||\n call.function.name.length === 0 ||\n typeof call.function.arguments !== 'string'\n ) {\n refuse('missing, duplicate or malformed tool invocation')\n }\n seen.add(call.id)\n pending.set(call.id, call.function.name)\n }\n }\n if (message.role === 'tool') {\n const id = message.tool_call_id\n if (typeof id !== 'string' || !pending.has(id)) {\n refuse('tool result has no captured invocation (or answers it more than once)')\n }\n if (message.name !== undefined && message.name !== pending.get(id)) {\n refuse('tool result name does not match its invocation')\n }\n pending.delete(id)\n } else if (message.tool_call_id !== undefined) {\n refuse('tool_call_id is only valid on a tool result')\n } else if (pending.size > 0 && message.tool_calls === undefined) {\n refuse('conversation advances before all tool results were captured')\n }\n }\n if (pending.size > 0) refuse('tool invocation has no captured result')\n}\n\n/** Legacy span history; callers with compacted contexts supply messagesOf instead. */\nfunction finalConversation(spans: Span[]): ChatMessage[] {\n const llms = spans.filter((s): s is LlmSpan => s.kind === 'llm')\n const last = llms[llms.length - 1]\n if (!last) return []\n const messages: ChatMessage[] = [...last.messages]\n if (last.output !== undefined && last.output !== '') {\n messages.push({ role: 'assistant', content: last.output })\n }\n return messages\n}\n\n// The reward derivations live in the leaf module `./reward` so gate and\n// reporting code can import them without dragging in the trace store; they are\n// re-exported here because the derivations shipped from this path.\nexport {\n isRealnessGated,\n observedScore,\n observedSplitScore,\n type ScoreOrigin,\n type ScorePreference,\n scoreOrigin,\n trainingReward,\n trainingScore,\n} from './reward'\n\nconst REWARD_SOURCE: Record<ReturnType<typeof scoreOrigin>, string> = {\n holdout: 'run-record/holdout-score',\n search: 'run-record/search-score',\n unscored: 'run-record/unscored',\n}\n\n/**\n * The mint door refuses an execution-only record: a missing training label is\n * not a zero reward, and not a mintable line either. Lines that already carry\n * `reward: null` — interchange imports, existing ledgers — stay valid on the\n * wire and keep their labeled gap; this guard is only about the\n * RunRecord→line door, where the producer can still be told to go score the\n * run instead of shipping an unlabeled row.\n */\nfunction requireTaskScore(record: RunRecord): void {\n if (runTaskScore(record) === undefined) {\n throw new ValidationError(`Cannot mint rollout for run ${record.runId}: task score is missing`)\n }\n}\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null\n\ninterface MintFieldCheck {\n /** The RunRecord path, spelled the way the caller has to fix it. */\n readonly field: string\n /** True when the record carries something the line can honestly be built from. */\n readonly present: (bag: Record<string, unknown>) => boolean\n /** What the caller writes onto the record, and why that value and not another. */\n readonly remedy: string\n}\n\n/**\n * The RunRecord fields mint reads that a record can be missing even though the\n * TYPE says it cannot. There are exactly two ways that happens:\n *\n * 1. The field was OPTIONAL when the record was serialized. `costProvenance`,\n * `terminalOutcome` and `scenarioId` were optional through agent-eval\n * 0.125 and became required in 0.126, with no on-disk migration — so every\n * ledger written before 0.126 is full of records the type calls complete.\n * 2. Mint reads a level DEEPER than the record's own type is checked at:\n * `outcome.raw`, `tokenUsage.input`, `tokenUsage.output`.\n *\n * Nothing else needs a check here. Every other field mint copies is a top-level\n * scalar landing in a typed slot on the line, where an absent value arrives as\n * `undefined` and `assertMinted` refuses it by name. These are the ones where an\n * absent value instead kills the join with `TypeError: Cannot read properties of\n * undefined`, or — worse — mints a line that reads as measured.\n *\n * This is deliberately NOT `validateRunRecord`. That validator answers \"is this\n * a valid RunRecord\", which is a wider question than \"can a rollout line be\n * built from this one\": it also enforces model-snapshot discipline, the\n * `terminalFailureReason` coupling, and the `costUsd === costProvenance.usd`\n * agreement. Routing the mint door through it would refuse records mint can\n * mint honestly today (a model alias with no snapshot date, for one), which is\n * a policy change with its own blast radius and not this bug. The door asks the\n * narrower question and answers it precisely.\n */\nconst MINT_FIELD_CHECKS: readonly MintFieldCheck[] = [\n {\n field: 'costProvenance',\n present: (bag) => isObject(bag.costProvenance) && typeof bag.costProvenance.kind === 'string',\n remedy:\n \"Records written before agent-eval 0.126 predate this field and carry `costUsd: 0` as the documented uncaptured sentinel, which is NOT an observed zero. Backfill it as costProvenance: { kind: 'uncaptured', usd: null } WITH costUsd: null — an uncaptured cost whose costUsd is non-null is rejected by validateRunRecord, so provenance alone leaves the record invalid.\",\n },\n {\n field: 'tokenUsage',\n present: (bag) => isObject(bag.tokenUsage),\n remedy:\n \"The line's cost.tokens_in and cost.tokens_out are read from it. Backfill it from the provider's usage report; mint will not write 0 for tokens nobody counted.\",\n },\n {\n field: 'tokenUsage.input',\n present: (bag) => !isObject(bag.tokenUsage) || typeof bag.tokenUsage.input === 'number',\n remedy: \"The line's cost.tokens_in is read from it, and a missing count is not a zero count.\",\n },\n {\n field: 'tokenUsage.output',\n present: (bag) => !isObject(bag.tokenUsage) || typeof bag.tokenUsage.output === 'number',\n remedy: \"The line's cost.tokens_out is read from it, and a missing count is not a zero count.\",\n },\n {\n field: 'outcome',\n present: (bag) => isObject(bag.outcome),\n remedy:\n \"The line's reward, reward_source and metrics are all read from it. A record with no outcome carries no training label at all, and mint refuses an unlabeled row.\",\n },\n {\n field: 'outcome.raw',\n // Reported only when `outcome` itself is present: one absent field should\n // produce one reason per CAUSE, not one per path that dereferences it.\n present: (bag) => !isObject(bag.outcome) || isObject(bag.outcome.raw),\n remedy:\n 'It is the metric bag copied verbatim into the line\\'s outcome.metrics. `{ ...undefined }` spreads to `{}` without complaint, so an absent bag would mint as \"this run reported no metrics\" — a different claim from \"this record predates the field\". Backfill it as {} only when that is what you mean.',\n },\n {\n field: 'terminalOutcome',\n present: (bag) => typeof bag.terminalOutcome === 'string',\n remedy:\n \"It became required in agent-eval 0.126. Backfill it from root-run or process evidence, or as 'unknown' when the producer has none — mint will not decide the line's is_completed and is_truncated for you.\",\n },\n {\n field: 'scenarioId',\n present: (bag) => typeof bag.scenarioId === 'string' && bag.scenarioId.length > 0,\n remedy:\n \"It became required in agent-eval 0.126 and becomes the line's task.instance_id, which must be a non-empty string. Backfill it from the scenario the run was dealt (pre-0.126 producers often left it in outcome.raw.scenario_id).\",\n },\n]\n\n/**\n * Why a record cannot be minted, one entry per missing field, empty when it can.\n *\n * Exported so a caller can partition a whole ledger — \"which of my 2742 records\n * predate 0.126\" — without catching an exception per record, and without\n * re-deriving the field list on their side. A re-derived list is a list that\n * drifts from the door it is supposed to predict.\n *\n * Takes a `RunRecord` because that is what the caller holds and what the\n * compiler agrees they hold. The type is precisely the thing that is wrong, so\n * the checks read the record as the untyped bag it actually is on disk.\n */\nexport function unmintableReasons(record: RunRecord): string[] {\n const bag = record as unknown as Record<string, unknown>\n return MINT_FIELD_CHECKS.filter((check) => !check.present(bag)).map(\n (check) => `${check.field} is missing. ${check.remedy}`,\n )\n}\n\n/**\n * The mint door THROWS on a record it cannot build a line from. It does NOT\n * normalise an absent `costProvenance` to `{kind:'uncaptured', usd:null}`, and\n * the choice is not stylistic:\n *\n * - Normalising cannot cover the record, only part of it. `terminalOutcome`\n * feeds `is_completed` and `is_truncated`, which the rollout schema requires\n * to be BOOLEAN — there is no null to fall back to, so every possible\n * default is a claim about how the run ended. A door that quietly fixes the\n * cost and invents the ending is a door no caller can predict.\n * - Normalising the cost requires knowing what `costUsd: 0` meant, and mint\n * cannot know. A genuinely free run and an uncaptured one are the same bytes\n * in a pre-0.126 record; only the producer can tell them apart. Guessing is\n * exactly the failure this guard exists to stop — the 0.125 optional chain\n * `record.costProvenance?.kind === 'uncaptured'` already made that guess,\n * silently, and every record it touched minted `cost.usd: 0`: an unmeasured\n * cost published as a measured zero, into a training dataset.\n * - `requireTaskScore`, directly above, already refuses an unlabeled record\n * for the same reason: \"nobody graded this\" is not \"graded zero\". \"Nobody\n * billed this\" is not \"billed zero\".\n *\n * The caller who wants historical records minted backfills them at their store,\n * in one pass, where `costUsd` can be corrected alongside `costProvenance` —\n * which is the only place that decision can be made correctly. The refusal names\n * the run, names every missing field, and spells the value to write.\n */\nfunction requireMintableRecord(record: RunRecord): void {\n const reasons = unmintableReasons(record)\n if (reasons.length === 0) return\n throw new ValidationError(`Cannot mint rollout for run ${record.runId}: ${reasons.join('\\n ')}`)\n}\n\n/** The search lineage a record's line is built from; undefined for a record outside a search. */\nasync function resolveSearchLineage(\n record: RunRecord,\n options: MintRolloutOptions,\n): Promise<RolloutSearchLineage | undefined> {\n if (record.search === undefined) return undefined\n const refuse: (detail: string) => never = (detail) => {\n throw new ValidationError(`Cannot mint rollout for search run ${record.runId}: ${detail}`)\n }\n if (!options.searchLineage) {\n refuse('pass searchLineage so generation, candidate_index, rep and parent come from its ledger')\n }\n const lineage = await options.searchLineage(record.search)\n const isCount = (value: unknown): boolean => Number.isSafeInteger(value) && (value as number) >= 0\n if (!isCount(lineage.depth)) refuse('lineage depth must be a non-negative integer')\n if (!isCount(lineage.ordinal)) refuse('lineage ordinal must be a non-negative integer')\n if (!isCount(lineage.rep)) refuse('lineage rep must be a non-negative integer')\n if (\n lineage.containingRunId !== null &&\n (typeof lineage.containingRunId !== 'string' || lineage.containingRunId.length === 0)\n ) {\n refuse('lineage containingRunId must be null or a non-empty run id')\n }\n if (lineage.containingRunId === record.runId) refuse('a run cannot contain itself')\n return lineage\n}\n\nconst SPLIT_FROM_TAG: Record<RunRecord['splitTag'], RolloutSplit> = {\n search: 'search',\n dev: 'dev',\n holdout: 'holdout',\n}\n\nfunction mintLine(\n record: RunRecord,\n lineage: RolloutSearchLineage | undefined,\n steps: RolloutStep[],\n messages: ChatMessage[],\n options: MintRolloutOptions,\n capturedAt: string,\n gap?: string,\n attempts?: readonly RolloutEvidenceAttempt[],\n lossyProjection = false,\n): MintedRolloutLine {\n // Field presence first, and BEFORE `requireTaskScore`: that guard reads\n // `record.outcome.searchScore` on its way to the answer, so an absent\n // `outcome` would throw a bare TypeError from inside the guard whose whole\n // job is to produce a clean refusal.\n //\n // Both branches of `mintRolloutRows` — the traced line and the gap line —\n // land here, which is the point: `mintLine` is the only constructor of a\n // `MintedRolloutLine` from a RunRecord, so there is no path into the waist\n // that skips the check and no way to get this wrong from the outside.\n requireMintableRecord(record)\n // A missing task score is refused before anything is built: an\n // execution-only record has no training label, and a missing label is\n // neither a zero reward nor a mintable row.\n requireTaskScore(record)\n // `reward` and `realness_gated` come out of one call, so neither door into\n // the waist can write one and forget the other.\n const rewardFields = rolloutRewardFields(record)\n // Only an observed or estimated amount is a total; a lower bound is not.\n const knownTotal =\n record.costProvenance.kind === 'observed' || record.costProvenance.kind === 'estimated'\n const terminalOutcome = record.terminalOutcome\n const isCompleted = terminalOutcome === 'succeeded' || terminalOutcome === 'failed'\n const isTruncated = terminalOutcome === 'cancelled' || terminalOutcome === 'incomplete'\n const terminalError =\n terminalOutcome === 'failed' ||\n terminalOutcome === 'cancelled' ||\n terminalOutcome === 'incomplete'\n ? (record.terminalFailureReason ?? `run ended ${terminalOutcome}`)\n : null\n // `assertMinted` rather than a cast: mint is the producer the whole gate\n // rests on, so it proves the line it just built is valid instead of asserting\n // it by fiat. The brand is unforgeable precisely because nobody casts to it.\n return assertMinted(\n {\n schema: ROLLOUT_SCHEMA,\n rollout_id: record.runId,\n parent_rollout_id: lineage?.containingRunId ?? null,\n run_id: record.runId,\n experiment_id: record.experimentId,\n candidate_id: record.candidateId,\n generation: lineage?.depth ?? null,\n candidate_index: lineage?.ordinal ?? null,\n role: options.role ?? 'agent',\n task: {\n suite: options.suite ?? record.experimentId,\n instance_id: record.scenarioId,\n split: SPLIT_FROM_TAG[record.splitTag],\n seed: record.seed,\n rep: lineage?.rep ?? 0,\n },\n policy: {\n harness: null,\n harness_version: null,\n model: record.model,\n provider: null,\n profile_commit: record.commitSha,\n prompt_hash: record.promptHash,\n config_hash: record.configHash,\n agent_profile_cell_id: record.agentProfile?.cellId ?? null,\n sampling: null,\n },\n messages,\n tool_defs: [],\n ...(steps.length > 0 ? { steps } : {}),\n outcome: {\n ...rewardFields,\n reward_source: REWARD_SOURCE[scoreOrigin(record)],\n verdict: null,\n // A verbatim bulk copy, deliberately UNFILTERED here. `outcome.raw`\n // holds the per-layer verifier scores (`layer.*`) that the reward was\n // derived from, so on a gated run this dict is the reward signal in\n // component form — but filtering it at this call site is the pattern\n // that has now leaked twice, because the next producer to write a\n // reward-bearing field forgets. The gate is applied to the whole\n // outcome once, in `assertMinted` below (`gateGamedOutcome`), which\n // moves the block to `provenance.gated_evidence` when the run is gated\n // and leaves it here untouched when it is not.\n metrics: { ...record.outcome.raw },\n is_completed: isCompleted,\n is_truncated: isTruncated,\n error: terminalError,\n },\n cost: {\n usd: knownTotal ? record.costUsd : null,\n tokens_in: record.tokenUsage.input,\n tokens_out: record.tokenUsage.output,\n tokens_reasoning: record.tokenUsage.reasoning ?? null,\n cache_read: record.tokenUsage.cached ?? null,\n cache_write: record.tokenUsage.cacheWrite ?? null,\n wall_s: Math.round(record.wallMs / 1000),\n },\n artifacts: {\n patch_path: null,\n run_dir: null,\n transcript_ref: record.traceRef ? `trace:${record.traceRef.traceId}` : null,\n },\n provenance: {\n captured_at: capturedAt,\n capture: 'mint',\n ...(record.search !== undefined ? { search: { ...record.search } } : {}),\n ...(attempts !== undefined ? { attempts: [...attempts] } : {}),\n ...(lossyProjection ? { lossy_projection: true } : {}),\n ...(gap !== undefined ? { gap } : {}),\n },\n },\n `minted rollout line for run ${record.runId}`,\n )\n}\n\n/**\n * Join RunRecords with their traces into canonical rollout lines. Records\n * without spans or an explicit capture are emitted as labeled gap lines and reported in\n * `missingTraces`. Execution-only records without a task score are rejected\n * because a missing training label is not a zero reward.\n */\nexport async function mintRolloutRows(\n records: RunRecord[],\n store: TraceStore,\n options: MintRolloutOptions = {},\n): Promise<MintRolloutResult> {\n const scrub = options.scrub ?? ((t) => t)\n const capturedAt = (options.now?.() ?? new Date()).toISOString()\n if (\n options.maxSteps !== undefined &&\n (!Number.isSafeInteger(options.maxSteps) || options.maxSteps < 1)\n ) {\n throw new ValidationError('maxSteps must be a positive integer')\n }\n const rows: MintedRolloutLine[] = []\n const missingTraces: string[] = []\n for (const record of records) {\n const trajectory = await buildTrajectory(store, record.runId)\n const captured = options.messagesOf ? await options.messagesOf(record.runId) : undefined\n const evidence = options.evidenceOf ? await options.evidenceOf(record.runId) : undefined\n if (evidence !== undefined && evidence?.runId !== record.runId) {\n throw new ValidationError(\n `Cannot mint rollout for run ${record.runId}: capture evidence belongs to another run`,\n )\n }\n if (\n options.evidenceOf &&\n (!evidence || !Array.isArray(evidence.attempts) || evidence.attempts.length === 0)\n ) {\n throw new ValidationError(\n `Cannot mint rollout for run ${record.runId}: provider attempt evidence is missing`,\n )\n }\n if (\n evidence?.attempts.some(\n (attempt) =>\n !attempt ||\n !Array.isArray(attempt.nativeSessionIds) ||\n !Array.isArray(attempt.processIds) ||\n !Array.isArray(attempt.missingReasons),\n )\n ) {\n throw new ValidationError(\n `Cannot mint rollout for run ${record.runId}: malformed provider attempt evidence`,\n )\n }\n const attempts = evidence?.attempts.map((attempt) => ({\n ...attempt,\n nativeSessionIds: [...attempt.nativeSessionIds],\n processIds: [...attempt.processIds],\n missingReasons: attempt.missingReasons.map(scrub),\n }))\n if (options.messagesOf && (!Array.isArray(captured) || captured.length === 0)) {\n throw new ValidationError(\n `Cannot mint rollout for run ${record.runId}: full capture is missing`,\n )\n }\n const lineage = await resolveSearchLineage(record, options)\n if (trajectory.steps.length === 0 && !options.messagesOf) {\n missingTraces.push(record.runId)\n rows.push(\n mintLine(\n record,\n lineage,\n [],\n [],\n options,\n capturedAt,\n 'no trace spans recorded for this runId',\n attempts,\n ),\n )\n continue\n }\n let steps = trajectory.steps.map((s) => projectStep(s.span, scrub))\n const omittedSteps =\n options.maxSteps !== undefined && steps.length > options.maxSteps\n ? steps.length - options.maxSteps\n : 0\n if (options.maxSteps !== undefined && omittedSteps > 0) {\n // Keep the head and tail — the middle of a long run is the least\n // informative for outcome attribution.\n const head = Math.ceil(options.maxSteps / 2)\n const tail = options.maxSteps - head\n steps = [...steps.slice(0, head), ...steps.slice(steps.length - tail)]\n }\n const spans = trajectory.steps.map((s) => s.span)\n const messages = captured ?? finalConversation(spans)\n requireToolLinkage(messages, record.runId)\n const conversation = messages.map((message) => projectMessage(message, scrub))\n // SFT drops copied context. That projection must not orphan a retained result.\n requireToolLinkage(\n conversation.filter((message) => message.is_copied_context !== true),\n record.runId,\n )\n const gaps: string[] = []\n if (conversation.length === 0) gaps.push('trace has no llm spans; no conversation to inline')\n else if (!options.messagesOf) {\n gaps.push('messages project only the last LLM context; full transcript was not captured')\n }\n if (omittedSteps > 0) gaps.push(`${omittedSteps} middle trace steps omitted by maxSteps`)\n for (const attempt of attempts ?? []) {\n if (attempt.missingReasons.length > 0) {\n gaps.push(`provider attempt ${attempt.ordinal}: ${attempt.missingReasons.join(', ')}`)\n }\n }\n rows.push(\n mintLine(\n record,\n lineage,\n steps,\n conversation,\n options,\n capturedAt,\n gaps.length > 0 ? gaps.join('; ') : undefined,\n attempts,\n (conversation.length > 0 && !options.messagesOf) ||\n omittedSteps > 0 ||\n (attempts?.some((attempt) => attempt.missingReasons.length > 0) ?? false),\n ),\n )\n }\n return { rows, missingTraces }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8GA,MAAM,UAAU,GAAY,UAAmC;CAE7D,OAAO,OADG,OAAO,MAAM,WAAW,IAAI,KAAK,UAAU,CAAC,MACpC,EAAE;AACtB;AAEA,SAAS,YAAY,MAAY,OAAqC;CACpE,MAAM,OAAoB;EACxB,MAAM,KAAK;EACX,MAAM,MAAM,KAAK,IAAI;EACrB,QAAQ,KAAK;EACb,YAAY,KAAK,YAAY,KAAA,IAAY,KAAK,UAAU,KAAK,YAAY,KAAA;CAC3E;CACA,IAAI,KAAK,SAAS,OAAO;EACvB,MAAM,MAAM;EACZ,MAAM,OAAO,IAAI,SAAS,IAAI,SAAS,SAAS;EAChD,IAAI,QAAQ,KAAK,YAAY,MAAM,KAAK,QAAQ,MAAM,KAAK,OAAO;EAClE,IAAI,IAAI,WAAW,KAAA,GAAW,KAAK,SAAS,MAAM,IAAI,MAAM;CAC9D,OAAO,IAAI,KAAK,SAAS,QAAQ;EAC/B,MAAM,OAAO;EACb,KAAK,QAAQ,OAAO,KAAK,MAAM,KAAK;EACpC,IAAI,KAAK,WAAW,KAAA,GAAW,KAAK,SAAS,OAAO,KAAK,QAAQ,KAAK;CACxE;CACA,OAAO;AACT;;AAGA,SAAS,eAAe,SAAsB,OAAqC;CACjF,OAAO;EACL,MAAM,QAAQ;EACd,SAAS,QAAQ,YA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,IAAI,QAAQ,eAAe,KAAK,IAAI,GAAG;EAGzF,KAAK,KACH,SACE,QACA,SACA,OACA,cACA,SACA,YACA,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI,IAAI,KAAA,GACpC,UACC,aAAa,SAAS,KAAK,CAAC,QAAQ,cACnC,eAAe,MACd,UAAU,MAAM,YAAY,QAAQ,eAAe,SAAS,CAAC,KAAK,MACvE,CACF;CACF;CACA,OAAO;EAAE;EAAM;CAAc;AAC/B"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"pareto-UzjB3ZBk.js","names":["RESAMPLES","plain","plain"],"sources":["../src/statistics/normalize-signed-zero.ts","../src/campaign/estimate-node.ts","../src/campaign/search-kernel-artifacts.ts","../src/campaign/search-claim.ts","../src/campaign/search-kernel-close.ts","../src/campaign/search-kernel-contract.ts","../src/campaign/search-kernel-claim.ts","../src/campaign/search-kernel-completions.ts","../src/campaign/search-kernel-lanes.ts","../src/search/lenses/shared.ts","../src/search/lenses/operator-yield.ts","../src/campaign/search-kernel-policy-view.ts","../src/campaign/search-kernel-progress.ts","../src/campaign/search-kernel-proposals.ts","../src/campaign/search-kernel-runner.ts","../src/campaign/search-kernel.ts","../src/pareto.ts"],"sourcesContent":["/** Normalize IEEE negative zero before numerical evidence reaches canonical JSON. */\nexport function normalizeSignedZero(value: number): number {\n return value === 0 ? 0 : value\n}\n","/**\n * Per-node statistics of a search.\n *\n * `estimateNode` is the one paired contrast of two nodes: it averages each\n * node's cells inside their units, pairs the units both nodes scored, and runs\n * `pairedDeltaTest` on the per-unit deltas. `estimateNodeFromCells` is the same\n * computation over cells a caller already holds, such as rows a server read\n * from its database. The bootstrap seed comes from `cellSetDigest`, the digest\n * of exactly the cells used, so a producer and a verifier that hold the same\n * cells report the same bits.\n *\n * `searchPosterior` gives every node a normal posterior on its improvement over\n * the root, which expansion policies sample parents from. Its numbers steer\n * spend and claim nothing.\n */\n\nimport { compareCodeUnits, hashCanonical } from '../ledger-core/canonical'\nimport { minimumPairsForPairedDeltaTest, pairedDeltaTest } from '../paired-delta-test'\nimport { BOOTSTRAP_GATE_MIN_N, DECISION_PAIRED_DELTA_STATISTIC } from '../statistics'\nimport { normalizeSignedZero as plain } from '../statistics/normalize-signed-zero'\nimport { SearchLedgerError } from './search-ledger-errors'\nimport type {\n NodeEstimate,\n SearchEstimateMethod,\n SearchLedgerHash,\n SearchSourceRef,\n SearchSplit,\n} from './search-ledger-types'\nimport {\n type SearchScoredCell,\n type SearchStateView,\n type SearchUnitScore,\n searchUnitScores,\n} from './search-state'\n\nconst CONFIDENCE = 0.95\nconst RESAMPLES = 2000\n/** 6 at 95 %: the smallest sample an exact one-sided sign test can resolve. */\nconst DESCRIPTIVE_FROM = minimumPairsForPairedDeltaTest(CONFIDENCE)\n\n/**\n * Every choice the numbers depend on. Its digest is the estimator's revision:\n * a producer and a verifier that report the same revision and the same\n * `cellSetDigest` report the same estimate. Change a value here whenever the\n * computation changes, so the revision moves with it.\n */\nconst ESTIMATOR_DEFINITION = {\n name: 'tangle.estimate-node.2026-09',\n unit: 'mean of the unit’s scored cells, summed in cellId order',\n pairing: 'units both nodes scored, in unitId order',\n statistic: DECISION_PAIRED_DELTA_STATISTIC,\n interval: 'percentile paired bootstrap',\n confidence: CONFIDENCE,\n resamples: RESAMPLES,\n rng: 'mulberry32',\n seed: 'the first 32 bits of cellSetDigest',\n signTest: 'exact, one-sided toward improvement in the objective direction',\n methods: {\n none: 'below 2 pairs',\n insufficient: `below ${DESCRIPTIVE_FROM} pairs`,\n descriptive: `below ${BOOTSTRAP_GATE_MIN_N} pairs`,\n bootstrap: `from ${BOOTSTRAP_GATE_MIN_N} pairs`,\n },\n indeterminate: 'every paired delta equal: no interval and no sign p',\n} as const\n\n/** The estimator every `NodeEstimate` names. */\nexport const SEARCH_ESTIMATOR: SearchSourceRef = {\n uri: 'npm:@tangle-network/agent-eval#estimateNode',\n revision: hashCanonical(ESTIMATOR_DEFINITION),\n}\n\n/** The method a paired sample of `pairs` units supports: the one staging\n * every `NodeEstimate` and every search lens uses. */\nexport function searchEstimateMethod(pairs: number): SearchEstimateMethod {\n if (pairs < 2) return 'none'\n if (pairs < DESCRIPTIVE_FROM) return 'insufficient'\n if (pairs < BOOTSTRAP_GATE_MIN_N) return 'descriptive'\n return 'bootstrap'\n}\n\nexport interface EstimateNodeCellsInput {\n nodeId: string\n against: string\n split: SearchSplit\n direction: 'maximize' | 'minimize'\n /** Every scored cell of `nodeId` on `split`. */\n nodeCells: readonly SearchScoredCell[]\n /** Every scored cell of `against` on `split`. */\n againstCells: readonly SearchScoredCell[]\n}\n\n/**\n * Digest of the cells an estimate reads, with the contrast they serve. Cells\n * are listed in cellId order, so the digest names the set, not the order it\n * was read in.\n */\nexport function searchCellSetDigest(\n input: Omit<EstimateNodeCellsInput, 'direction'>,\n): SearchLedgerHash {\n const list = (cells: readonly SearchScoredCell[]) =>\n [...cells]\n .sort((left, right) => compareCodeUnits(left.cellId, right.cellId))\n .map((cell) => [cell.cellId, cell.unitId, cell.attempt, cell.score])\n return hashCanonical({\n contrast: [input.nodeId, input.against],\n split: input.split,\n nodeCells: list(input.nodeCells),\n againstCells: list(input.againstCells),\n })\n}\n\n/**\n * The paired contrast of `nodeId` against `against` on the units both scored.\n *\n * `delta` is the mean per-unit difference, node minus `against`, in the\n * metric's own units; for a `minimize` objective an improvement is negative.\n * The exact sign test is one-sided toward improvement in the objective's\n * direction. Unscored cells (errored, cancelled or in flight) are absent from\n * the inputs, never zero.\n *\n * - `none` (0 or 1 pair): no delta.\n * - `insufficient` (2 to 5): the delta only.\n * - `descriptive` (6 to 19): the bootstrap interval as spread, and the sign-test p.\n * - `bootstrap` (20 or more): the decision-grade bootstrap interval.\n *\n * When every paired delta is equal the interval would have zero width, which\n * is an absence of evidence; the estimate is then `indeterminate` and carries\n * neither an interval nor a p-value.\n */\nexport function estimateNodeFromCells(input: EstimateNodeCellsInput): NodeEstimate {\n const { nodeId, against, split, direction } = input\n if (nodeId === against) {\n throw new SearchLedgerError(`node ${nodeId} cannot be estimated against itself`)\n }\n assertDistinctCells([...input.nodeCells, ...input.againstCells], nodeId, against)\n const cellSetDigest = searchCellSetDigest(input)\n const nodeUnits = searchUnitScores(input.nodeCells)\n const { node, other } = pairUnits(nodeUnits, unitMeans(searchUnitScores(input.againstCells)))\n const pairs = node.length\n const method = searchEstimateMethod(pairs)\n const base = {\n against,\n split,\n units: nodeUnits.length,\n pairs,\n method,\n cellSetDigest,\n estimator: SEARCH_ESTIMATOR,\n }\n if (method === 'none') {\n return { ...base, delta: null, interval: null, exactSignP: null, indeterminate: false }\n }\n // The test's `after - before` is the improvement: node minus against when\n // larger is better, against minus node when smaller is.\n const maximize = direction === 'maximize'\n const test = pairedDeltaTest(maximize ? other : node, maximize ? node : other, {\n statistic: DECISION_PAIRED_DELTA_STATISTIC,\n confidence: CONFIDENCE,\n resamples: RESAMPLES,\n seed: seedFromDigest(cellSetDigest),\n })\n const { mean, low, high } = test.bootstrap\n const indeterminate = test.indeterminate\n const spread = (method === 'descriptive' || method === 'bootstrap') && !indeterminate\n return {\n ...base,\n delta: plain(maximize ? mean : -mean),\n interval: spread ? (maximize ? [plain(low), plain(high)] : [plain(-high), plain(-low)]) : null,\n exactSignP: method === 'descriptive' && !indeterminate ? test.pValue : null,\n indeterminate,\n }\n}\n\n/**\n * `estimateNodeFromCells` over the cells a search state holds: `nodeId`\n * against `against` on one split, in the direction the search's objective\n * declares.\n */\nexport function estimateNode(\n state: SearchStateView,\n nodeId: string,\n options: { against: string; split: SearchSplit },\n): NodeEstimate {\n const header = state.header\n if (!header) throw new SearchLedgerError(`search ${state.searchId} has not been opened`)\n for (const id of [nodeId, options.against]) {\n if (!state.hasNode(id)) {\n throw new SearchLedgerError(`node ${id} is not in search ${state.searchId}`)\n }\n }\n return estimateNodeFromCells({\n nodeId,\n against: options.against,\n split: options.split,\n direction: header.objective.direction,\n nodeCells: state.scoredCells(nodeId, options.split),\n againstCells: state.scoredCells(options.against, options.split),\n })\n}\n\n/** A node's normal posterior on its improvement over the root. */\nexport interface NodePosterior {\n nodeId: string\n /** Units the node and the root both scored. */\n pairs: number\n /** Mean per-unit improvement over the root in the objective's direction,\n * so larger is better for either direction. Null without a shared unit. */\n mean: number | null\n /** The pooled variance divided by `pairs`. Null when either is unknown. */\n variance: number | null\n}\n\nexport interface SearchPosterior {\n split: SearchSplit\n rootNodeId: string\n /**\n * Between-unit variance of the per-unit improvements over the root, pooled\n * across every non-root node with at least 2 shared units. Null until some\n * node has 2.\n */\n pooledVariance: number | null\n /** Sum over the pooled nodes of their shared units minus one. */\n degreesOfFreedom: number\n /** Every node in registration order; the root first, at exactly 0. */\n nodes: NodePosterior[]\n}\n\n/**\n * The posterior every node's parent-selection draw uses. Each node's mean is\n * its improvement over the root on shared units; its variance is the search's\n * pooled between-unit variance divided by its unit count, so a node measured\n * on one unit has a wide posterior rather than none. The root is the reference\n * and sits at exactly 0.\n */\nexport function searchPosterior(\n state: SearchStateView,\n options: { split?: SearchSplit } = {},\n): SearchPosterior {\n const split = options.split ?? 'selection'\n const header = state.header\n if (!header) throw new SearchLedgerError(`search ${state.searchId} has not been opened`)\n const rootNodeId = state.rootNodeId\n if (rootNodeId === null) {\n throw new SearchLedgerError(`search ${state.searchId} has no root node yet`)\n }\n const sign = header.objective.direction === 'maximize' ? 1 : -1\n const root = searchUnitScores(state.scoredCells(rootNodeId, split))\n const rootMeans = unitMeans(root)\n const nodes: NodePosterior[] = []\n let squares = 0\n let degreesOfFreedom = 0\n for (const nodeId of state.nodeIds()) {\n if (nodeId === rootNodeId) {\n const measured = root.length > 0\n nodes.push({\n nodeId,\n pairs: root.length,\n mean: measured ? 0 : null,\n variance: measured ? 0 : null,\n })\n continue\n }\n const { node, other } = pairUnits(searchUnitScores(state.scoredCells(nodeId, split)), rootMeans)\n const gains = node.map((value, index) => sign * (value - other[index]!))\n const mean = gains.length > 0 ? sum(gains) / gains.length : null\n if (mean !== null && gains.length >= 2) {\n squares += sum(gains.map((gain) => (gain - mean) ** 2))\n degreesOfFreedom += gains.length - 1\n }\n nodes.push({\n nodeId,\n pairs: gains.length,\n mean: mean === null ? null : plain(mean),\n variance: null,\n })\n }\n const pooledVariance = degreesOfFreedom > 0 ? squares / degreesOfFreedom : null\n if (pooledVariance !== null) {\n for (const posterior of nodes) {\n if (posterior.nodeId !== rootNodeId && posterior.pairs > 0) {\n posterior.variance = pooledVariance / posterior.pairs\n }\n }\n }\n return { split, rootNodeId, pooledVariance, degreesOfFreedom, nodes }\n}\n\nfunction unitMeans(units: readonly SearchUnitScore[]): ReadonlyMap<string, number> {\n return new Map(units.map((unit) => [unit.unitId, unit.mean]))\n}\n\n/** Unit means of two nodes on the units both scored, aligned in the node's\n * unitId order. */\nfunction pairUnits(\n node: readonly SearchUnitScore[],\n otherMeans: ReadonlyMap<string, number>,\n): { node: number[]; other: number[] } {\n const paired = { node: [] as number[], other: [] as number[] }\n for (const unit of node) {\n const mean = otherMeans.get(unit.unitId)\n if (mean === undefined) continue\n paired.node.push(unit.mean)\n paired.other.push(mean)\n }\n return paired\n}\n\nfunction assertDistinctCells(\n cells: readonly SearchScoredCell[],\n nodeId: string,\n against: string,\n): void {\n const seen = new Set<string>()\n for (const cell of cells) {\n if (seen.has(cell.cellId)) {\n throw new SearchLedgerError(\n `cell ${cell.cellId} appears twice in the estimate of ${nodeId} against ${against}`,\n )\n }\n if (!Number.isFinite(cell.score)) {\n throw new SearchLedgerError(`cell ${cell.cellId} has a non-finite score ${cell.score}`)\n }\n seen.add(cell.cellId)\n }\n}\n\n/** The first 32 bits of a `sha256:` digest, as a bootstrap's seed. */\nexport function seedFromDigest(digest: SearchLedgerHash): number {\n return Number.parseInt(digest.slice('sha256:'.length, 'sha256:'.length + 8), 16) | 0\n}\n\nfunction sum(values: readonly number[]): number {\n let total = 0\n for (const value of values) total += value\n return total\n}\n","/** The artifact each node holds: kept in memory once seen, else loaded from the ledger. */\n\nexport class SearchArtifactCache<TArtifact> {\n private readonly artifacts = new Map<string, TArtifact>()\n /** Children a proposal returned, by artifact digest, until they are registered. */\n private readonly proposed = new Map<string, TArtifact>()\n\n constructor(private readonly load: (nodeId: string) => TArtifact) {}\n\n get(nodeId: string): TArtifact {\n const held = this.artifacts.get(nodeId)\n if (held !== undefined) return held\n const artifact = this.load(nodeId)\n this.artifacts.set(nodeId, artifact)\n return artifact\n }\n\n seed(nodeId: string, artifact: TArtifact): void {\n this.artifacts.set(nodeId, artifact)\n }\n\n /** Hold a proposed child until the ledger registers its node. */\n propose(digest: string, artifact: TArtifact): void {\n this.proposed.set(digest, artifact)\n }\n\n /** The node registered: it takes the artifact proposed under its digest, if one is held. */\n register(nodeId: string, digest: string): void {\n const held = this.proposed.get(digest)\n if (held === undefined) return\n this.proposed.delete(digest)\n if (!this.artifacts.has(nodeId)) this.artifacts.set(nodeId, held)\n }\n}\n","/**\n * The claim: the one statement a search makes about its nodes, made once, on\n * its sealed test split, after the search stops expanding.\n *\n * `planSearchClaim` fixes the claim's design from the ledger before any test\n * cell runs: up to 3 finalists ranked by selection mean, the estimator the\n * paired decision will use, the number of finalists the family-wise confidence\n * is divided among, and a power check on selection data. The kernel stores the\n * plan on the ledger's `claim` operation, so the ledger proves the design was\n * fixed before the test data existed. `decideSearchClaim` then reads the test\n * cells of the root and the finalists, which ran together, and decides each\n * finalist against the root with `decidePairedPromotion` at the Bonferroni\n * confidence `1 - 0.05 / k`.\n *\n * Every number is a pure function of the ledger: the power simulation is\n * seeded from the search's seed and the decisions from the digest of the test\n * cells they read, so a verifier with the same ledger gets the same claim.\n */\n\nimport { canonicalString, hashCanonical } from '../ledger-core/canonical'\nimport { decidePairedPromotion, type PairedPromotionDecision } from '../paired-promotion-decision'\nimport {\n type PairedPromotionAlternative,\n type PairedPromotionPowerCall,\n pairedPromotionPower,\n} from '../paired-promotion-power'\nimport { mean } from '../statistics/mean'\nimport { normalizeSignedZero as plain } from '../statistics/normalize-signed-zero'\nimport { estimateNode, searchPosterior, seedFromDigest } from './estimate-node'\nimport type {\n NodeEstimate,\n SearchClaim,\n SearchClaimEstimator,\n SearchClaimFinalist,\n SearchClaimPower,\n SearchClaimTest,\n SearchCloseReason,\n SearchNodeDecision,\n SearchSourceRef,\n} from './search-ledger-types'\nimport {\n SEARCH_CLAIM_MAX_FINALISTS,\n type SearchStateView,\n type SearchUnitScore,\n} from './search-state'\n\nconst FAMILY_CONFIDENCE = 0.95\nconst TARGET_POWER = 0.8\nconst POWER_SIMULATIONS = 500\nconst RESAMPLES = 2000\n\n/**\n * Every rule and parameter the claim depends on. Its digest is the claim's\n * revision; change a value here whenever the procedure changes, so the\n * revision moves with it.\n */\nconst CLAIM_DEFINITION = {\n name: 'tangle.search-claim.2026-09',\n finalists: `up to ${SEARCH_CLAIM_MAX_FINALISTS} non-root nodes not decided invalid that scored every selection unit and beat the root's mean on the selection units they share, ranked by selection mean in the objective's direction, then registration order`,\n familyConfidence: FAMILY_CONFIDENCE,\n correction: 'Bonferroni: each of k finalists against the root at 1 - (1 - familyConfidence) / k',\n finalistCount:\n 'the largest k whose test cells the unspent claim reserve and headroom cover and whose power reaches the target',\n estimator:\n 'binary with scale s when every train, selection and test unit has one task at one repeat and every pre-test score is 0 or s; otherwise continuous',\n power: {\n method: 'pairedPromotionPower of the claim decision, simulated at the claim minimumEffect',\n continuous: 'per-unit improvement normal with the pooled selection variance',\n binary:\n 'discordant units at the pooled selection variance over 2 s^2 per side, shifted by minimumEffect / s; concordant units pass at the root selection pass rate',\n targetPower: TARGET_POWER,\n simulations: POWER_SIMULATIONS,\n seed: 'the first 32 bits of hashCanonical([search seed, k])',\n },\n decision: {\n call: 'decidePairedPromotion(root, finalist) on per-unit test means in the objective direction',\n threshold: 0,\n minPairs: 'every test unit',\n resamples: RESAMPLES,\n seed: \"the first 32 bits of the finalist's test cellSetDigest\",\n },\n select: 'the promoted finalist with the largest improvement; ties to the better selection rank',\n ship: 'a promoted finalist that scored every test unit, with the root, on held-out units, under a pinned judge',\n} as const\n\n/** The claim procedure every `SearchClaim` and claim plan names. */\nexport const SEARCH_CLAIM_RULE: SearchSourceRef = {\n uri: 'npm:@tangle-network/agent-eval#searchClaim',\n revision: hashCanonical(CLAIM_DEFINITION),\n}\n\n/** The rule name decisions made by the claim record. */\nexport const SEARCH_CLAIM_RULE_NAME = CLAIM_DEFINITION.name\n\n/**\n * The claim reserve a search needs: the root and 3 finalists on every test\n * task at `reps` repeats, each held at `cellUsd`. Declare at least this as\n * `budget.reservedClaimUsd`; `runSearch` refuses to start a capped search\n * with less.\n */\nexport function searchClaimReserveUsd(input: {\n testTasks: number\n reps: number\n cellUsd: number\n}): number {\n return (1 + SEARCH_CLAIM_MAX_FINALISTS) * input.testTasks * input.reps * input.cellUsd\n}\n\n/**\n * The claim's design, fixed before any test cell runs, and stored as the\n * `claim-plan` artifact of the ledger's `claim` operation.\n */\nexport interface SearchClaimPlan {\n kind: 'search-claim-plan'\n rule: SearchSourceRef\n /** Why expansion stopped; the search closes with this reason. */\n stopReason: SearchCloseReason\n /** Best first. Every one is decided `finalist` and named by the claim. */\n finalists: Array<{ nodeId: string; selectionMean: number }>\n power: SearchClaimPower\n /** `run`: the root and the finalists run every test task. Otherwise the\n * claim closes with this decision and spends nothing on test cells. */\n test: 'run' | 'hold' | 'test-cannot-resolve'\n reason: string\n}\n\nexport interface PlanSearchClaimInput {\n stopReason: SearchCloseReason\n /** Repeats per test task. */\n reps: number\n /** Whether the budget admits the test cells of the root and `finalists`. */\n affordable(finalists: number): boolean\n}\n\n/** Fix the claim's design from a search that stopped expanding. */\nexport function planSearchClaim(\n state: SearchStateView,\n input: PlanSearchClaimInput,\n): SearchClaimPlan {\n const header = requireHeader(state)\n const root = state.rootNodeId!\n const plan = (\n finalists: SearchClaimPlan['finalists'],\n power: SearchClaimPower,\n test: SearchClaimPlan['test'],\n reason: string,\n ): SearchClaimPlan => ({\n kind: 'search-claim-plan',\n rule: SEARCH_CLAIM_RULE,\n stopReason: input.stopReason,\n finalists,\n power,\n test,\n reason,\n })\n const selectionUnits = unitIds(header.splits.selection.tasks)\n const testUnits = unitIds(header.splits.test.tasks)\n if (testUnits.length === 0) {\n return plan(\n [],\n { unknown: 'the search has no test split' },\n 'hold',\n 'the search has no test split, so it makes no claim',\n )\n }\n if (selectionUnits.length === 0) {\n return plan(\n [],\n { unknown: 'the search has no selection split to choose finalists on' },\n 'hold',\n 'the search has no selection split, so no finalist can be chosen without the test data',\n )\n }\n const candidates = rankFinalists(state, selectionUnits)\n if (candidates.length === 0) {\n return plan(\n [],\n { unknown: 'no node went to test' },\n 'hold',\n \"no node scored every selection unit and beat the root's selection mean, so the search keeps the root\",\n )\n }\n const minimumEffect = header.objective.claim.minimumEffect\n if (minimumEffect === undefined) {\n return plan(\n candidates.slice(0, 1),\n { unknown: 'the claim declares no minimumEffect' },\n 'test-cannot-resolve',\n 'the claim declares no minimumEffect, so no test split can be shown to resolve it',\n )\n }\n const { pooledVariance } = searchPosterior(state, { split: 'selection' })\n if (pooledVariance === null) {\n return plan(\n candidates.slice(0, 1),\n { unknown: 'no node shares 2 selection units with the root, so the variance is unknown' },\n 'test-cannot-resolve',\n 'the selection split gives no variance for the power check, so the test cannot be shown to resolve the minimum effect',\n )\n }\n const estimator = claimEstimator(state, input.reps)\n const rootPassRate = passRate(state.unitScores(root, 'selection'), estimator)\n let best: SearchClaimPower | null = null\n let budgetBound = false\n for (let k = candidates.length; k >= 1; k--) {\n const power = claimPower({\n units: testUnits.length,\n finalists: k,\n minimumEffect,\n pooledVariance,\n estimator,\n rootPassRate,\n seed: header.policy.seed,\n })\n best = power\n if (!power.adequate) continue\n if (!input.affordable(k)) {\n budgetBound = true\n continue\n }\n return plan(\n candidates.slice(0, k),\n power,\n 'run',\n `${k} finalist${k === 1 ? '' : 's'} go to test: power ${round(power.powerAtMinimumEffect)} at an improvement of ${minimumEffect} on ${testUnits.length} test units reaches ${TARGET_POWER} at confidence ${round(bonferroni(k))} each`,\n )\n }\n const power = best!\n return plan(\n candidates.slice(0, 1),\n power,\n 'test-cannot-resolve',\n budgetBound\n ? 'the unspent claim reserve and headroom do not cover the test cells of the root and one finalist'\n : `even one finalist reaches power ${round('adequate' in power ? power.powerAtMinimumEffect : 0)} at an improvement of ${minimumEffect} on ${testUnits.length} test units, below ${TARGET_POWER}`,\n )\n}\n\n/** A node decision the claim makes, ready for `recorder.decideNode`. */\nexport interface SearchClaimDecision {\n nodeId: string\n decision: SearchNodeDecision\n basis: NodeEstimate | null\n rule: string\n reason: string\n}\n\n/**\n * Decide the claim from the test cells of the root and the finalists. Call it\n * once every claim cell is settled or cancelled. It returns the claim and the\n * terminal decisions of the root and every finalist.\n */\nexport function decideSearchClaim(\n state: SearchStateView,\n plan: SearchClaimPlan,\n): { claim: SearchClaim; decisions: SearchClaimDecision[] } {\n const header = requireHeader(state)\n const root = state.rootNodeId!\n const rootScored = (['train', 'selection', 'test'] as const).some(\n (split) => state.scoredCells(root, split).length > 0,\n )\n const keepRoot = rootScored ? root : null\n const rule = SEARCH_CLAIM_RULE_NAME\n const decisions: SearchClaimDecision[] = []\n const claimOf = (\n finalists: SearchClaimFinalist[],\n selected: string | null,\n decision: SearchClaim['decision'],\n reason: string,\n ): SearchClaim => ({\n rule: SEARCH_CLAIM_RULE,\n confidence: FAMILY_CONFIDENCE,\n power: plan.power,\n finalists,\n selected,\n decision,\n reason,\n })\n\n if (plan.test !== 'run') {\n for (const finalist of plan.finalists) {\n decisions.push({\n nodeId: finalist.nodeId,\n decision: { status: 'rejected' },\n basis: null,\n rule,\n reason: `no test cell ran: ${plan.reason}`,\n })\n }\n decisions.push(rootDecision(root, rootScored ? 'kept' : 'unscored', rule, plan.reason))\n return {\n claim: claimOf(\n plan.finalists.map((finalist) => ({\n nodeId: finalist.nodeId,\n estimate: null,\n test: null,\n promote: false,\n })),\n keepRoot,\n plan.test,\n plan.reason,\n ),\n decisions,\n }\n }\n\n const power = plan.power\n if (!('adequate' in power)) throw new Error('a claim that runs its test cells has a known power')\n const k = plan.finalists.length\n const confidence = bonferroni(k)\n const testUnits = unitIds(header.splits.test.tasks)\n const maximize = header.objective.direction === 'maximize'\n const rootUnits = state.unitScores(root, 'test')\n const tested = plan.finalists.map(({ nodeId }) => {\n const estimate = estimateNode(state, nodeId, { against: root, split: 'test' })\n const test = pairedTest({\n root: rootUnits,\n node: state.unitScores(nodeId, 'test'),\n testUnits,\n confidence,\n estimator: power.estimator,\n maximize,\n seed: seedFromDigest(estimate.cellSetDigest),\n })\n return { nodeId, estimate, ...test }\n })\n\n const promoted = tested\n .map((entry, rank) => ({ ...entry, rank }))\n .filter((entry) => entry.promote)\n .sort((a, b) => b.improvement! - a.improvement! || a.rank - b.rank)\n const winner = promoted[0] ?? null\n const blockers: string[] = []\n if (!header.splits.heldOutUnits) blockers.push('the test units also appear in train or selection')\n if ('unknown' in header.objective.judge) blockers.push('the judge is not pinned')\n const ship = winner !== null && blockers.length === 0\n const selected = ship ? winner.nodeId : keepRoot\n const reason = ship\n ? `finalist ${winner.nodeId} beat the root on the ${testUnits.length} test units at confidence ${round(confidence)} (${k} finalist${k === 1 ? '' : 's'}, family-wise ${FAMILY_CONFIDENCE})`\n : winner !== null\n ? `finalist ${winner.nodeId} beat the root, but the claim cannot ship: ${blockers.join('; ')}`\n : `no finalist beat the root on the test split at confidence ${round(confidence)} (${k} finalist${k === 1 ? '' : 's'}, family-wise ${FAMILY_CONFIDENCE})`\n\n for (const entry of tested) {\n decisions.push({\n nodeId: entry.nodeId,\n decision: { status: ship && entry.nodeId === winner!.nodeId ? 'selected' : 'rejected' },\n basis: entry.estimate,\n rule,\n reason:\n ship && entry.nodeId === winner!.nodeId\n ? reason\n : entry.promote\n ? ship\n ? `promoted, but finalist ${winner!.nodeId} improved more on the test split`\n : reason\n : entry.why,\n })\n }\n decisions.push(\n rootDecision(root, ship ? 'replaced' : rootScored ? 'kept' : 'unscored', rule, reason),\n )\n return {\n claim: claimOf(\n tested.map((entry) => ({\n nodeId: entry.nodeId,\n estimate: entry.estimate,\n test: entry.test,\n promote: entry.promote,\n })),\n selected,\n ship ? 'ship' : 'hold',\n reason,\n ),\n decisions,\n }\n}\n\n/** Whether a closed search's claim is the one its own ledger supports. */\nexport type SearchClaimVerification =\n | { status: 'verified' }\n /** The claim differs from the one the claim rule makes from the ledger. */\n | { status: 'mismatch'; differences: string[] }\n /** The claim names a rule revision this code does not implement, so this\n * code can neither confirm nor refute it. */\n | { status: 'unknown'; reason: string }\n\n/**\n * Make a closed search's claim again from its ledger alone and compare it with\n * the recorded one, byte for byte: the power check, the finalists, each\n * finalist's test estimate and deciding interval, the selection, the decision\n * and the reason. A producer's claim is not evidence until this holds; a store\n * keeps what this function derives, not what the producer wrote.\n *\n * It needs no blob, so it works on a store that keeps digests only. The\n * finalists are the nodes the ledger decided `finalist`, in decision order.\n * The one input the ledger cannot replay is whether the budget covered k\n * finalists' test cells; the claim cells that ran answer it (none ran: the\n * budget covered none). Test repeats come from the claim cells too; without\n * test cells, the recorded estimator stands for them (binary needs one repeat,\n * so any other count reproduces continuous).\n *\n * Returns null for a search that made no claim.\n */\nexport function verifySearchClaim(state: SearchStateView): SearchClaimVerification | null {\n const closed = state.closed\n if (!closed) {\n throw new Error(`search ${state.searchId} is open; its claim is made when it closes`)\n }\n const recorded = closed.claim\n if (recorded === null) return null\n if (recorded.rule.revision !== SEARCH_CLAIM_RULE.revision) {\n return {\n status: 'unknown',\n reason: `the claim names rule revision ${recorded.rule.revision}; this code implements ${SEARCH_CLAIM_RULE.revision}`,\n }\n }\n const claimCells = state.cells().filter((cell) => cell.stage === 'claim')\n const decided = state\n .nodes()\n .flatMap((node) => {\n const first = node.decisions.find((record) => record.decision.status === 'finalist')\n return first ? [{ nodeId: node.nodeId, sequence: first.sequence }] : []\n })\n .sort((a, b) => a.sequence - b.sequence)\n .map((entry) => entry.nodeId)\n const reps =\n claimCells.length > 0\n ? 1 + Math.max(...claimCells.map((cell) => cell.rep))\n : 'adequate' in recorded.power && recorded.power.estimator.kind === 'binary'\n ? 1\n : 2\n const plan = planSearchClaim(state, {\n stopReason: closed.reason,\n reps,\n affordable: (finalists) => claimCells.length > 0 && finalists <= decided.length,\n })\n const differences: string[] = []\n const planned = plan.finalists.map((finalist) => finalist.nodeId)\n if (canonicalString(planned) !== canonicalString(decided)) {\n differences.push(\n `finalists: the rule picks [${planned.join(', ')}], the ledger decided [${decided.join(', ')}]`,\n )\n }\n if ((plan.test === 'run') !== claimCells.length > 0) {\n differences.push(\n `test: the plan ${plan.test === 'run' ? 'runs' : 'skips'} the test cells, and ${claimCells.length} ran`,\n )\n }\n const expected = decideSearchClaim(state, plan).claim\n for (const key of ['decision', 'selected', 'confidence', 'power', 'reason'] as const) {\n if (canonicalString(expected[key]) !== canonicalString(recorded[key])) {\n differences.push(\n `${key}: the ledger supports ${canonicalString(expected[key])}, the claim records ${canonicalString(recorded[key])}`,\n )\n }\n }\n const count = Math.max(expected.finalists.length, recorded.finalists.length)\n for (let index = 0; index < count; index++) {\n const want = expected.finalists[index]\n const have = recorded.finalists[index]\n if (canonicalString(want ?? null) === canonicalString(have ?? null)) continue\n const fields = (['nodeId', 'promote', 'test', 'estimate'] as const).filter(\n (field) => canonicalString(want?.[field] ?? null) !== canonicalString(have?.[field] ?? null),\n )\n differences.push(\n `finalist ${index + 1} (${have?.nodeId ?? want?.nodeId}): ${fields.join(', ')} differ from what the ledger supports`,\n )\n }\n return differences.length === 0 ? { status: 'verified' } : { status: 'mismatch', differences }\n}\n\n/**\n * The paired decision a closed search's claim made for one finalist it\n * tested: `decidePairedPromotion` on per-unit test means with the root as\n * control, in the objective's direction (its `delta` is the improvement), at\n * the finalist's Bonferroni confidence, with the claim's estimator, resamples\n * and seed. A consumer cites it with the claim as the evidence that promoted\n * the finalist, instead of deciding a second time from the same cells.\n *\n * It is made again from the ledger alone and must reproduce the claim's\n * recorded test for the finalist byte for byte; it throws when it does not,\n * when the search is open, and when the claim names a rule revision this code\n * does not implement. Returns null when the claim tested no such finalist.\n */\nexport function searchClaimDecision(\n state: SearchStateView,\n nodeId: string,\n): PairedPromotionDecision | null {\n const closed = state.closed\n if (!closed) {\n throw new Error(`search ${state.searchId} is open; its claim is made when it closes`)\n }\n const claim = closed.claim\n if (claim === null) return null\n if (claim.rule.revision !== SEARCH_CLAIM_RULE.revision) {\n throw new Error(\n `the claim of search ${state.searchId} names rule revision ${claim.rule.revision}; this code implements ${SEARCH_CLAIM_RULE.revision}`,\n )\n }\n const finalist = claim.finalists.find((entry) => entry.nodeId === nodeId)\n if (finalist === undefined || finalist.test === null || !('adequate' in claim.power)) {\n return null\n }\n const header = requireHeader(state)\n const root = state.rootNodeId!\n const estimate = estimateNode(state, nodeId, { against: root, split: 'test' })\n const tested = pairedTest({\n root: state.unitScores(root, 'test'),\n node: state.unitScores(nodeId, 'test'),\n testUnits: unitIds(header.splits.test.tasks),\n confidence: bonferroni(claim.finalists.length),\n estimator: claim.power.estimator,\n maximize: header.objective.direction === 'maximize',\n seed: seedFromDigest(estimate.cellSetDigest),\n })\n if (tested.decision === null || canonicalString(tested.test) !== canonicalString(finalist.test)) {\n throw new Error(\n `search ${state.searchId}: the ledger does not reproduce the claim's test of ${nodeId}; verify the claim with verifySearchClaim`,\n )\n }\n return tested.decision\n}\n\n/** Per-finalist confidence for `k` finalists. */\nfunction bonferroni(k: number): number {\n return 1 - (1 - FAMILY_CONFIDENCE) / k\n}\n\nfunction rootDecision(\n root: string,\n fate: 'kept' | 'replaced' | 'unscored',\n rule: string,\n reason: string,\n): SearchClaimDecision {\n return {\n nodeId: root,\n decision: { status: fate === 'kept' ? 'selected' : 'rejected' },\n basis: null,\n rule,\n reason:\n fate === 'kept'\n ? `the search keeps the root: ${reason}`\n : fate === 'replaced'\n ? `a finalist replaces the root: ${reason}`\n : 'the root has no scored cell, so the search keeps nothing',\n }\n}\n\n/** Nodes eligible to go to test, best first, at most `SEARCH_CLAIM_MAX_FINALISTS`. */\nfunction rankFinalists(\n state: SearchStateView,\n selectionUnits: readonly string[],\n): Array<{ nodeId: string; selectionMean: number }> {\n const header = requireHeader(state)\n const sign = header.objective.direction === 'maximize' ? 1 : -1\n const root = state.rootNodeId!\n const rootMeans = new Map(\n state.unitScores(root, 'selection').map((unit) => [unit.unitId, unit.mean]),\n )\n const ranked: Array<{ nodeId: string; selectionMean: number; ordinal: number }> = []\n for (const node of state.nodes()) {\n if (node.nodeId === root || node.status === 'invalid') continue\n const units = state.unitScores(node.nodeId, 'selection')\n if (units.length !== selectionUnits.length) continue\n let gain = 0\n let shared = 0\n for (const unit of units) {\n const rootMean = rootMeans.get(unit.unitId)\n if (rootMean === undefined) continue\n gain += sign * (unit.mean - rootMean)\n shared += 1\n }\n if (shared === 0 || gain <= 0) continue\n ranked.push({\n nodeId: node.nodeId,\n selectionMean: mean(units.map((unit) => unit.mean)),\n ordinal: node.ordinal,\n })\n }\n ranked.sort((a, b) => sign * (b.selectionMean - a.selectionMean) || a.ordinal - b.ordinal)\n return ranked\n .slice(0, SEARCH_CLAIM_MAX_FINALISTS)\n .map(({ nodeId, selectionMean }) => ({ nodeId, selectionMean }))\n}\n\n/**\n * The paired decision's estimator, fixed from pre-test data. A per-unit mean\n * is binary only when each unit holds one task at one repeat and every score\n * seen before the test is 0 or one positive value.\n */\nfunction claimEstimator(state: SearchStateView, reps: number): SearchClaimEstimator {\n const header = requireHeader(state)\n const oneTaskPerUnit = (['train', 'selection', 'test'] as const).every((split) => {\n const tasks = header.splits[split].tasks\n return unitIds(tasks).length === tasks.length\n })\n if (!oneTaskPerUnit || reps !== 1) return { kind: 'continuous' }\n let scale: number | null = null\n for (const nodeId of state.nodeIds()) {\n for (const split of ['train', 'selection'] as const) {\n for (const cell of state.scoredCells(nodeId, split)) {\n if (cell.score === 0) continue\n if (cell.score < 0 || (scale !== null && cell.score !== scale))\n return { kind: 'continuous' }\n scale = cell.score\n }\n }\n }\n return scale === null ? { kind: 'continuous' } : { kind: 'binary', scale }\n}\n\nfunction passRate(units: readonly SearchUnitScore[], estimator: SearchClaimEstimator): number {\n if (estimator.kind !== 'binary' || units.length === 0) return 0\n return units.filter((unit) => unit.mean === estimator.scale).length / units.length\n}\n\nfunction claimPower(input: {\n units: number\n finalists: number\n minimumEffect: number\n pooledVariance: number\n estimator: SearchClaimEstimator\n rootPassRate: number\n seed: number\n}): Extract<SearchClaimPower, { adequate: boolean }> {\n const { units, finalists, minimumEffect, pooledVariance, estimator } = input\n const confidence = bonferroni(finalists)\n let alternative: PairedPromotionAlternative\n let call: PairedPromotionPowerCall\n if (estimator.kind === 'binary') {\n const s = estimator.scale\n const shift = Math.min(1, minimumEffect / s)\n const discordance = Math.min(0.5, pooledVariance / (2 * s * s))\n const loss = Math.max(0, discordance - shift / 2)\n const win = Math.min(1 - loss, loss + shift)\n const concordant = Math.max(0, 1 - win - loss)\n alternative = {\n cells: [\n {\n probability: win,\n pass: { control: false, treatment: true },\n delta: { kind: 'point', value: s },\n },\n {\n probability: loss,\n pass: { control: true, treatment: false },\n delta: { kind: 'point', value: -s },\n },\n {\n probability: concordant * input.rootPassRate,\n pass: { control: true, treatment: true },\n delta: { kind: 'point', value: 0 },\n },\n {\n probability: concordant * (1 - input.rootPassRate),\n pass: { control: false, treatment: false },\n delta: { kind: 'point', value: 0 },\n },\n ],\n }\n call = { outcome: 'pass', options: { binaryScale: s, confidence, threshold: 0 } }\n } else {\n alternative = {\n cells: [\n {\n probability: 1,\n delta: { kind: 'normal', mean: minimumEffect, sd: Math.sqrt(pooledVariance) },\n },\n ],\n }\n call = {\n outcome: 'delta',\n options: { continuous: true, confidence, threshold: 0, resamples: RESAMPLES },\n }\n }\n const simulated = pairedPromotionPower({\n n: units,\n alternative,\n calls: [call],\n simulations: POWER_SIMULATIONS,\n seed: seedFromDigest(hashCanonical([input.seed, finalists])),\n })\n return {\n adequate: simulated.power >= TARGET_POWER,\n minimumEffect,\n powerAtMinimumEffect: simulated.power,\n targetPower: TARGET_POWER,\n units,\n finalists,\n pooledVariance,\n estimator,\n }\n}\n\n/**\n * One finalist against the root on the test split, in the objective's\n * direction, requiring every test unit scored by both.\n */\nfunction pairedTest(input: {\n root: readonly SearchUnitScore[]\n node: readonly SearchUnitScore[]\n testUnits: readonly string[]\n confidence: number\n estimator: SearchClaimEstimator\n maximize: boolean\n seed: number\n}): {\n test: SearchClaimTest | null\n decision: PairedPromotionDecision | null\n promote: boolean\n improvement: number | null\n why: string\n} {\n const rootMeans = new Map(input.root.map((unit) => [unit.unitId, unit.mean]))\n const before: number[] = []\n const after: number[] = []\n for (const unit of input.node) {\n const rootMean = rootMeans.get(unit.unitId)\n if (rootMean === undefined) continue\n // `after - before` is the improvement in either direction.\n before.push(input.maximize ? rootMean : unit.mean)\n after.push(input.maximize ? unit.mean : rootMean)\n }\n const pairs = before.length\n if (pairs === 0) {\n return {\n test: null,\n decision: null,\n promote: false,\n improvement: null,\n why: 'no test unit was scored by both it and the root',\n }\n }\n const { estimator } = input\n if (\n estimator.kind === 'binary' &&\n [...before, ...after].some((value) => value !== 0 && value !== estimator.scale)\n ) {\n return {\n test: null,\n decision: null,\n promote: false,\n improvement: null,\n why: `a test score left the two-point scale {0, ${estimator.scale}} the claim fixed before the test`,\n }\n }\n const decision: PairedPromotionDecision = decidePairedPromotion(before, after, {\n confidence: input.confidence,\n threshold: 0,\n minPairs: input.testUnits.length,\n resamples: RESAMPLES,\n seed: input.seed,\n ...(estimator.kind === 'binary' ? { binaryScale: estimator.scale } : { continuous: true }),\n })\n const test: SearchClaimTest = {\n pairs,\n confidence: input.confidence,\n method: decision.method,\n delta: plain(input.maximize ? decision.delta : -decision.delta),\n interval: input.maximize\n ? [plain(decision.low), plain(decision.high)]\n : [plain(-decision.high), plain(-decision.low)],\n }\n const complete = pairs === input.testUnits.length\n const promote = decision.promote && complete\n const why = !complete\n ? `it and the root scored ${pairs} of ${input.testUnits.length} test units, and a claim needs every one`\n : decision.promote\n ? 'promoted'\n : !decision.sufficient\n ? `${pairs} test units are below the ${decision.minimumPairs} its paired test needs`\n : decision.indeterminate\n ? `its test interval has no width: ${decision.indeterminateCause}`\n : decision.exactTestVetoes\n ? \"McNemar's exact test vetoes the improvement\"\n : `its improvement interval [${round(decision.low)}, ${round(decision.high)}] at confidence ${round(input.confidence)} does not exclude 0`\n return { test, decision, promote, improvement: decision.delta, why }\n}\n\nfunction requireHeader(state: SearchStateView) {\n const header = state.header\n if (!header) throw new Error(`search ${state.searchId} has not been opened`)\n if (state.rootNodeId === null) throw new Error(`search ${state.searchId} has no root node`)\n return header\n}\n\nfunction unitIds(tasks: ReadonlyArray<{ unitId: string }>): string[] {\n return [...new Set(tasks.map((task) => task.unitId))]\n}\n\nfunction round(value: number): number {\n return Math.round(value * 1e4) / 1e4\n}\n","/** Final unclaimed selections and verification of the closed search receipt. */\nimport { estimateNode } from './estimate-node'\nimport { verifySearchClaim } from './search-claim'\nimport type { SearchRunResult } from './search-kernel-contract'\nimport type { NodeEstimate, SearchCloseReason } from './search-ledger-types'\nimport type { SearchPolicyView } from './search-policy'\nimport type { SearchNode, SearchStateView } from './search-state'\n\n/** Decisions for a search without a held-out claim, derived before its ledger advances. */\nexport function unclaimedSearchDecisions(\n state: SearchStateView,\n view: SearchPolicyView,\n leader: string,\n context: { rule: string; stopReason: SearchCloseReason | null; screened: ReadonlySet<string> },\n) {\n const { split } = view\n const root = state.rootNodeId!\n const leaderUnits = view.unitScores(leader).map((unit) => unit.unitId)\n // Decide from one read of the state, then append: an append moves the\n // ledger on and retires the view.\n return state\n .nodes()\n .filter((node) => !isTerminal(node))\n .map((node) => {\n const scored = state.scoredCells(node.nodeId, split).length > 0\n const lead = node.nodeId === leader && scored\n const against = node.nodeId === leader ? root : leader\n const basis: NodeEstimate | null =\n node.nodeId === against || !scored\n ? null\n : estimateNode(state, node.nodeId, { against, split })\n const units = new Set(view.unitScores(node.nodeId).map((unit) => unit.unitId))\n return {\n nodeId: node.nodeId,\n decision: { status: lead ? ('selected' as const) : ('rejected' as const) },\n basis,\n rule: context.rule,\n reason: lead\n ? `the leader when the search stopped (${context.stopReason}): a budget decision on the ${split} split, which claims nothing`\n : !context.screened.has(node.nodeId) || !scored\n ? 'the search stopped before this node was measured'\n : !view.complete(node.nodeId)\n ? 'it left a unit unscored, so it could not lead'\n : leaderUnits.some((unitId) => !units.has(unitId))\n ? 'the search stopped before it was measured on every unit the leader was'\n : 'it did not beat the leader on the units they share',\n }\n })\n}\n\nexport function closedSearchResult(state: SearchStateView): SearchRunResult {\n const claimVerification = verifySearchClaim(state)\n if (claimVerification?.status === 'mismatch') {\n throw new Error(\n `runSearch: search ${state.searchId} closed with a claim its ledger does not support: ${claimVerification.differences.join('; ')}`,\n )\n }\n return {\n state,\n leader: state.audit.selectedNodeId ?? state.rootNodeId!,\n reason: state.closed!.reason,\n claim: state.closed!.claim,\n claimVerification,\n }\n}\n\nexport function isTerminal(node: SearchNode): boolean {\n return node.status !== null && node.status !== 'advanced'\n}\n","/** Search execution ports, persisted proposal shape, and versioned kernel rules. */\nimport { hashCanonical } from '../ledger-core/canonical'\nimport type { SearchAllocator, SearchCellPlan } from './allocation'\nimport type { SearchClaimVerification } from './search-claim'\nimport type {\n RegisterSearchNodeInput,\n SearchRecorder,\n SettleSearchCellInput,\n} from './search-ledger-recording'\nimport type {\n SearchArtifactRef,\n SearchAttemptAccounting,\n SearchCellStage,\n SearchClaim,\n SearchCloseReason,\n SearchEdgeOperator,\n SearchOperationRecordedEvent,\n SearchProposerKind,\n SearchSourceRef,\n SearchSplit,\n SearchUnknown,\n} from './search-ledger-types'\nimport type { SearchPolicy } from './search-policy'\nimport type { SearchNode, SearchStateView } from './search-state'\n\n/**\n * Every rule the kernel's decisions depend on. Its digest is the kernel's\n * revision in a ledger's `process.executionRef`; change a value here whenever\n * a rule changes, so the revision moves with it.\n */\nconst KERNEL_DEFINITION = {\n name: 'tangle.search-kernel.2026-09',\n dispatch:\n 'claim, then rung and root, then screen, then train; first allocated first within a stage',\n expansion:\n 'when no cell waits, fewer than twice the lanes capacity run, the cap admits one proposal and its expected screens, and overspend has not taken the search past its cap',\n parents: 'a policy names at least one parent, and every parent finished its screen',\n reservation: {\n hard: 'the lane per-cell maximum',\n estimate: '1.5 times the p99 of the lane settled cells once 20 settled, else the lane prior',\n },\n retries: 'a retryable errored attempt runs again, up to maxAttempts',\n rungs:\n 'when a node finishes its cells, the allocator names the nodes it advances, deepest rung first; each is recorded advanced and its rung allocated when the cap admits the rung',\n resume:\n 'an unrecorded operation is recorded failed at an unknown cost with floor 0; a recorded proposal is finished from its stored output; an unsettled cell is offered to adopt before it runs',\n writers: 'one kernel per ledger file on a host, by a pid lock beside the ledger',\n divergence:\n 'a node whose train mean over shared units rises above its parent while its descriptive or bootstrap selection interval against the parent lies wholly on the worse side is decided invalid when its cells finish',\n claim:\n 'with a test split: after expansion stops, the claim plan is stored on the claim operation, the finalists are decided, the root and finalist test cells run together, and the claim decides; the kernel refuses to start a claim without a selection split, a minimumEffect, a pinned judge, or (under a cap) a claim reserve for the root and 3 finalists plus a cap for one screening round',\n close:\n 'the allocator prunes the nodes left waiting on a rung, except the policy leader; then, with a test split, the claim decides; without one, the policy leader is selected when it has a scored cell; every other undecided node is rejected',\n complete:\n 'a node leads only when it has a scored cell on the ranked split and no cell there ended unscored: a final unscored outcome, or an error with no attempt left',\n} as const\n\n/** The kernel every `runSearch` ledger names as its search implementation. */\nexport const SEARCH_KERNEL_SOURCE: SearchSourceRef = {\n uri: 'npm:@tangle-network/agent-eval#runSearch',\n revision: hashCanonical(KERNEL_DEFINITION),\n}\n\nexport { USD_TOLERANCE } from './search-ledger-constraints'\n/** The operation that holds the claim's plan. */\nexport const CLAIM_OPERATION = 'claim'\n/** Settled cells a lane needs before its own cost distribution sets its estimate. */\nexport const ESTIMATE_FROM_CELLS = 20\nexport const ESTIMATE_MARGIN = 1.5\nexport const DEFAULT_MAX_ATTEMPTS = 3\n/** Dispatch order: claim cells first, then rungs and the root, then screens, then train. */\nexport const STAGE_PRIORITY: Record<SearchCellStage, number> = {\n claim: 0,\n rung: 1,\n root: 1,\n screen: 2,\n train: 3,\n external: 3,\n}\n\n/** An execution lane: a pool of slots whose cells share a cost rule. */\nexport interface SearchLane {\n name: string\n /** Cells the lane runs at once. */\n capacity: number\n /** `hard`: the lane enforces `cellUsd` as each cell's maximum. `estimate`:\n * it cannot, and the kernel holds an estimate, recording any overshoot. */\n costCap: 'hard' | 'estimate'\n /** The enforced per-cell maximum of a hard lane; the prior estimate of an\n * estimate lane until it has settled enough cells to estimate its own. */\n cellUsd: number\n}\n\n/** One attempt at one cell, as the kernel hands it to an executor. */\nexport interface SearchCellWork<TArtifact> {\n searchId: string\n cellId: string\n nodeId: string\n taskId: string\n unitId: string\n split: SearchSplit\n rep: number\n stage: SearchCellStage\n lane: string\n attempt: number\n /** `cellId:attempt`: the id an executor keys the attempt's run by. */\n runId: string\n artifact: TArtifact\n signal: AbortSignal\n}\n\n/** What an attempt produced: everything `cell-settled` records except the\n * coordinates the kernel owns. An environment fault is an `errored` outcome,\n * not a rejection; a rejection stops the search. */\nexport type SearchCellResult = Omit<SettleSearchCellInput, 'cellId' | 'attempt'>\n\n/** The executor port: lanes, placement, running a cell, and adopting an\n * attempt an earlier kernel process started. */\nexport interface SearchExecutor<TArtifact> {\n lanes(): readonly SearchLane[]\n /** The lane a planned cell runs on. */\n place(cell: SearchCellPlan & { nodeId: string }): string\n run(work: SearchCellWork<TArtifact>): Promise<SearchCellResult>\n /** The result of `work.runId` if the executor already has it, else null.\n * Called before the first dispatch of a cell the ledger shows unsettled when\n * the kernel starts, so a restart does not run an attempt twice. */\n adopt(work: SearchCellWork<TArtifact>): Promise<SearchCellResult | null>\n}\n\n/** How a search stores, compares and restores its artifacts. */\nexport interface SearchArtifactCodec<TArtifact> {\n /** The artifact as a content-addressed node; stores its bytes. */\n node(recorder: SearchRecorder, artifact: TArtifact): RegisterSearchNodeInput\n /** The parent-to-child diff, stored as a blob, or why there is none. */\n diff(\n recorder: SearchRecorder,\n parent: TArtifact,\n child: TArtifact,\n ): SearchArtifactRef | SearchUnknown\n /** The artifact a node holds, read back from its stored bytes. */\n load(recorder: SearchRecorder, node: SearchNode): TArtifact\n}\n\nexport interface SearchProposalRequest<TArtifact> {\n expansion: number\n operationId: string\n operator: Exclude<SearchEdgeOperator, 'seed' | 'derive'>\n /** The parents the policy chose, primary first. */\n parents: ReadonlyArray<{ nodeId: string; artifact: TArtifact }>\n /** The node the search keeps now. */\n leader: string\n signal: AbortSignal\n}\n\n/** One child a proposal returned. */\nexport interface SearchProposedChild<TArtifact> {\n artifact: TArtifact\n label: string\n /** The proposer's reason; redacted with the share profile before it is stored. */\n rationale: string\n /** Typed JSON the proposer attaches to the child, stored with the proposal\n * and never interpreted by the kernel. */\n attribution?: Readonly<Record<string, unknown>>\n}\n\nexport interface SearchProposalResult<TArtifact> {\n children: ReadonlyArray<SearchProposedChild<TArtifact>>\n /** Set when the proposer judges the search converged; expansion stops. */\n stop?: string\n /** What generated the children; default the port's `execution`. */\n execution?: SearchOperationRecordedEvent['execution']\n accounting: SearchAttemptAccounting\n}\n\n/** The proposer port: derives children from the parents the policy chose. */\nexport interface SearchProposerPort<TArtifact> {\n readonly name: string\n readonly kind: SearchProposerKind\n readonly source: SearchSourceRef\n readonly execution: SearchOperationRecordedEvent['execution']\n /** Prior hold for one proposal until 20 proposals have settled. Default 0. */\n readonly reservationUsd?: number\n /** Children one proposal usually returns, to price an expansion's screens\n * before it runs. Default 1. */\n readonly childrenPerProposal?: number\n propose(request: SearchProposalRequest<TArtifact>): Promise<SearchProposalResult<TArtifact>>\n}\n\nexport interface RunSearchOptions<TArtifact> {\n /** An opened recorder; its header names this policy and allocator. */\n recorder: SearchRecorder\n /** The starting artifact: the seeded root. */\n root: TArtifact\n codec: SearchArtifactCodec<TArtifact>\n policy: SearchPolicy\n allocation: SearchAllocator\n proposer: SearchProposerPort<TArtifact>\n executor: SearchExecutor<TArtifact>\n /** Refuse a child before it runs: the reason, or null to admit it. A\n * refused child is recorded, decided `invalid`, and never becomes a parent. */\n admit?: (artifact: TArtifact) => string | null\n /** Stop expanding after this many proposals. */\n maxExpansions?: number\n /** Attempts per cell for retryable environment errors. Default 3. */\n maxAttempts?: number\n /** Aborting pauses the search: in-flight cells are aborted, what settled is\n * recorded, the ledger stays open, and the call rejects. Run the kernel on\n * the same ledger again to continue. */\n signal?: AbortSignal\n /** Milliseconds since the epoch, for the deadline. Default `Date.now`. */\n now?: () => number\n}\n\nexport interface SearchRunResult {\n /** The closed search. */\n state: SearchStateView\n /** The node the search keeps: the claim's selection, or without a claim the\n * policy leader; the root when nothing was selected. */\n leader: string\n reason: SearchCloseReason\n /** The claim on the sealed test split; null for a search without one. */\n claim: SearchClaim | null\n /** The claim made again from the ledger alone (`verifySearchClaim`): never\n * `mismatch`, which `runSearch` throws; `unknown` for a claim another rule\n * revision made; null without a claim. */\n claimVerification: SearchClaimVerification | null\n}\n\n/** The stored output of one proposal: enough to register its children again. */\nexport interface SearchProposalBlob {\n kind: 'search-proposal'\n operator: SearchProposalRequest<unknown>['operator']\n parents: string[]\n selection: { rule: string; evidence: Record<string, number> }\n children: Array<{\n node: RegisterSearchNodeInput\n diffs: Array<SearchArtifactRef | SearchUnknown>\n label: string\n rationale: string\n attribution: Readonly<Record<string, unknown>> | null\n invalid: string | null\n }>\n}\n\n/** The expansion index a kernel operation id encodes, or null. */\nexport function searchExpansionIndex(operationId: string): number | null {\n const match = /^expand-(\\d+)$/.exec(operationId)\n return match ? Number(match[1]) : null\n}\n","/** Sealed-test claim planning, persistence, placement, and final ledger decisions. */\nimport type { SearchAllocator, SearchCellPlan } from './allocation'\nimport { estimateNode } from './estimate-node'\nimport {\n decideSearchClaim,\n planSearchClaim,\n SEARCH_CLAIM_RULE,\n SEARCH_CLAIM_RULE_NAME,\n type SearchClaimPlan,\n searchClaimReserveUsd,\n} from './search-claim'\nimport { isTerminal } from './search-kernel-close'\nimport type { SearchExecutor, SearchLane } from './search-kernel-contract'\nimport { CLAIM_OPERATION, USD_TOLERANCE } from './search-kernel-contract'\nimport type { SearchRecorder } from './search-ledger-recording'\nimport type { SearchCloseReason, SearchReservation } from './search-ledger-types'\nimport { type SearchCell, type SearchStateView, searchCellId } from './search-state'\n\ninterface SearchClaimHost {\n stopReason: SearchCloseReason | null\n readonly state: SearchStateView\n readonly recorder: SearchRecorder\n readonly options: {\n readonly allocation: SearchAllocator\n readonly executor: Pick<SearchExecutor<unknown>, 'place'>\n readonly proposer: { readonly childrenPerProposal?: number }\n }\n readonly lanes: ReadonlyMap<string, SearchLane>\n refresh(): Promise<void>\n cellReservation(lane: SearchLane): SearchReservation\n maxCellReservation(): number\n operationReservation(): SearchReservation\n enqueue(cell: SearchCell): void\n}\n\n/** The sealed-test lifecycle: preflight, durable plan, cell allocation, and final claim. */\nexport class SearchKernelClaim {\n plan: SearchClaimPlan | null = null\n\n constructor(private readonly host: SearchClaimHost) {}\n\n /** Refuse an unclaimable search before its first paid cell starts. */\n assertReady(): void {\n const header = this.host.state.header!\n const testTasks = header.splits.test.tasks.length\n if (testTasks === 0) return\n const refuse = (why: string): never => {\n throw new Error(\n `runSearch: search ${this.host.recorder.searchId} has a test split, but ${why}`,\n )\n }\n if (header.splits.selection.tasks.length === 0) {\n refuse('no selection split to choose its finalists on')\n }\n if (header.objective.claim.minimumEffect === undefined) {\n refuse('its claim declares no minimumEffect for the power check')\n }\n if ('unknown' in header.objective.judge) {\n refuse(\n 'its judge is not pinned; a claim with an unknown judge cannot ship, and a resumed search could mix two judges',\n )\n }\n const { maxUsd, reservedClaimUsd } = header.budget\n if (maxUsd === null) return\n const cellUsd = this.host.maxCellReservation()\n const need = searchClaimReserveUsd({\n testTasks,\n reps: this.host.options.allocation.reps,\n cellUsd,\n })\n if (reservedClaimUsd + USD_TOLERANCE < need) {\n refuse(\n `its claim reserve $${reservedClaimUsd} is below the $${need} the root and 3 finalists need on ${testTasks} test tasks at $${cellUsd} a cell`,\n )\n }\n const rootCells = this.host.options.allocation.plan(\n this.host.state,\n this.host.state.rootNodeId!,\n 0,\n ).length\n const screens =\n (this.host.options.proposer.childrenPerProposal ?? 1) *\n this.host.options.allocation.screenSize(this.host.state)\n const round = this.host.operationReservation().usd + (rootCells + screens) * cellUsd\n if (maxUsd - reservedClaimUsd + USD_TOLERANCE < round) {\n refuse(\n `its cap $${maxUsd} less the claim reserve $${reservedClaimUsd} does not cover the root and one screening round ($${round})`,\n )\n }\n }\n\n /** Recover the exact durable claim design left by an earlier process. */\n async restore(): Promise<void> {\n const operation = this.host.state.operation(CLAIM_OPERATION)\n if (!operation) return\n const ref = operation.artifacts.find((artifact) => artifact.role === 'claim-plan')\n if (!ref) throw new Error(`runSearch: the ${CLAIM_OPERATION} operation has no stored plan`)\n const plan = this.host.recorder.readBlob(ref) as SearchClaimPlan\n if (!operation.recorded) await this.recordClaimOperation()\n this.plan = plan\n this.host.stopReason = plan.stopReason\n }\n\n async begin(): Promise<void> {\n await this.host.refresh()\n const stopReason = this.host.stopReason ?? 'converged'\n const header = this.host.state.header!\n const reps = this.host.options.allocation.reps\n const plan = planSearchClaim(this.host.state, {\n stopReason,\n reps,\n affordable: (finalists) => {\n const placed = this.claimCells(finalists, this.host.state.rootNodeId!)\n const hold = placed.reduce((sum, cell) => sum + cell.reservation.usd, 0)\n const { headroomUsd, claimReserveUsd } = this.host.state.budget\n const { maxCells } = header.budget\n return (\n (headroomUsd === null || hold <= headroomUsd + claimReserveUsd + USD_TOLERANCE) &&\n (maxCells === null || this.host.state.audit.cells.allocated + placed.length <= maxCells)\n )\n },\n })\n await this.host.recorder.startOperation({\n operationId: CLAIM_OPERATION,\n operationKind: 'selection',\n reservation: null,\n artifacts: [this.host.recorder.blob('claim-plan', plan)],\n })\n await this.recordClaimOperation()\n this.plan = plan\n this.host.stopReason = stopReason\n await this.apply(plan)\n }\n\n private async recordClaimOperation(): Promise<void> {\n await this.host.recorder.recordOperation({\n operationId: CLAIM_OPERATION,\n operationKind: 'selection',\n execution: { kind: 'deterministic', source: SEARCH_CLAIM_RULE },\n outcome: { status: 'completed' },\n accounting: {\n tokens: { status: 'known', inputTokens: 0, outputTokens: 0, cachedTokens: 0 },\n cost: { status: 'known', usd: 0, source: 'free' },\n },\n })\n await this.host.refresh()\n }\n\n /** Decide finalists and allocate all interleaved test cells before any starts. Idempotent. */\n async apply(plan: SearchClaimPlan): Promise<void> {\n const root = this.host.state.rootNodeId!\n // Estimate from one read of the state, then append: an append retires the view.\n const bases = plan.finalists.map((finalist) =>\n estimateNode(this.host.state, finalist.nodeId, { against: root, split: 'selection' }),\n )\n for (const [rank, finalist] of plan.finalists.entries()) {\n await this.host.recorder.decideNode({\n nodeId: finalist.nodeId,\n decision: { status: 'finalist' },\n basis: bases[rank]!,\n rule: SEARCH_CLAIM_RULE_NAME,\n reason: `rank ${rank + 1} of ${plan.finalists.length} by selection mean (${finalist.selectionMean}); ${plan.reason}`,\n })\n }\n await this.host.refresh()\n if (plan.test !== 'run') return\n const missing = this.claimCells(plan.finalists.length, root, plan)\n .map((cell) => ({\n ...cell,\n cellId: searchCellId(\n this.host.recorder.searchId,\n cell.nodeId,\n cell.plan.taskId,\n 'test',\n cell.plan.rep,\n ),\n }))\n .filter((cell) => !this.host.state.cell(cell.cellId))\n for (const cell of missing) {\n await this.host.recorder.allocateCell({\n nodeId: cell.nodeId,\n taskId: cell.plan.taskId,\n split: 'test',\n rep: cell.plan.rep,\n stage: 'claim',\n lane: cell.lane.name,\n reservation: cell.reservation,\n })\n }\n await this.host.refresh()\n for (const cell of missing) this.host.enqueue(this.host.state.cell(cell.cellId)!)\n }\n\n private claimCells(\n finalists: number,\n root: string,\n plan?: SearchClaimPlan,\n ): Array<{\n nodeId: string\n plan: SearchCellPlan\n lane: SearchLane\n reservation: SearchReservation\n }> {\n const header = this.host.state.header!\n // While pricing, the arms are placeholders: placement and holds depend on\n // the lane, never on which node runs.\n const arms = [root, ...(plan ? plan.finalists.map((entry) => entry.nodeId) : [])]\n while (arms.length < finalists + 1) arms.push(root)\n const cells = []\n for (const task of header.splits.test.tasks) {\n for (let rep = 0; rep < this.host.options.allocation.reps; rep++) {\n for (const nodeId of arms) {\n const cellPlan: SearchCellPlan = {\n taskId: task.taskId,\n split: 'test',\n rep,\n stage: 'claim',\n }\n const laneName = this.host.options.executor.place({ ...cellPlan, nodeId })\n const lane = this.host.lanes.get(laneName)\n if (!lane) {\n throw new Error(`runSearch: the executor placed a cell on unknown lane ${laneName}`)\n }\n cells.push({ nodeId, plan: cellPlan, lane, reservation: this.host.cellReservation(lane) })\n }\n }\n }\n return cells\n }\n\n async close(plan: SearchClaimPlan): Promise<void> {\n const { claim, decisions } = decideSearchClaim(this.host.state, plan)\n const decided = new Set(decisions.map((decision) => decision.nodeId))\n const root = this.host.state.rootNodeId!\n const rest = this.host.state\n .nodes()\n .filter((node) => !decided.has(node.nodeId) && !isTerminal(node))\n .map((node) => {\n const scored = this.host.state.scoredCells(node.nodeId, 'selection').length > 0\n return {\n nodeId: node.nodeId,\n decision: { status: 'rejected' as const },\n basis: scored\n ? estimateNode(this.host.state, node.nodeId, { against: root, split: 'selection' })\n : null,\n rule: SEARCH_CLAIM_RULE_NAME,\n reason: scored\n ? 'not a finalist: the claim tests at most 3 nodes that scored every selection unit and beat the root, best selection mean first'\n : 'the search stopped before this node was measured on the selection split',\n }\n })\n for (const decision of [...decisions, ...rest]) await this.host.recorder.decideNode(decision)\n await this.host.recorder.close({ reason: plan.stopReason, claim })\n await this.host.refresh()\n }\n}\n","/** Hand-off between work that finishes asynchronously and the loop that records it. */\n\n/** Completions in arrival order; one waiter at a time sleeps until one arrives or `wakeUp` fires. */\nexport class SearchCompletionQueue<T> {\n private readonly items: T[] = []\n private wake: (() => void) | null = null\n\n /** The next completion, or null when `wakeUp` ended the wait without one. */\n async next(): Promise<T | null> {\n if (this.items.length === 0) {\n await new Promise<void>((resolve) => {\n this.wake = resolve\n })\n }\n return this.items.shift() ?? null\n }\n\n push(item: T): void {\n this.items.push(item)\n this.wakeUp()\n }\n\n wakeUp(): void {\n const wake = this.wake\n this.wake = null\n wake?.()\n }\n}\n","/** Execution lanes: their queues, in-flight counts, and the dollar holds sized from settled spend. */\nimport {\n ESTIMATE_FROM_CELLS,\n ESTIMATE_MARGIN,\n type SearchLane,\n STAGE_PRIORITY,\n USD_TOLERANCE,\n} from './search-kernel-contract'\nimport type { SearchReservation } from './search-ledger-types'\nimport type { SearchCell, SearchStateView } from './search-state'\n\nexport interface SearchLaneState extends SearchLane {\n inFlight: number\n /** Queued cell ids by stage priority. */\n queues: string[][]\n settledCosts: number[]\n}\n\ninterface SearchLanesHost {\n state(): SearchStateView\n now(): number\n /** The reservation a proposal holds before enough have settled to estimate one. */\n operationPriorUsd(): number\n}\n\nexport class SearchLanes {\n readonly byName = new Map<string, SearchLaneState>()\n private readonly operationCosts: number[] = []\n\n constructor(\n declared: Iterable<SearchLane>,\n private readonly host: SearchLanesHost,\n ) {\n for (const lane of declared) {\n if (!Number.isSafeInteger(lane.capacity) || lane.capacity < 1) {\n throw new TypeError(`runSearch: lane ${lane.name} needs a positive integer capacity`)\n }\n if (!Number.isFinite(lane.cellUsd) || lane.cellUsd < 0) {\n throw new TypeError(`runSearch: lane ${lane.name} needs a finite non-negative cellUsd`)\n }\n if (this.byName.has(lane.name))\n throw new TypeError(`runSearch: lane ${lane.name} is declared twice`)\n this.byName.set(lane.name, {\n ...lane,\n inFlight: 0,\n queues: [[], [], [], []],\n settledCosts: [],\n })\n }\n if (this.byName.size === 0) throw new TypeError('runSearch: the executor declares no lane')\n }\n\n enqueue(cell: SearchCell): void {\n this.byName.get(cell.lane!)!.queues[STAGE_PRIORITY[cell.stage]]!.push(cell.cellId)\n }\n\n queuedCount(): number {\n let count = 0\n for (const lane of this.byName.values()) {\n for (const queue of lane.queues) count += queue.length\n }\n return count\n }\n\n /** Concurrent slots the lanes offer, within the budget's concurrency cap. */\n capacity(): number {\n let total = 0\n for (const lane of this.byName.values()) total += lane.capacity\n const cap = this.host.state().header!.budget.maxConcurrency\n return cap === null ? total : Math.min(cap, total)\n }\n\n /** A hard lane holds its enforced maximum. An estimate lane holds 1.5 times\n * the 99th percentile of its settled cells once 20 settled, else its prior. */\n cellReservation(lane: SearchLaneState): SearchReservation {\n if (lane.costCap === 'hard') return { kind: 'hard', usd: lane.cellUsd }\n return { kind: 'estimate', usd: estimate(lane.settledCosts, lane.cellUsd) }\n }\n\n maxCellReservation(): number {\n let most = 0\n for (const lane of this.byName.values()) {\n most = Math.max(most, this.cellReservation(lane).usd)\n }\n return most\n }\n\n operationReservation(): SearchReservation {\n return {\n kind: 'estimate',\n usd: estimate(this.operationCosts, this.host.operationPriorUsd()),\n }\n }\n\n /** A recorded proposal's spend sizes the next proposal's hold. */\n recordOperationCost(usd: number): void {\n this.operationCosts.push(usd)\n }\n\n /** Overspend took committed spend, open holds and the unspent claim reserve\n * past the cap. Nothing new is proposed then, even at a zero-dollar prior. */\n overCap(): boolean {\n const state = this.host.state()\n const { maxUsd } = state.header!.budget\n if (maxUsd === null) return false\n const { committedUsd, openReservationUsd } = state.audit.spend\n const used = committedUsd + openReservationUsd + state.budget.claimReserveUsd\n return used > maxUsd + USD_TOLERANCE\n }\n\n pastDeadline(): boolean {\n const deadline = this.host.state().header!.budget.deadline\n return deadline !== null && this.host.now() >= Date.parse(deadline)\n }\n}\n\nfunction estimate(costs: readonly number[], prior: number): number {\n if (costs.length < ESTIMATE_FROM_CELLS) return prior\n const sorted = [...costs].sort((a, b) => a - b)\n const p99 = sorted[Math.min(sorted.length - 1, Math.ceil(0.99 * sorted.length) - 1)]!\n return Math.round(ESTIMATE_MARGIN * p99 * 1e9) / 1e9\n}\n","/**\n * Shared, pure helpers for `src/search/lenses/*`.\n *\n * Every lens is a pure function of a `SearchStateView` (search-tree-design\n * §12): it reads no other record type and does no I/O. These helpers exist so\n * each lens states its own numbers instead of re-deriving thresholds; they\n * reuse agent-eval's own statistics and estimator revisions rather than\n * inventing new ones.\n */\n\nimport { searchEstimateMethod } from '../../campaign/estimate-node'\nimport type { SearchStateView } from '../../campaign/search-state'\nimport { minimumPairsForPairedDeltaTest } from '../../paired-delta-test'\nimport { confidenceInterval } from '../../statistics'\n\n/** The search's own ranking split: selection when the search declares one,\n * else train. Matches `searchPolicyView` and `agent-eval search show`, so a\n * lens ranks nodes on exactly the split the search itself ranks them on. */\nexport function rankingSplit(state: SearchStateView): 'train' | 'selection' {\n const header = state.header\n return header && header.splits.selection.tasks.length > 0 ? 'selection' : 'train'\n}\n\n/** The smallest sample an exact one-sided sign test can resolve at 95%: the\n * same gate `NodeEstimate.method` uses for `insufficient`. */\nexport const INSUFFICIENT_FROM = minimumPairsForPairedDeltaTest(0.95)\n\n/** One named signal a `SearchPolicy` can read: a small, quantitative payload\n * under one label, so a policy reads `signal.value` without knowing a lens's\n * full `data` shape. */\nexport interface LensSignal<T> {\n name: string\n value: T\n}\n\nexport interface LensResult<TData, TSignal> {\n data: TData\n signal: LensSignal<TSignal>\n}\n\n/** A descriptive summary of an independent (unpaired) numeric sample, staged\n * by `NodeEstimate.method`'s own function (`searchEstimateMethod`): `none`\n * below 2 observations, with no mean (one observation is no estimate, §6.4),\n * `insufficient` below {@link INSUFFICIENT_FROM}, `descriptive` (bootstrap\n * interval, spread only) below `BOOTSTRAP_GATE_MIN_N`, `bootstrap`\n * (decision-grade interval) from there. Unlike `estimateNode`, these samples\n * are not paired on a shared unit, so this is never a claim — only a\n * lens's own honest description of what it measured. */\nexport interface LensSampleSummary {\n n: number\n mean: number | null\n method: 'none' | 'insufficient' | 'descriptive' | 'bootstrap'\n interval: [number, number] | null\n /** How `interval` was computed; null without one. The samples are\n * independent (unpaired), so it is a percentile bootstrap of their mean:\n * 1000 resamples at 95%, seeded by the caller or else by a hash of the data,\n * so a fixed sample always gives the same interval. */\n intervalMethod: 'percentile-bootstrap-of-mean' | null\n}\n\nexport function summarizeSamples(samples: readonly number[], seed?: number): LensSampleSummary {\n const n = samples.length\n const method = searchEstimateMethod(n)\n if (method === 'none') return { n, mean: null, method, interval: null, intervalMethod: null }\n const mean = samples.reduce((a, b) => a + b, 0) / n\n if (method === 'insufficient') {\n return { n, mean, method, interval: null, intervalMethod: null }\n }\n const { lower, upper } = confidenceInterval(\n [...samples],\n 0.95,\n seed === undefined ? {} : { seed },\n )\n return {\n n,\n mean,\n method,\n interval: [lower, upper],\n intervalMethod: 'percentile-bootstrap-of-mean',\n }\n}\n","/**\n * `operatorYield(state)`: outcome counts and yield per known dollar, by the\n * operator each edge names (search-tree-design §12).\n *\n * A node counts once, under the operator of the edge that registered it. A\n * re-proposal (an edge into a node an earlier edge registered) adds a\n * proposal and a `reproposals` count to its operator, but no outcome and no\n * yield sample: it produced no new artifact and no new measurement, so\n * counting its node again would repeat one measurement as independent\n * evidence.\n *\n * \"Yield\" reuses `searchPosterior` (E3, `../../campaign/estimate-node`): its\n * per-node mean is already the node's improvement over the root, oriented so\n * larger is always better regardless of the objective's direction — this\n * lens adds no second orientation rule of its own. A child's sample is\n * `posteriorMean / screenCostUsd`: the gain over the known cost of producing\n * and screening the node, which is the operator's doing. That cost is the\n * node's share of its proposal (the candidate-generation operation's cost\n * split evenly over every child edge the operation recorded, re-proposals\n * included) plus its cells allocated before its first decision: the first\n * rung and the proposer's train feedback, which the allocator plans together\n * at admission. Cells a later rung or the claim adds come after an\n * `advanced` or `finalist` decision; they are the allocator's and the\n * claim's choice, not the operator's, so an operator whose children advance\n * is not charged for the measurement their success earned. A seed edge\n * proposed nothing, so the root's cost is its cells alone.\n *\n * A child enters the sample only when both numbers are known: the node\n * shares 2 or more units with the root (one shared unit is no estimate,\n * §6.4); the edge names a recorded proposal operation whose cost is known;\n * every screen cell has run and has a known cost (an unpriced or unrecorded\n * part never floors a node to an artificially cheap, inflated yield); and it\n * was not decided `invalid` (a judge integrity or admission failure: its\n * score is not evidence of improvement, and `editCredit` excludes such nodes\n * the same way). A $0-known-cost node is excluded from yield (division by\n * zero is not a yield), not treated as free.\n */\n\nimport { searchPosterior } from '../../campaign/estimate-node'\nimport type {\n SearchEdgeOperator,\n SearchEdgeRecordedEvent,\n SearchNodeStatus,\n} from '../../campaign/search-ledger-types'\nimport type { SearchNode, SearchStateView } from '../../campaign/search-state'\nimport { rankingSplit, type LensSampleSummary, summarizeSamples } from './shared'\n\n/** The operators an expansion may choose (`SearchExpansion.operator` in\n * `search-policy.ts`): every edge operator except `seed` (the search's own\n * start) and `derive` (a cross-search edge a proposer never chooses). */\nexport const EXPANSION_OPERATORS = ['draft', 'improve', 'debug', 'merge'] as const\nexport type ExpansionOperator = (typeof EXPANSION_OPERATORS)[number]\n\n/** The bandit's own gate: an operator's weight is used only once it has this\n * many yield-eligible outcomes; below it, the policy falls back to a fixed\n * weight for that operator. Same threshold `NodeEstimate.method` uses for\n * `insufficient` (`minimumPairsForPairedDeltaTest(0.95)` = 6). */\nexport const MIN_OUTCOMES_FOR_WEIGHT = 6\n\nconst YIELD_METHOD =\n \"per registered node, searchPosterior's mean gain over the root divided by the known cost of producing and screening the node: its even share of the proposal operation's cost over the operation's child edges, plus its cells allocated before its first decision (first rung and train feedback; later rungs and the claim excluded); no sample when the node was decided invalid, shares fewer than 2 units with the root, or any part of that cost is unknown, unrecorded or zero\"\n\nexport interface OperatorOutcomeCounts {\n advanced: number\n finalist: number\n selected: number\n pruned: number\n rejected: number\n invalid: number\n undecided: number\n}\n\nexport interface OperatorYieldRow {\n operator: SearchEdgeOperator\n /** Edges recorded with this operator, re-proposals included. */\n proposals: number\n /** Of `proposals`, edges into a node an earlier edge registered. */\n reproposals: number\n /** Nodes this operator registered, by their latest status: one per node. */\n outcomes: OperatorOutcomeCounts\n /** Registered nodes excluded from `yield`: decided invalid, fewer than 2\n * units shared with the root, or a proposal or screen cost that is\n * unknown, unrecorded or zero. Never imputed into `yield`. */\n excluded: number\n yield: LensSampleSummary\n}\n\nexport interface OperatorYieldData {\n split: 'train' | 'selection'\n /** How a yield sample is computed. */\n method: string\n rows: OperatorYieldRow[]\n}\n\nexport interface OperatorYieldOptions {\n split?: 'train' | 'selection'\n}\n\n/** One weight per expandable operator: an operator's yield mean once it has\n * `MIN_OUTCOMES_FOR_WEIGHT` or more samples, else `null` (not yet trusted —\n * the policy's own fallback decides what an untrusted operator gets). */\nexport type OperatorYieldSignal = Record<ExpansionOperator, number | null>\n\nexport function operatorYield(\n state: SearchStateView,\n options: OperatorYieldOptions = {},\n): { data: OperatorYieldData; signal: { name: string; value: OperatorYieldSignal } } {\n const split = options.split ?? rankingSplit(state)\n // `searchPosterior` needs an opened search with a root; before that there\n // is no edge to count either.\n const posteriorByNode = new Map(\n state.header && state.rootNodeId !== null\n ? searchPosterior(state, { split }).nodes.map((node) => [node.nodeId, node])\n : [],\n )\n\n const grouped = new Map<\n SearchEdgeOperator,\n {\n proposals: number\n reproposals: number\n outcomes: OperatorOutcomeCounts\n excluded: number\n samples: number[]\n }\n >()\n const group = (operator: SearchEdgeOperator) => {\n let existing = grouped.get(operator)\n if (!existing) {\n existing = {\n proposals: 0,\n reproposals: 0,\n outcomes: {\n advanced: 0,\n finalist: 0,\n selected: 0,\n pruned: 0,\n rejected: 0,\n invalid: 0,\n undecided: 0,\n },\n excluded: 0,\n samples: [],\n }\n grouped.set(operator, existing)\n }\n return existing\n }\n\n const edges = state.edges()\n // Every child a proposal returned shares its cost evenly, a re-proposal's\n // share included: the proposal produced that artifact too.\n const childEdges = new Map<string, number>()\n for (const edge of edges) {\n const operationId = edge.proposer?.operationId\n if (operationId) childEdges.set(operationId, (childEdges.get(operationId) ?? 0) + 1)\n }\n\n for (const edge of edges) {\n const child = state.node(edge.childNodeId)\n if (!child) continue\n const bucket = group(edge.operator)\n bucket.proposals += 1\n if (child.edgeIds[0] !== edge.edgeId) {\n bucket.reproposals += 1\n continue\n }\n bucket.outcomes[statusKey(child.status)] += 1\n\n const posterior = posteriorByNode.get(child.nodeId)\n const costUsd = screenCostUsd(state, child, edge, childEdges)\n if (\n child.status === 'invalid' ||\n !posterior ||\n posterior.mean === null ||\n posterior.pairs < 2 ||\n costUsd === null ||\n costUsd <= 0\n ) {\n bucket.excluded += 1\n continue\n }\n bucket.samples.push(posterior.mean / costUsd)\n }\n\n const rows: OperatorYieldRow[] = [...grouped.entries()]\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([operator, bucket]) => ({\n operator,\n proposals: bucket.proposals,\n reproposals: bucket.reproposals,\n outcomes: bucket.outcomes,\n excluded: bucket.excluded,\n yield: summarizeSamples(bucket.samples),\n }))\n\n const signalValue = {} as OperatorYieldSignal\n for (const operator of EXPANSION_OPERATORS) {\n const row = rows.find((r) => r.operator === operator)\n signalValue[operator] =\n row && row.yield.n >= MIN_OUTCOMES_FOR_WEIGHT && row.yield.mean !== null\n ? row.yield.mean\n : null\n }\n\n return {\n data: { split, method: YIELD_METHOD, rows },\n signal: { name: 'operatorYield.weights', value: signalValue },\n }\n}\n\n/** The known cost of producing and screening `node`, which `edge` registered;\n * null when any part of it is unknown. The screen ends at the node's first\n * decision: the allocator records `advanced` before it allocates a further\n * rung, and the claim decides `finalist` before it allocates test cells. */\nfunction screenCostUsd(\n state: SearchStateView,\n node: SearchNode,\n edge: SearchEdgeRecordedEvent,\n childEdges: ReadonlyMap<string, number>,\n): number | null {\n let usd = 0\n if (edge.proposer !== null) {\n const { operationId } = edge.proposer\n if (operationId === null) return null\n const operation = state.operation(operationId)\n if (!operation?.recorded || !operation.costKnown) return null\n usd += operation.spentUsd / childEdges.get(operationId)!\n }\n const screenEnd = node.decisions[0]?.sequence ?? Number.POSITIVE_INFINITY\n for (const cell of state.cells({ nodeId: node.nodeId })) {\n if (cell.allocatedSequence > screenEnd) continue\n // A cell that has not run has no cost yet, so its cost is not known.\n if (!cell.costKnown || (cell.attempts === 0 && cell.cancelled === null)) return null\n usd += cell.spentUsd\n }\n return usd\n}\n\nfunction statusKey(status: SearchNodeStatus | null): keyof OperatorOutcomeCounts {\n return status ?? 'undecided'\n}\n","/** Policy observations and divergence decisions from train and selection evidence. */\nimport { type OperatorYieldSignal, operatorYield } from '../search/lenses/operator-yield'\nimport { estimateNode, type SearchPosterior, searchPosterior } from './estimate-node'\nimport { DEFAULT_MAX_ATTEMPTS } from './search-kernel-contract'\nimport type { NodeEstimate } from './search-ledger-types'\nimport type { SearchPolicyNode, SearchPolicyView } from './search-policy'\nimport type { SearchStateView } from './search-state'\n\n/**\n * A policy's read of a search: `screened` lists the admitted nodes whose screen\n * finished, in registration order; `screening` counts the admitted nodes still\n * being screened. Nodes are ranked on the selection split, or on train when\n * the search declares no selection split. The view reads no test cell.\n * `maxAttempts` (default 3, the kernel's) says when an errored cell has no\n * attempt left, which makes its unit a dodge.\n */\nexport function searchPolicyView(\n state: SearchStateView,\n input: {\n screened: readonly string[]\n screening: number\n expansions: number\n maxAttempts?: number\n },\n): SearchPolicyView {\n const maxAttempts = input.maxAttempts ?? DEFAULT_MAX_ATTEMPTS\n const header = state.header\n if (!header) throw new Error(`search ${state.searchId} has not been opened`)\n const split = header.splits.selection.tasks.length > 0 ? 'selection' : 'train'\n let nodes: SearchPolicyNode[] | undefined\n let operatorWeights: OperatorYieldSignal | undefined\n return {\n searchId: state.searchId,\n seed: header.policy.seed,\n direction: header.objective.direction,\n split,\n rootNodeId: state.rootNodeId!,\n expansions: input.expansions,\n screened: [...input.screened],\n screening: input.screening,\n complete: (nodeId) => {\n // A cell still to run (queued, in flight, or retrying) and a cell\n // cancelled before it ran do not count against the node; a cell that\n // ran and ended unscored does.\n let scored = false\n for (const cell of state.cells({ nodeId })) {\n if (cell.split !== split) continue\n if (cell.score !== null) scored = true\n else if (cell.final || (cell.outcome === 'errored' && cell.attempts >= maxAttempts)) {\n return false\n }\n }\n return scored\n },\n unitScores: (nodeId) => state.unitScores(nodeId, split),\n estimate: (nodeId, against) => estimateNode(state, nodeId, { against, split }),\n nodes: () => {\n nodes ??= policyNodes(state)\n return nodes\n },\n get posterior() {\n let posterior = POSTERIORS.get(state)\n if (!posterior) {\n posterior = searchPosterior(state, { split })\n POSTERIORS.set(state, posterior)\n }\n return posterior\n },\n get operatorWeights() {\n operatorWeights ??= operatorYield(state, { split }).signal.value\n return operatorWeights\n },\n }\n}\n\n/** One posterior per ledger state: a state view is retired when the ledger\n * moves on, so the view it was computed from names the sequence. */\nconst POSTERIORS = new WeakMap<SearchStateView, SearchPosterior>()\n\n/** Every node whose edge is recorded, with its lineage and its defects outside\n * the test split. */\nfunction policyNodes(state: SearchStateView): SearchPolicyNode[] {\n const nodes: SearchPolicyNode[] = []\n for (const node of state.nodes()) {\n const edgeId = node.edgeIds[0]\n if (edgeId === undefined) continue\n let outcomes = 0\n let defects = 0\n for (const cell of state.cells({ nodeId: node.nodeId })) {\n if (cell.split === 'test' || !cell.final) continue\n outcomes += 1\n if (cell.outcome === 'failed') defects += 1\n }\n const edge = state.edge(edgeId)!\n nodes.push({\n nodeId: node.nodeId,\n ordinal: node.ordinal,\n parent: node.primaryParentId,\n operator: edge.operator,\n rule: edge.selection?.rule ?? null,\n children: node.children,\n status: node.status,\n outcomes,\n defects,\n })\n }\n return nodes\n}\n\n/**\n * The divergence rule: a node whose train mean rose over its parent's on the\n * train units they share while its selection interval against the parent (6\n * or more units, not indeterminate) lies wholly on the worse side. Train is\n * what the proposer reads; a gain there that selection contradicts is the\n * signature of fitting the feedback instead of the task.\n */\nexport function searchDivergence(\n state: SearchStateView,\n nodeId: string,\n): { basis: NodeEstimate; reason: string } | null {\n const header = state.header\n const node = state.node(nodeId)\n const parent = node?.primaryParentId ?? null\n if (!header || parent === null || header.splits.selection.tasks.length === 0) return null\n const selection = estimateNode(state, nodeId, { against: parent, split: 'selection' })\n if (selection.interval === null) return null\n const maximize = header.objective.direction === 'maximize'\n const [low, high] = selection.interval\n if (maximize ? high >= 0 : low <= 0) return null\n const parentTrain = new Map(\n state.unitScores(parent, 'train').map((unit) => [unit.unitId, unit.mean]),\n )\n let gain = 0\n let shared = 0\n for (const unit of state.unitScores(nodeId, 'train')) {\n const before = parentTrain.get(unit.unitId)\n if (before === undefined) continue\n gain += maximize ? unit.mean - before : before - unit.mean\n shared += 1\n }\n if (shared === 0 || gain <= 0) return null\n const trainGain = Math.round((gain / shared) * 1e4) / 1e4\n return {\n basis: selection,\n reason: `its train mean rose ${trainGain} over its parent's on ${shared} shared train unit${shared === 1 ? '' : 's'}, while its selection interval against the parent, [${round4(low)}, ${round4(high)}] on ${selection.pairs} units, lies wholly on the worse side`,\n }\n}\n\nfunction round4(value: number): number {\n return Math.round(value * 1e4) / 1e4\n}\n","/** Which nodes are admitted, how many cells each still runs, and which finished their screen. */\nimport type { SearchStateView } from './search-state'\n\nexport class SearchNodeProgress {\n /** Unfinished cells per node. */\n private readonly pending = new Map<string, number>()\n /** Admitted nodes whose screen finished, in registration order. */\n screened: string[] = []\n readonly screenedSet = new Set<string>()\n readonly admitted = new Set<string>()\n\n constructor(private readonly state: () => SearchStateView) {}\n\n /** Unfinished cells of a node; zero when none was ever allocated. */\n count(nodeId: string): number {\n return this.pending.get(nodeId) ?? 0\n }\n\n add(nodeId: string, cells: number): void {\n this.pending.set(nodeId, this.count(nodeId) + cells)\n }\n\n /** One of the node's cells finished; returns how many remain. */\n release(nodeId: string): number {\n const left = (this.pending.get(nodeId) ?? 1) - 1\n this.pending.set(nodeId, left)\n return left\n }\n\n /** Admitted and running nothing: ready for the allocator to rank. */\n idle(nodeId: string): boolean {\n return this.admitted.has(nodeId) && this.count(nodeId) === 0\n }\n\n screening(): number {\n return this.admitted.size - this.screenedSet.size\n }\n\n markScreened(nodeId: string): void {\n if (this.screenedSet.has(nodeId)) return\n this.screenedSet.add(nodeId)\n const state = this.state()\n const ordinal = state.node(nodeId)!.ordinal\n let index = this.screened.length\n while (index > 0 && state.node(this.screened[index - 1]!)!.ordinal > ordinal) index--\n this.screened = [...this.screened.slice(0, index), nodeId, ...this.screened.slice(index)]\n }\n}\n","/** The one proposal in flight and the proposals that have completed. */\n\nexport class SearchProposalSlot {\n /** The running proposal, or null when none runs. */\n running: Promise<void> | null = null\n private controller: AbortController | null = null\n /** Operations started: the next one's id. */\n started = 0\n /** Proposals that completed, by operation index. A proposal an interrupted\n * process lost counts toward none of the stop rules, so a resumed search\n * makes the proposals the uninterrupted one would have made. */\n readonly completed: number[] = []\n\n begin(running: Promise<void>, controller: AbortController): void {\n this.running = running\n this.controller = controller\n }\n\n end(): void {\n this.running = null\n this.controller = null\n }\n\n abort(reason: unknown): void {\n this.controller?.abort(reason)\n }\n\n /** Completed proposals made after the given expansion. */\n completedAfter(expansion: number): number {\n return this.completed.filter((index) => index > expansion).length\n }\n}\n","/** Event loop and mutable scheduling state for one ledger-backed search. */\nimport { redactText } from '../trace/redact'\nimport type { SearchAllocationView, SearchRungDecision } from './allocation'\nimport { SearchArtifactCache } from './search-kernel-artifacts'\nimport { SearchKernelClaim } from './search-kernel-claim'\nimport { closedSearchResult, isTerminal, unclaimedSearchDecisions } from './search-kernel-close'\nimport { SearchCompletionQueue } from './search-kernel-completions'\nimport type {\n RunSearchOptions,\n SearchCellResult,\n SearchCellWork,\n SearchProposalBlob,\n SearchProposalRequest,\n SearchProposalResult,\n SearchRunResult,\n} from './search-kernel-contract'\nimport {\n DEFAULT_MAX_ATTEMPTS,\n STAGE_PRIORITY,\n searchExpansionIndex,\n USD_TOLERANCE,\n} from './search-kernel-contract'\nimport { type SearchLaneState, SearchLanes } from './search-kernel-lanes'\nimport { searchDivergence, searchPolicyView } from './search-kernel-policy-view'\nimport { SearchNodeProgress } from './search-kernel-progress'\nimport { SearchProposalSlot } from './search-kernel-proposals'\nimport { FileSearchLedger } from './search-ledger'\nimport type { SearchRecorder } from './search-ledger-recording'\nimport type { SearchAttemptAccounting, SearchCloseReason } from './search-ledger-types'\nimport type { SearchPolicyView } from './search-policy'\nimport { type SearchCell, type SearchStateView, searchCellId } from './search-state'\nimport { acquireSingleRunLock } from './single-run-lock'\n\ntype Completion =\n | { kind: 'cell'; cellId: string; attempt: number; result?: SearchCellResult; error?: unknown }\n | {\n kind: 'proposal'\n expansion: number\n operationId: string\n request: SearchProposalRequest<unknown>\n selection: { rule: string; evidence: Record<string, number> }\n result?: SearchProposalResult<unknown>\n error?: unknown\n }\n\nexport class SearchKernel<TArtifact> {\n private readonly options: RunSearchOptions<TArtifact>\n private readonly recorder: SearchRecorder\n private readonly maxAttempts: number\n private state!: SearchStateView\n private readonly lanes: SearchLanes\n private readonly inFlight = new Map<string, AbortController>()\n private readonly proposals = new SearchProposalSlot()\n private readonly completions = new SearchCompletionQueue<Completion>()\n private readonly progress = new SearchNodeProgress(() => this.state)\n private readonly expansionOf = new Map<string, number>()\n private readonly artifacts: SearchArtifactCache<TArtifact>\n /** Cells the ledger showed unsettled at start: an earlier process may hold their attempt. */\n private readonly adoptable = new Set<string>()\n private stopReason: SearchCloseReason | null = null\n private failure: { error: unknown } | null = null\n /** The claim's design once expansion stopped; the search then only claims. */\n private readonly claim: SearchKernelClaim\n\n constructor(options: RunSearchOptions<TArtifact>) {\n this.options = options\n this.recorder = options.recorder\n this.maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS\n if (!Number.isSafeInteger(this.maxAttempts) || this.maxAttempts < 1) {\n throw new TypeError('runSearch: maxAttempts must be a positive integer')\n }\n const { maxExpansions } = options\n if (\n maxExpansions !== undefined &&\n (!Number.isSafeInteger(maxExpansions) || maxExpansions < 0)\n ) {\n throw new TypeError('runSearch: maxExpansions must be a non-negative integer')\n }\n this.lanes = new SearchLanes(options.executor.lanes(), {\n state: () => this.state,\n now: options.now ?? Date.now,\n operationPriorUsd: () => options.proposer.reservationUsd ?? 0,\n })\n this.artifacts = new SearchArtifactCache((nodeId) =>\n options.codec.load(options.recorder, this.state.node(nodeId)!),\n )\n\n const kernel = this\n this.claim = new SearchKernelClaim({\n get state() {\n return kernel.state\n },\n get stopReason() {\n return kernel.stopReason\n },\n set stopReason(reason) {\n kernel.stopReason = reason\n },\n recorder: this.recorder,\n options,\n lanes: this.lanes.byName,\n refresh: () => this.refresh(),\n cellReservation: (lane) => this.lanes.cellReservation(this.lanes.byName.get(lane.name)!),\n maxCellReservation: () => this.lanes.maxCellReservation(),\n operationReservation: () => this.lanes.operationReservation(),\n enqueue: (cell) => this.lanes.enqueue(cell),\n })\n }\n\n async run(): Promise<SearchRunResult> {\n // One writer per search on a host: a second kernel on the same ledger\n // file is refused while the first lives; a killed holder's lock is\n // reclaimed. Across hosts the ledger's own chain refuses a fork.\n const { ledger } = this.recorder\n const lock =\n ledger instanceof FileSearchLedger\n ? acquireSingleRunLock({ lockPath: `${ledger.path}.run.lock` })\n : null\n try {\n return await this.runLocked()\n } finally {\n lock?.release()\n }\n }\n\n private async runLocked(): Promise<SearchRunResult> {\n await this.refresh()\n const header = this.state.header\n if (!header) throw new Error(`runSearch: search ${this.recorder.searchId} has not been opened`)\n if (\n header.policy.expansion !== this.options.policy.name ||\n header.policy.allocation !== this.options.allocation.name\n ) {\n throw new Error(\n `runSearch: search ${this.recorder.searchId} was opened with policy ${header.policy.expansion} and allocation ${header.policy.allocation}, not ${this.options.policy.name} and ${this.options.allocation.name}`,\n )\n }\n if (this.state.closed) return closedSearchResult(this.state)\n await this.restore()\n const { signal } = this.options\n const onAbort = (): void => {\n for (const controller of this.inFlight.values()) controller.abort(signal?.reason)\n this.proposals.abort(signal?.reason)\n this.completions.wakeUp()\n }\n signal?.addEventListener('abort', onAbort, { once: true })\n try {\n if (this.claim.plan) await this.claim.apply(this.claim.plan)\n await this.loop()\n if (!this.failure && !this.claim.plan && this.state.header!.splits.test.tasks.length > 0) {\n await this.claim.begin()\n await this.loop()\n }\n } finally {\n signal?.removeEventListener('abort', onAbort)\n }\n if (this.failure) throw this.failure.error\n await this.close()\n return closedSearchResult(this.state)\n }\n\n // ── Start and resume ────────────────────────────────────────────────\n\n private async restore(): Promise<void> {\n const rootInput = this.options.codec.node(this.recorder, this.options.root)\n const rootId = this.state.rootNodeId\n if (rootId === null) {\n const { nodeId } = await this.recorder.registerNode(rootInput)\n await this.recorder.recordEdge({\n childNodeId: nodeId,\n parents: [],\n operator: 'seed',\n attribution: 'explicit',\n proposer: null,\n proposalKey: 'root',\n rationale: { unknown: 'the root is the caller-supplied starting artifact' },\n diffs: [],\n label: 'root',\n })\n await this.refresh()\n } else if (this.state.node(rootId)!.artifactDigest !== rootInput.artifactDigest) {\n throw new Error(\n `runSearch: search ${this.recorder.searchId} started from another root artifact; a changed start is a derived search`,\n )\n }\n const root = this.state.rootNodeId!\n this.artifacts.seed(root, this.options.root)\n this.expansionOf.set(root, -1)\n if (this.state.audit.cells.allocated === 0) this.claim.assertReady()\n await this.claim.restore()\n\n // Operations an earlier process started and never recorded: their spend\n // is unknown, so each is recorded failed with a floor of zero.\n const recorded: number[] = []\n for (let expansion = 0; ; expansion++) {\n const operationId = `expand-${expansion}`\n const operation = this.state.operation(operationId)\n if (!operation) break\n this.proposals.started = expansion + 1\n if (operation.recorded) {\n this.lanes.recordOperationCost(operation.spentUsd)\n recorded.push(expansion)\n if (operation.outcome === 'completed') this.proposals.completed.push(expansion)\n continue\n }\n await this.recorder.recordOperation({\n operationId,\n operationKind: 'candidate-generation',\n execution: this.options.proposer.execution,\n outcome: {\n status: 'failed',\n failure: {\n code: 'interrupted',\n message: 'the search stopped while this proposal ran; its output was lost',\n },\n },\n accounting: interruptedAccounting(),\n })\n await this.refresh()\n }\n\n for (const node of this.state.nodes()) {\n if (node.edgeIds.length === 0) continue\n const edge = this.state.edge(node.edgeIds[0]!)!\n const expansion = edge.proposer?.operationId\n ? searchExpansionIndex(edge.proposer.operationId)\n : null\n this.expansionOf.set(node.nodeId, expansion ?? -1)\n if (node.status !== 'invalid') this.progress.admitted.add(node.nodeId)\n }\n for (const cell of this.state.cells()) {\n const lane = cell.lane === null ? undefined : this.lanes.byName.get(cell.lane)\n if (cell.final && lane) lane.settledCosts.push(cell.spentUsd)\n if (this.cellDone(cell)) continue\n if (!lane) {\n throw new Error(\n `runSearch: cell ${cell.cellId} was placed on lane ${String(cell.lane)}, which the executor does not declare`,\n )\n }\n this.adoptable.add(cell.cellId)\n this.lanes.enqueue(cell)\n if (cell.stage !== 'claim') this.progress.add(cell.nodeId, 1)\n }\n // Once the claim began the search only claims: nothing is proposed or\n // allocated outside the test.\n if (this.claim.plan) return\n // A proposal recorded before its children all were: finish it from its output.\n for (const expansion of recorded) await this.finishProposal(expansion)\n for (const node of this.state.nodes()) {\n if (this.progress.admitted.has(node.nodeId) && !isTerminal(node))\n await this.allocateFor(node.nodeId)\n }\n for (const nodeId of this.state.nodeIds()) {\n if (!this.progress.admitted.has(nodeId)) continue\n // An advanced node finished its screen before its rung cells were\n // allocated, so it stays a parent while they run, as it was before the\n // restart.\n if (this.state.node(nodeId)!.status === 'advanced') this.progress.markScreened(nodeId)\n else if (this.progress.count(nodeId) === 0) await this.screenDone(nodeId)\n }\n // A node may have finished a rung before the interrupted process recorded\n // what its rank earned.\n await this.advance()\n }\n\n // ── The loop ────────────────────────────────────────────────────────\n\n private async loop(): Promise<void> {\n for (;;) {\n if (this.failure || this.options.signal?.aborted) {\n await this.drain(this.failure?.error ?? this.options.signal?.reason)\n this.failure ??= { error: this.options.signal?.reason ?? new Error('aborted') }\n return\n }\n if (this.lanes.pastDeadline()) {\n // Past the deadline nothing new starts, so what waits is cancelled.\n this.stopReason ??= 'deadline'\n if (this.lanes.queuedCount() > 0) await this.cancelQueued('deadline')\n }\n this.dispatch()\n const blocked =\n this.stopReason === null && this.proposals.running === null ? await this.tryExpand() : null\n const busy = this.inFlight.size > 0 || this.proposals.running !== null\n if (!busy) {\n if (this.lanes.queuedCount() > 0) continue\n this.stopReason ??= blocked ?? 'converged'\n return\n }\n await this.handle(await this.completions.next())\n }\n }\n\n private async handle(completion: Completion | null): Promise<void> {\n if (completion === null) return\n if (completion.kind === 'cell') await this.settle(completion)\n else await this.recordProposal(completion)\n }\n\n /** Abort everything in flight and record what still completes. */\n private async drain(reason: unknown): Promise<void> {\n for (const controller of this.inFlight.values()) controller.abort(reason)\n this.proposals.abort(reason)\n while (this.inFlight.size > 0 || this.proposals.running !== null) {\n await this.handle(await this.completions.next())\n }\n }\n\n // ── Cells ───────────────────────────────────────────────────────────\n\n /** Fill free lane slots with queued cells. A queued cell was admitted when\n * it was allocated, so starting it needs no further decision. */\n private dispatch(): void {\n if (this.failure || this.options.signal?.aborted) return\n // Past the deadline the search stops, but its claim still runs: the\n // claim's budget was reserved at the start.\n const claimOnly = this.lanes.pastDeadline()\n const cap = this.state.header!.budget.maxConcurrency\n for (const lane of this.lanes.byName.values()) {\n while (lane.inFlight < lane.capacity && (cap === null || this.inFlight.size < cap)) {\n const queue = claimOnly\n ? lane.queues[STAGE_PRIORITY.claim]\n : lane.queues.find((waiting) => waiting.length > 0)\n const cellId = queue?.shift()\n if (cellId === undefined) break\n this.start(cellId, lane)\n }\n }\n }\n\n private start(cellId: string, lane: SearchLaneState): void {\n const cell = this.state.cell(cellId)!\n const attempt = cell.attempts + 1\n const controller = new AbortController()\n const work: SearchCellWork<TArtifact> = {\n searchId: this.recorder.searchId,\n cellId,\n nodeId: cell.nodeId,\n taskId: cell.taskId,\n unitId: cell.unitId,\n split: cell.split,\n rep: cell.rep,\n stage: cell.stage,\n lane: lane.name,\n attempt,\n runId: `${cellId}:${attempt}`,\n artifact: this.artifacts.get(cell.nodeId),\n signal: controller.signal,\n }\n const adopt = this.adoptable.delete(cellId)\n this.inFlight.set(cellId, controller)\n lane.inFlight += 1\n const { executor } = this.options\n void (async () =>\n (adopt ? await executor.adopt(work) : null) ?? (await executor.run(work)))().then(\n (result) => this.completions.push({ kind: 'cell', cellId, attempt, result }),\n (error: unknown) => this.completions.push({ kind: 'cell', cellId, attempt, error }),\n )\n }\n\n private async settle(completion: Extract<Completion, { kind: 'cell' }>): Promise<void> {\n const { cellId, attempt } = completion\n this.inFlight.delete(cellId)\n const before = this.state.cell(cellId)!\n const lane = this.lanes.byName.get(before.lane!)!\n lane.inFlight -= 1\n if (!completion.result) {\n this.failure ??= { error: completion.error }\n return\n }\n // The freed slot takes the next queued cell before this result is\n // written, so no slot idles while the ledger syncs.\n this.dispatch()\n if (\n (this.failure || this.options.signal?.aborted) &&\n completion.result.outcome.status === 'errored'\n ) {\n // An attempt that ends in an error while the search stops may have\n // failed because it was interrupted. It stays unsettled, so a resumed\n // search adopts or reruns it instead of recording the interruption.\n return\n }\n await this.recorder.settleCell({ ...completion.result, cellId, attempt })\n await this.refresh()\n const cell = this.state.cell(cellId)!\n if (cell.final) lane.settledCosts.push(cell.spentUsd)\n if (!this.cellDone(cell)) {\n if (this.failure || this.options.signal?.aborted) return\n this.lanes.enqueue(cell)\n return\n }\n if (cell.stage === 'claim') return\n const left = this.progress.release(cell.nodeId)\n if (left === 0) await this.onNodeIdle(cell.nodeId)\n }\n\n /** Every cell allocated to the node is done: its screen, or a rung. */\n private async onNodeIdle(nodeId: string): Promise<void> {\n if (!(await this.screenDone(nodeId))) return\n await this.advance()\n }\n\n /** Record the rank decisions the allocator now supports and allocate the\n * rungs they open. Past the deadline, once the claim began, or once the\n * search fails or is aborted, no rung opens; a search that stopped\n * expanding still measures the nodes that earned it. */\n private async advance(): Promise<void> {\n if (\n this.claim.plan ||\n this.failure ||\n this.options.signal?.aborted ||\n this.lanes.pastDeadline()\n ) {\n return\n }\n for (const decision of this.options.allocation.advance(this.allocationView())) {\n await this.allocateFor(decision.nodeId, decision)\n }\n }\n\n /**\n * A node's allocated cells all finished. A node that diverges (its train\n * mean rose over its parent's while its selection interval against the\n * parent lies wholly on the worse side) is decided `invalid` and never\n * becomes a parent; any other node is screened. Returns whether it was.\n */\n private async screenDone(nodeId: string): Promise<boolean> {\n // The check reads the screen alone: a node the allocator advanced passed\n // it when its screen finished, and a restart must not re-judge it on the\n // rung cells it earned since.\n if (\n !this.claim.plan &&\n !this.progress.screenedSet.has(nodeId) &&\n this.state.node(nodeId)!.status !== 'advanced'\n ) {\n const divergence = searchDivergence(this.state, nodeId)\n if (divergence) {\n await this.recorder.decideNode({\n nodeId,\n decision: { status: 'invalid' },\n basis: divergence.basis,\n rule: 'divergence',\n reason: divergence.reason,\n })\n await this.refresh()\n this.progress.admitted.delete(nodeId)\n return false\n }\n }\n this.progress.markScreened(nodeId)\n return true\n }\n\n /**\n * Allocate the cells the allocator plans for a node through its rung and the\n * ledger lacks. With a rank decision, the rung is the decision's, and the\n * decision is recorded first, only once the cap admits the rung's cells.\n * Returns false when the cap or `maxCells` refused them.\n */\n private async allocateFor(nodeId: string, decision?: SearchRungDecision): Promise<boolean> {\n const rung =\n decision?.decision.status === 'advanced'\n ? decision.decision.rung\n : (this.state.node(nodeId)!.rung ?? 0)\n const plans = this.options.allocation\n .plan(this.state, nodeId, rung)\n .filter(\n (plan) =>\n !this.state.cell(\n searchCellId(this.recorder.searchId, nodeId, plan.taskId, plan.split, plan.rep),\n ),\n )\n if (plans.length === 0) {\n if (decision) await this.decide(decision)\n return true\n }\n const placed = plans.map((plan) => {\n const laneName = this.options.executor.place({ ...plan, nodeId })\n const lane = this.lanes.byName.get(laneName)\n if (!lane)\n throw new Error(`runSearch: the executor placed a cell on unknown lane ${laneName}`)\n return { plan, lane, reservation: this.lanes.cellReservation(lane) }\n })\n const hold = placed.reduce((sum, { reservation }) => sum + reservation.usd, 0)\n const { headroomUsd } = this.state.budget\n if (headroomUsd !== null && hold > headroomUsd + USD_TOLERANCE) return false\n const { maxCells } = this.state.header!.budget\n if (maxCells !== null && this.state.audit.cells.allocated + placed.length > maxCells) {\n return false\n }\n if (decision) await this.decide(decision)\n for (const { plan, lane, reservation } of placed) {\n await this.recorder.allocateCell({\n nodeId,\n taskId: plan.taskId,\n split: plan.split,\n rep: plan.rep,\n stage: plan.stage,\n lane: lane.name,\n reservation,\n })\n }\n await this.refresh()\n for (const { plan } of placed) {\n const cellId = searchCellId(this.recorder.searchId, nodeId, plan.taskId, plan.split, plan.rep)\n this.lanes.enqueue(this.state.cell(cellId)!)\n }\n this.progress.add(nodeId, placed.length)\n this.dispatch()\n return true\n }\n\n private async decide(decision: SearchRungDecision): Promise<void> {\n await this.recorder.decideNode(decision)\n await this.refresh()\n }\n\n private async cancelQueued(reason: 'deadline' | 'budget'): Promise<void> {\n for (const lane of this.lanes.byName.values()) {\n for (const [priority, queue] of lane.queues.entries()) {\n if (priority === STAGE_PRIORITY.claim) continue\n for (const cellId of queue.splice(0)) {\n const cell = this.state.cell(cellId)!\n // A cell with a settled attempt already counts as settled; only a\n // never-run cell is cancelled.\n if (cell.attempts === 0) {\n await this.recorder.cancelCell({ cellId, reason })\n await this.refresh()\n }\n if (this.progress.release(cell.nodeId) === 0) this.progress.markScreened(cell.nodeId)\n }\n }\n }\n }\n\n /** No further attempt will run: a final outcome, a cancellation, or a\n * retryable error that used up its attempts. */\n private cellDone(cell: SearchCell): boolean {\n return (\n cell.final ||\n cell.cancelled !== null ||\n (cell.outcome === 'errored' && cell.attempts >= this.maxAttempts)\n )\n }\n\n // ── Expansion ───────────────────────────────────────────────────────\n\n /** Start a proposal when the rules admit one; otherwise say why not. */\n private async tryExpand(): Promise<SearchCloseReason | null> {\n const { maxNodes, maxCells } = this.state.header!.budget\n if (maxNodes !== null && this.state.audit.nodes >= maxNodes) return 'max-nodes'\n const { maxExpansions } = this.options\n if (maxExpansions !== undefined && this.proposals.completed.length >= maxExpansions)\n return 'max-nodes'\n if (this.lanes.queuedCount() > 0) return 'converged'\n if (this.inFlight.size >= 2 * this.lanes.capacity()) return 'converged'\n const view = this.policyView()\n const { policy } = this.options\n const leader = policy.leader(view)\n if (\n policy.patience !== undefined &&\n this.proposals.completedAfter(this.expansionOf.get(leader) ?? -1) >= policy.patience\n ) {\n return 'patience'\n }\n const screen = this.options.allocation.screenSize(this.state)\n const operation = this.lanes.operationReservation()\n const children = this.options.proposer.childrenPerProposal ?? 1\n const need = operation.usd + children * screen * this.lanes.maxCellReservation()\n const { headroomUsd } = this.state.budget\n if (headroomUsd !== null && (need > headroomUsd + USD_TOLERANCE || this.lanes.overCap())) {\n return 'budget'\n }\n if (maxCells !== null && this.state.audit.cells.allocated + children * screen > maxCells) {\n return 'budget'\n }\n const expansion = policy.expand(view)\n if (expansion === null) return 'converged'\n const screened = new Set(view.screened)\n if (expansion.parents.length === 0) {\n throw new Error(`runSearch: policy ${policy.name} proposed an expansion without a parent`)\n }\n for (const parent of expansion.parents) {\n if (!screened.has(parent)) {\n throw new Error(\n `runSearch: policy ${policy.name} named parent ${parent}, which has not finished its screen; a node becomes a parent only after its screen completes`,\n )\n }\n }\n\n const index = this.proposals.started++\n const operationId = `expand-${index}`\n await this.recorder.startOperation({\n operationId,\n operationKind: 'candidate-generation',\n reservation: operation,\n })\n await this.refresh()\n const controller = new AbortController()\n const request: SearchProposalRequest<TArtifact> = {\n expansion: index,\n operationId,\n operator: expansion.operator,\n parents: expansion.parents.map((nodeId) => ({\n nodeId,\n artifact: this.artifacts.get(nodeId),\n })),\n leader,\n signal: controller.signal,\n }\n const running = this.options.proposer.propose(request).then(\n (result) =>\n this.completions.push({\n kind: 'proposal',\n expansion: index,\n operationId,\n request,\n selection: expansion.selection,\n result,\n }),\n (error: unknown) =>\n this.completions.push({\n kind: 'proposal',\n expansion: index,\n operationId,\n request,\n selection: expansion.selection,\n error,\n }),\n )\n this.proposals.begin(running, controller)\n return null\n }\n\n private async recordProposal(\n completion: Extract<Completion, { kind: 'proposal' }>,\n ): Promise<void> {\n this.proposals.end()\n const { operationId, expansion } = completion\n const { proposer, codec, admit } = this.options\n const result = completion.result as SearchProposalResult<TArtifact> | undefined\n if (!result) {\n await this.recorder.recordOperation({\n operationId,\n operationKind: 'candidate-generation',\n execution: proposer.execution,\n outcome: {\n status: 'failed',\n failure: { code: 'proposer-error', message: errorMessage(completion.error) },\n },\n accounting: interruptedAccounting(),\n })\n await this.refresh()\n this.failure ??= { error: completion.error }\n return\n }\n const { maxNodes } = this.state.header!.budget\n const room = maxNodes === null ? Number.POSITIVE_INFINITY : maxNodes - this.state.audit.nodes\n const parents = completion.request.parents as ReadonlyArray<{\n nodeId: string\n artifact: TArtifact\n }>\n const blob: SearchProposalBlob = {\n kind: 'search-proposal',\n operator: completion.request.operator,\n parents: parents.map((parent) => parent.nodeId),\n selection: completion.selection,\n children: result.children.slice(0, Math.max(0, room)).map((child) => ({\n node: codec.node(this.recorder, child.artifact),\n diffs: parents.map((parent) => codec.diff(this.recorder, parent.artifact, child.artifact)),\n label: redactText(child.label, { profile: 'share' }),\n rationale: redactText(child.rationale, { profile: 'share' }),\n attribution: child.attribution ?? null,\n invalid: admit?.(child.artifact) ?? null,\n })),\n }\n await this.recorder.recordOperation({\n operationId,\n operationKind: 'candidate-generation',\n execution: result.execution ?? proposer.execution,\n outcome: { status: 'completed' },\n accounting: result.accounting,\n artifacts: [this.recorder.blob('proposal', blob)],\n })\n await this.refresh()\n this.lanes.recordOperationCost(this.state.operation(operationId)!.spentUsd)\n this.proposals.completed.push(expansion)\n for (const [index, child] of blob.children.entries()) {\n this.artifacts.propose(child.node.artifactDigest, result.children[index]!.artifact)\n }\n if (result.stop !== undefined || blob.children.length === 0) this.stopReason ??= 'converged'\n await this.finishProposal(expansion)\n }\n\n /** Register every child a recorded proposal produced, each once. */\n private async finishProposal(expansion: number): Promise<void> {\n const operationId = `expand-${expansion}`\n const operation = this.state.operation(operationId)\n const ref = operation?.artifacts.find((artifact) => artifact.role === 'proposal')\n if (!operation?.recorded || operation.outcome !== 'completed' || !ref) return\n const blob = this.recorder.readBlob(ref) as SearchProposalBlob\n const { proposer } = this.options\n for (const [index, child] of blob.children.entries()) {\n const { nodeId } = await this.recorder.registerNode(child.node)\n this.artifacts.register(nodeId, child.node.artifactDigest)\n const edgeId = await this.recorder.recordEdge({\n childNodeId: nodeId,\n parents: blob.parents,\n operator: blob.operator,\n attribution: 'explicit',\n proposer: {\n kind: proposer.kind,\n name: proposer.name,\n operationId,\n source: proposer.source,\n },\n proposalKey: `${operationId}:${index}`,\n selection: blob.selection,\n rationale: child.rationale,\n diffs: child.diffs,\n label: child.label,\n })\n await this.refresh()\n const node = this.state.node(nodeId)!\n if (node.edgeIds[0] !== edgeId) continue // a re-proposal: a second edge, not re-measured\n this.expansionOf.set(nodeId, expansion)\n if (child.invalid !== null) {\n await this.recorder.decideNode({\n nodeId,\n decision: { status: 'invalid' },\n rule: 'admission',\n reason: child.invalid,\n })\n await this.refresh()\n continue\n }\n // On resume, a child the divergence rule already decided invalid stays\n // out: it is never screened, so it is never a parent.\n if (this.progress.admitted.has(nodeId) || node.status === 'invalid') continue\n this.progress.admitted.add(nodeId)\n await this.allocateFor(nodeId)\n if (this.progress.count(nodeId) === 0) this.progress.markScreened(nodeId)\n }\n }\n\n // ── Close ───────────────────────────────────────────────────────────\n\n private async close(): Promise<void> {\n await this.refresh()\n // Nodes left waiting on a rung are pruned with their rank; the policy's\n // leader is kept for the decisions below.\n const keep = this.options.policy.leader(this.policyView())\n for (const decision of this.options.allocation.prune(this.allocationView(), keep)) {\n await this.decide(decision)\n }\n if (this.claim.plan) {\n await this.claim.close(this.claim.plan)\n return\n }\n const view = this.policyView()\n const leader = this.options.policy.leader(view)\n const decisions = unclaimedSearchDecisions(this.state, view, leader, {\n rule: this.options.policy.name,\n stopReason: this.stopReason,\n screened: this.progress.screenedSet,\n })\n for (const decision of decisions) await this.recorder.decideNode(decision)\n await this.recorder.close({ reason: this.stopReason ?? 'converged', claim: null })\n await this.refresh()\n }\n\n // ── Reads ───────────────────────────────────────────────────────────\n\n private policyView(): SearchPolicyView {\n return searchPolicyView(this.state, {\n screened: this.progress.screened,\n screening: this.progress.screening(),\n expansions: this.proposals.completed.length,\n maxAttempts: this.maxAttempts,\n })\n }\n\n private allocationView(): SearchAllocationView {\n return {\n state: this.state,\n idle: (nodeId) => this.progress.idle(nodeId),\n }\n }\n\n private async refresh(): Promise<void> {\n this.state = await this.recorder.state()\n }\n}\n\n/** Spend of work whose result was lost: unknown, with no proven floor. */\nfunction interruptedAccounting(): SearchAttemptAccounting {\n return {\n tokens: { status: 'unknown', reason: 'the result of this work was lost' },\n cost: {\n status: 'unknown',\n knownLowerBoundUsd: 0,\n reason: 'the result of this work was lost, so its spend is unknown',\n },\n }\n}\n\nfunction errorMessage(error: unknown): string {\n const text = error instanceof Error ? error.message : String(error)\n return text.trim().length > 0 ? text : 'the proposer failed without a message'\n}\n","/**\n * The search kernel: one event-driven loop that every optimizer runs on.\n *\n * It separates three decisions that a generation loop fuses: where to expand\n * (the `SearchPolicy`), where to spend rollouts (the `SearchAllocator`), and\n * what to claim (the claim step, on the sealed test split). There is no\n * generation barrier: a lane that frees up takes the next allocated cell, and\n * the policy proposes when no cell waits and the budget admits a screen.\n *\n * Every step appends to the search ledger before the kernel acts on it, and the\n * ledger is the only checkpoint. Restarting the kernel on the same ledger\n * replays it and continues: an operation that started without a result is\n * recorded as failed with an unknown cost; a recorded proposal whose children\n * were not all registered is finished from its stored output; an allocated\n * cell without an outcome is first offered to `executor.adopt`, then run.\n *\n * The admission rule is the ledger's: committed spend, open reservations, the\n * unspent claim reserve and a new reservation stay within the cap. The kernel\n * checks it before it asks, prices an expansion (one proposal plus one screen)\n * before the proposer runs, and records spend above a reservation as\n * overspend, never refused.\n *\n * A search with a test split ends in its claim. When expansion stops, the\n * kernel fixes the claim's design (`planSearchClaim`) and stores it on the\n * ledger's `claim` operation before any test cell exists, decides the\n * finalists, runs the root's and the finalists' test cells together, and\n * closes with the claim `decideSearchClaim` makes from them. A node whose\n * train mean rises while its selection interval against its parent lies below\n * zero is decided `invalid` by the divergence rule and never becomes a parent.\n */\n\nimport type { RunSearchOptions, SearchRunResult } from './search-kernel-contract'\nimport { SearchKernel } from './search-kernel-runner'\n\nexport type {\n RunSearchOptions,\n SearchArtifactCodec,\n SearchCellResult,\n SearchCellWork,\n SearchExecutor,\n SearchLane,\n SearchProposalBlob,\n SearchProposalRequest,\n SearchProposalResult,\n SearchProposedChild,\n SearchProposerPort,\n SearchRunResult,\n} from './search-kernel-contract'\nexport { SEARCH_KERNEL_SOURCE, searchExpansionIndex } from './search-kernel-contract'\nexport { searchDivergence, searchPolicyView } from './search-kernel-policy-view'\n\n/** Run a search to its close, or continue one from its ledger. */\nexport async function runSearch<TArtifact>(\n options: RunSearchOptions<TArtifact>,\n): Promise<SearchRunResult> {\n return new SearchKernel(options).run()\n}\n","/**\n * Pareto frontier — multi-objective optimization over candidate runs.\n *\n * Lifted from ADC pareto.ts and blueprint-agent frontier.ts. When you're\n * trading off (cost, latency, quality) or (passRate, tokenBudget,\n * ttfb), you rarely have a single \"winner\" — you have a set of\n * non-dominated candidates. This module exposes:\n *\n * - `paretoFrontier`: filter a set of candidates to the non-dominated ones\n * - `dominates`: does A dominate B across all objectives?\n *\n * Each objective is declared with a direction: 'maximize' (higher=better)\n * or 'minimize' (lower=better). Candidates are any object; pass an\n * `objective(candidate)` accessor.\n */\n\nexport type Direction = 'maximize' | 'minimize'\n\nexport interface Objective<T> {\n /** Stable label used in reports. */\n name: string\n direction: Direction\n value: (candidate: T) => number\n}\n\nexport interface ParetoResult<T> {\n frontier: T[]\n dominated: T[]\n /** Index map: frontier[i] dominates each of dominatedBy[i]. */\n dominanceMap: Array<{ dominator: T; dominated: T[] }>\n}\n\n/** Does candidate A weakly dominate B — strictly better on at least one objective and no worse on any? */\nexport function dominates<T>(a: T, b: T, objectives: Objective<T>[]): boolean {\n let strictlyBetter = false\n for (const obj of objectives) {\n const av = obj.value(a)\n const bv = obj.value(b)\n if (!Number.isFinite(av) || !Number.isFinite(bv)) return false\n const aIsBetter = obj.direction === 'maximize' ? av > bv : av < bv\n const aIsWorse = obj.direction === 'maximize' ? av < bv : av > bv\n if (aIsWorse) return false\n if (aIsBetter) strictlyBetter = true\n }\n return strictlyBetter\n}\n\n/**\n * Compute the non-dominated frontier. Candidates with NaN/Infinity on any\n * objective are excluded (can't rank them). A candidate enters the frontier\n * iff no other candidate dominates it.\n */\nexport function paretoFrontier<T>(candidates: T[], objectives: Objective<T>[]): ParetoResult<T> {\n if (objectives.length === 0) {\n throw new Error('paretoFrontier: at least 1 objective required')\n }\n const valid = candidates.filter((c) => objectives.every((o) => Number.isFinite(o.value(c))))\n const frontier: T[] = []\n const dominated: T[] = []\n for (const c of valid) {\n const isDominated = valid.some((other) => other !== c && dominates(other, c, objectives))\n if (isDominated) dominated.push(c)\n else frontier.push(c)\n }\n const dominanceMap = frontier.map((d) => ({\n dominator: d,\n dominated: dominated.filter((x) => dominates(d, x, objectives)),\n }))\n return { frontier, dominated, dominanceMap }\n}\n\n/**\n * NSGA-II crowding distance — secondary sort for ties on the frontier.\n *\n * When the Pareto front collapses to a single point (or many candidates tie\n * on dominance), naive selection picks arbitrarily and the population\n * degenerates over generations. NSGA-II preserves diversity by preferring\n * candidates with more empty space around them on the frontier.\n *\n * Returns an array of `{ candidate, distance }` in the SAME order as the\n * input. Higher distance = more isolated = should be preferred when\n * preserving diversity.\n */\nexport function crowdingDistance<T>(\n candidates: T[],\n objectives: Objective<T>[],\n): Array<{ candidate: T; distance: number }> {\n const distances = new Map<T, number>(candidates.map((c) => [c, 0]))\n\n for (const obj of objectives) {\n const sorted = [...candidates].sort((a, b) => obj.value(a) - obj.value(b))\n const min = obj.value(sorted[0]!)\n const max = obj.value(sorted[sorted.length - 1]!)\n const range = max - min || 1\n\n // Boundary points get infinity (always preferred for diversity).\n distances.set(sorted[0]!, Infinity)\n distances.set(sorted[sorted.length - 1]!, Infinity)\n for (let i = 1; i < sorted.length - 1; i++) {\n const prev = obj.value(sorted[i - 1]!)\n const next = obj.value(sorted[i + 1]!)\n const current = distances.get(sorted[i]!)!\n if (current === Infinity) continue\n distances.set(sorted[i]!, current + (next - prev) / range)\n }\n }\n\n return candidates.map((c) => ({ candidate: c, distance: distances.get(c) ?? 0 }))\n}\n\n/**\n * Pareto frontier with tie-break by crowding distance — the canonical\n * NSGA-II selection step. Returns the frontier sorted by descending crowding\n * distance so callers can `.slice(0, k)` to pick K diverse winners.\n */\nexport function paretoFrontierWithCrowding<T>(\n candidates: T[],\n objectives: Objective<T>[],\n): Array<{ candidate: T; distance: number }> {\n const { frontier } = paretoFrontier(candidates, objectives)\n if (frontier.length === 0) return []\n const distances = crowdingDistance(frontier, objectives)\n return distances.sort((a, b) => b.distance - a.distance)\n}\n"],"mappings":";;;;;;;;;;AACA,SAAgB,oBAAoB,OAAuB;CACzD,OAAO,UAAU,IAAI,IAAI;AAC3B;;;;;;;;;;;;;;;;;ACgCA,MAAM,aAAa;AACnB,MAAMA,cAAY;;AAElB,MAAM,mBAAm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