@tangle-network/agent-eval 0.216.1 → 0.218.1

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 (532) hide show
  1. package/CHANGELOG.md +137 -57
  2. package/README.md +2 -2
  3. package/dist/adapters/http.d.ts +2 -2
  4. package/dist/{agent-profile-VFcQncbW.d.ts → agent-profile-DTt8uGP9.d.ts} +4 -17
  5. package/dist/agent-profile-DTt8uGP9.d.ts.map +1 -0
  6. package/dist/{agent-profile-cell-BK8mlqlq.js → agent-profile-cell-B1V1gUZs.js} +4 -53
  7. package/dist/agent-profile-cell-B1V1gUZs.js.map +1 -0
  8. package/dist/{agent-profile-cell-BNp-Js9F.d.ts → agent-profile-cell-BcpFbNd5.d.ts} +2 -22
  9. package/dist/agent-profile-cell-BcpFbNd5.d.ts.map +1 -0
  10. package/dist/{agreement-irr-BEWLIF3_.js → agreement-irr-BhAqjluA.js} +5 -5
  11. package/dist/agreement-irr-BhAqjluA.js.map +1 -0
  12. package/dist/analyst/index.d.ts +36 -169
  13. package/dist/analyst/index.d.ts.map +1 -1
  14. package/dist/analyst/index.js +17 -192
  15. package/dist/analyst/index.js.map +1 -1
  16. package/dist/{analyze-runs-D68fd-su.d.ts → analyze-runs-DjlZOVXx.d.ts} +5 -5
  17. package/dist/{analyze-runs-D68fd-su.d.ts.map → analyze-runs-DjlZOVXx.d.ts.map} +1 -1
  18. package/dist/{analyze-runs-C84irm4i.js → analyze-runs-DqPJaJ4X.js} +225 -21
  19. package/dist/analyze-runs-DqPJaJ4X.js.map +1 -0
  20. package/dist/authenticity/index.d.ts +0 -23
  21. package/dist/authenticity/index.d.ts.map +1 -1
  22. package/dist/authenticity/index.js +1 -34
  23. package/dist/authenticity/index.js.map +1 -1
  24. package/dist/{benchmark-command-By0vh8q7.js → benchmark-command-BupdHRyf.js} +1225 -661
  25. package/dist/benchmark-command-BupdHRyf.js.map +1 -0
  26. package/dist/benchmarks/index.d.ts +5 -6
  27. package/dist/benchmarks/index.d.ts.map +1 -1
  28. package/dist/benchmarks/index.js +4 -4
  29. package/dist/benchmarks/index.js.map +1 -1
  30. package/dist/builder-eval/index.d.ts +3 -3
  31. package/dist/builder-eval/index.js +2 -2
  32. package/dist/builder-eval/index.js.map +1 -1
  33. package/dist/campaign/index.d.ts +7 -7
  34. package/dist/campaign/index.js +15 -15
  35. package/dist/{campaign-BudZ70zo.js → campaign-CGvUTnmc.js} +324 -800
  36. package/dist/campaign-CGvUTnmc.js.map +1 -0
  37. package/dist/{campaign-evidence-Clrn4hBV.js → campaign-evidence-DunzcJGv.js} +10 -18
  38. package/dist/{campaign-evidence-Clrn4hBV.js.map → campaign-evidence-DunzcJGv.js.map} +1 -1
  39. package/dist/{canonical-B2RqLofv.js → canonical-Dq2hOQ8L.js} +2 -2
  40. package/dist/{canonical-B2RqLofv.js.map → canonical-Dq2hOQ8L.js.map} +1 -1
  41. package/dist/cell-spend-DEWR3nj-.js +90 -0
  42. package/dist/cell-spend-DEWR3nj-.js.map +1 -0
  43. package/dist/{chat-client-l-MVDlDk.js → chat-client-B2pXlPdx.js} +2 -2
  44. package/dist/{chat-client-l-MVDlDk.js.map → chat-client-B2pXlPdx.js.map} +1 -1
  45. package/dist/{chat-json-call-puMArmtW.js → chat-json-call-Dm9c-b41.js} +3 -2
  46. package/dist/chat-json-call-Dm9c-b41.js.map +1 -0
  47. package/dist/{claim-q4HQhK1G.js → claim-BPVuyHuy.js} +3 -3
  48. package/dist/{claim-q4HQhK1G.js.map → claim-BPVuyHuy.js.map} +1 -1
  49. package/dist/cli.js +113 -12
  50. package/dist/cli.js.map +1 -1
  51. package/dist/{client-BzL9niqi.d.ts → client-hwo3cJjR.d.ts} +3 -16
  52. package/dist/client-hwo3cJjR.d.ts.map +1 -0
  53. package/dist/{cluster-bootstrap-qcUWYFl-.js → cluster-bootstrap-DEwwhl0C.js} +3 -3
  54. package/dist/{cluster-bootstrap-qcUWYFl-.js.map → cluster-bootstrap-DEwwhl0C.js.map} +1 -1
  55. package/dist/{produced-state-BsDmnwxc.js → completion-verifier-DbLVf3i8.js} +9 -64
  56. package/dist/completion-verifier-DbLVf3i8.js.map +1 -0
  57. package/dist/contract/index.d.ts +12 -12
  58. package/dist/contract/index.js +107 -403
  59. package/dist/contract/index.js.map +1 -1
  60. package/dist/{cost-ledger-BP8V4kUQ.js → cost-ledger-D0352Z4d.js} +4 -8
  61. package/dist/cost-ledger-D0352Z4d.js.map +1 -0
  62. package/dist/dataset-DQqhOCPt.d.ts.map +1 -1
  63. package/dist/{default-registry-COhk9g36.js → default-registry-BJ-Pq6yL.js} +314 -285
  64. package/dist/default-registry-BJ-Pq6yL.js.map +1 -0
  65. package/dist/{default-registry-DzHiGruW.d.ts → default-registry-DXgLmoDI.d.ts} +7 -50
  66. package/dist/default-registry-DXgLmoDI.d.ts.map +1 -0
  67. package/dist/{define-agent-eval-CNTPzIkp.js → define-agent-eval-BGdFKlrc.js} +170 -110
  68. package/dist/define-agent-eval-BGdFKlrc.js.map +1 -0
  69. package/dist/{define-agent-eval-WSck0CZJ.d.ts → define-agent-eval-BlH10zEw.d.ts} +8 -8
  70. package/dist/define-agent-eval-BlH10zEw.d.ts.map +1 -0
  71. package/dist/{descriptive-DboxPZrG.js → descriptive-CVNy48rR.js} +2 -2
  72. package/dist/{descriptive-DboxPZrG.js.map → descriptive-CVNy48rR.js.map} +1 -1
  73. package/dist/diagnosis/index.d.ts +4 -14
  74. package/dist/diagnosis/index.d.ts.map +1 -1
  75. package/dist/diagnosis/index.js +67 -28
  76. package/dist/diagnosis/index.js.map +1 -1
  77. package/dist/{dspy-rlm-engine-LRCu61m5.js → dspy-rlm-engine-CSMwudLO.js} +5 -10
  78. package/dist/dspy-rlm-engine-CSMwudLO.js.map +1 -0
  79. package/dist/{emitter-HcCmFQl_.d.ts → emitter-DABYYTcH.d.ts} +5 -5
  80. package/dist/emitter-DABYYTcH.d.ts.map +1 -0
  81. package/dist/emitter-DbMXUIVP.js.map +1 -1
  82. package/dist/{engine-3A_4jOlI.d.ts → engine-BvZ0R-36.d.ts} +17 -21
  83. package/dist/engine-BvZ0R-36.d.ts.map +1 -0
  84. package/dist/{equal-terms-BtdXayCJ.js → equal-terms-DbPGcVtI.js} +2 -2
  85. package/dist/equal-terms-DbPGcVtI.js.map +1 -0
  86. package/dist/{errors-DVZiqS7K.js → errors-BcOs5MKW.js} +2 -8
  87. package/dist/{errors-DVZiqS7K.js.map → errors-BcOs5MKW.js.map} +1 -1
  88. package/dist/eval-campaign-BUMIxKTE.js +393 -0
  89. package/dist/eval-campaign-BUMIxKTE.js.map +1 -0
  90. package/dist/{evaluation-6Yoi74gM.d.ts → evaluation-BOZ38vOH.d.ts} +7 -7
  91. package/dist/evaluation-BOZ38vOH.d.ts.map +1 -0
  92. package/dist/evaluation.d.ts +2 -2
  93. package/dist/evaluation.js +1 -1
  94. package/dist/evaluation.js.map +1 -1
  95. package/dist/{exact-types-ClugMJfI.d.ts → exact-types-CflbJ9f3.d.ts} +2 -2
  96. package/dist/{exact-types-ClugMJfI.d.ts.map → exact-types-CflbJ9f3.d.ts.map} +1 -1
  97. package/dist/{exec-ChJ6d5if.js → exec-CpbtOXVt.js} +2 -24
  98. package/dist/{exec-ChJ6d5if.js.map → exec-CpbtOXVt.js.map} +1 -1
  99. package/dist/execution-tracks-CpgFPpS5.js.map +1 -1
  100. package/dist/experiment/index.d.ts +9 -112
  101. package/dist/experiment/index.d.ts.map +1 -1
  102. package/dist/experiment/index.js +258 -311
  103. package/dist/experiment/index.js.map +1 -1
  104. package/dist/{exporters-X4xwla8A.js → exporters-DWvM16LE.js} +3 -3
  105. package/dist/exporters-DWvM16LE.js.map +1 -0
  106. package/dist/{exporters-ChTnR90l.d.ts → exporters-Dk3oEbK_.d.ts} +2 -4
  107. package/dist/{exporters-ChTnR90l.d.ts.map → exporters-Dk3oEbK_.d.ts.map} +1 -1
  108. package/dist/{external-optimizer-process-BjMGUuds.js → external-optimizer-process-C3Wm7Vhn.js} +4 -3
  109. package/dist/external-optimizer-process-C3Wm7Vhn.js.map +1 -0
  110. package/dist/{external-optimizer-subprocess-BqW0hHcI.js → external-optimizer-subprocess-B5gdLRZv.js} +9 -11
  111. package/dist/external-optimizer-subprocess-B5gdLRZv.js.map +1 -0
  112. package/dist/{extract-usage-BrnzRJ6H.js → extract-usage-BZLU01kR.js} +2 -23
  113. package/dist/{extract-usage-BrnzRJ6H.js.map → extract-usage-BZLU01kR.js.map} +1 -1
  114. package/dist/{failure-cluster-CbgEDcFJ.d.ts → failure-cluster-DN0t63Z0.d.ts} +4 -43
  115. package/dist/failure-cluster-DN0t63Z0.d.ts.map +1 -0
  116. package/dist/{failure-taxonomy-CjabTATj.js → failure-taxonomy-Bx5oWqaW.js} +2 -19
  117. package/dist/{failure-taxonomy-CjabTATj.js.map → failure-taxonomy-Bx5oWqaW.js.map} +1 -1
  118. package/dist/{feedback-trajectory-C4EG0nNH.d.ts → feedback-trajectory-BWmhRBGu.d.ts} +7 -9
  119. package/dist/feedback-trajectory-BWmhRBGu.d.ts.map +1 -0
  120. package/dist/{semantic-concept-judge-BQF8te0T.js → findings-store-BtTzPL0d.js} +9 -249
  121. package/dist/findings-store-BtTzPL0d.js.map +1 -0
  122. package/dist/fuzz.d.ts +19 -62
  123. package/dist/fuzz.d.ts.map +1 -1
  124. package/dist/fuzz.js +62 -108
  125. package/dist/fuzz.js.map +1 -1
  126. package/dist/{hf-dataset-BR2yhuNn.js → hf-dataset-CKxIJQba.js} +4 -24
  127. package/dist/hf-dataset-CKxIJQba.js.map +1 -0
  128. package/dist/hosted/index.d.ts +2 -2
  129. package/dist/hosted/index.js +2 -2
  130. package/dist/{index-CyszSg4O.d.ts → index-B16FNdW5.d.ts} +145 -360
  131. package/dist/index-B16FNdW5.d.ts.map +1 -0
  132. package/dist/{index-DV-jSzxF.d.ts → index-BLGqZ81N.d.ts} +10 -15
  133. package/dist/{index-DV-jSzxF.d.ts.map → index-BLGqZ81N.d.ts.map} +1 -1
  134. package/dist/{index-BO41eGj5.d.ts → index-CX-GAUpw.d.ts} +3 -7
  135. package/dist/index-CX-GAUpw.d.ts.map +1 -0
  136. package/dist/{index-DHKEAv3s.d.ts → index-CalAsXMR.d.ts} +8 -68
  137. package/dist/index-CalAsXMR.d.ts.map +1 -0
  138. package/dist/{index-BFRO6chs.d.ts → index-CiRwLv2R.d.ts} +5 -69
  139. package/dist/index-CiRwLv2R.d.ts.map +1 -0
  140. package/dist/{index-DPcngtwt.d.ts → index-DbMOXYnP.d.ts} +11 -36
  141. package/dist/index-DbMOXYnP.d.ts.map +1 -0
  142. package/dist/index.d.ts +211 -218
  143. package/dist/index.d.ts.map +1 -1
  144. package/dist/index.js +999 -1714
  145. package/dist/index.js.map +1 -1
  146. package/dist/{integrity-dLiDe2kD.js → integrity-C8oUeB0g.js} +326 -203
  147. package/dist/integrity-C8oUeB0g.js.map +1 -0
  148. package/dist/{integrity-BXOsAb3i.js → integrity-W4CADcFc.js} +3 -7
  149. package/dist/{integrity-BXOsAb3i.js.map → integrity-W4CADcFc.js.map} +1 -1
  150. package/dist/{integrity-DAMEDFaC.d.ts → integrity-_qgZLA5p.d.ts} +4 -6
  151. package/dist/{integrity-DAMEDFaC.d.ts.map → integrity-_qgZLA5p.d.ts.map} +1 -1
  152. package/dist/{internal-Epl-YBZW.js → internal-BTK91Bqt.js} +3 -3
  153. package/dist/{internal-Epl-YBZW.js.map → internal-BTK91Bqt.js.map} +1 -1
  154. package/dist/{interval-CELpye1n.js → interval-Dq9gt7jx.js} +3 -3
  155. package/dist/{interval-CELpye1n.js.map → interval-Dq9gt7jx.js.map} +1 -1
  156. package/dist/{journal-DfRz9kps.js → journal-C7om8Gum.js} +157 -147
  157. package/dist/journal-C7om8Gum.js.map +1 -0
  158. package/dist/json-BhdsJaOQ.js +111 -0
  159. package/dist/json-BhdsJaOQ.js.map +1 -0
  160. package/dist/{judge-calibration-BpCy5XQl.js → judge-calibration-BkXMIWA4.js} +3 -3
  161. package/dist/{judge-calibration-BpCy5XQl.js.map → judge-calibration-BkXMIWA4.js.map} +1 -1
  162. package/dist/{judge-gate-iY9s4L44.js → judge-gate-Co5tuh57.js} +4 -27
  163. package/dist/{judge-gate-iY9s4L44.js.map → judge-gate-Co5tuh57.js.map} +1 -1
  164. package/dist/{judge-gate-CE7CQAgt.d.ts → judge-gate-DsL0yFcb.d.ts} +8 -9
  165. package/dist/judge-gate-DsL0yFcb.d.ts.map +1 -0
  166. package/dist/{kind-factory-BobI5Jy3.js → kind-factory-Gy4fXixd.js} +88 -17
  167. package/dist/kind-factory-Gy4fXixd.js.map +1 -0
  168. package/dist/ledger-core/index.d.ts +2 -2
  169. package/dist/ledger-core/index.js +4 -4
  170. package/dist/ledger-core/lock-holder.d.ts +2 -0
  171. package/dist/ledger-core/lock-holder.js +181 -0
  172. package/dist/ledger-core/lock-holder.js.map +1 -0
  173. package/dist/{ledger-core-Gq7yp8lP.js → ledger-core-CAxUdDk0.js} +5 -84
  174. package/dist/ledger-core-CAxUdDk0.js.map +1 -0
  175. package/dist/{llm-client-CyBAoYiX.js → llm-client-_Y6ic-tf.js} +243 -355
  176. package/dist/llm-client-_Y6ic-tf.js.map +1 -0
  177. package/dist/{llm-judge-CG12SQJq.js → llm-judge-Djxh-Uhs.js} +662 -482
  178. package/dist/llm-judge-Djxh-Uhs.js.map +1 -0
  179. package/dist/lock-holder-DaJbfpci.d.ts +86 -0
  180. package/dist/lock-holder-DaJbfpci.d.ts.map +1 -0
  181. package/dist/matrix/index.d.ts +3 -3
  182. package/dist/matrix/index.js +3 -2
  183. package/dist/{matrix-Dm0BQW7U.js → matrix-B8l-Nsxd.js} +3 -88
  184. package/dist/matrix-B8l-Nsxd.js.map +1 -0
  185. package/dist/{matrix-DSrSxjjy.d.ts → matrix-CCSBna4q.d.ts} +9 -18
  186. package/dist/matrix-CCSBna4q.d.ts.map +1 -0
  187. package/dist/{mean-DHoMiudD.js → mean-BbA_JCzW.js} +39 -5
  188. package/dist/mean-BbA_JCzW.js.map +1 -0
  189. package/dist/meta-eval/index.d.ts +5 -5
  190. package/dist/meta-eval/index.js +10 -10
  191. package/dist/metrics-BKaPBtIG.js.map +1 -1
  192. package/dist/{mint-DNU8QPG4.d.ts → mint-BRZXuwRi.d.ts} +4 -4
  193. package/dist/{mint-DNU8QPG4.d.ts.map → mint-BRZXuwRi.d.ts.map} +1 -1
  194. package/dist/{mint-QaD5cA0u.js → mint-CbdwjTPW.js} +4 -4
  195. package/dist/{mint-QaD5cA0u.js.map → mint-CbdwjTPW.js.map} +1 -1
  196. package/dist/{multi-layer-verifier-BUaQ4C17.d.ts → multi-layer-verifier-DEgMUk6v.d.ts} +2 -2
  197. package/dist/{multi-layer-verifier-BUaQ4C17.d.ts.map → multi-layer-verifier-DEgMUk6v.d.ts.map} +1 -1
  198. package/dist/{multiplicity-DQUFcbW4.js → multiplicity-Sg0U7h8j.js} +2 -2
  199. package/dist/{multiplicity-DQUFcbW4.js.map → multiplicity-Sg0U7h8j.js.map} +1 -1
  200. package/dist/multishot/golden/index.d.ts +1 -23
  201. package/dist/multishot/golden/index.d.ts.map +1 -1
  202. package/dist/multishot/golden/index.js +3 -3
  203. package/dist/multishot/golden/index.js.map +1 -1
  204. package/dist/multishot/index.d.ts +3 -12
  205. package/dist/multishot/index.d.ts.map +1 -1
  206. package/dist/multishot/index.js +4 -3
  207. package/dist/multishot/index.js.map +1 -1
  208. package/dist/openapi.json +114 -10
  209. package/dist/{otel-spans-B9tUXRHF.js → otel-spans-CdN909k1.js} +3 -3
  210. package/dist/{otel-spans-B9tUXRHF.js.map → otel-spans-CdN909k1.js.map} +1 -1
  211. package/dist/{paired-arms-CwMGJsrS.js → paired-arms-Ct4LTKc1.js} +32 -9
  212. package/dist/paired-arms-Ct4LTKc1.js.map +1 -0
  213. package/dist/{paired-binary-CvpFHfKZ.js → paired-binary-B_nejA44.js} +3 -36
  214. package/dist/paired-binary-B_nejA44.js.map +1 -0
  215. package/dist/{paired-promotion-decision-DPKz8ZnF.d.ts → paired-promotion-decision-CQMJ5xGN.d.ts} +2 -34
  216. package/dist/paired-promotion-decision-CQMJ5xGN.d.ts.map +1 -0
  217. package/dist/{paired-promotion-decision-DsAPYGCm.js → paired-promotion-decision-D0SHb-ZL.js} +3 -3
  218. package/dist/{paired-promotion-decision-DsAPYGCm.js.map → paired-promotion-decision-D0SHb-ZL.js.map} +1 -1
  219. package/dist/{pareto-Cm6ndrWN.js → pareto-CTv8vozZ.js} +11 -11
  220. package/dist/pareto-CTv8vozZ.js.map +1 -0
  221. package/dist/pipelines/index.d.ts +16 -19
  222. package/dist/pipelines/index.d.ts.map +1 -1
  223. package/dist/pipelines/index.js +4 -68
  224. package/dist/pipelines/index.js.map +1 -1
  225. package/dist/{power-and-mde-Hj2ubb4B.js → power-and-mde-N5nU4_Ly.js} +3 -3
  226. package/dist/{power-and-mde-Hj2ubb4B.js.map → power-and-mde-N5nU4_Ly.js.map} +1 -1
  227. package/dist/{prime-protocol-CHKgA3a6.js → prime-protocol-BFgGrEMP.js} +3 -3
  228. package/dist/prime-protocol-BFgGrEMP.js.map +1 -0
  229. package/dist/{prime-protocol-HiB9HX7E.d.ts → prime-protocol-BWG2DQIk.d.ts} +3 -21
  230. package/dist/prime-protocol-BWG2DQIk.d.ts.map +1 -0
  231. package/dist/profile-cell.d.ts +2 -2
  232. package/dist/profile-cell.js +2 -2
  233. package/dist/{promotion-gate-BawrdPYr.d.ts → promotion-gate-CxEHRsZW.d.ts} +7 -8
  234. package/dist/{promotion-gate-BawrdPYr.d.ts.map → promotion-gate-CxEHRsZW.d.ts.map} +1 -1
  235. package/dist/{promotion-policy-KO57gbyV.js → promotion-policy-6A8osGr_.js} +4 -4
  236. package/dist/{promotion-policy-KO57gbyV.js.map → promotion-policy-6A8osGr_.js.map} +1 -1
  237. package/dist/{proposal-findings-CY1xKn_a.js → proposal-findings-n-5WBbEx.js} +3 -3
  238. package/dist/proposal-findings-n-5WBbEx.js.map +1 -0
  239. package/dist/{query-BUCZCK7F.js → query-B_RZ36an.js} +5 -5
  240. package/dist/query-B_RZ36an.js.map +1 -0
  241. package/dist/{query-DK1nWcmp.d.ts → query-Cmv_U8vf.d.ts} +4 -24
  242. package/dist/{query-DK1nWcmp.d.ts.map → query-Cmv_U8vf.d.ts.map} +1 -1
  243. package/dist/{random-ByUSnV9w.js → random-DDDcC7YU.js} +2 -2
  244. package/dist/{random-ByUSnV9w.js.map → random-DDDcC7YU.js.map} +1 -1
  245. package/dist/{raw-provider-sink-DoHz4JNG.js → raw-provider-sink-75w4FWBj.js} +2 -2
  246. package/dist/{raw-provider-sink-DoHz4JNG.js.map → raw-provider-sink-75w4FWBj.js.map} +1 -1
  247. package/dist/{redact-mtCCcT8z.d.ts → redact-DXdlFb_U.d.ts} +2 -3
  248. package/dist/redact-DXdlFb_U.d.ts.map +1 -0
  249. package/dist/{redact-B5xXKqQ3.js → redact-mtkTiJVk.js} +2 -7
  250. package/dist/{redact-B5xXKqQ3.js.map → redact-mtkTiJVk.js.map} +1 -1
  251. package/dist/{registry-D7_hm2fK.d.ts → registry-ssNoHzwD.d.ts} +4 -4
  252. package/dist/{registry-D7_hm2fK.d.ts.map → registry-ssNoHzwD.d.ts.map} +1 -1
  253. package/dist/{release-confidence-CpuP65S5.js → release-confidence-CYIFH-fp.js} +6 -11
  254. package/dist/release-confidence-CYIFH-fp.js.map +1 -0
  255. package/dist/{report-command-SC9nqb4M.js → render-Cs34y0iX.js} +625 -587
  256. package/dist/render-Cs34y0iX.js.map +1 -0
  257. package/dist/reporting.d.ts +6 -6
  258. package/dist/reporting.js +8 -8
  259. package/dist/{researcher-CEcfku-T.d.ts → researcher-GU1tV4dn.d.ts} +9 -9
  260. package/dist/{researcher-CEcfku-T.d.ts.map → researcher-GU1tV4dn.d.ts.map} +1 -1
  261. package/dist/{reward-CpCmAM8L.d.ts → reward-DrZ71vnf.d.ts} +3 -26
  262. package/dist/reward-DrZ71vnf.d.ts.map +1 -0
  263. package/dist/{reward-hacking-E0d-WVcP.js → reward-hacking-ByuETaIb.js} +3 -3
  264. package/dist/{reward-hacking-E0d-WVcP.js.map → reward-hacking-ByuETaIb.js.map} +1 -1
  265. package/dist/{reward-hacking-RVdZ6Kkt.d.ts → reward-hacking-E52wq86n.d.ts} +5 -18
  266. package/dist/reward-hacking-E52wq86n.d.ts.map +1 -0
  267. package/dist/reward-nw2xZGZG.js.map +1 -1
  268. package/dist/rl.d.ts +117 -295
  269. package/dist/rl.d.ts.map +1 -1
  270. package/dist/rl.js +27 -747
  271. package/dist/rl.js.map +1 -1
  272. package/dist/rollout/index.d.ts +5 -5
  273. package/dist/rollout/index.js +7 -8
  274. package/dist/{rollout-DZV1t2Wg.js → rollout-Dd1ucT_M.js} +88 -13
  275. package/dist/rollout-Dd1ucT_M.js.map +1 -0
  276. package/dist/{rubric-predictive-validity-DaFW70y9.js → rubric-predictive-validity-D3_oI72N.js} +3 -3
  277. package/dist/{rubric-predictive-validity-DaFW70y9.js.map → rubric-predictive-validity-D3_oI72N.js.map} +1 -1
  278. package/dist/{rubric-predictive-validity-C03EC7ZE.d.ts → rubric-predictive-validity-DiwT8PbL.d.ts} +2 -2
  279. package/dist/{rubric-predictive-validity-C03EC7ZE.d.ts.map → rubric-predictive-validity-DiwT8PbL.d.ts.map} +1 -1
  280. package/dist/{run-record-C1E24G2A.d.ts → run-record-CaxbLq6Y.d.ts} +4 -10
  281. package/dist/run-record-CaxbLq6Y.d.ts.map +1 -0
  282. package/dist/{run-record-C5e7FjhJ.js → run-record-CysKLB93.js} +3 -3
  283. package/dist/run-record-CysKLB93.js.map +1 -0
  284. package/dist/{run-record-Boc5IUTp.js → run-record-DhEJgoPz.js} +4 -4
  285. package/dist/{run-record-Boc5IUTp.js.map → run-record-DhEJgoPz.js.map} +1 -1
  286. package/dist/sandbox-harness-BlSOu4LX.d.ts.map +1 -1
  287. package/dist/{schema-CSf6qWgZ.js → schema-Bt2vLFm3.js} +2 -14
  288. package/dist/schema-Bt2vLFm3.js.map +1 -0
  289. package/dist/schema-C-ziyJD7.d.ts.map +1 -1
  290. package/dist/{schema-BuiujZ-g.js → schema-CvhfLjtZ.js} +78 -48
  291. package/dist/schema-CvhfLjtZ.js.map +1 -0
  292. package/dist/{schema-2g7trUwH.d.ts → schema-D6EVKzTB.d.ts} +4 -5
  293. package/dist/schema-D6EVKzTB.d.ts.map +1 -0
  294. package/dist/search/index.d.ts +3 -31
  295. package/dist/search/index.d.ts.map +1 -1
  296. package/dist/search/index.js +4 -4
  297. package/dist/{search-kernel-DyNEa6IU.d.ts → search-kernel-p9JB3SmL.d.ts} +10 -27
  298. package/dist/search-kernel-p9JB3SmL.d.ts.map +1 -0
  299. package/dist/{search-ledger-CVUGLDZp.js → search-ledger-ClpN4I3e.js} +7 -7
  300. package/dist/{search-ledger-CVUGLDZp.js.map → search-ledger-ClpN4I3e.js.map} +1 -1
  301. package/dist/{search-ledger-file-DDQUgvCg.js → search-ledger-file-Bd5Tioq6.js} +4 -4
  302. package/dist/search-ledger-file-Bd5Tioq6.js.map +1 -0
  303. package/dist/{search-shipper-BOSD46qv.js → search-shipper-Bg2HW3Uv.js} +4 -4
  304. package/dist/search-shipper-Bg2HW3Uv.js.map +1 -0
  305. package/dist/{search-summary-BQCSWf1g.js → search-summary-CrBuvVnf.js} +5 -5
  306. package/dist/{search-summary-BQCSWf1g.js.map → search-summary-CrBuvVnf.js.map} +1 -1
  307. package/dist/{sequential-CzK5DarL.js → sequential-BVv1sjsw.js} +2 -32
  308. package/dist/{sequential-CzK5DarL.js.map → sequential-BVv1sjsw.js.map} +1 -1
  309. package/dist/{sequential-Bf_pbE50.js → sequential-CimQrbjv.js} +5 -5
  310. package/dist/sequential-CimQrbjv.js.map +1 -0
  311. package/dist/{sequential-BhsrMupG.d.ts → sequential-KwGspfeR.d.ts} +2 -9
  312. package/dist/{sequential-BhsrMupG.d.ts.map → sequential-KwGspfeR.d.ts.map} +1 -1
  313. package/dist/{sequential-eprocess-DM_qENCl.js → sequential-eprocess-DodI6RoF.js} +2 -2
  314. package/dist/{sequential-eprocess-DM_qENCl.js.map → sequential-eprocess-DodI6RoF.js.map} +1 -1
  315. package/dist/{server-e9oWO_bN.js → server-C6M0qR8h.js} +101 -101
  316. package/dist/server-C6M0qR8h.js.map +1 -0
  317. package/dist/{single-run-lock-CV9Eyd_q.js → single-run-lock-Dekd8_Wv.js} +7 -7
  318. package/dist/single-run-lock-Dekd8_Wv.js.map +1 -0
  319. package/dist/{skillopt-optimization-method-BiwA8nfX.js → skillopt-optimization-method-5dlex7MJ.js} +1386 -1184
  320. package/dist/skillopt-optimization-method-5dlex7MJ.js.map +1 -0
  321. package/dist/{spans-BHAUXMGN.d.ts → spans-CVngGij3.d.ts} +2 -2
  322. package/dist/{spans-BHAUXMGN.d.ts.map → spans-CVngGij3.d.ts.map} +1 -1
  323. package/dist/{statistical-heldout-CYpGaoDH.d.ts → statistical-heldout-BHfLZHrm.d.ts} +8 -67
  324. package/dist/statistical-heldout-BHfLZHrm.d.ts.map +1 -0
  325. package/dist/{statistical-heldout-42NlCNDe.js → statistical-heldout-Bksv92Th.js} +3 -3
  326. package/dist/statistical-heldout-Bksv92Th.js.map +1 -0
  327. package/dist/{steps-Bg5-KVx1.d.ts → steps-DlepJPwD.d.ts} +2 -56
  328. package/dist/steps-DlepJPwD.d.ts.map +1 -0
  329. package/dist/{store-C4avFjIi.d.ts → store-B3nWRy3B.d.ts} +2 -2
  330. package/dist/{store-C4avFjIi.d.ts.map → store-B3nWRy3B.d.ts.map} +1 -1
  331. package/dist/{store-otlp-DJ9dtA5x.js → store-otlp-BteDAbHK.js} +3 -3
  332. package/dist/{store-otlp-DJ9dtA5x.js.map → store-otlp-BteDAbHK.js.map} +1 -1
  333. package/dist/{store-tool-spans-CIX5arAG.js → store-tool-spans-D5l_OfTJ.js} +8 -8
  334. package/dist/store-tool-spans-D5l_OfTJ.js.map +1 -0
  335. package/dist/{store-tool-spans-DdCSPa7C.d.ts → store-tool-spans-DZS0HWVf.d.ts} +9 -18
  336. package/dist/store-tool-spans-DZS0HWVf.d.ts.map +1 -0
  337. package/dist/storyboard/index.d.ts +4 -11
  338. package/dist/storyboard/index.d.ts.map +1 -1
  339. package/dist/storyboard/index.js +1 -16
  340. package/dist/storyboard/index.js.map +1 -1
  341. package/dist/{summary-report-V_JACR4Y.js → summary-report-BsXJoYX5.js} +88 -10
  342. package/dist/summary-report-BsXJoYX5.js.map +1 -0
  343. package/dist/{summary-report-bdFDXq0b.d.ts → summary-report-CkbRcSuu.d.ts} +25 -19
  344. package/dist/summary-report-CkbRcSuu.d.ts.map +1 -0
  345. package/dist/supervisor-run/index.d.ts +60 -28
  346. package/dist/supervisor-run/index.d.ts.map +1 -1
  347. package/dist/supervisor-run/index.js +4 -458
  348. package/dist/supervisor-run/index.js.map +1 -1
  349. package/dist/{systemone-BomhHr2c.d.ts → systemone-BMzDJb1i.d.ts} +5 -5
  350. package/dist/{systemone-BomhHr2c.d.ts.map → systemone-BMzDJb1i.d.ts.map} +1 -1
  351. package/dist/systemone-protocol.js +1 -1
  352. package/dist/{systemone-review-CUVcQJu6.d.ts → systemone-review-CwE6JGIp.d.ts} +2 -2
  353. package/dist/{systemone-review-CUVcQJu6.d.ts.map → systemone-review-CwE6JGIp.d.ts.map} +1 -1
  354. package/dist/{systemone-review-D7sXwsqq.js → systemone-review-DzdOJ8I6.js} +3 -3
  355. package/dist/{systemone-review-D7sXwsqq.js.map → systemone-review-DzdOJ8I6.js.map} +1 -1
  356. package/dist/systemone.d.ts +5 -5
  357. package/dist/systemone.js +5 -5
  358. package/dist/systemone.js.map +1 -1
  359. package/dist/{task-failure-attributes-hEmASjix.js → task-failure-attributes-BMsblaDh.js} +3 -3
  360. package/dist/task-failure-attributes-BMsblaDh.js.map +1 -0
  361. package/dist/{terminal-record-DZyQZ3pz.js → terminal-record-D4Rv-j1W.js} +244 -196
  362. package/dist/terminal-record-D4Rv-j1W.js.map +1 -0
  363. package/dist/{tool-groups-C3NEcdCM.d.ts → tool-groups-DyNz2JZ_.d.ts} +3 -3
  364. package/dist/tool-groups-DyNz2JZ_.d.ts.map +1 -0
  365. package/dist/{tool-waste-BKgvd-TP.d.ts → tool-waste-CkjzWmeY.d.ts} +25 -28
  366. package/dist/tool-waste-CkjzWmeY.d.ts.map +1 -0
  367. package/dist/{tool-waste-BlesqTqW.js → tool-waste-DLsjS_p-.js} +5 -5
  368. package/dist/{tool-waste-BlesqTqW.js.map → tool-waste-DLsjS_p-.js.map} +1 -1
  369. package/dist/{trace-questions-CM2CAocU.d.ts → trace-questions-xxwgsuMi.d.ts} +4 -9
  370. package/dist/{trace-questions-CM2CAocU.d.ts.map → trace-questions-xxwgsuMi.d.ts.map} +1 -1
  371. package/dist/trace-repair/index.d.ts +14 -211
  372. package/dist/trace-repair/index.d.ts.map +1 -1
  373. package/dist/trace-repair/index.js +865 -981
  374. package/dist/trace-repair/index.js.map +1 -1
  375. package/dist/traces.d.ts +18 -46
  376. package/dist/traces.d.ts.map +1 -1
  377. package/dist/traces.js +13 -13
  378. package/dist/traces.js.map +1 -1
  379. package/dist/trajectory-replay/index.d.ts +7 -118
  380. package/dist/trajectory-replay/index.d.ts.map +1 -1
  381. package/dist/trajectory-replay/index.js +921 -869
  382. package/dist/trajectory-replay/index.js.map +1 -1
  383. package/dist/{tree-C1XYeXvy.js → tree-B5e1uAeL.js} +132 -21
  384. package/dist/tree-B5e1uAeL.js.map +1 -0
  385. package/dist/{types-Cbe2fWBa.d.ts → types-BKCzzmit.d.ts} +3 -3
  386. package/dist/{types-Cbe2fWBa.d.ts.map → types-BKCzzmit.d.ts.map} +1 -1
  387. package/dist/{types-B3jzCp0p.js → types-BXgASBCL.js} +2 -2
  388. package/dist/{types-B3jzCp0p.js.map → types-BXgASBCL.js.map} +1 -1
  389. package/dist/{types-C1tnkEgM.d.ts → types-CW8ewATZ.d.ts} +4 -113
  390. package/dist/types-CW8ewATZ.d.ts.map +1 -0
  391. package/dist/{types-BqkVmHfv.d.ts → types-CmXY0PQf.d.ts} +2 -4
  392. package/dist/types-CmXY0PQf.d.ts.map +1 -0
  393. package/dist/{types-C02qtnG8.d.ts → types-D-mgRzlh.d.ts} +7 -28
  394. package/dist/types-D-mgRzlh.d.ts.map +1 -0
  395. package/dist/{types-IXD2HJzu.js → types-DqFMNTgK.js} +2 -4
  396. package/dist/types-DqFMNTgK.js.map +1 -0
  397. package/dist/{types-Cq8mSbq8.d.ts → types-DtkO1G9L.d.ts} +7 -9
  398. package/dist/{types-Cq8mSbq8.d.ts.map → types-DtkO1G9L.d.ts.map} +1 -1
  399. package/dist/{verdict-Dl0tiT1X.js → verdict-BGQmxQ8A.js} +3 -3
  400. package/dist/verdict-BGQmxQ8A.js.map +1 -0
  401. package/dist/{verdict-E4eRNf7-.d.ts → verdict-C24NELtN.d.ts} +2 -15
  402. package/dist/{verdict-E4eRNf7-.d.ts.map → verdict-C24NELtN.d.ts.map} +1 -1
  403. package/dist/{verdict-cache-Bm8EKL2s.js → verdict-cache-CL_7tePD.js} +2 -2
  404. package/dist/verdict-cache-CL_7tePD.js.map +1 -0
  405. package/dist/wire/index.d.ts +31 -410
  406. package/dist/wire/index.d.ts.map +1 -1
  407. package/dist/wire/index.js +2 -2
  408. package/docs/changes/jev-evidence-review.md +1 -1
  409. package/docs/changes/jev-product-adoption.md +1 -1
  410. package/docs/changes/jev-recorded-evidence.md +1 -1
  411. package/docs/design/statistics-decisions.md +18 -18
  412. package/docs/design.md +1 -1
  413. package/docs/eval-surface-map.md +1 -0
  414. package/docs/evaluation-integrity.md +1 -1
  415. package/docs/profile-json-identity.md +1 -2
  416. package/docs/proofs/campaign-attempt-retention-20261001/README.md +2 -2
  417. package/docs/public-api.md +158 -538
  418. package/docs/rollout.md +1 -1
  419. package/docs/trace-repair-admission.md +1 -1
  420. package/docs/wire-protocol.md +1 -1
  421. package/package.json +7 -2
  422. package/dist/active-curriculum-B_Lc9kfO.js +0 -61
  423. package/dist/active-curriculum-B_Lc9kfO.js.map +0 -1
  424. package/dist/agent-profile-VFcQncbW.d.ts.map +0 -1
  425. package/dist/agent-profile-cell-BK8mlqlq.js.map +0 -1
  426. package/dist/agent-profile-cell-BNp-Js9F.d.ts.map +0 -1
  427. package/dist/agreement-irr-BEWLIF3_.js.map +0 -1
  428. package/dist/analyze-runs-C84irm4i.js.map +0 -1
  429. package/dist/baseline-Udi_PLuT.js +0 -259
  430. package/dist/baseline-Udi_PLuT.js.map +0 -1
  431. package/dist/benchmark-CXmVVHH2.js +0 -562
  432. package/dist/benchmark-CXmVVHH2.js.map +0 -1
  433. package/dist/benchmark-command-By0vh8q7.js.map +0 -1
  434. package/dist/campaign-BudZ70zo.js.map +0 -1
  435. package/dist/chat-json-call-puMArmtW.js.map +0 -1
  436. package/dist/claude-jsonl-dZir12m6.js +0 -86
  437. package/dist/claude-jsonl-dZir12m6.js.map +0 -1
  438. package/dist/client-BzL9niqi.d.ts.map +0 -1
  439. package/dist/cost-ledger-BP8V4kUQ.js.map +0 -1
  440. package/dist/counterfactual-CPaWN99-.d.ts +0 -60
  441. package/dist/counterfactual-CPaWN99-.d.ts.map +0 -1
  442. package/dist/counterfactual-Dn3veueY.js +0 -98
  443. package/dist/counterfactual-Dn3veueY.js.map +0 -1
  444. package/dist/default-registry-COhk9g36.js.map +0 -1
  445. package/dist/default-registry-DzHiGruW.d.ts.map +0 -1
  446. package/dist/define-agent-eval-CNTPzIkp.js.map +0 -1
  447. package/dist/define-agent-eval-WSck0CZJ.d.ts.map +0 -1
  448. package/dist/dspy-rlm-engine-LRCu61m5.js.map +0 -1
  449. package/dist/effect-sizes-BhzEpXMc.js +0 -82
  450. package/dist/effect-sizes-BhzEpXMc.js.map +0 -1
  451. package/dist/emitter-HcCmFQl_.d.ts.map +0 -1
  452. package/dist/engine-3A_4jOlI.d.ts.map +0 -1
  453. package/dist/equal-terms-BtdXayCJ.js.map +0 -1
  454. package/dist/eval-campaign-90jeaCAI.js +0 -343
  455. package/dist/eval-campaign-90jeaCAI.js.map +0 -1
  456. package/dist/evaluation-6Yoi74gM.d.ts.map +0 -1
  457. package/dist/exporters-X4xwla8A.js.map +0 -1
  458. package/dist/external-optimizer-process-BjMGUuds.js.map +0 -1
  459. package/dist/external-optimizer-subprocess-BqW0hHcI.js.map +0 -1
  460. package/dist/failure-cluster-CbgEDcFJ.d.ts.map +0 -1
  461. package/dist/feedback-trajectory-C4EG0nNH.d.ts.map +0 -1
  462. package/dist/hf-dataset-BR2yhuNn.js.map +0 -1
  463. package/dist/index-BFRO6chs.d.ts.map +0 -1
  464. package/dist/index-BO41eGj5.d.ts.map +0 -1
  465. package/dist/index-CyszSg4O.d.ts.map +0 -1
  466. package/dist/index-DHKEAv3s.d.ts.map +0 -1
  467. package/dist/index-DPcngtwt.d.ts.map +0 -1
  468. package/dist/integrity-dLiDe2kD.js.map +0 -1
  469. package/dist/journal-DfRz9kps.js.map +0 -1
  470. package/dist/judge-gate-CE7CQAgt.d.ts.map +0 -1
  471. package/dist/kind-factory-BobI5Jy3.js.map +0 -1
  472. package/dist/ledger-core-Gq7yp8lP.js.map +0 -1
  473. package/dist/llm-client-CyBAoYiX.js.map +0 -1
  474. package/dist/llm-judge-CG12SQJq.js.map +0 -1
  475. package/dist/matrix-DSrSxjjy.d.ts.map +0 -1
  476. package/dist/matrix-Dm0BQW7U.js.map +0 -1
  477. package/dist/mean-DHoMiudD.js.map +0 -1
  478. package/dist/normal-DsJZtrJc.js +0 -25
  479. package/dist/normal-DsJZtrJc.js.map +0 -1
  480. package/dist/paired-arms-CwMGJsrS.js.map +0 -1
  481. package/dist/paired-binary-CvpFHfKZ.js.map +0 -1
  482. package/dist/paired-promotion-decision-DPKz8ZnF.d.ts.map +0 -1
  483. package/dist/pareto-Cm6ndrWN.js.map +0 -1
  484. package/dist/prime-protocol-CHKgA3a6.js.map +0 -1
  485. package/dist/prime-protocol-HiB9HX7E.d.ts.map +0 -1
  486. package/dist/produced-state-BsDmnwxc.js.map +0 -1
  487. package/dist/proposal-findings-CY1xKn_a.js.map +0 -1
  488. package/dist/query-BUCZCK7F.js.map +0 -1
  489. package/dist/redact-mtCCcT8z.d.ts.map +0 -1
  490. package/dist/release-confidence-CpuP65S5.js.map +0 -1
  491. package/dist/report-command-SC9nqb4M.js.map +0 -1
  492. package/dist/reward-CpCmAM8L.d.ts.map +0 -1
  493. package/dist/reward-hacking-RVdZ6Kkt.d.ts.map +0 -1
  494. package/dist/rollout-DZV1t2Wg.js.map +0 -1
  495. package/dist/run-record-C1E24G2A.d.ts.map +0 -1
  496. package/dist/run-record-C5e7FjhJ.js.map +0 -1
  497. package/dist/schema-2g7trUwH.d.ts.map +0 -1
  498. package/dist/schema-BuiujZ-g.js.map +0 -1
  499. package/dist/schema-CSf6qWgZ.js.map +0 -1
  500. package/dist/search-kernel-DyNEa6IU.d.ts.map +0 -1
  501. package/dist/search-ledger-file-DDQUgvCg.js.map +0 -1
  502. package/dist/search-shipper-BOSD46qv.js.map +0 -1
  503. package/dist/semantic-concept-judge-BQF8te0T.js.map +0 -1
  504. package/dist/sequential-Bf_pbE50.js.map +0 -1
  505. package/dist/server-e9oWO_bN.js.map +0 -1
  506. package/dist/single-run-lock-CV9Eyd_q.js.map +0 -1
  507. package/dist/skillopt-optimization-method-BiwA8nfX.js.map +0 -1
  508. package/dist/statistical-heldout-42NlCNDe.js.map +0 -1
  509. package/dist/statistical-heldout-CYpGaoDH.d.ts.map +0 -1
  510. package/dist/steps-Bg5-KVx1.d.ts.map +0 -1
  511. package/dist/store-tool-spans-CIX5arAG.js.map +0 -1
  512. package/dist/store-tool-spans-DdCSPa7C.d.ts.map +0 -1
  513. package/dist/student-t-DVPW7CdL.js +0 -39
  514. package/dist/student-t-DVPW7CdL.js.map +0 -1
  515. package/dist/summary-report-V_JACR4Y.js.map +0 -1
  516. package/dist/summary-report-bdFDXq0b.d.ts.map +0 -1
  517. package/dist/task-failure-attributes-hEmASjix.js.map +0 -1
  518. package/dist/terminal-record-DZyQZ3pz.js.map +0 -1
  519. package/dist/tool-groups-C3NEcdCM.d.ts.map +0 -1
  520. package/dist/tool-waste-BKgvd-TP.d.ts.map +0 -1
  521. package/dist/trajectory-Y1fmdlw7.d.ts +0 -24
  522. package/dist/trajectory-Y1fmdlw7.d.ts.map +0 -1
  523. package/dist/tree-C1XYeXvy.js.map +0 -1
  524. package/dist/types-BqkVmHfv.d.ts.map +0 -1
  525. package/dist/types-C02qtnG8.d.ts.map +0 -1
  526. package/dist/types-C1tnkEgM.d.ts.map +0 -1
  527. package/dist/types-IXD2HJzu.js.map +0 -1
  528. package/dist/usage-receipt-Cx3xNeyB.js +0 -76
  529. package/dist/usage-receipt-Cx3xNeyB.js.map +0 -1
  530. package/dist/verdict-Dl0tiT1X.js.map +0 -1
  531. package/dist/verdict-cache-Bm8EKL2s.js.map +0 -1
  532. package/docs/design/self-improvement-evidence-audit.md +0 -263
package/dist/fuzz.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"fuzz.js","names":[],"sources":["../src/fuzz/cube.ts","../src/fuzz/capsule.ts","../src/fuzz/policies.ts","../src/fuzz/explorer.ts","../src/fuzz/fuzz-agent.ts","../src/fuzz/gates.ts","../src/fuzz/tools.ts"],"sourcesContent":["/**\n * Input-space tiling + coverage projection.\n *\n * Cells are the cartesian product of the input axes — the stratification plan,\n * enumerable up front so the planned-vs-covered denominator is honest. Coverage\n * is projected from the evaluation log: per cell, the full DISTRIBUTION of the\n * headline score, of each scored dimension, and of evaluation latency — a bare\n * mean hides outliers, so every aggregate carries its spread. Per-cell cost is\n * split known-dollars vs unknown-runs, never folded into a fabricated $0.\n */\n\nimport type { BehaviorSpace, Cell, CoverageCell, Distribution, Evaluation } from './types'\n\n/** One recorded evaluation — the unit coverage and the capsule are built from. */\nexport interface EvalRecord {\n cell: Cell\n ev: Evaluation\n /** The objective's interest score for this evaluation. */\n interest: number\n /** Evaluation wall-clock — engine-measured unless `ev.latencyMs` overrode it. */\n latencyMs: number\n /** Known dollars for this run. `null` = cost tracking was wired but this\n * run's cost was unknowable (counted apart). Absent = not tracked at all. */\n costUsd?: number | null\n}\n\n/** Enumerate every input cell (cartesian product of the axes), in stable order. */\nexport function enumerateCells(space: BehaviorSpace): Cell[] {\n if (space.axes.length === 0) return []\n let partials: Array<Record<string, string>> = [{}]\n for (const axis of space.axes) {\n const next: Array<Record<string, string>> = []\n for (const partial of partials) {\n for (const value of axis.values) next.push({ ...partial, [axis.name]: value })\n }\n partials = next\n }\n return partials.map((coords) => ({ id: cellId(space, coords), coords }))\n}\n\n/** Deterministic id for a coordinate map, e.g. `matterType=nda|difficulty=hard`. */\nexport function cellId(space: BehaviorSpace, coords: Record<string, string>): string {\n return space.axes.map((a) => `${a.name}=${coords[a.name]}`).join('|')\n}\n\n/** Nearest-rank percentile on a pre-sorted ascending sample. */\nfunction percentile(sorted: number[], p: number): number {\n const idx = Math.min(sorted.length - 1, Math.max(0, Math.ceil(p * sorted.length) - 1))\n return sorted[idx] as number\n}\n\n/** Summarize a sample. Throws on an empty sample — callers represent \"no data\"\n * as `null`, never as a zeroed distribution. */\nexport function distribution(values: number[]): Distribution {\n if (values.length === 0)\n throw new Error('distribution: empty sample — represent missing data as null, not zeros')\n const sorted = [...values].sort((a, b) => a - b)\n const mean = sorted.reduce((a, b) => a + b, 0) / sorted.length\n return {\n mean,\n median: percentile(sorted, 0.5),\n p90: percentile(sorted, 0.9),\n min: sorted[0] as number,\n max: sorted[sorted.length - 1] as number,\n n: sorted.length,\n }\n}\n\n/**\n * Project the evaluation log into the per-input-cell coverage map. A cell with\n * no evaluations reports `score: null` (honestly uncovered), never zeros.\n */\nexport function buildCoverage(cells: Cell[], log: EvalRecord[], threshold: number): CoverageCell[] {\n const byCell = new Map<string, EvalRecord[]>()\n for (const r of log) {\n const arr = byCell.get(r.cell.id) ?? []\n arr.push(r)\n byCell.set(r.cell.id, arr)\n }\n return cells.map((cell) => {\n const recs = byCell.get(cell.id) ?? []\n const runs = recs.length\n if (runs === 0)\n return { cell, runs: 0, score: null, findingRate: 0, dimensions: {}, latencyMs: null }\n\n const score = distribution(recs.map((r) => r.ev.score))\n const latencyMs = distribution(recs.map((r) => r.latencyMs))\n const findingRate = recs.filter((r) => r.interest >= threshold).length / runs\n\n const dimSamples: Record<string, number[]> = {}\n for (const r of recs) {\n for (const [k, v] of Object.entries(r.ev.scores ?? {})) {\n const samples = dimSamples[k] ?? []\n samples.push(v)\n dimSamples[k] = samples\n }\n }\n const dimensions: Record<string, Distribution> = {}\n for (const [k, xs] of Object.entries(dimSamples)) dimensions[k] = distribution(xs)\n\n // Cost fields appear only when tracking was wired: known dollars sum, and\n // tracked-but-unknown runs counted apart — never folded in as $0.\n const tracked = recs.filter((r) => r.costUsd !== undefined)\n const known = tracked.filter((r) => r.costUsd !== null)\n const cost =\n tracked.length > 0\n ? {\n costUsd: known.reduce((a, r) => a + (r.costUsd as number), 0),\n ...(tracked.length > known.length\n ? { costUnknownRuns: tracked.length - known.length }\n : {}),\n }\n : {}\n\n return { cell, runs, score, findingRate, dimensions, latencyMs, ...cost }\n })\n}\n","/**\n * The capsule — the artifact every exploration produces.\n *\n * `buildCapsule` assembles coverage + verified findings + the QD archive into a\n * pure `CapsuleData` (no clock, no I/O — deterministic and snapshot-testable).\n * `renderCapsuleHtml` turns it into a standalone page: the input-cell heat-map\n * (planned vs covered), per-dimension weakness chips, and the minimized finding\n * exemplars. One artifact — the hardening map and the shareable proof object.\n */\n\nimport type { EvalRecord } from './cube'\nimport { buildCoverage, distribution } from './cube'\nimport type { ArchiveEntry, CapsuleData, Cell, CoverageCell, Distribution, Finding } from './types'\n\nexport interface BuildCapsuleInput<S> {\n target: string\n objective: string\n cells: Cell[]\n log: EvalRecord[]\n /** The objective's notable threshold — drives findingRate. */\n threshold: number\n archive: ArchiveEntry<S>[]\n findings: Finding<S>[]\n candidateFindings: number\n runsUsed: number\n /** Known-dollar / unknown-run split — present only when cost tracking was\n * wired; the capsule never fabricates a $0 total. */\n cost?: { costUsd: number; costUnknownRuns: number }\n /** Evaluations that threw — infra outcomes, never folded into robustness. */\n evalErrors: number\n /** Set when the consecutive-error circuit breaker stopped the run early. */\n stoppedEarly?: { reason: 'eval-errors'; detail: string }\n}\n\nexport function buildCapsule<S>(input: BuildCapsuleInput<S>): CapsuleData<S> {\n const coverage = buildCoverage(input.cells, input.log, input.threshold)\n const covered = coverage.filter((c) => c.runs > 0)\n // Cells weigh equally: variance steering sends more runs to weak cells, so a\n // run-weighted average would bias the headline low.\n const robustness =\n covered.length === 0 ? null : distribution(covered.map((c) => (c.score as Distribution).mean))\n const latencyMs = input.log.length === 0 ? null : distribution(input.log.map((r) => r.latencyMs))\n // Measured-descriptor bins beyond the bare input cell — observed, never planned.\n const behaviorBinsObserved = input.archive.filter((e) => e.binId !== e.cell.id).length\n\n return {\n target: input.target,\n objective: input.objective,\n coverage,\n findings: [...input.findings].sort((a, b) => b.interest - a.interest),\n archive: [...input.archive].sort((a, b) => b.interest - a.interest),\n stats: {\n totalRuns: input.runsUsed,\n cellsTotal: input.cells.length,\n cellsCovered: covered.length,\n behaviorBinsObserved,\n candidateFindings: input.candidateFindings,\n verifiedFindings: input.findings.length,\n robustness,\n latencyMs,\n ...(input.cost\n ? { costUsd: input.cost.costUsd, costUnknownRuns: input.cost.costUnknownRuns }\n : {}),\n evalErrors: input.evalErrors,\n ...(input.stoppedEarly ? { stoppedEarly: input.stoppedEarly } : {}),\n },\n }\n}\n\n// ── HTML capsule ──────────────────────────────────────────────────────────────\n\nfunction esc(s: string): string {\n return s.replace(\n /[&<>\"]/g,\n (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;' })[c] as string,\n )\n}\n\n/** red (0) → amber (.5) → green (1); uncovered cells render gray. */\nfunction robustnessColor(r: number | null): string {\n if (r == null) return '#2a2a2e'\n return `hsl(${Math.round(r * 120)} 70% 42%)`\n}\n\nfunction pct(x: number): string {\n return `${Math.round(x * 100)}%`\n}\n\nfunction deriveAxes(coverage: CoverageCell[]): Array<{ name: string; values: string[] }> {\n const order: string[] = []\n const seen = new Map<string, Set<string>>()\n for (const c of coverage) {\n for (const [k, v] of Object.entries(c.cell.coords)) {\n if (!seen.has(k)) {\n seen.set(k, new Set())\n order.push(k)\n }\n seen.get(k)?.add(v)\n }\n }\n return order.map((name) => ({ name, values: [...(seen.get(name) ?? [])] }))\n}\n\n/** The weakest dimension chip for a cell, e.g. `safety 32%` — shown when scores exist. */\nfunction weakestDim(c: CoverageCell): string {\n const entries = Object.entries(c.dimensions).map(([k, d]) => [k, d.mean] as [string, number])\n if (entries.length === 0) return ''\n const sorted = entries.sort((a, b) => a[1] - b[1])\n const w = sorted[0]\n if (!w) return ''\n return `<span class=\"dim\">${esc(w[0])} ${pct(w[1])}</span>`\n}\n\nfunction heatmapHtml(coverage: CoverageCell[]): string {\n const axes = deriveAxes(coverage)\n const byId = new Map(coverage.map((c) => [c.cell.id, c]))\n const tile = (c: CoverageCell | undefined, label: string): string => {\n const r = c?.score?.mean ?? null\n const title = c?.score\n ? `${pct(c.score.mean)} robust (median ${pct(c.score.median)}, min ${pct(c.score.min)}) · ${c.runs} runs · ${pct(c.findingRate)} flagged${c.latencyMs ? ` · ${(c.latencyMs.median / 1000).toFixed(1)}s median` : ''}${c.costUsd !== undefined ? ` · $${c.costUsd.toFixed(2)}` : ''}`\n : 'not covered'\n return `<div class=\"tile\" style=\"background:${robustnessColor(r)}\" title=\"${esc(title)}\">${label ? `<span class=\"tl\">${esc(label)}</span>` : ''}<span class=\"tv\">${c && r != null ? pct(r) : '—'}</span>${c ? weakestDim(c) : ''}</div>`\n }\n\n const rowAxis = axes[0]\n const colAxis = axes[1]\n if (axes.length === 2 && rowAxis && colAxis) {\n const head = `<tr><th></th>${colAxis.values.map((v) => `<th>${esc(v)}</th>`).join('')}</tr>`\n const rows = rowAxis.values\n .map((rv) => {\n const cells = colAxis.values\n .map((cv) => {\n const id = `${rowAxis.name}=${rv}|${colAxis.name}=${cv}`\n return `<td>${tile(byId.get(id), '')}</td>`\n })\n .join('')\n return `<tr><th class=\"rh\">${esc(rv)}</th>${cells}</tr>`\n })\n .join('')\n return `<div class=\"axis-label\">rows: <b>${esc(rowAxis.name)}</b> · cols: <b>${esc(colAxis.name)}</b></div><table class=\"heat\">${head}${rows}</table>`\n }\n\n const sorted = [...coverage].sort((a, b) => (a.score?.mean ?? 2) - (b.score?.mean ?? 2))\n return `<div class=\"grid\">${sorted.map((c) => tile(c, Object.values(c.cell.coords).join(' · '))).join('')}</div>`\n}\n\nfunction findingsHtml<S>(findings: Finding<S>[], limit: number): string {\n if (findings.length === 0)\n return `<p class=\"none\">No verified findings — the target held across every covered cell.</p>`\n return findings\n .slice(0, limit)\n .map((f) => {\n const coords = Object.entries(f.cell.coords)\n .map(([k, v]) => `${k}:${v}`)\n .join(' · ')\n const labels = (f.evaluation.labels ?? [])\n .map((l) => `<span class=\"fclass\">${esc(l)}</span>`)\n .join('')\n const dims = Object.entries(f.evaluation.scores ?? {})\n .sort((a, b) => a[1] - b[1])\n .slice(0, 3)\n .map(([k, v]) => `<span class=\"dim\">${esc(k)} ${pct(v)}</span>`)\n .join('')\n return `<div class=\"fail\"><div class=\"fmeta\"><span class=\"fcell\">${esc(coords)}</span>${labels}<span class=\"fsev\">interest ${pct(f.interest)}</span></div><div class=\"sevbar\"><div class=\"sevfill\" style=\"width:${pct(f.interest)}\"></div></div><div class=\"ftext\">${esc(f.text ?? '(scenario text not captured)')}</div>${dims ? `<div class=\"fdims\">${dims}</div>` : ''}</div>`\n })\n .join('')\n}\n\nexport interface RenderCapsuleOptions {\n /** Max finding exemplars to show. Default 8. */\n maxFindings?: number\n /** ISO timestamp to stamp into the page (keeps the pure capsule clock-free). */\n generatedAt?: string\n}\n\n/** Render a self-contained HTML capsule — heat-map + per-dimension chips + verified findings. */\nexport function renderCapsuleHtml<S>(\n capsule: CapsuleData<S>,\n opts: RenderCapsuleOptions = {},\n): string {\n const s = capsule.stats\n const kpi = (label: string, value: string, accent = '#e6e6e6'): string =>\n `<div class=\"kpi\"><div class=\"kv\" style=\"color:${accent}\">${esc(value)}</div><div class=\"kl\">${esc(label)}</div></div>`\n const lift = capsule.lift\n ? kpi(\n 'hardening lift',\n `${capsule.lift.before.toFixed(2)} → ${capsule.lift.after.toFixed(2)}`,\n '#5ad17a',\n )\n : ''\n // Cost KPI only when tracking was wired — an untracked run never shows $0.\n // Unpriced runs are named in the label (amber): the total is a lower bound.\n const cost =\n s.costUsd !== undefined\n ? kpi(\n s.costUnknownRuns ? `cost · ${s.costUnknownRuns} runs unpriced` : 'cost',\n `$${s.costUsd.toFixed(2)}`,\n s.costUnknownRuns ? '#e5c07b' : '#e6e6e6',\n )\n : ''\n const stamp = opts.generatedAt ?? capsule.generatedAt ?? ''\n\n return `<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n<title>${esc(capsule.objective)} capsule — ${esc(capsule.target)}</title>\n<style>\n:root{color-scheme:dark}\n*{box-sizing:border-box}\nbody{margin:0;background:#0c0c0f;color:#e6e6e6;font:14px/1.5 ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,sans-serif}\n.wrap{max-width:980px;margin:0 auto;padding:40px 24px}\nh1{font-size:22px;margin:0 0 2px;letter-spacing:-.01em}\n.sub{color:#8a8a93;font-size:13px;margin-bottom:28px}\n.kpis{display:flex;gap:14px;flex-wrap:wrap;margin-bottom:32px}\n.kpi{background:#16161b;border:1px solid #24242b;border-radius:12px;padding:14px 18px;min-width:120px}\n.kv{font-size:24px;font-weight:650;letter-spacing:-.02em}\n.kl{color:#8a8a93;font-size:12px;margin-top:2px}\nh2{font-size:13px;text-transform:uppercase;letter-spacing:.08em;color:#8a8a93;margin:34px 0 14px}\n.axis-label{color:#8a8a93;font-size:12px;margin-bottom:10px}\ntable.heat{border-collapse:separate;border-spacing:6px}\ntable.heat th{font-weight:500;color:#a8a8b0;font-size:12px;padding:4px 8px;text-align:center}\ntable.heat th.rh{text-align:right}\n.tile{position:relative;width:104px;height:66px;border-radius:10px;display:flex;flex-direction:column;justify-content:center;align-items:center;gap:1px;color:#06120a;font-weight:600}\n.tile .tv{font-size:17px}\n.tile .tl{font-size:10px;font-weight:600;opacity:.9;padding:0 6px;text-align:center}\n.tile .dim{font-size:9px;font-weight:600;opacity:.85;background:rgba(0,0,0,.22);padding:0 6px;border-radius:999px}\n.grid{display:flex;flex-wrap:wrap;gap:8px}\n.grid .tile{width:138px;height:74px}\n.fail{background:#16161b;border:1px solid #24242b;border-left:3px solid #d1495b;border-radius:10px;padding:12px 14px;margin-bottom:10px}\n.fmeta{display:flex;gap:10px;align-items:center;font-size:12px;color:#a8a8b0;margin-bottom:8px}\n.fcell{color:#cfcfd6}\n.fclass{background:#2a1a1d;color:#e58a96;padding:1px 8px;border-radius:999px;font-size:11px}\n.fsev{margin-left:auto;color:#e58a96}\n.sevbar{height:4px;background:#24242b;border-radius:2px;overflow:hidden;margin-bottom:10px}\n.sevfill{height:100%;background:#d1495b}\n.ftext{font-size:13px;color:#d8d8df;white-space:pre-wrap}\n.fdims{display:flex;gap:6px;margin-top:8px}\n.fdims .dim{background:#1d2530;color:#9fc1e8;padding:1px 8px;border-radius:999px;font-size:11px}\n.none{color:#5ad17a}\n.foot{color:#5a5a63;font-size:11px;margin-top:36px}\n</style></head><body><div class=\"wrap\">\n<h1>${esc(capsule.objective)} exploration · ${esc(capsule.target)}</h1>\n<div class=\"sub\">${s.totalRuns} scenarios across ${s.cellsCovered}/${s.cellsTotal} planned cells${s.behaviorBinsObserved > 0 ? ` · ${s.behaviorBinsObserved} measured behavior bins` : ''}${stamp ? ` · ${esc(stamp)}` : ''}</div>\n<div class=\"kpis\">\n${s.robustness ? kpi('robustness', `${pct(s.robustness.mean)}`, s.robustness.mean < 0.6 ? '#e58a96' : '#5ad17a') : ''}\n${s.robustness ? kpi('cell spread', `${pct(s.robustness.min)}–${pct(s.robustness.max)}`) : ''}\n${s.latencyMs ? kpi('median latency', `${(s.latencyMs.median / 1000).toFixed(1)}s`, s.latencyMs.p90 > 4 * s.latencyMs.median ? '#e5b566' : '#e6e6e6') : ''}\n${kpi('verified findings', String(s.verifiedFindings), s.verifiedFindings > 0 ? '#e58a96' : '#5ad17a')}\n${kpi('cells covered', `${s.cellsCovered}/${s.cellsTotal}`)}\n${kpi('scenarios run', String(s.totalRuns))}\n${cost}\n${s.evalErrors > 0 ? kpi('eval errors', String(s.evalErrors), '#e5b566') : ''}\n${lift}\n</div>\n${s.stoppedEarly ? `<div class=\"sub\" style=\"color:#e5b566\">stopped early: ${esc(s.stoppedEarly.detail)} — coverage below reflects the completed portion only</div>` : ''}\n<h2>Coverage map</h2>\n${heatmapHtml(capsule.coverage)}\n<h2>Verified findings${s.candidateFindings > s.verifiedFindings ? ` · ${s.verifiedFindings} of ${s.candidateFindings} candidates passed the validity gates` : ''}</h2>\n${findingsHtml(capsule.findings, opts.maxFindings ?? 8)}\n<div class=\"foot\">Findings are gate-verified: each is a fair, answerable task that reproduces under a meaning-preserving rephrase, minimized to the smallest trigger.</div>\n</div></body></html>`\n}\n","/**\n * Shipped policies for the exploration engine.\n *\n * `MutationProposer` is a plain function type — an agent running a generator skill\n * IS a proposer (`(ctx) => dispatchToSkill(ctx)`), no wrapper needed. `mutationProposer`\n * builds the deterministic, LLM-free one from mutation operators. Objectives are\n * interfaces because the engine reads `kind` + `threshold` off them.\n */\n\nimport type { AdversarialMutation } from '../rl/adversarial'\nimport type {\n Cell,\n Evaluation,\n MutationProposer,\n Objective,\n ObjectiveContext,\n ProposeContext,\n} from './types'\n\nconst clamp01 = (x: number): number => Math.max(0, Math.min(1, x))\n\n// ── proposers ─────────────────────────────────────────────────────────────────\n\n/**\n * Perturbation-based search: apply the cell's mutation operators to the current\n * elites + seeds, deduping by id. Elites first — mutating the most interesting\n * scenario found so far is what makes the search deepen across rounds.\n */\nexport function mutationProposer<S>(opts: {\n mutationsFor: (cell: Cell) => AdversarialMutation<S>[]\n scenarioId: (s: S) => string\n}): MutationProposer<S> {\n return async (ctx: ProposeContext<S>): Promise<S[]> => {\n const mutations = opts.mutationsFor(ctx.cell)\n const parents = [...ctx.elites, ...ctx.seeds]\n const seen = new Set(parents.map(opts.scenarioId))\n const out: S[] = []\n for (const parent of parents) {\n if (out.length >= ctx.count) break\n for (const m of mutations) {\n const children = await m.mutate(parent, ctx.rng)\n for (const child of children) {\n const id = opts.scenarioId(child)\n if (seen.has(id)) continue\n seen.add(id)\n out.push(child)\n if (out.length >= ctx.count) break\n }\n if (out.length >= ctx.count) break\n }\n }\n return out\n }\n}\n\n// ── objectives ────────────────────────────────────────────────────────────────\n\n/** Adversarial: a low headline score is interesting — find where the agent fails. */\nexport function adversarialObjective(threshold = 0.5): Objective {\n return { kind: 'adversarial', threshold, interest: (ev) => clamp01(1 - ev.score) }\n}\n\nfunction hamming(\n a: Record<string, string> | undefined,\n b: Record<string, string> | undefined,\n): number {\n if (!a || !b) return 1\n const keys = new Set([...Object.keys(a), ...Object.keys(b)])\n if (keys.size === 0) return 0\n let diff = 0\n for (const k of keys) if (a[k] !== b[k]) diff++\n return diff / keys.size\n}\n\n/**\n * Novelty: interesting when far from the archive in score AND measured behavior\n * descriptor — quality-diversity's diversity pressure; drives corpus growth\n * rather than re-finding the same hole.\n */\nexport function noveltyObjective(threshold = 0.3): Objective {\n return {\n kind: 'novelty',\n threshold,\n interest: (ev: Evaluation, ctx: ObjectiveContext) => {\n const scoreNovelty =\n ctx.archiveScores.length === 0\n ? 1\n : Math.min(...ctx.archiveScores.map((s) => Math.abs(s - ev.score)))\n const descNovelty =\n ctx.archiveDescriptors.length === 0\n ? 1\n : Math.min(...ctx.archiveDescriptors.map((d) => hamming(d, ev.descriptor)))\n return clamp01(0.5 * scoreNovelty + 0.5 * descNovelty)\n },\n }\n}\n","/**\n * The exploration engine — a stateful session over a behavior space.\n *\n * Each `step()`: allocate budget across INPUT cells (floor first, then variance\n * steering toward the least-certain cells), propose candidates (the proposer\n * reads current elites + findings, so the search deepens generationally),\n * evaluate with bounded concurrency, archive the most interesting scenario per\n * input×measured bin, and admit notable candidates that pass the validity gates.\n * `run()` loops to budget. `coverage()`/`findings()`/`capsule()` read live state —\n * the surface `makeExploreTools` exposes so an agent can drive the session.\n *\n * One evaluation log (`EvalRecord[]`) is the source of truth; allocation\n * observations and coverage are projections of it.\n */\n\nimport { CostLedger, type CostLedgerHandle, CostReceiptCaptureError } from '../cost-ledger'\nimport { ValidationError } from '../errors'\nimport { varianceBasedCurriculum } from '../rl/active-curriculum'\nimport { mulberry32 } from '../statistics/random'\nimport { buildCapsule } from './capsule'\nimport type { EvalRecord } from './cube'\nimport { enumerateCells } from './cube'\nimport { adversarialObjective } from './policies'\nimport type {\n ArchiveEntry,\n CapsuleData,\n Cell,\n CoverageCell,\n ExploreOptions,\n Finding,\n Objective,\n} from './types'\n\nasync function pMap<T>(\n items: T[],\n fn: (item: T) => Promise<void>,\n concurrency: number,\n signal?: AbortSignal,\n): Promise<void> {\n let i = 0\n const workers = Array.from(\n { length: Math.max(1, Math.min(concurrency, items.length)) },\n async () => {\n while (i < items.length) {\n if (signal?.aborted) return\n const item = items[i++]\n if (item === undefined) return\n await fn(item)\n }\n },\n )\n await Promise.all(workers)\n}\n\nexport class BehaviorExplorer<S> {\n private readonly cells: Cell[]\n private readonly cellById: Map<string, Cell>\n private readonly objective: Objective\n private readonly threshold: number\n private readonly floorPerCell: number\n private readonly perRoundBudget: number\n\n /** The single evaluation log — coverage + allocation are projections of it. */\n private readonly log: Array<EvalRecord & { scenarioId: string }> = []\n /** binId (input × measured coords) → the most interesting entry seen. */\n private readonly archiveByBin = new Map<string, ArchiveEntry<S>>()\n private readonly _findings: Finding<S>[] = []\n private runsUsed = 0\n private candidateFindings = 0\n private evalErrors = 0\n private consecutiveEvalErrors = 0\n private stoppedEarly: { reason: 'eval-errors'; detail: string } | undefined\n private readonly rng: () => number\n private readonly costLedger?: CostLedgerHandle\n private readonly costPhase = 'fuzz.explore'\n\n constructor(private readonly opts: ExploreOptions<S>) {\n this.cells = enumerateCells(opts.space)\n if (this.cells.length === 0)\n throw new Error('BehaviorExplorer: space has no cells — every axis needs ≥1 value')\n if (opts.costBudgetUsd !== undefined) {\n if (\n typeof opts.costBudgetUsd !== 'number' ||\n !Number.isFinite(opts.costBudgetUsd) ||\n opts.costBudgetUsd < 0\n ) {\n throw new RangeError(\n `BehaviorExplorer: costBudgetUsd must be a nonnegative finite number, got ${String(opts.costBudgetUsd)}`,\n )\n }\n }\n if (!opts.costOf && (opts.costBudgetUsd !== undefined || opts.ledger || opts.onCost)) {\n throw new ValidationError(\n 'BehaviorExplorer: costBudgetUsd/ledger/onCost require costOf — the explorer ' +\n 'cannot know run cost without it; supply costOf or drop the cost options',\n )\n }\n if (\n (opts.costBudgetUsd !== undefined || opts.ledger?.costCeilingUsd !== undefined) &&\n !opts.maximumChargeOf\n ) {\n throw new ValidationError(\n 'BehaviorExplorer: capped cost tracking requires maximumChargeOf before evaluation',\n )\n }\n if (\n opts.ledger &&\n opts.costBudgetUsd !== undefined &&\n opts.ledger.costCeilingUsd !== opts.costBudgetUsd\n ) {\n throw new ValidationError(\n 'BehaviorExplorer: costBudgetUsd must match the supplied CostLedger ceiling',\n )\n }\n if (opts.costOf) this.costLedger = opts.ledger ?? new CostLedger(opts.costBudgetUsd)\n this.cellById = new Map(this.cells.map((c) => [c.id, c]))\n this.objective = opts.objective ?? adversarialObjective(0.5)\n this.threshold = this.objective.threshold ?? 0.5\n this.floorPerCell = opts.floorPerCell ?? 2\n this.perRoundBudget = Math.max(\n this.cells.length * this.floorPerCell,\n Math.ceil(opts.budget / 4),\n )\n this.rng = mulberry32(opts.seed ?? 1)\n }\n\n private binId(cell: Cell, descriptor: Record<string, string> | undefined): string {\n if (!descriptor || Object.keys(descriptor).length === 0) return cell.id\n const measured = Object.keys(descriptor)\n .sort()\n .map((k) => `${k}=${descriptor[k]}`)\n .join('|')\n return `${cell.id}|${measured}`\n }\n\n private allocate(budget: number): Array<{ cellId: string; count: number }> {\n if ((this.opts.allocation ?? 'variance') === 'uniform') {\n const per = Math.max(this.floorPerCell, Math.floor(budget / this.cells.length))\n return this.cells.map((c) => ({ cellId: c.id, count: per }))\n }\n return varianceBasedCurriculum(\n this.log.map((r) => ({\n variantId: r.cell.id,\n scenarioId: '*',\n score: r.ev.score,\n })),\n this.cells.map((c) => ({ variantId: c.id, scenarioId: '*' })),\n { budget, floorPerCell: this.floorPerCell },\n ).map((a) => ({ cellId: a.variantId, count: a.count }))\n }\n\n private objectiveContext() {\n const entries = [...this.archiveByBin.values()]\n return {\n archiveScores: entries.map((e) => e.evaluation.score),\n archiveDescriptors: entries.map((e) => e.evaluation.descriptor),\n }\n }\n\n /** Elites whose INPUT cell matches — what the proposer mutates/deepens from. */\n private elitesFor(cellId: string): S[] {\n const out: S[] = []\n for (const e of this.archiveByBin.values()) if (e.cell.id === cellId) out.push(e.scenario)\n return out\n }\n\n /** One allocate → propose → evaluate → gate → archive round. */\n async step(): Promise<{ runs: number; findings: Finding<S>[] }> {\n const remaining = this.opts.budget - this.runsUsed\n if (remaining <= 0 || this.opts.signal?.aborted) return { runs: 0, findings: [] }\n\n const allocations = this.allocate(Math.min(this.perRoundBudget, remaining))\n const newFindings: Finding<S>[] = []\n let runsThisStep = 0\n\n for (const alloc of allocations) {\n if (\n this.runsUsed >= this.opts.budget ||\n this.stoppedEarly !== undefined ||\n this.opts.signal?.aborted\n )\n break\n const cell = this.cellById.get(alloc.cellId)\n if (!cell) continue\n const cap = Math.min(alloc.count, this.opts.budget - this.runsUsed)\n if (cap <= 0) continue\n this.opts.onProgress?.({ type: 'cell-allocated', cell, count: cap })\n\n const seeds = await this.opts.seedsFor(cell)\n const elites = this.elitesFor(cell.id)\n const proposed = await this.opts.proposer({\n cell,\n seeds,\n elites,\n findings: this._findings,\n count: cap,\n rng: this.rng,\n })\n // Cold cells evaluate their seeds first (the coverage floor); warm cells\n // trust the proposer, which already saw the elites.\n const cold = this.log.every((r) => r.cell.id !== cell.id)\n const toEval = [...(cold ? seeds : []), ...proposed].slice(0, cap)\n\n await pMap(\n toEval,\n async (scenario) => {\n if (\n this.runsUsed >= this.opts.budget ||\n this.stoppedEarly !== undefined ||\n this.opts.signal?.aborted\n )\n return\n // evaluate/gates/minimize cross an external boundary (router, backend,\n // judge). A throw there is an infra outcome: record it as a typed\n // eval-error and keep exploring — one 5xx must not kill a campaign.\n // Consecutive failures trip the circuit breaker instead, so a dead\n // backend stops the run rather than burning the remaining budget.\n try {\n const startedAt = performance.now()\n const paid = this.costLedger\n ? await this.costLedger.runPaidCall({\n channel: 'agent',\n phase: this.costPhase,\n actor: 'fuzz.evaluate',\n tags: { target: this.opts.target, cell: cell.id },\n signal: this.opts.signal,\n maximumCharge: this.opts.maximumChargeOf?.(scenario, cell),\n execute: () => this.opts.evaluate(scenario, cell),\n receipt: (evaluation) => {\n const cost = this.opts.costOf!(scenario, cell, evaluation)\n if (cost === null) {\n return {\n model: 'unattributed',\n inputTokens: 0,\n outputTokens: 0,\n costUnknown: true,\n }\n }\n if (!Number.isFinite(cost.usd) || cost.usd < 0) {\n throw new RangeError(\n `BehaviorExplorer: costOf returned an invalid usd (${String(cost.usd)}) — ` +\n 'return null when cost is unknown, never a fabricated number',\n )\n }\n return {\n model: cost.model ?? 'unattributed',\n inputTokens: 0,\n outputTokens: 0,\n actualCostUsd: cost.usd,\n }\n },\n })\n : undefined\n if (paid && !paid.succeeded) {\n if (\n paid.error instanceof CostReceiptCaptureError &&\n paid.error.receiptError instanceof RangeError\n ) {\n throw paid.error.receiptError\n }\n throw paid.error\n }\n const ev = paid ? paid.value : await this.opts.evaluate(scenario, cell)\n // Consumer-measured latency wins (it can exclude judge time); the\n // engine's wall-clock is the default so latency is never missing.\n const latencyMs = ev.latencyMs ?? performance.now() - startedAt\n this.runsUsed++\n runsThisStep++\n this.consecutiveEvalErrors = 0\n const costUsd = paid\n ? paid.receipt.costUnknown\n ? null\n : paid.receipt.costUsd\n : undefined\n if (paid?.receipt.actualCostUsd !== undefined) {\n this.opts.onCost?.({ usd: paid.receipt.actualCostUsd, channel: 'agent' })\n }\n const interest = this.objective.interest(ev, this.objectiveContext())\n this.log.push({\n cell,\n ev,\n interest,\n latencyMs,\n ...(costUsd !== undefined ? { costUsd } : {}),\n scenarioId: this.opts.scenarioId(scenario),\n })\n this.opts.onProgress?.({ type: 'evaluated', cell, scenario, evaluation: ev })\n\n const bin = this.binId(cell, ev.descriptor)\n const cur = this.archiveByBin.get(bin)\n if (!cur || interest > cur.interest)\n this.archiveByBin.set(bin, { binId: bin, cell, scenario, evaluation: ev, interest })\n\n if (interest < this.threshold) return\n this.candidateFindings++\n if (this.opts.gates?.isValid && !(await this.opts.gates.isValid(scenario, ev, cell)))\n return\n if (\n this.opts.gates?.isUncontaminated &&\n !(await this.opts.gates.isUncontaminated(scenario, ev, cell))\n )\n return\n\n const minimized = this.opts.minimize\n ? await this.opts.minimize(scenario, this.opts.evaluate, cell)\n : scenario\n const finding: Finding<S> = {\n id: this.opts.scenarioId(scenario),\n cell,\n scenario,\n minimized,\n text: this.opts.scenarioText?.(minimized),\n evaluation: ev,\n interest,\n objective: this.objective.kind,\n }\n this._findings.push(finding)\n newFindings.push(finding)\n this.opts.onProgress?.({ type: 'finding', finding })\n } catch (err) {\n // Internal validation errors (e.g. a fabricated costOf number) are\n // programming mistakes, not backend outcomes — they stay loud.\n if (err instanceof RangeError) throw err\n this.evalErrors++\n this.consecutiveEvalErrors++\n const message = err instanceof Error ? err.message : String(err)\n this.opts.onProgress?.({\n type: 'eval-error',\n cell,\n scenarioId: this.opts.scenarioId(scenario),\n message,\n })\n const limit = this.opts.maxConsecutiveEvalErrors ?? 5\n if (this.consecutiveEvalErrors >= limit) {\n this.stoppedEarly = {\n reason: 'eval-errors',\n detail: `${this.consecutiveEvalErrors} consecutive eval errors (last: ${message})`,\n }\n }\n }\n },\n this.opts.concurrency ?? 1,\n this.opts.signal,\n )\n }\n\n this.opts.onProgress?.({ type: 'round', runsUsed: this.runsUsed, budget: this.opts.budget })\n return { runs: runsThisStep, findings: newFindings }\n }\n\n /** Loop `step()` until the run or dollar budget is spent, the signal aborts,\n * or no progress is made. */\n async run(): Promise<CapsuleData<S>> {\n while (\n this.runsUsed < this.opts.budget &&\n this.stoppedEarly === undefined &&\n !this.opts.signal?.aborted\n ) {\n const { runs } = await this.step()\n if (runs === 0 && this.stoppedEarly === undefined) break\n }\n return this.capsule()\n }\n\n coverage(): CoverageCell[] {\n return this.capsule().coverage\n }\n\n findings(): Finding<S>[] {\n return [...this._findings].sort((a, b) => b.interest - a.interest)\n }\n\n capsule(): CapsuleData<S> {\n const cost = this.costLedger?.summary({\n phase: this.costPhase,\n tags: { target: this.opts.target },\n })\n return buildCapsule({\n target: this.opts.target,\n objective: this.objective.kind,\n cells: this.cells,\n log: this.log,\n threshold: this.threshold,\n archive: [...this.archiveByBin.values()],\n findings: this._findings,\n candidateFindings: this.candidateFindings,\n runsUsed: this.runsUsed,\n cost: cost\n ? {\n costUsd: cost.totalCostUsd,\n costUnknownRuns: cost.byChannel.reduce((sum, row) => sum + row.unpricedCalls, 0),\n }\n : undefined,\n evalErrors: this.evalErrors,\n stoppedEarly: this.stoppedEarly,\n })\n }\n}\n","/**\n * `fuzzAgent` — the adversarial batch preset over `BehaviorExplorer`.\n *\n * One call: explore the space to budget with the adversarial objective and\n * return the capsule. For agent-driven, incremental, or multi-objective use,\n * construct a `BehaviorExplorer` and drive it via `makeExploreTools`.\n */\n\nimport { BehaviorExplorer } from './explorer'\nimport { adversarialObjective } from './policies'\nimport type { CapsuleData, ExploreOptions } from './types'\n\nexport type FuzzAgentOptions<S> = Omit<ExploreOptions<S>, 'objective'> & {\n /** Score strictly below this is a candidate failure. Default 0.5. */\n failureThreshold?: number\n}\n\nexport async function fuzzAgent<S>(\n opts: FuzzAgentOptions<S>,\n): Promise<{ capsule: CapsuleData<S> }> {\n const { failureThreshold, ...rest } = opts\n const explorer = new BehaviorExplorer<S>({\n ...rest,\n objective: adversarialObjective(failureThreshold ?? 0.5),\n })\n return { capsule: await explorer.run() }\n}\n","/**\n * Validity gates — what separates a fuzzer from a slop generator.\n *\n * A notable candidate is admitted only when it is fair and reproducible. None of\n * these are on by default: the live wiring opts in, so reported findings carry\n * their proof.\n */\n\nimport type { Cell, Evaluation, Evaluator, ValidityGates } from './types'\n\n/** Combine gate sets; a candidate must pass every gate in every set. */\nexport function composeGates<S>(...sets: Array<ValidityGates<S> | undefined>): ValidityGates<S> {\n const present = sets.filter((s): s is ValidityGates<S> => s != null)\n return {\n isValid: async (scenario, ev, cell) => {\n for (const g of present) {\n if (g.isValid && !(await g.isValid(scenario, ev, cell))) return false\n }\n return true\n },\n isUncontaminated: async (scenario, ev, cell) => {\n for (const g of present) {\n if (g.isUncontaminated && !(await g.isUncontaminated(scenario, ev, cell))) return false\n }\n return true\n },\n }\n}\n\n/**\n * Reproducibility gate. Re-run the target on a meaning-preserving rephrase of the\n * flagged scenario; keep the finding only when the rephrase ALSO scores below the\n * threshold. A finding that flips under a cosmetic rewrite was keyed to surface\n * form, not the task — a false signal we must not report. Costs one extra\n * evaluation per candidate (candidates are rare, so cheap).\n */\nexport function perturbationStabilityGate<S>(opts: {\n evaluate: Evaluator<S>\n /** Produce a semantic-preserving rephrase. Return null to skip (treated as pass). */\n perturb: (scenario: S) => S | null\n /** Score strictly below this still counts as failing. Default 0.5. */\n failureThreshold?: number\n}): ValidityGates<S> {\n const threshold = opts.failureThreshold ?? 0.5\n return {\n isUncontaminated: async (scenario: S, _ev: Evaluation, cell: Cell) => {\n const rephrased = opts.perturb(scenario)\n if (rephrased == null) return true\n const re = await opts.evaluate(rephrased, cell)\n return re.score < threshold\n },\n }\n}\n\n/**\n * Severity-floor gate. Reject borderline candidates whose score sits in a band\n * just under the threshold — judge noise, not a real defect.\n */\nexport function severityFloorGate<S>(opts: {\n failureThreshold?: number\n margin?: number\n}): ValidityGates<S> {\n const threshold = opts.failureThreshold ?? 0.5\n const margin = opts.margin ?? 0.1\n return {\n isValid: (_scenario, ev: Evaluation) => ev.score <= threshold - margin,\n }\n}\n","/**\n * Agent-drivable surface over a live exploration session.\n *\n * Framework-neutral tool defs ({name, description, parameters: JSON Schema,\n * handler}) so the on-demand agent — not a batch script — drives the search:\n * step it, read coverage, inspect findings, render the capsule. Transport\n * encodings (OpenAI function shape, MCP) are one-line mappings the host owns.\n */\n\nimport { renderCapsuleHtml } from './capsule'\nimport type { BehaviorExplorer } from './explorer'\n\nexport interface ExploreToolDef {\n name: string\n description: string\n /** JSON Schema (draft-07+) for the arguments. */\n parameters: Record<string, unknown>\n handler: (args: unknown, ctx?: { signal?: AbortSignal }) => Promise<unknown>\n}\n\nconst NO_ARGS = { type: 'object', properties: {}, additionalProperties: false }\n\nexport function makeExploreTools<S>(explorer: BehaviorExplorer<S>): ExploreToolDef[] {\n return [\n {\n name: 'explore_step',\n description:\n 'Run one exploration round: allocate budget across cells, propose + evaluate scenarios, archive elites, admit gate-verified findings. Returns runs spent and new findings.',\n parameters: NO_ARGS,\n handler: async () => {\n const { runs, findings } = await explorer.step()\n return { runs, newFindings: findings.length, findings }\n },\n },\n {\n name: 'explore_coverage',\n description:\n 'Read the live coverage map: per planned cell — runs, robustness (null = uncovered), finding rate, per-dimension means.',\n parameters: NO_ARGS,\n handler: async () => explorer.coverage(),\n },\n {\n name: 'explore_findings',\n description: 'List gate-verified findings so far, sorted by descending interest.',\n parameters: {\n type: 'object',\n properties: { limit: { type: 'number', description: 'max findings to return' } },\n additionalProperties: false,\n },\n handler: async (args) => {\n const limit = (args as { limit?: number } | undefined)?.limit\n const all = explorer.findings()\n return typeof limit === 'number' ? all.slice(0, limit) : all\n },\n },\n {\n name: 'explore_capsule',\n description:\n 'Build the capsule artifact from the current session state. format \"data\" returns the structured CapsuleData; \"html\" returns the standalone page.',\n parameters: {\n type: 'object',\n properties: {\n format: { type: 'string', enum: ['data', 'html'] },\n generatedAt: { type: 'string', description: 'ISO timestamp to stamp into the page' },\n },\n additionalProperties: false,\n },\n handler: async (args) => {\n const a = (args ?? {}) as { format?: string; generatedAt?: string }\n const capsule = explorer.capsule()\n if (a.format === 'html') return renderCapsuleHtml(capsule, { generatedAt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AC/C,OAAO;KAAE;KAAM,aAAa,SAAS;KAAQ;IAAS;GACxD;EACF;EACA;GACE,MAAM;GACN,aACE;GACF,YAAY;GACZ,SAAS,YAAY,SAAS,SAAS;EACzC;EACA;GACE,MAAM;GACN,aAAa;GACb,YAAY;IACV,MAAM;IACN,YAAY,EAAE,OAAO;KAAE,MAAM;KAAU,aAAa;IAAyB,EAAE;IAC/E,sBAAsB;GACxB;GACA,SAAS,OAAO,SAAS;IACvB,MAAM,QAAS,MAAyC;IACxD,MAAM,MAAM,SAAS,SAAS;IAC9B,OAAO,OAAO,UAAU,WAAW,IAAI,MAAM,GAAG,KAAK,IAAI;GAC3D;EACF;EACA;GACE,MAAM;GACN,aACE;GACF,YAAY;IACV,MAAM;IACN,YAAY;KACV,QAAQ;MAAE,MAAM;MAAU,MAAM,CAAC,QAAQ,MAAM;KAAE;KACjD,aAAa;MAAE,MAAM;MAAU,aAAa;KAAuC;IACrF;IACA,sBAAsB;GACxB;GACA,SAAS,OAAO,SAAS;IACvB,MAAM,IAAK,QAAQ,CAAC;IACpB,MAAM,UAAU,SAAS,QAAQ;IACjC,IAAI,EAAE,WAAW,QAAQ,OAAO,kBAAkB,SAAS,EAAE,aAAa,EAAE,YAAY,CAAC;IACzF,OAAO;GACT;EACF;CACF;AACF"}
1
+ {"version":3,"file":"fuzz.js","names":[],"sources":["../src/fuzz/cube.ts","../src/fuzz/capsule.ts","../src/rl/active-curriculum.ts","../src/fuzz/policies.ts","../src/fuzz/explorer.ts","../src/fuzz/fuzz-agent.ts","../src/fuzz/gates.ts"],"sourcesContent":["/**\n * Input-space tiling + coverage projection.\n *\n * Cells are the cartesian product of the input axes — the stratification plan,\n * enumerable up front so the planned-vs-covered denominator is honest. Coverage\n * is projected from the evaluation log: per cell, the full DISTRIBUTION of the\n * headline score, of each scored dimension, and of evaluation latency — a bare\n * mean hides outliers, so every aggregate carries its spread. Per-cell cost is\n * split known-dollars vs unknown-runs, never folded into a fabricated $0.\n */\n\nimport type { BehaviorSpace, Cell, CoverageCell, Distribution, Evaluation } from './types'\n\n/** One recorded evaluation — the unit coverage and the capsule are built from. */\nexport interface EvalRecord {\n cell: Cell\n ev: Evaluation\n /** The objective's interest score for this evaluation. */\n interest: number\n /** Evaluation wall-clock — engine-measured unless `ev.latencyMs` overrode it. */\n latencyMs: number\n /** Known dollars for this run. `null` = cost tracking was wired but this\n * run's cost was unknowable (counted apart). Absent = not tracked at all. */\n costUsd?: number | null\n}\n\n/** Enumerate every input cell (cartesian product of the axes), in stable order. */\nexport function enumerateCells(space: BehaviorSpace): Cell[] {\n if (space.axes.length === 0) return []\n let partials: Array<Record<string, string>> = [{}]\n for (const axis of space.axes) {\n const next: Array<Record<string, string>> = []\n for (const partial of partials) {\n for (const value of axis.values) next.push({ ...partial, [axis.name]: value })\n }\n partials = next\n }\n return partials.map((coords) => ({ id: cellId(space, coords), coords }))\n}\n\n/** Deterministic id for a coordinate map, e.g. `matterType=nda|difficulty=hard`. */\nexport function cellId(space: BehaviorSpace, coords: Record<string, string>): string {\n return space.axes.map((a) => `${a.name}=${coords[a.name]}`).join('|')\n}\n\n/** Nearest-rank percentile on a pre-sorted ascending sample. */\nfunction percentile(sorted: number[], p: number): number {\n const idx = Math.min(sorted.length - 1, Math.max(0, Math.ceil(p * sorted.length) - 1))\n return sorted[idx] as number\n}\n\n/** Summarize a sample. Throws on an empty sample — callers represent \"no data\"\n * as `null`, never as a zeroed distribution. */\nexport function distribution(values: number[]): Distribution {\n if (values.length === 0)\n throw new Error('distribution: empty sample — represent missing data as null, not zeros')\n const sorted = [...values].sort((a, b) => a - b)\n const mean = sorted.reduce((a, b) => a + b, 0) / sorted.length\n return {\n mean,\n median: percentile(sorted, 0.5),\n p90: percentile(sorted, 0.9),\n min: sorted[0] as number,\n max: sorted[sorted.length - 1] as number,\n n: sorted.length,\n }\n}\n\n/**\n * Project the evaluation log into the per-input-cell coverage map. A cell with\n * no evaluations reports `score: null` (honestly uncovered), never zeros.\n */\nexport function buildCoverage(cells: Cell[], log: EvalRecord[], threshold: number): CoverageCell[] {\n const byCell = new Map<string, EvalRecord[]>()\n for (const r of log) {\n const arr = byCell.get(r.cell.id) ?? []\n arr.push(r)\n byCell.set(r.cell.id, arr)\n }\n return cells.map((cell) => {\n const recs = byCell.get(cell.id) ?? []\n const runs = recs.length\n if (runs === 0)\n return { cell, runs: 0, score: null, findingRate: 0, dimensions: {}, latencyMs: null }\n\n const score = distribution(recs.map((r) => r.ev.score))\n const latencyMs = distribution(recs.map((r) => r.latencyMs))\n const findingRate = recs.filter((r) => r.interest >= threshold).length / runs\n\n const dimSamples: Record<string, number[]> = {}\n for (const r of recs) {\n for (const [k, v] of Object.entries(r.ev.scores ?? {})) {\n const samples = dimSamples[k] ?? []\n samples.push(v)\n dimSamples[k] = samples\n }\n }\n const dimensions: Record<string, Distribution> = {}\n for (const [k, xs] of Object.entries(dimSamples)) dimensions[k] = distribution(xs)\n\n // Cost fields appear only when tracking was wired: known dollars sum, and\n // tracked-but-unknown runs counted apart — never folded in as $0.\n const tracked = recs.filter((r) => r.costUsd !== undefined)\n const known = tracked.filter((r) => r.costUsd !== null)\n const cost =\n tracked.length > 0\n ? {\n costUsd: known.reduce((a, r) => a + (r.costUsd as number), 0),\n ...(tracked.length > known.length\n ? { costUnknownRuns: tracked.length - known.length }\n : {}),\n }\n : {}\n\n return { cell, runs, score, findingRate, dimensions, latencyMs, ...cost }\n })\n}\n","/**\n * The capsule — the artifact every exploration produces.\n *\n * `buildCapsule` assembles coverage + verified findings + the QD archive into a\n * pure `CapsuleData` (no clock, no I/O — deterministic and snapshot-testable).\n * `renderCapsuleHtml` turns it into a standalone page: the input-cell heat-map\n * (planned vs covered), per-dimension weakness chips, and the minimized finding\n * exemplars. One artifact — the hardening map and the shareable proof object.\n */\n\nimport type { EvalRecord } from './cube'\nimport { buildCoverage, distribution } from './cube'\nimport type { ArchiveEntry, CapsuleData, Cell, CoverageCell, Distribution, FuzzFinding } from './types'\n\nexport interface BuildCapsuleInput<S> {\n target: string\n objective: string\n cells: Cell[]\n log: EvalRecord[]\n /** The objective's notable threshold — drives findingRate. */\n threshold: number\n archive: ArchiveEntry<S>[]\n findings: FuzzFinding<S>[]\n candidateFindings: number\n runsUsed: number\n /** Known-dollar / unknown-run split — present only when cost tracking was\n * wired; the capsule never fabricates a $0 total. */\n cost?: { costUsd: number; costUnknownRuns: number }\n /** Evaluations that threw — infra outcomes, never folded into robustness. */\n evalErrors: number\n /** Set when the consecutive-error circuit breaker stopped the run early. */\n stoppedEarly?: { reason: 'eval-errors'; detail: string }\n}\n\nexport function buildCapsule<S>(input: BuildCapsuleInput<S>): CapsuleData<S> {\n const coverage = buildCoverage(input.cells, input.log, input.threshold)\n const covered = coverage.filter((c) => c.runs > 0)\n // Cells weigh equally: variance steering sends more runs to weak cells, so a\n // run-weighted average would bias the headline low.\n const robustness =\n covered.length === 0 ? null : distribution(covered.map((c) => (c.score as Distribution).mean))\n const latencyMs = input.log.length === 0 ? null : distribution(input.log.map((r) => r.latencyMs))\n // Measured-descriptor bins beyond the bare input cell — observed, never planned.\n const behaviorBinsObserved = input.archive.filter((e) => e.binId !== e.cell.id).length\n\n return {\n target: input.target,\n objective: input.objective,\n coverage,\n findings: [...input.findings].sort((a, b) => b.interest - a.interest),\n archive: [...input.archive].sort((a, b) => b.interest - a.interest),\n stats: {\n totalRuns: input.runsUsed,\n cellsTotal: input.cells.length,\n cellsCovered: covered.length,\n behaviorBinsObserved,\n candidateFindings: input.candidateFindings,\n verifiedFindings: input.findings.length,\n robustness,\n latencyMs,\n ...(input.cost\n ? { costUsd: input.cost.costUsd, costUnknownRuns: input.cost.costUnknownRuns }\n : {}),\n evalErrors: input.evalErrors,\n ...(input.stoppedEarly ? { stoppedEarly: input.stoppedEarly } : {}),\n },\n }\n}\n\n// ── HTML capsule ──────────────────────────────────────────────────────────────\n\nfunction esc(s: string): string {\n return s.replace(\n /[&<>\"]/g,\n (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;' })[c] as string,\n )\n}\n\n/** red (0) → amber (.5) → green (1); uncovered cells render gray. */\nfunction robustnessColor(r: number | null): string {\n if (r == null) return '#2a2a2e'\n return `hsl(${Math.round(r * 120)} 70% 42%)`\n}\n\nfunction pct(x: number): string {\n return `${Math.round(x * 100)}%`\n}\n\nfunction deriveAxes(coverage: CoverageCell[]): Array<{ name: string; values: string[] }> {\n const order: string[] = []\n const seen = new Map<string, Set<string>>()\n for (const c of coverage) {\n for (const [k, v] of Object.entries(c.cell.coords)) {\n if (!seen.has(k)) {\n seen.set(k, new Set())\n order.push(k)\n }\n seen.get(k)?.add(v)\n }\n }\n return order.map((name) => ({ name, values: [...(seen.get(name) ?? [])] }))\n}\n\n/** The weakest dimension chip for a cell, e.g. `safety 32%` — shown when scores exist. */\nfunction weakestDim(c: CoverageCell): string {\n const entries = Object.entries(c.dimensions).map(([k, d]) => [k, d.mean] as [string, number])\n if (entries.length === 0) return ''\n const sorted = entries.sort((a, b) => a[1] - b[1])\n const w = sorted[0]\n if (!w) return ''\n return `<span class=\"dim\">${esc(w[0])} ${pct(w[1])}</span>`\n}\n\nfunction heatmapHtml(coverage: CoverageCell[]): string {\n const axes = deriveAxes(coverage)\n const byId = new Map(coverage.map((c) => [c.cell.id, c]))\n const tile = (c: CoverageCell | undefined, label: string): string => {\n const r = c?.score?.mean ?? null\n const title = c?.score\n ? `${pct(c.score.mean)} robust (median ${pct(c.score.median)}, min ${pct(c.score.min)}) · ${c.runs} runs · ${pct(c.findingRate)} flagged${c.latencyMs ? ` · ${(c.latencyMs.median / 1000).toFixed(1)}s median` : ''}${c.costUsd !== undefined ? ` · $${c.costUsd.toFixed(2)}` : ''}`\n : 'not covered'\n return `<div class=\"tile\" style=\"background:${robustnessColor(r)}\" title=\"${esc(title)}\">${label ? `<span class=\"tl\">${esc(label)}</span>` : ''}<span class=\"tv\">${c && r != null ? pct(r) : '—'}</span>${c ? weakestDim(c) : ''}</div>`\n }\n\n const rowAxis = axes[0]\n const colAxis = axes[1]\n if (axes.length === 2 && rowAxis && colAxis) {\n const head = `<tr><th></th>${colAxis.values.map((v) => `<th>${esc(v)}</th>`).join('')}</tr>`\n const rows = rowAxis.values\n .map((rv) => {\n const cells = colAxis.values\n .map((cv) => {\n const id = `${rowAxis.name}=${rv}|${colAxis.name}=${cv}`\n return `<td>${tile(byId.get(id), '')}</td>`\n })\n .join('')\n return `<tr><th class=\"rh\">${esc(rv)}</th>${cells}</tr>`\n })\n .join('')\n return `<div class=\"axis-label\">rows: <b>${esc(rowAxis.name)}</b> · cols: <b>${esc(colAxis.name)}</b></div><table class=\"heat\">${head}${rows}</table>`\n }\n\n const sorted = [...coverage].sort((a, b) => (a.score?.mean ?? 2) - (b.score?.mean ?? 2))\n return `<div class=\"grid\">${sorted.map((c) => tile(c, Object.values(c.cell.coords).join(' · '))).join('')}</div>`\n}\n\nfunction findingsHtml<S>(findings: FuzzFinding<S>[], limit: number): string {\n if (findings.length === 0)\n return `<p class=\"none\">No verified findings — the target held across every covered cell.</p>`\n return findings\n .slice(0, limit)\n .map((f) => {\n const coords = Object.entries(f.cell.coords)\n .map(([k, v]) => `${k}:${v}`)\n .join(' · ')\n const labels = (f.evaluation.labels ?? [])\n .map((l) => `<span class=\"fclass\">${esc(l)}</span>`)\n .join('')\n const dims = Object.entries(f.evaluation.scores ?? {})\n .sort((a, b) => a[1] - b[1])\n .slice(0, 3)\n .map(([k, v]) => `<span class=\"dim\">${esc(k)} ${pct(v)}</span>`)\n .join('')\n return `<div class=\"fail\"><div class=\"fmeta\"><span class=\"fcell\">${esc(coords)}</span>${labels}<span class=\"fsev\">interest ${pct(f.interest)}</span></div><div class=\"sevbar\"><div class=\"sevfill\" style=\"width:${pct(f.interest)}\"></div></div><div class=\"ftext\">${esc(f.text ?? '(scenario text not captured)')}</div>${dims ? `<div class=\"fdims\">${dims}</div>` : ''}</div>`\n })\n .join('')\n}\n\nexport interface RenderCapsuleOptions {\n /** Max finding exemplars to show. Default 8. */\n maxFindings?: number\n /** ISO timestamp to stamp into the page (keeps the pure capsule clock-free). */\n generatedAt?: string\n}\n\n/** Render a self-contained HTML capsule — heat-map + per-dimension chips + verified findings. */\nexport function renderCapsuleHtml<S>(\n capsule: CapsuleData<S>,\n opts: RenderCapsuleOptions = {},\n): string {\n const s = capsule.stats\n const kpi = (label: string, value: string, accent = '#e6e6e6'): string =>\n `<div class=\"kpi\"><div class=\"kv\" style=\"color:${accent}\">${esc(value)}</div><div class=\"kl\">${esc(label)}</div></div>`\n const lift = capsule.lift\n ? kpi(\n 'hardening lift',\n `${capsule.lift.before.toFixed(2)} → ${capsule.lift.after.toFixed(2)}`,\n '#5ad17a',\n )\n : ''\n // Cost KPI only when tracking was wired — an untracked run never shows $0.\n // Unpriced runs are named in the label (amber): the total is a lower bound.\n const cost =\n s.costUsd !== undefined\n ? kpi(\n s.costUnknownRuns ? `cost · ${s.costUnknownRuns} runs unpriced` : 'cost',\n `$${s.costUsd.toFixed(2)}`,\n s.costUnknownRuns ? '#e5c07b' : '#e6e6e6',\n )\n : ''\n const stamp = opts.generatedAt ?? capsule.generatedAt ?? ''\n\n return `<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n<title>${esc(capsule.objective)} capsule — ${esc(capsule.target)}</title>\n<style>\n:root{color-scheme:dark}\n*{box-sizing:border-box}\nbody{margin:0;background:#0c0c0f;color:#e6e6e6;font:14px/1.5 ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,sans-serif}\n.wrap{max-width:980px;margin:0 auto;padding:40px 24px}\nh1{font-size:22px;margin:0 0 2px;letter-spacing:-.01em}\n.sub{color:#8a8a93;font-size:13px;margin-bottom:28px}\n.kpis{display:flex;gap:14px;flex-wrap:wrap;margin-bottom:32px}\n.kpi{background:#16161b;border:1px solid #24242b;border-radius:12px;padding:14px 18px;min-width:120px}\n.kv{font-size:24px;font-weight:650;letter-spacing:-.02em}\n.kl{color:#8a8a93;font-size:12px;margin-top:2px}\nh2{font-size:13px;text-transform:uppercase;letter-spacing:.08em;color:#8a8a93;margin:34px 0 14px}\n.axis-label{color:#8a8a93;font-size:12px;margin-bottom:10px}\ntable.heat{border-collapse:separate;border-spacing:6px}\ntable.heat th{font-weight:500;color:#a8a8b0;font-size:12px;padding:4px 8px;text-align:center}\ntable.heat th.rh{text-align:right}\n.tile{position:relative;width:104px;height:66px;border-radius:10px;display:flex;flex-direction:column;justify-content:center;align-items:center;gap:1px;color:#06120a;font-weight:600}\n.tile .tv{font-size:17px}\n.tile .tl{font-size:10px;font-weight:600;opacity:.9;padding:0 6px;text-align:center}\n.tile .dim{font-size:9px;font-weight:600;opacity:.85;background:rgba(0,0,0,.22);padding:0 6px;border-radius:999px}\n.grid{display:flex;flex-wrap:wrap;gap:8px}\n.grid .tile{width:138px;height:74px}\n.fail{background:#16161b;border:1px solid #24242b;border-left:3px solid #d1495b;border-radius:10px;padding:12px 14px;margin-bottom:10px}\n.fmeta{display:flex;gap:10px;align-items:center;font-size:12px;color:#a8a8b0;margin-bottom:8px}\n.fcell{color:#cfcfd6}\n.fclass{background:#2a1a1d;color:#e58a96;padding:1px 8px;border-radius:999px;font-size:11px}\n.fsev{margin-left:auto;color:#e58a96}\n.sevbar{height:4px;background:#24242b;border-radius:2px;overflow:hidden;margin-bottom:10px}\n.sevfill{height:100%;background:#d1495b}\n.ftext{font-size:13px;color:#d8d8df;white-space:pre-wrap}\n.fdims{display:flex;gap:6px;margin-top:8px}\n.fdims .dim{background:#1d2530;color:#9fc1e8;padding:1px 8px;border-radius:999px;font-size:11px}\n.none{color:#5ad17a}\n.foot{color:#5a5a63;font-size:11px;margin-top:36px}\n</style></head><body><div class=\"wrap\">\n<h1>${esc(capsule.objective)} exploration · ${esc(capsule.target)}</h1>\n<div class=\"sub\">${s.totalRuns} scenarios across ${s.cellsCovered}/${s.cellsTotal} planned cells${s.behaviorBinsObserved > 0 ? ` · ${s.behaviorBinsObserved} measured behavior bins` : ''}${stamp ? ` · ${esc(stamp)}` : ''}</div>\n<div class=\"kpis\">\n${s.robustness ? kpi('robustness', `${pct(s.robustness.mean)}`, s.robustness.mean < 0.6 ? '#e58a96' : '#5ad17a') : ''}\n${s.robustness ? kpi('cell spread', `${pct(s.robustness.min)}–${pct(s.robustness.max)}`) : ''}\n${s.latencyMs ? kpi('median latency', `${(s.latencyMs.median / 1000).toFixed(1)}s`, s.latencyMs.p90 > 4 * s.latencyMs.median ? '#e5b566' : '#e6e6e6') : ''}\n${kpi('verified findings', String(s.verifiedFindings), s.verifiedFindings > 0 ? '#e58a96' : '#5ad17a')}\n${kpi('cells covered', `${s.cellsCovered}/${s.cellsTotal}`)}\n${kpi('scenarios run', String(s.totalRuns))}\n${cost}\n${s.evalErrors > 0 ? kpi('eval errors', String(s.evalErrors), '#e5b566') : ''}\n${lift}\n</div>\n${s.stoppedEarly ? `<div class=\"sub\" style=\"color:#e5b566\">stopped early: ${esc(s.stoppedEarly.detail)} — coverage below reflects the completed portion only</div>` : ''}\n<h2>Coverage map</h2>\n${heatmapHtml(capsule.coverage)}\n<h2>Verified findings${s.candidateFindings > s.verifiedFindings ? ` · ${s.verifiedFindings} of ${s.candidateFindings} candidates passed the validity gates` : ''}</h2>\n${findingsHtml(capsule.findings, opts.maxFindings ?? 8)}\n<div class=\"foot\">Findings are gate-verified: each is a fair, answerable task that reproduces under a meaning-preserving rephrase, minimized to the smallest trigger.</div>\n</div></body></html>`\n}\n","/**\n * Adaptive curriculum: active scenario selection by variance.\n *\n * Fixed scenario sets waste sample budget on cells whose outcome is already\n * settled. `varianceBasedCurriculum` scores each (variant, scenario) cell by\n * the empirical variance of past observations and allocates the next round's\n * budget toward the noisy and under-sampled cells. The output is a next-round\n * allocation, a list of (variant, scenario, count) triples, which the\n * consumer runs and feeds back.\n *\n * Choosing which search node to expand is not a curriculum; it belongs to the\n * search policy (`aide` draws parents by Thompson sampling over each node's\n * posterior, in `campaign/search-policy.ts`). Scenario generation belongs to\n * the adversarial primitive.\n */\n\nexport interface CellObservation {\n variantId: string\n scenarioId: string\n /** Observed score in [0, 1]. */\n score: number\n}\n\nexport interface CurriculumAllocation {\n variantId: string\n scenarioId: string\n /** How many additional reps to run on this cell. */\n count: number\n /** Strategy-specific reason for the allocation. */\n reason: string\n}\n\nexport interface VarianceCurriculumOptions {\n /** Total reps to allocate across all cells. */\n budget: number\n /**\n * Smoothing prior on variance — keeps the allocator from concentrating\n * on a cell with one observation just because its 1-sample variance is\n * 0. Default 0.05.\n */\n variancePrior?: number\n /**\n * Minimum reps per cell — even when the variance estimate is low, give\n * every cell at least this many. Default 1.\n */\n floorPerCell?: number\n}\n\n/**\n * Variance-proportional allocation. For each cell, estimate variance from\n * past observations + a prior, then allocate the budget proportional to\n * (sqrt(variance) + 1/sqrt(n)) — a classical optimal-allocation rule\n * (Neyman 1934) that balances \"explore noisy cells\" with \"explore\n * under-sampled cells.\"\n */\nexport function varianceBasedCurriculum(\n observations: CellObservation[],\n candidateCells: Array<{ variantId: string; scenarioId: string }>,\n opts: VarianceCurriculumOptions,\n): CurriculumAllocation[] {\n const variancePrior = opts.variancePrior ?? 0.05\n const floor = opts.floorPerCell ?? 1\n const budget = opts.budget\n\n const grouped = new Map<string, number[]>()\n for (const o of observations) {\n const k = `${o.variantId}::${o.scenarioId}`\n const arr = grouped.get(k) ?? []\n arr.push(o.score)\n grouped.set(k, arr)\n }\n\n const cellStats = candidateCells.map((c) => {\n const k = `${c.variantId}::${c.scenarioId}`\n const samples = grouped.get(k) ?? []\n const n = samples.length\n const mean = n === 0 ? 0.5 : samples.reduce((s, v) => s + v, 0) / n\n const variance =\n n < 2\n ? variancePrior\n : samples.reduce((s, v) => s + (v - mean) ** 2, 0) / (n - 1) + variancePrior\n // Neyman optimal allocation: weight ∝ √variance; add √(1/n) to break\n // ties toward under-sampled cells.\n const weight = Math.sqrt(variance) + 1 / Math.sqrt(Math.max(1, n))\n return { variantId: c.variantId, scenarioId: c.scenarioId, n, mean, variance, weight }\n })\n\n // Reserve floor*N for the floor; allocate the rest proportional to weight.\n const floorTotal = floor * cellStats.length\n if (floorTotal >= budget) {\n const each = Math.max(1, Math.floor(budget / Math.max(1, cellStats.length)))\n return cellStats.map((c) => ({\n variantId: c.variantId,\n scenarioId: c.scenarioId,\n count: each,\n reason: `floor allocation (budget tight; n=${c.n})`,\n }))\n }\n const remaining = budget - floorTotal\n const totalWeight = cellStats.reduce((s, c) => s + c.weight, 0)\n return cellStats.map((c) => {\n const proportional = totalWeight === 0 ? 0 : Math.round((c.weight / totalWeight) * remaining)\n return {\n variantId: c.variantId,\n scenarioId: c.scenarioId,\n count: floor + proportional,\n reason: `variance ${c.variance.toFixed(3)} (n=${c.n}, mean=${c.mean.toFixed(3)})`,\n }\n })\n}\n","/**\n * Shipped policies for the exploration engine.\n *\n * `MutationProposer` is a plain function type — an agent running a generator skill\n * IS a proposer (`(ctx) => dispatchToSkill(ctx)`), no wrapper needed. `mutationProposer`\n * builds the deterministic, LLM-free one from mutation operators. Objectives are\n * interfaces because the engine reads `kind` + `threshold` off them.\n */\n\nimport type { AdversarialMutation } from '../rl/adversarial'\nimport type {\n Cell,\n MutationProposer,\n FuzzObjective,\n FuzzProposeContext,\n} from './types'\n\nconst clamp01 = (x: number): number => Math.max(0, Math.min(1, x))\n\n// ── proposers ─────────────────────────────────────────────────────────────────\n\n/**\n * Perturbation-based search: apply the cell's mutation operators to the current\n * elites + seeds, deduping by id. Elites first — mutating the most interesting\n * scenario found so far is what makes the search deepen across rounds.\n */\nexport function mutationProposer<S>(opts: {\n mutationsFor: (cell: Cell) => AdversarialMutation<S>[]\n scenarioId: (s: S) => string\n}): MutationProposer<S> {\n return async (ctx: FuzzProposeContext<S>): Promise<S[]> => {\n const mutations = opts.mutationsFor(ctx.cell)\n const parents = [...ctx.elites, ...ctx.seeds]\n const seen = new Set(parents.map(opts.scenarioId))\n const out: S[] = []\n for (const parent of parents) {\n if (out.length >= ctx.count) break\n for (const m of mutations) {\n const children = await m.mutate(parent, ctx.rng)\n for (const child of children) {\n const id = opts.scenarioId(child)\n if (seen.has(id)) continue\n seen.add(id)\n out.push(child)\n if (out.length >= ctx.count) break\n }\n if (out.length >= ctx.count) break\n }\n }\n return out\n }\n}\n\n// ── objectives ────────────────────────────────────────────────────────────────\n\n/** Adversarial: a low headline score is interesting — find where the agent fails. */\nexport function adversarialObjective(threshold = 0.5): FuzzObjective {\n return { kind: 'adversarial', threshold, interest: (ev) => clamp01(1 - ev.score) }\n}\n\n\n\n\n","/**\n * The exploration engine — a stateful session over a behavior space.\n *\n * Each `step()`: allocate budget across INPUT cells (floor first, then variance\n * steering toward the least-certain cells), propose candidates (the proposer\n * reads current elites + findings, so the search deepens generationally),\n * evaluate with bounded concurrency, archive the most interesting scenario per\n * input×measured bin, and admit notable candidates that pass the validity gates.\n * `run()` loops to budget. `coverage()`/`findings()`/`capsule()` read live state —\n * the surface `makeExploreTools` exposes so an agent can drive the session.\n *\n * One evaluation log (`EvalRecord[]`) is the source of truth; allocation\n * observations and coverage are projections of it.\n */\n\nimport { CostLedger, type CostLedgerHandle, CostReceiptCaptureError } from '../cost-ledger'\nimport { ValidationError } from '../errors'\nimport { varianceBasedCurriculum } from '../rl/active-curriculum'\nimport { mulberry32 } from '../statistics/random'\nimport { buildCapsule } from './capsule'\nimport type { EvalRecord } from './cube'\nimport { enumerateCells } from './cube'\nimport { adversarialObjective } from './policies'\nimport type {\n ArchiveEntry,\n CapsuleData,\n Cell,\n CoverageCell,\n ExploreOptions,\n FuzzFinding,\n FuzzObjective,\n} from './types'\n\nasync function pMap<T>(\n items: T[],\n fn: (item: T) => Promise<void>,\n concurrency: number,\n signal?: AbortSignal,\n): Promise<void> {\n let i = 0\n const workers = Array.from(\n { length: Math.max(1, Math.min(concurrency, items.length)) },\n async () => {\n while (i < items.length) {\n if (signal?.aborted) return\n const item = items[i++]\n if (item === undefined) return\n await fn(item)\n }\n },\n )\n await Promise.all(workers)\n}\n\nexport class BehaviorExplorer<S> {\n private readonly cells: Cell[]\n private readonly cellById: Map<string, Cell>\n private readonly objective: FuzzObjective\n private readonly threshold: number\n private readonly floorPerCell: number\n private readonly perRoundBudget: number\n\n /** The single evaluation log — coverage + allocation are projections of it. */\n private readonly log: Array<EvalRecord & { scenarioId: string }> = []\n /** binId (input × measured coords) → the most interesting entry seen. */\n private readonly archiveByBin = new Map<string, ArchiveEntry<S>>()\n private readonly _findings: FuzzFinding<S>[] = []\n private runsUsed = 0\n private candidateFindings = 0\n private evalErrors = 0\n private consecutiveEvalErrors = 0\n private stoppedEarly: { reason: 'eval-errors'; detail: string } | undefined\n private readonly rng: () => number\n private readonly costLedger?: CostLedgerHandle\n private readonly costPhase = 'fuzz.explore'\n\n constructor(private readonly opts: ExploreOptions<S>) {\n this.cells = enumerateCells(opts.space)\n if (this.cells.length === 0)\n throw new Error('BehaviorExplorer: space has no cells — every axis needs ≥1 value')\n if (opts.costBudgetUsd !== undefined) {\n if (\n typeof opts.costBudgetUsd !== 'number' ||\n !Number.isFinite(opts.costBudgetUsd) ||\n opts.costBudgetUsd < 0\n ) {\n throw new RangeError(\n `BehaviorExplorer: costBudgetUsd must be a nonnegative finite number, got ${String(opts.costBudgetUsd)}`,\n )\n }\n }\n if (!opts.costOf && (opts.costBudgetUsd !== undefined || opts.ledger || opts.onCost)) {\n throw new ValidationError(\n 'BehaviorExplorer: costBudgetUsd/ledger/onCost require costOf — the explorer ' +\n 'cannot know run cost without it; supply costOf or drop the cost options',\n )\n }\n if (\n (opts.costBudgetUsd !== undefined || opts.ledger?.costCeilingUsd !== undefined) &&\n !opts.maximumChargeOf\n ) {\n throw new ValidationError(\n 'BehaviorExplorer: capped cost tracking requires maximumChargeOf before evaluation',\n )\n }\n if (\n opts.ledger &&\n opts.costBudgetUsd !== undefined &&\n opts.ledger.costCeilingUsd !== opts.costBudgetUsd\n ) {\n throw new ValidationError(\n 'BehaviorExplorer: costBudgetUsd must match the supplied CostLedger ceiling',\n )\n }\n if (opts.costOf) this.costLedger = opts.ledger ?? new CostLedger(opts.costBudgetUsd)\n this.cellById = new Map(this.cells.map((c) => [c.id, c]))\n this.objective = opts.objective ?? adversarialObjective(0.5)\n this.threshold = this.objective.threshold ?? 0.5\n this.floorPerCell = opts.floorPerCell ?? 2\n this.perRoundBudget = Math.max(\n this.cells.length * this.floorPerCell,\n Math.ceil(opts.budget / 4),\n )\n this.rng = mulberry32(opts.seed ?? 1)\n }\n\n private binId(cell: Cell, descriptor: Record<string, string> | undefined): string {\n if (!descriptor || Object.keys(descriptor).length === 0) return cell.id\n const measured = Object.keys(descriptor)\n .sort()\n .map((k) => `${k}=${descriptor[k]}`)\n .join('|')\n return `${cell.id}|${measured}`\n }\n\n private allocate(budget: number): Array<{ cellId: string; count: number }> {\n if ((this.opts.allocation ?? 'variance') === 'uniform') {\n const per = Math.max(this.floorPerCell, Math.floor(budget / this.cells.length))\n return this.cells.map((c) => ({ cellId: c.id, count: per }))\n }\n return varianceBasedCurriculum(\n this.log.map((r) => ({\n variantId: r.cell.id,\n scenarioId: '*',\n score: r.ev.score,\n })),\n this.cells.map((c) => ({ variantId: c.id, scenarioId: '*' })),\n { budget, floorPerCell: this.floorPerCell },\n ).map((a) => ({ cellId: a.variantId, count: a.count }))\n }\n\n private objectiveContext() {\n const entries = [...this.archiveByBin.values()]\n return {\n archiveScores: entries.map((e) => e.evaluation.score),\n archiveDescriptors: entries.map((e) => e.evaluation.descriptor),\n }\n }\n\n /** Elites whose INPUT cell matches — what the proposer mutates/deepens from. */\n private elitesFor(cellId: string): S[] {\n const out: S[] = []\n for (const e of this.archiveByBin.values()) if (e.cell.id === cellId) out.push(e.scenario)\n return out\n }\n\n /** One allocate → propose → evaluate → gate → archive round. */\n async step(): Promise<{ runs: number; findings: FuzzFinding<S>[] }> {\n const remaining = this.opts.budget - this.runsUsed\n if (remaining <= 0 || this.opts.signal?.aborted) return { runs: 0, findings: [] }\n\n const allocations = this.allocate(Math.min(this.perRoundBudget, remaining))\n const newFindings: FuzzFinding<S>[] = []\n let runsThisStep = 0\n\n for (const alloc of allocations) {\n if (\n this.runsUsed >= this.opts.budget ||\n this.stoppedEarly !== undefined ||\n this.opts.signal?.aborted\n )\n break\n const cell = this.cellById.get(alloc.cellId)\n if (!cell) continue\n const cap = Math.min(alloc.count, this.opts.budget - this.runsUsed)\n if (cap <= 0) continue\n this.opts.onProgress?.({ type: 'cell-allocated', cell, count: cap })\n\n const seeds = await this.opts.seedsFor(cell)\n const elites = this.elitesFor(cell.id)\n const proposed = await this.opts.proposer({\n cell,\n seeds,\n elites,\n findings: this._findings,\n count: cap,\n rng: this.rng,\n })\n // Cold cells evaluate their seeds first (the coverage floor); warm cells\n // trust the proposer, which already saw the elites.\n const cold = this.log.every((r) => r.cell.id !== cell.id)\n const toEval = [...(cold ? seeds : []), ...proposed].slice(0, cap)\n\n await pMap(\n toEval,\n async (scenario) => {\n if (\n this.runsUsed >= this.opts.budget ||\n this.stoppedEarly !== undefined ||\n this.opts.signal?.aborted\n )\n return\n // evaluate/gates/minimize cross an external boundary (router, backend,\n // judge). A throw there is an infra outcome: record it as a typed\n // eval-error and keep exploring — one 5xx must not kill a campaign.\n // Consecutive failures trip the circuit breaker instead, so a dead\n // backend stops the run rather than burning the remaining budget.\n try {\n const startedAt = performance.now()\n const paid = this.costLedger\n ? await this.costLedger.runPaidCall({\n channel: 'agent',\n phase: this.costPhase,\n actor: 'fuzz.evaluate',\n tags: { target: this.opts.target, cell: cell.id },\n signal: this.opts.signal,\n maximumCharge: this.opts.maximumChargeOf?.(scenario, cell),\n execute: () => this.opts.evaluate(scenario, cell),\n receipt: (evaluation) => {\n const cost = this.opts.costOf!(scenario, cell, evaluation)\n if (cost === null) {\n return {\n model: 'unattributed',\n inputTokens: 0,\n outputTokens: 0,\n costUnknown: true,\n }\n }\n if (!Number.isFinite(cost.usd) || cost.usd < 0) {\n throw new RangeError(\n `BehaviorExplorer: costOf returned an invalid usd (${String(cost.usd)}) — ` +\n 'return null when cost is unknown, never a fabricated number',\n )\n }\n return {\n model: cost.model ?? 'unattributed',\n inputTokens: 0,\n outputTokens: 0,\n actualCostUsd: cost.usd,\n }\n },\n })\n : undefined\n if (paid && !paid.succeeded) {\n if (\n paid.error instanceof CostReceiptCaptureError &&\n paid.error.receiptError instanceof RangeError\n ) {\n throw paid.error.receiptError\n }\n throw paid.error\n }\n const ev = paid ? paid.value : await this.opts.evaluate(scenario, cell)\n // Consumer-measured latency wins (it can exclude judge time); the\n // engine's wall-clock is the default so latency is never missing.\n const latencyMs = ev.latencyMs ?? performance.now() - startedAt\n this.runsUsed++\n runsThisStep++\n this.consecutiveEvalErrors = 0\n const costUsd = paid\n ? paid.receipt.costUnknown\n ? null\n : paid.receipt.costUsd\n : undefined\n if (paid?.receipt.actualCostUsd !== undefined) {\n this.opts.onCost?.({ usd: paid.receipt.actualCostUsd, channel: 'agent' })\n }\n const interest = this.objective.interest(ev, this.objectiveContext())\n this.log.push({\n cell,\n ev,\n interest,\n latencyMs,\n ...(costUsd !== undefined ? { costUsd } : {}),\n scenarioId: this.opts.scenarioId(scenario),\n })\n this.opts.onProgress?.({ type: 'evaluated', cell, scenario, evaluation: ev })\n\n const bin = this.binId(cell, ev.descriptor)\n const cur = this.archiveByBin.get(bin)\n if (!cur || interest > cur.interest)\n this.archiveByBin.set(bin, { binId: bin, cell, scenario, evaluation: ev, interest })\n\n if (interest < this.threshold) return\n this.candidateFindings++\n if (this.opts.gates?.isValid && !(await this.opts.gates.isValid(scenario, ev, cell)))\n return\n if (\n this.opts.gates?.isUncontaminated &&\n !(await this.opts.gates.isUncontaminated(scenario, ev, cell))\n )\n return\n\n const minimized = this.opts.minimize\n ? await this.opts.minimize(scenario, this.opts.evaluate, cell)\n : scenario\n const finding: FuzzFinding<S> = {\n id: this.opts.scenarioId(scenario),\n cell,\n scenario,\n minimized,\n text: this.opts.scenarioText?.(minimized),\n evaluation: ev,\n interest,\n objective: this.objective.kind,\n }\n this._findings.push(finding)\n newFindings.push(finding)\n this.opts.onProgress?.({ type: 'finding', finding })\n } catch (err) {\n // Internal validation errors (e.g. a fabricated costOf number) are\n // programming mistakes, not backend outcomes — they stay loud.\n if (err instanceof RangeError) throw err\n this.evalErrors++\n this.consecutiveEvalErrors++\n const message = err instanceof Error ? err.message : String(err)\n this.opts.onProgress?.({\n type: 'eval-error',\n cell,\n scenarioId: this.opts.scenarioId(scenario),\n message,\n })\n const limit = this.opts.maxConsecutiveEvalErrors ?? 5\n if (this.consecutiveEvalErrors >= limit) {\n this.stoppedEarly = {\n reason: 'eval-errors',\n detail: `${this.consecutiveEvalErrors} consecutive eval errors (last: ${message})`,\n }\n }\n }\n },\n this.opts.concurrency ?? 1,\n this.opts.signal,\n )\n }\n\n this.opts.onProgress?.({ type: 'round', runsUsed: this.runsUsed, budget: this.opts.budget })\n return { runs: runsThisStep, findings: newFindings }\n }\n\n /** Loop `step()` until the run or dollar budget is spent, the signal aborts,\n * or no progress is made. */\n async run(): Promise<CapsuleData<S>> {\n while (\n this.runsUsed < this.opts.budget &&\n this.stoppedEarly === undefined &&\n !this.opts.signal?.aborted\n ) {\n const { runs } = await this.step()\n if (runs === 0 && this.stoppedEarly === undefined) break\n }\n return this.capsule()\n }\n\n coverage(): CoverageCell[] {\n return this.capsule().coverage\n }\n\n findings(): FuzzFinding<S>[] {\n return [...this._findings].sort((a, b) => b.interest - a.interest)\n }\n\n capsule(): CapsuleData<S> {\n const cost = this.costLedger?.summary({\n phase: this.costPhase,\n tags: { target: this.opts.target },\n })\n return buildCapsule({\n target: this.opts.target,\n objective: this.objective.kind,\n cells: this.cells,\n log: this.log,\n threshold: this.threshold,\n archive: [...this.archiveByBin.values()],\n findings: this._findings,\n candidateFindings: this.candidateFindings,\n runsUsed: this.runsUsed,\n cost: cost\n ? {\n costUsd: cost.totalCostUsd,\n costUnknownRuns: cost.byChannel.reduce((sum, row) => sum + row.unpricedCalls, 0),\n }\n : undefined,\n evalErrors: this.evalErrors,\n stoppedEarly: this.stoppedEarly,\n })\n }\n}\n","/**\n * `fuzzAgent` — the adversarial batch preset over `BehaviorExplorer`.\n *\n * One call: explore the space to budget with the adversarial objective and\n * return the capsule. For agent-driven, incremental, or multi-objective use,\n * construct a `BehaviorExplorer` and drive it via `makeExploreTools`.\n */\n\nimport { BehaviorExplorer } from './explorer'\nimport { adversarialObjective } from './policies'\nimport type { CapsuleData, ExploreOptions } from './types'\n\nexport type FuzzAgentOptions<S> = Omit<ExploreOptions<S>, 'objective'> & {\n /** Score strictly below this is a candidate failure. Default 0.5. */\n failureThreshold?: number\n}\n\nexport async function fuzzAgent<S>(\n opts: FuzzAgentOptions<S>,\n): Promise<{ capsule: CapsuleData<S> }> {\n const { failureThreshold, ...rest } = opts\n const explorer = new BehaviorExplorer<S>({\n ...rest,\n objective: adversarialObjective(failureThreshold ?? 0.5),\n })\n return { capsule: await explorer.run() }\n}\n","/**\n * Validity gates — what separates a fuzzer from a slop generator.\n *\n * A notable candidate is admitted only when it is fair and reproducible. None of\n * these are on by default: the live wiring opts in, so reported findings carry\n * their proof.\n */\n\nimport type { Cell, Evaluation, Evaluator, ValidityGates } from './types'\n\n/** Combine gate sets; a candidate must pass every gate in every set. */\nexport function composeGates<S>(...sets: Array<ValidityGates<S> | undefined>): ValidityGates<S> {\n const present = sets.filter((s): s is ValidityGates<S> => s != null)\n return {\n isValid: async (scenario, ev, cell) => {\n for (const g of present) {\n if (g.isValid && !(await g.isValid(scenario, ev, cell))) return false\n }\n return true\n },\n isUncontaminated: async (scenario, ev, cell) => {\n for (const g of present) {\n if (g.isUncontaminated && !(await g.isUncontaminated(scenario, ev, cell))) return false\n }\n return true\n },\n }\n}\n\n/**\n * Reproducibility gate. Re-run the target on a meaning-preserving rephrase of the\n * flagged scenario; keep the finding only when the rephrase ALSO scores below the\n * threshold. A finding that flips under a cosmetic rewrite was keyed to surface\n * form, not the task — a false signal we must not report. Costs one extra\n * evaluation per candidate (candidates are rare, so cheap).\n */\nexport function perturbationStabilityGate<S>(opts: {\n evaluate: Evaluator<S>\n /** Produce a semantic-preserving rephrase. Return null to skip (treated as pass). */\n perturb: (scenario: S) => S | null\n /** Score strictly below this still counts as failing. Default 0.5. */\n failureThreshold?: number\n}): ValidityGates<S> {\n const threshold = opts.failureThreshold ?? 0.5\n return {\n isUncontaminated: async (scenario: S, _ev: Evaluation, cell: Cell) => {\n const rephrased = opts.perturb(scenario)\n if (rephrased == null) return true\n const re = await opts.evaluate(rephrased, cell)\n return re.score < threshold\n },\n }\n}\n\n/**\n * Severity-floor gate. Reject borderline candidates whose score sits in a band\n * just under the threshold — judge noise, not a real defect.\n */\nexport function severityFloorGate<S>(opts: {\n failureThreshold?: number\n margin?: number\n}): ValidityGates<S> {\n const threshold = opts.failureThreshold ?? 0.5\n const margin = opts.margin ?? 0.1\n return {\n isValid: (_scenario, ev: Evaluation) => ev.score <= threshold - margin,\n }\n}\n"],"mappings":";;;;;AA2BA,SAAgB,eAAe,OAA8B;CAC3D,IAAI,MAAM,KAAK,WAAW,GAAG,OAAO,CAAC;CACrC,IAAI,WAA0C,CAAC,CAAC,CAAC;CACjD,KAAK,MAAM,QAAQ,MAAM,MAAM;EAC7B,MAAM,OAAsC,CAAC;EAC7C,KAAK,MAAM,WAAW,UACpB,KAAK,MAAM,SAAS,KAAK,QAAQ,KAAK,KAAK;GAAE,GAAG;IAAU,KAAK,OAAO;EAAM,CAAC;EAE/E,WAAW;CACb;CACA,OAAO,SAAS,KAAK,YAAY;EAAE,IAAI,OAAO,OAAO,MAAM;EAAG;CAAO,EAAE;AACzE;;AAGA,SAAgB,OAAO,OAAsB,QAAwC;CACnF,OAAO,MAAM,KAAK,KAAK,MAAM,GAAG,EAAE,KAAK,GAAG,OAAO,EAAE,OAAO,CAAC,CAAC,KAAK,GAAG;AACtE;;AAGA,SAAS,WAAW,QAAkB,GAAmB;CAEvD,OAAO,OADK,KAAK,IAAI,OAAO,SAAS,GAAG,KAAK,IAAI,GAAG,KAAK,KAAK,IAAI,OAAO,MAAM,IAAI,CAAC,CACpE;AAClB;;;AAIA,SAAgB,aAAa,QAAgC;CA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AC;CACH;AACF;;;;;;;;;;AC5XA,eAAsB,UACpB,MACsC;CACtC,MAAM,EAAE,kBAAkB,GAAG,SAAS;CAKtC,OAAO,EAAE,SAAS,MAAM,IAJH,iBAAoB;EACvC,GAAG;EACH,WAAW,qBAAqB,oBAAoB,EAAG;CACzD,CAC+B,CAAC,CAAC,IAAI,EAAE;AACzC;;;;ACfA,SAAgB,aAAgB,GAAG,MAA6D;CAC9F,MAAM,UAAU,KAAK,QAAQ,MAA6B,KAAK,IAAI;CACnE,OAAO;EACL,SAAS,OAAO,UAAU,IAAI,SAAS;GACrC,KAAK,MAAM,KAAK,SACd,IAAI,EAAE,WAAW,CAAE,MAAM,EAAE,QAAQ,UAAU,IAAI,IAAI,GAAI,OAAO;GAElE,OAAO;EACT;EACA,kBAAkB,OAAO,UAAU,IAAI,SAAS;GAC9C,KAAK,MAAM,KAAK,SACd,IAAI,EAAE,oBAAoB,CAAE,MAAM,EAAE,iBAAiB,UAAU,IAAI,IAAI,GAAI,OAAO;GAEpF,OAAO;EACT;CACF;AACF;;;;;;;;AASA,SAAgB,0BAA6B,MAMxB;CACnB,MAAM,YAAY,KAAK,oBAAoB;CAC3C,OAAO,EACL,kBAAkB,OAAO,UAAa,KAAiB,SAAe;EACpE,MAAM,YAAY,KAAK,QAAQ,QAAQ;EACvC,IAAI,aAAa,MAAM,OAAO;EAE9B,QAAO,MADU,KAAK,SAAS,WAAW,IAAI,EAAA,CACpC,QAAQ;CACpB,EACF;AACF;;;;;AAMA,SAAgB,kBAAqB,MAGhB;CACnB,MAAM,YAAY,KAAK,oBAAoB;CAC3C,MAAM,SAAS,KAAK,UAAU;CAC9B,OAAO,EACL,UAAU,WAAW,OAAmB,GAAG,SAAS,YAAY,OAClE;AACF"}
@@ -1,5 +1,5 @@
1
- import { a as assertMinted, c as assertRolloutLine, d as isTrainableSplit, h as GATE_POLICIES, m as GATE_CHECK_IDS, n as ROLLOUT_ROLES, r as ROLLOUT_SCHEMA, v as undeclaredStepPayload } from "./schema-BuiujZ-g.js";
2
- import { l as toVerifiersRolloutOutputs, o as toRftItems, r as toJsonl, s as toSftRows } from "./exporters-X4xwla8A.js";
1
+ import { a as assertMinted, c as assertRolloutLine, d as isTrainableSplit, h as GATE_POLICIES, m as GATE_CHECK_IDS, n as ROLLOUT_ROLES, r as ROLLOUT_SCHEMA, v as undeclaredStepPayload } from "./schema-CvhfLjtZ.js";
2
+ import { a as toRftItems, o as toSftRows, r as toJsonl, s as toVerifiersRolloutOutputs } from "./exporters-DWvM16LE.js";
3
3
  import { basename, dirname, join } from "node:path";
4
4
  import { spawnSync } from "node:child_process";
5
5
  import { appendFile, mkdir, readFile, writeFile } from "node:fs/promises";
@@ -49,26 +49,6 @@ async function appendRolloutLines(path, lines) {
49
49
  async function readRolloutLedger(path) {
50
50
  return readLines(path, (parsed, context) => assertMinted(parsed, context));
51
51
  }
52
- /**
53
- * Read a ledger under the WRITE-side policy (`validateRolloutLine`), which
54
- * omits the unscreened-reward check. `writeRolloutLedger` accepts a
55
- * supervision-journal row (`realness_screened: false` with a positive reward
56
- * — the documented `unscreenedRewardFields` shape), and `GATE_POLICIES` says
57
- * such rows "must stay writable, readable and reportable"; a read API that
58
- * only re-validated under `assertMinted` made every such file unreadable —
59
- * write-accepted but read-refused is a data-loss trap.
60
- *
61
- * The result is `RolloutLine[]`, NOT `MintedRolloutLine[]`: nothing read here
62
- * can reach a training exporter without passing `assertMinted`, so the
63
- * promotion gate (which DOES enforce unscreened-reward) is exactly as closed
64
- * as before. Use `readRolloutLedger` when the file is training data.
65
- */
66
- async function readRolloutJournal(path) {
67
- return readLines(path, (parsed, context) => {
68
- assertRolloutLine(parsed, context);
69
- return parsed;
70
- });
71
- }
72
52
  async function readLines(path, admit) {
73
53
  const raw = await readFile(path, "utf8");
74
54
  const lines = [];
@@ -758,6 +738,6 @@ async function runRolloutReleaseCli(argv) {
758
738
  return 0;
759
739
  }
760
740
  //#endregion
761
- export { writeRolloutLedger as S, measureFormatGate as _, addScrubCounts as a, readRolloutJournal as b, scrubLines as c, FORMAT_FILES as d, RELEASE_FORMATS as f, gatedRolloutIds as g, assertGateReport as h, runRolloutReleaseCli as i, scrubRolloutLine as l, FORMAT_GATE_DISPOSITION as m, parseRolloutReleaseArgs as n, defaultRolloutScrubber as o, buildDatasetCard as p, planPushCommand as r, emptyScrubCounts as s, buildHfDataset as t, scrubText as u, releaseRowRefs as v, readRolloutLedger as x, appendRolloutLines as y };
741
+ export { scrubText as a, appendRolloutLines as c, scrubLines as i, readRolloutLedger as l, runRolloutReleaseCli as n, buildDatasetCard as o, defaultRolloutScrubber as r, assertGateReport as s, buildHfDataset as t, writeRolloutLedger as u };
762
742
 
763
- //# sourceMappingURL=hf-dataset-BR2yhuNn.js.map
743
+ //# sourceMappingURL=hf-dataset-CKxIJQba.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hf-dataset-CKxIJQba.js","names":[],"sources":["../src/rollout/ledger.ts","../src/rollout/release/gate-report.ts","../src/rollout/release/card.ts","../src/rollout/release/scrub.ts","../src/rollout/release/hf-dataset.ts"],"sourcesContent":["/**\n * Rollout-ledger file API — append-only JSONL of validated `tangle.rollout.v1`\n * lines. Writes validate BEFORE touching disk (a bad line never lands);\n * reads validate line-by-line and fail loud with the line number, because a\n * silently-skipped rollout is a corrupted dataset.\n *\n * \"Validate\" includes the anti-Goodhart invariant (a realness-gated line may\n * not carry a positive reward), so a poisoned line can neither enter a ledger\n * nor leave one.\n *\n * Two read modes, matching the two write-side row classes: `readRolloutLedger`\n * re-validates under the mint policy (training data), `readRolloutJournal`\n * under the write policy (supervision journals, whose unscreened positive\n * rewards are writable and must stay readable).\n */\n\nimport { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { dirname } from 'node:path'\nimport { assertMinted, assertRolloutLine, type MintedRolloutLine, type RolloutLine } from './schema'\n\nfunction serialize(lines: RolloutLine[]): string {\n for (const [i, line] of lines.entries()) assertRolloutLine(line, `rollout line [${i}]`)\n return lines.map((line) => JSON.stringify(line)).join('\\n') + (lines.length > 0 ? '\\n' : '')\n}\n\n/** Replace the ledger file with exactly `lines`. */\nexport async function writeRolloutLedger(path: string, lines: RolloutLine[]): Promise<void> {\n const payload = serialize(lines)\n await mkdir(dirname(path), { recursive: true })\n await writeFile(path, payload)\n}\n\n/** Append `lines` to the ledger file (created if absent). */\nexport async function appendRolloutLines(path: string, lines: RolloutLine[]): Promise<void> {\n if (lines.length === 0) return\n const payload = serialize(lines)\n await mkdir(dirname(path), { recursive: true })\n await appendFile(path, payload)\n}\n\n/**\n * Read and validate every line. Throws on the first malformed/invalid line\n * (with its 1-based line number) — fail-closed, never a silent drop.\n *\n * Validation includes the anti-Goodhart invariant, which is why the result is\n * `MintedRolloutLine[]`: a ledger file is the main way a rollout reaches this\n * process from outside the type system (another run, another machine, a\n * hand-edited JSONL), so this read is the runtime boundary where a poisoned\n * line is refused rather than exported.\n */\nexport async function readRolloutLedger(path: string): Promise<MintedRolloutLine[]> {\n return readLines(path, (parsed, context) => assertMinted(parsed, context))\n}\n\n\n\nasync function readLines<T>(\n path: string,\n admit: (parsed: unknown, context: string) => T,\n): Promise<T[]> {\n const raw = await readFile(path, 'utf8')\n const lines: T[] = []\n const rawLines = raw.split('\\n')\n for (let i = 0; i < rawLines.length; i++) {\n const text = rawLines[i]\n if (!text?.trim()) continue\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch (error) {\n throw new Error(\n `${path}:${i + 1}: malformed JSON — ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n lines.push(admit(parsed, `${path}:${i + 1}`))\n }\n return lines\n}\n","/**\n * Per-format accounting of the anti-Goodhart gate for one dataset release.\n *\n * The defect this exists to make impossible: a dataset card that STATES what\n * the gate does while the build does something else. A sentence in a README is\n * a claim about bytes it never reads, so it drifts the moment an exporter\n * changes — and the drift ships to whoever downloads the dataset.\n *\n * So the card is not allowed to assert anything about the gate. The build\n * measures the rows it is ABOUT TO WRITE (`measureFormatGate`), the measurement\n * is checked against the declared per-format disposition (`assertGateReport`,\n * which throws rather than warns), and the card renders only numbers handed to\n * it. A card that disagrees with its own data files cannot be produced without\n * failing the build first.\n *\n * The dispositions themselves are the release policy, stated once as data:\n *\n * sft EXCLUDE — an SFT row is an imitation target. A gamed\n * trajectory must never be imitated, at any weight.\n * verifiers ZERO_AND_FLAG — reward is a signed learning signal here, so a\n * gamed trajectory at reward 0 is a correct\n * negative. Dropping it would bias the negative\n * population toward honest failures and leave a\n * trainer no example of what gaming looks like\n * when it is penalized.\n * rft ZERO_AND_FLAG — RFT re-samples the completion; only the prompt\n * and the grader's `reference.*` verdict ship, so\n * nothing gamed is imitated. The flag is what lets\n * a grader author skip the instance.\n * raw ZERO_AND_FLAG — a faithful audit dump. Removing rows from it\n * would defeat its only purpose, and the gated\n * row is the one an auditor most wants.\n *\n * `ZERO_AND_FLAG` is never `reward: 0` alone. Zeroing without the label makes a\n * faked success indistinguishable from an honest failure — it hides the gamed\n * population from the buyer instead of disclosing it. Every included format\n * carries `realness_gated` on the row itself.\n *\n * And `ZERO_AND_FLAG` means the whole outcome, not the scalar. A gated row that\n * ships `reward: 0` beside the per-layer verifier scores the reward was\n * computed from has not been zeroed in any sense a trainer respects; the\n * accounting therefore measures every reward-derived number each format writes,\n * not just the one field.\n */\n\nimport type { RftItem, SftRow, VerifiersRolloutOutput } from '../exporters'\nimport {\n GATE_CHECK_IDS,\n GATE_POLICIES,\n type GateCheckId,\n undeclaredStepPayload,\n} from '../gate-checks'\nimport type { MintedRolloutLine } from '../schema'\nimport type { ReleaseFormat } from './card'\n\n/** What a format does with a line the realness gate flagged. */\nexport type GateDisposition = 'exclude' | 'zero-and-flag'\n\nexport const FORMAT_GATE_DISPOSITION: Record<ReleaseFormat, GateDisposition> = {\n sft: 'exclude',\n verifiers: 'zero-and-flag',\n rft: 'zero-and-flag',\n raw: 'zero-and-flag',\n}\n\n/** What the gate accounting reads off an emitted row, per format. */\nexport interface ReleaseRowRef {\n rollout_id: string\n reward: number | null\n /**\n * The rest of the row that was DERIVED from the reward — the per-layer score\n * dict, the judge verdict record, whatever this format ships beside the\n * scalar. Walked for positive numbers, so the certification is about the\n * whole outcome rather than one field.\n *\n * Absent when the format's row carries nothing but the scalar. NOT the whole\n * row: `cost.tokens_in`, `wall_s` and `total_steps` are positive numbers that\n * have nothing to do with the reward, and a certification that flags them is\n * a certification nobody can act on.\n */\n evidence?: unknown\n /**\n * The screen claim AS EMITTED — read off the row, not off the line it came\n * from, because what ships is what matters. Required, not optional: an\n * optional field is how a format quietly opts out of the check that reads it,\n * and every emitted row shape carries `RealnessLabels` precisely so no adapter\n * has to.\n */\n realness_screened: boolean | null\n /**\n * The part of an emitted `steps[]` the wire format does not declare.\n *\n * Separate from `evidence` because the declared step fields are FULL of\n * legitimate positive numbers — `durationMs`, `llm_call_count`,\n * `prompt_token_ids` — and a certification that flags those is one nobody can\n * act on. Only the undeclared remainder is unclassified reward-bearing\n * payload, which is the same partition the check applies.\n *\n * Set only by formats whose row carries steps: today `raw` alone.\n */\n stepEvidence?: unknown\n}\n\n/** A positive number found inside an emitted gated row, with where it was. */\nexport interface EmittedEvidence {\n /** JSON-ish path from the row's evidence root, e.g. `metrics['layer.tests']`. */\n path: string\n value: number\n}\n\nexport interface FormatGateCounts {\n /** Gated lines that reached this format's exporter. */\n input: number\n /** Gated rows the format actually wrote. */\n emitted: number\n /**\n * Gated lines this format did not write. Not all of these are the gate:\n * `verifiers` also drops gap lines (empty transcript) and `rft` drops lines\n * with no prompt turn, so an excluded count can mix both causes.\n */\n excluded: number\n /** Highest reward on an emitted gated row; `null` when none was emitted. */\n maxEmittedReward: number | null\n /**\n * The largest positive number found in the reward-DERIVED payload of an\n * emitted gated row, and its path; `null` when there is none.\n *\n * This column exists because the release once certified CLEAN while leaking.\n * `assertGateReport` inspected `outcome.reward` alone, so a gated row shipping\n * `reward: 0` next to `metrics['layer.tests']: 1` — the deterministic verifier\n * score the reward was computed from, and the per-rubric score dict of the\n * Prime Intellect verifiers format — passed, and the card rendered \"max reward\n * | 0\" over a file that carried the gamed signal at full value. A wrong\n * certification is worse than the leak: it is the leak plus a document saying\n * there isn't one.\n */\n maxEmittedEvidence: EmittedEvidence | null\n /**\n * Rows this format wrote carrying a positive reward whose producer DECLARED\n * that no authenticity screen ever ran on it (`realness_screened: false`).\n *\n * Measured over EVERY emitted row, not just the gated ones: an unscreened\n * reward is by definition one the gate never had a verdict on, so it is not in\n * the gated set and a measurement scoped to that set would report 0 forever.\n * `assertMinted` already refuses these, which is exactly why the release still\n * measures them — the last door before a public dataset does not get to assume\n * the earlier doors held.\n */\n unscreenedPositiveRows: number\n /** Highest reward on such a row; `null` when there is none. */\n maxUnscreenedReward: number | null\n /**\n * The largest positive number found in an emitted gated row's UNDECLARED\n * per-step payload, and its path; `null` when there is none.\n *\n * The column exists because the gate read `outcome` and nothing else for\n * three rounds, so a gated line shipping `steps: [{kind, name, reward: 0.86}]`\n * certified clean — the release accounting agreed with the exporter that a\n * per-step reward was not a reward.\n */\n maxEmittedStepEvidence: EmittedEvidence | null\n}\n\nexport interface GateReport {\n /** Gated lines in the release input, after the split/proposer filters. */\n gatedLines: number\n byFormat: Partial<Record<ReleaseFormat, FormatGateCounts>>\n}\n\n/** Rollout ids of every gated line, the key the emitted rows are matched on. */\nexport function gatedRolloutIds(lines: readonly MintedRolloutLine[]): Set<string> {\n return new Set(lines.filter((line) => line.outcome.realness_gated).map((line) => line.rollout_id))\n}\n\n/**\n * Row refs per format. Written as one adapter per format so that the knowledge\n * of WHERE the id and reward live in each published shape sits next to the\n * assertion that uses it — an exporter that moves either field breaks here\n * rather than silently reporting zero gated rows.\n */\nexport const releaseRowRefs = {\n // An SFT row is `{messages, metadata}` and `metadata` holds ids plus the\n // scalar — no reward-derived payload beyond `reward` itself, and the gated\n // disposition is EXCLUDE anyway.\n sft: (rows: readonly SftRow[]): ReleaseRowRef[] =>\n rows.map((row) => ({\n rollout_id: row.metadata.rollout_id,\n reward: row.metadata.reward,\n realness_screened: row.metadata.realness_screened,\n })),\n // `metrics` IS the per-rubric score dict in the Prime Intellect verifiers\n // format — the same numbers the reward was computed from. This is the leak\n // that shipped.\n verifiers: (rows: readonly VerifiersRolloutOutput[]): ReleaseRowRef[] =>\n rows.map((row) => ({\n rollout_id: row.info.rollout_id,\n reward: row.reward,\n evidence: row.metrics,\n realness_screened: row.info.realness_screened,\n })),\n // RFT re-samples the completion, but the grader reads `item.reference.*`, so\n // the verbatim judge verdict is a reward-bearing field on the row.\n rft: (rows: readonly RftItem[]): ReleaseRowRef[] =>\n rows.map((row) => ({\n rollout_id: row.reference.rollout_id,\n reward: row.reference.reward,\n evidence: row.reference.verdict,\n realness_screened: row.reference.realness_screened,\n })),\n raw: (lines: readonly MintedRolloutLine[]): ReleaseRowRef[] =>\n lines.map((line) => ({\n rollout_id: line.rollout_id,\n reward: line.outcome.reward,\n // `provenance.gated_evidence` is deliberately NOT walked: relocating the\n // diagnostics there is what the gate DOES, and the raw config is the\n // audit dump those diagnostics exist for.\n evidence: { metrics: line.outcome.metrics, verdict: line.outcome.verdict },\n // `raw` is the only config that writes the whole line, so it is the only\n // one whose rows can carry a per-step reward.\n stepEvidence: undeclaredStepPayload(line.steps),\n realness_screened: line.outcome.realness_screened ?? null,\n })),\n}\n\n/** Every positive finite number inside a row's reward-derived payload, with its path. */\nfunction positiveNumbersIn(value: unknown, path: string): EmittedEvidence[] {\n if (typeof value === 'number') {\n return Number.isFinite(value) && value > 0 ? [{ path, value }] : []\n }\n if (Array.isArray(value)) {\n return value.flatMap((item, i) => positiveNumbersIn(item, `${path}[${i}]`))\n }\n if (typeof value === 'object' && value !== null) {\n return Object.entries(value).flatMap(([key, child]) =>\n positiveNumbersIn(child, path === '' ? key : `${path}.${key}`),\n )\n }\n return []\n}\n\n/** Measure one format's gated rows from the refs of the rows about to be written. */\nexport function measureFormatGate(\n gated: ReadonlySet<string>,\n refs: readonly ReleaseRowRef[],\n): FormatGateCounts {\n const emitted = refs.filter((ref) => gated.has(ref.rollout_id))\n const rewards = emitted.map((ref) => ref.reward).filter((r): r is number => r !== null)\n const evidence = emitted.flatMap((ref) => positiveNumbersIn(ref.evidence, ''))\n const stepEvidence = emitted.flatMap((ref) => positiveNumbersIn(ref.stepEvidence, 'steps'))\n const unscreened = refs\n .filter((ref) => ref.realness_screened === false)\n .map((ref) => ref.reward)\n .filter((r): r is number => r !== null && r > 0)\n return {\n input: gated.size,\n emitted: emitted.length,\n excluded: gated.size - emitted.length,\n maxEmittedReward: rewards.length === 0 ? null : Math.max(...rewards),\n maxEmittedEvidence: evidence.reduce<EmittedEvidence | null>(\n (best, found) => (best === null || found.value > best.value ? found : best),\n null,\n ),\n unscreenedPositiveRows: unscreened.length,\n maxUnscreenedReward: unscreened.length === 0 ? null : Math.max(...unscreened),\n maxEmittedStepEvidence: stepEvidence.reduce<EmittedEvidence | null>(\n (best, found) => (best === null || found.value > best.value ? found : best),\n null,\n ),\n }\n}\n\n/**\n * The measured form of each canonical gate check, over the rows a release is\n * ABOUT TO WRITE. Returns the failure message, or `null` when the format is\n * clean on that check.\n *\n * TOTAL over `GateCheckId` — this map and `GATE_POLICIES.assertGateReport` are\n * the two things a new check breaks here, so the release certifier cannot be\n * left behind by a check added anywhere else in the package. That is the whole\n * point: for four rounds each guard composed its own subset by hand, and a\n * release certifying CLEAN while leaking is the most expensive version of that\n * mistake, because it is the leak plus a document saying there isn't one.\n */\nconst REPORT_MEASURES: {\n readonly [K in GateCheckId]: (format: ReleaseFormat, counts: FormatGateCounts) => string | null\n} = {\n 'reward-relationship': (format, counts) =>\n counts.maxEmittedReward === null || counts.maxEmittedReward <= 0\n ? null\n : `release format \"${format}\": ${counts.emitted} realness-gated row(s) carry a positive ` +\n `reward (max ${counts.maxEmittedReward}). A run flagged as gamed may not ship a ` +\n 'positive reward in any config.',\n 'gated-evidence': (format, counts) => {\n if (counts.maxEmittedEvidence === null) return null\n const { path, value } = counts.maxEmittedEvidence\n return (\n `release format \"${format}\": ${counts.emitted} realness-gated row(s) carry a positive ` +\n `reward-derived number (${path} = ${value}). Zeroing the scalar is not enough — the ` +\n 'per-layer scores and judge verdict a fabricated reward was computed FROM are the ' +\n 'same signal in component form, and in this format they are read as training input. ' +\n 'They belong in `provenance.gated_evidence` (see `gateGamedOutcome`), not on the row.'\n )\n },\n 'undeclared-step-payload': (format, counts) => {\n if (counts.maxEmittedStepEvidence === null) return null\n const { path, value } = counts.maxEmittedStepEvidence\n return (\n `release format \"${format}\": ${counts.emitted} realness-gated row(s) carry a positive ` +\n `per-step number under a field \\`tangle.rollout.v1\\` does not declare (${path} = ${value}). ` +\n 'A per-step reward is the same training signal as the scalar, in credit-assignment form, ' +\n 'and the exporters copy `steps` through verbatim — so the row ships it beside a `reward` ' +\n 'of 0. It belongs in `provenance.gated_evidence.steps` (see `gateGamedOutcome`).'\n )\n },\n 'unscreened-reward': (format, counts) =>\n counts.maxUnscreenedReward === null\n ? null\n : `release format \"${format}\": ${counts.unscreenedPositiveRows} row(s) carry a positive ` +\n `reward (max ${counts.maxUnscreenedReward}) whose producer declares that NO authenticity ` +\n 'screen ran on it (`realness_screened: false`). Nothing has established those successes ' +\n 'are real, and a published dataset may not present an unqualified verdict as a measured ' +\n 'one. Screen the runs, or publish them at `reward: null`.',\n}\n\n/**\n * Fail the build when the measurement disagrees with the declared policy.\n *\n * Throws, never filters: an emitted positive reward on a gated row means an\n * exporter upstream stopped applying the gate, and silently dropping the row\n * would hide the producer that made it — the producer is the actual defect.\n *\n * Certifies the whole emitted outcome, not `reward` alone. The earlier version\n * checked one field and therefore certified a release CLEAN while its\n * `verifiers/train.jsonl` shipped the gamed run's per-layer scores at 1.0 in\n * the top-level `metrics` dict — the card then rendered \"max reward | 0\" over\n * exactly that file. A certification that is wrong is worse than an\n * uncertified leak, so the checks it runs are no longer written down here at\n * all: it iterates `GATE_CHECK_IDS` under its own declared policy.\n */\nexport function assertGateReport(report: GateReport): void {\n for (const [format, counts] of Object.entries(report.byFormat) as Array<\n [ReleaseFormat, FormatGateCounts]\n >) {\n for (const id of GATE_CHECK_IDS) {\n if (GATE_POLICIES.assertGateReport[id].kind !== 'enforce') continue\n const failure = REPORT_MEASURES[id](format, counts)\n if (failure !== null) throw new Error(failure)\n }\n // Not a gate check: this one is the RELEASE POLICY (`FORMAT_GATE_DISPOSITION`)\n // rather than the anti-Goodhart invariant — it asks whether the format did\n // what it said it would with gated rows, not whether a row is poisoned.\n if (FORMAT_GATE_DISPOSITION[format] === 'exclude' && counts.emitted > 0) {\n throw new Error(\n `release format \"${format}\" declares gated lines EXCLUDED but wrote ${counts.emitted} ` +\n 'of them.',\n )\n }\n }\n}\n","/**\n * HuggingFace dataset-card (README.md) generation for a rollout-ledger release.\n *\n * The card is a pure function of the SCRUBBED lines plus the release options —\n * no timestamps, no environment reads — so rebuilding from the same ledger\n * yields byte-identical output. It documents the schema, provenance (run ids,\n * generations, the official judge), per-role reward semantics including the\n * inherited/contribution caveat, and a role × reward counts table.\n */\n\nimport { type MintedRolloutLine, ROLLOUT_ROLES, ROLLOUT_SCHEMA, type RolloutRole } from '../schema'\nimport { assertGateReport, FORMAT_GATE_DISPOSITION, type GateReport } from './gate-report'\nimport type { ScrubCounts } from './scrub'\n\nexport const RELEASE_FORMATS = ['sft', 'verifiers', 'rft', 'raw'] as const\nexport type ReleaseFormat = (typeof RELEASE_FORMATS)[number]\n\n/** Format → data file path inside the dataset dir (train split only). */\nexport const FORMAT_FILES: Record<ReleaseFormat, string> = {\n sft: 'sft/train.jsonl',\n verifiers: 'verifiers/train.jsonl',\n rft: 'rft/train.jsonl',\n raw: 'raw/train.jsonl',\n}\n\nconst FORMAT_DESCRIPTIONS: Record<ReleaseFormat, string> = {\n sft: 'Successful trainable-split transcripts (`reward >= 1`, never realness-gated) as `{messages, metadata}` chat JSONL.',\n verifiers:\n 'Prime Intellect verifiers `RolloutOutput`: prompt/completion split at the first assistant turn, plus reward, metrics, tool defs, and token usage.',\n rft: 'OpenAI RFT items: prompt turns plus `reference.*` verdict fields for a grader (completions are re-sampled during RFT).',\n raw: `Full \\`${ROLLOUT_SCHEMA}\\` ledger lines (scrubbed), one per agent invocation.`,\n}\n\nexport interface DatasetCardInputs {\n /** Scrubbed, release-filtered lines (what actually ships). */\n lines: MintedRolloutLine[]\n formats: ReleaseFormat[]\n includeProposers: boolean\n /** Source ledger basenames, for provenance. */\n sourceFiles: string[]\n scrubTotals: ScrubCounts\n excluded: { proposers: number; nonTrain: number }\n formatCounts: Partial<Record<ReleaseFormat, number>>\n /**\n * Per-format anti-Goodhart accounting MEASURED on the rows the build wrote.\n * Required, not optional: the card's only statement about the gate is a\n * render of these numbers, so a card cannot be produced without them and\n * cannot drift from the data files it ships beside.\n */\n gate: GateReport\n}\n\nfunction unique(values: Array<string | null>): string[] {\n return [...new Set(values.filter((v): v is string => v !== null))].sort()\n}\n\nfunction formatReward(reward: number | null): string {\n if (reward === null) return 'null'\n return Number.isInteger(reward) ? String(reward) : reward.toFixed(4)\n}\n\nfunction markdownTable(header: string[], rows: string[][]): string {\n return [\n `| ${header.join(' | ')} |`,\n `| ${header.map(() => '---').join(' | ')} |`,\n ...rows.map((row) => `| ${row.join(' | ')} |`),\n ].join('\\n')\n}\n\n/** Where the anti-Goodhart flag lives on each format's emitted row. */\nconst GATE_FLAG_FIELD: Record<ReleaseFormat, string> = {\n sft: '— (no gated row is written)',\n verifiers: '`info.realness_gated`',\n rft: '`reference.realness_gated`',\n raw: '`outcome.realness_gated`',\n}\n\nconst GATE_POLICY_LABEL: Record<ReleaseFormat, string> = {\n sft: 'EXCLUDED — an SFT row is an imitation target',\n verifiers: 'INCLUDED, reward forced to 0, flagged',\n rft: 'INCLUDED, reward forced to 0, flagged',\n raw: 'INCLUDED verbatim, flagged',\n}\n\nfunction gateSection(formats: ReleaseFormat[], gate: GateReport, totalLines: number): string {\n const rows = formats.map((format) => {\n const counts = gate.byFormat[format]\n return [\n format,\n GATE_POLICY_LABEL[format],\n String(counts?.emitted ?? 0),\n String(counts?.excluded ?? 0),\n counts?.maxEmittedReward === null || counts === undefined\n ? '—'\n : formatReward(counts.maxEmittedReward),\n counts?.maxEmittedEvidence == null\n ? '—'\n : `${counts.maxEmittedEvidence.path} = ${counts.maxEmittedEvidence.value}`,\n GATE_FLAG_FIELD[format],\n ]\n })\n const mixedExclusion = formats.some(\n (format) => FORMAT_GATE_DISPOSITION[format] === 'zero-and-flag',\n )\n return [\n `\\`outcome.realness_gated: true\\` marks a run whose success signal was faked (it satisfied the proxy without doing the work). **${gate.gatedLines} of ${totalLines} lines in this release are gated.**`,\n '',\n 'The gate is enforced, not asserted. A line pairing `realness_gated: true` with a reward above 0 is rejected by the schema validator, so it cannot be read out of a source ledger or written into `raw/train.jsonl` at all; on a gated line the numbers the reward was computed from (`outcome.metrics`, the verbatim judge `outcome.verdict`, and any per-step field the schema does not declare — a per-step reward is the same signal in credit-assignment form) are moved out of `outcome` and `steps[]` and into `provenance.gated_evidence`, where no config reads them as training input; the exporters re-check the same invariant on every line; and the release build measures the rows it is about to write and refuses to write ANY file if a gated row carries a positive reward — or any positive number derived from one — in ANY config.',\n '',\n 'The table below is **measured on the rows in this release**, not a description of intent — the build counts the emitted rows and this card renders those counts:',\n '',\n markdownTable(\n [\n 'config',\n 'policy',\n 'gated rows written',\n 'gated rows not written',\n 'max reward',\n 'max reward-derived number',\n 'flag',\n ],\n rows,\n ),\n '',\n 'Why gated rows are kept where they are kept: an SFT row is imitated verbatim, so a gamed trajectory must never appear in one at any weight. In `verifiers` the reward is a signed learning signal, and a gamed trajectory at reward 0 is a correct negative — dropping it would bias the negative population toward honest failures and leave a trainer no example of gaming being penalized. `rft` re-samples the completion, so only the prompt and the grader reference ship. `raw` is a faithful audit dump, where the gated row is the one an auditor most wants.',\n '',\n \"Reward 0 is never the only label: every included config carries the flag on the row itself, because zeroing alone makes a faked success indistinguishable from an honest failure. Filter on the flag to drop the gamed population, or select on it to mine it. The gated run's own measurements are not destroyed either — they are parked verbatim under `provenance.gated_evidence` in `raw/train.jsonl`, which is where an auditor can see what the run claimed and why it was flagged.\",\n mixedExclusion\n ? '\\n\"Gated rows not written\" is not all gate: `verifiers` also drops gap lines (empty transcript) and `rft` drops lines with no prompt turn, so that column can mix both causes.'\n : '',\n ]\n .join('\\n')\n .trimEnd()\n}\n\nfunction roleRewardRows(lines: MintedRolloutLine[]): string[][] {\n const counts = new Map<RolloutRole, Map<string, number>>()\n for (const line of lines) {\n const byReward = counts.get(line.role) ?? new Map<string, number>()\n const key = formatReward(line.outcome.reward)\n byReward.set(key, (byReward.get(key) ?? 0) + 1)\n counts.set(line.role, byReward)\n }\n const rows: string[][] = []\n for (const role of ROLLOUT_ROLES) {\n const byReward = counts.get(role)\n if (!byReward) continue\n const keys = [...byReward.keys()].sort((a, b) => {\n if (a === 'null') return 1\n if (b === 'null') return -1\n return Number(b) - Number(a)\n })\n for (const key of keys) rows.push([role, key, String(byReward.get(key))])\n }\n return rows\n}\n\nexport function buildDatasetCard(inputs: DatasetCardInputs): string {\n const {\n lines,\n formats,\n includeProposers,\n sourceFiles,\n scrubTotals,\n excluded,\n formatCounts,\n gate,\n } = inputs\n // The card is the artifact a buyer reads; it may not render a gate report\n // that violates the release policy even when called outside the build.\n assertGateReport(gate)\n\n const runIds = unique(lines.map((line) => line.run_id))\n const generations = [...new Set(lines.map((line) => line.generation))]\n .filter((g): g is number => g !== null)\n .sort((a, b) => a - b)\n const models = unique(lines.map((line) => line.policy.model))\n const harnesses = unique(lines.map((line) => line.policy.harness))\n const captures = unique(lines.map((line) => line.provenance.capture))\n const rewardSources = unique(lines.map((line) => line.outcome.reward_source))\n const gapLines = lines.filter((line) => line.messages.length === 0).length\n const gatedLines = lines.filter((line) => line.outcome.realness_gated).length\n if (gatedLines !== gate.gatedLines) {\n throw new Error(\n `dataset card: gate report claims ${gate.gatedLines} realness-gated line(s) but the lines ` +\n `it describes contain ${gatedLines} — the card and the build measured different data.`,\n )\n }\n\n const configs = formats\n .map((format) =>\n [\n ` - config_name: ${format}`,\n ' data_files:',\n ' - split: train',\n ` path: ${FORMAT_FILES[format]}`,\n ].join('\\n'),\n )\n .join('\\n')\n\n const frontmatter = [\n '---',\n 'license: unknown',\n 'pretty_name: Tangle rollout ledger — agent trajectories',\n 'configs:',\n configs,\n '---',\n ].join('\\n')\n\n const formatsTable = markdownTable(\n ['config', 'path', 'rows', 'contents'],\n formats.map((format) => [\n format,\n `\\`${FORMAT_FILES[format]}\\``,\n String(formatCounts[format] ?? 0),\n FORMAT_DESCRIPTIONS[format],\n ]),\n )\n\n const countsTable = markdownTable(['role', 'reward', 'lines'], roleRewardRows(lines))\n\n const scrubTable = markdownTable(\n ['rule', 'rewrites'],\n Object.entries(scrubTotals).map(([rule, count]) => [rule, String(count)]),\n )\n\n const proposerNote = includeProposers\n ? 'Proposer sessions are INCLUDED (`--include-proposers`); their transcripts contain improvement-loop harness source.'\n : `Proposer sessions are excluded by default (${excluded.proposers} lines dropped); they contain improvement-loop harness source. Rebuild with \\`--include-proposers\\` to keep them.`\n\n return `${frontmatter}\n\n# Tangle rollout ledger — agent trajectories\n\nOne line per agent invocation (supervisor episode, worker session, proposer shot, judge call, analyst pass) captured by the \\`${ROLLOUT_SCHEMA}\\` rollout ledger, labeled with improvement-loop coordinates and the official-judge reward, with the full message transcript inline.\n\nThis release contains the **trainable split only** (\\`search\\`). Holdout, dev, and canary splits are structurally excluded at build time, and the build additionally drops any non-trainable line as a fail-closed filter (${excluded.nonTrain} dropped here).\n\n## Formats\n\n${formatsTable}\n\n## Anti-Goodhart gate (\\`realness_gated\\`)\n\n${gateSection(formats, gate, lines.length)}\n\n## Schema (\\`${ROLLOUT_SCHEMA}\\`)\n\nEach raw line carries:\n\n- \\`rollout_id\\` / \\`parent_rollout_id\\` — invocation identity; workers point at their spawning supervisor episode.\n- \\`run_id\\`, \\`experiment_id\\`, \\`candidate_id\\` — run/experiment/candidate identity from the producing RunRecord, when present.\n- \\`generation\\`, \\`candidate_index\\` — improvement-loop coordinates (\\`-1\\` = baseline campaign; \\`null\\` = not an improvement loop).\n- \\`role\\` — one of ${ROLLOUT_ROLES.map((role) => `\\`${role}\\``).join(', ')}.\n- \\`task\\` — suite, instance id, split, seed, replicate index.\n- \\`policy\\` — harness, model, provider, profile commit, prompt/config hashes, sampling params.\n- \\`messages\\` / \\`tool_defs\\` — full transcript in canonical OpenAI chat-with-tools form (including \\`reasoning_content\\`). An empty \\`messages\\` array is a labeled gap line; \\`provenance.gap\\` says why the transcript could not be recovered (${gapLines} gap lines in this release).\n- \\`outcome\\` — \\`reward\\` (the single scalar), \\`reward_source\\`, the verbatim judge \\`verdict\\`, non-scalar \\`metrics\\`, and \\`realness_gated\\` (anti-Goodhart flag; see [Anti-Goodhart gate](#anti-goodhart-gate-realness_gated) for the per-config treatment and the measured counts).\n- \\`cost\\` — usd, token counts, wall time.\n- \\`artifacts\\` / \\`provenance\\` — patch/run-dir/transcript pointers (scrubbed) and capture metadata.\n\n## Provenance\n\n- Source ledgers: ${sourceFiles.map((file) => `\\`${file}\\``).join(', ')}\n- Run ids: ${runIds.map((id) => `\\`${id}\\``).join(', ')}\n- Generations: ${generations.join(', ')} (\\`-1\\` = baseline campaign)\n- Models: ${models.map((m) => `\\`${m}\\``).join(', ')}\n- Harnesses: ${harnesses.map((h) => `\\`${h}\\``).join(', ')}\n- Capture modes: ${captures.join(', ')}\n- Every reward traces to a named source (reward sources in this release: ${rewardSources.map((s) => `\\`${s}\\``).join(', ')}).\n\n${proposerNote}\n\n## Reward semantics per role\n\n- **agent** — the producing RunRecord's holdout/search score, with the realness gate forcing gamed successes to 0.\n- **supervisor** — the official-judge verdict on the episode's delivered artifact (1 = resolved, 0 = not).\n- **worker** — INHERITED from the parent supervisor episode (\\`…/inherited\\`). Caveat: reward 1 does not establish this worker's individual contribution (sibling workers in the same episode share the episode outcome), and reward 0 does not prove this worker failed.\n- **proposer** — the fraction of improvement-set instances the proposed candidate resolved (\\`…/candidate-resolved-fraction\\`); a scalar in [0, 1], not a binary verdict.\n- **judge / analyst** — carry the episode verdict where one applies; otherwise \\`reward: null\\` (a labeled gap, never 0).\n\n## Counts\n\n${countsTable}\n\nTotal lines: ${lines.length}\n\n## Scrubbing\n\nAbsolute home paths were rewritten to \\`$WORK\\`, credential-shaped strings were replaced with \\`[REDACTED:<kind>]\\` markers, internal hostnames were normalized to \\`*.internal.example\\`, and username-bearing incidentals (\\`ls -l\\` owner columns, per-user pytest tmpdirs) were normalized to \\`user\\` / \\`$USER\\`. Rewrite counts for this release (full per-file breakdown in \\`scrub-report.json\\`):\n\n${scrubTable}\n\n## License\n\n\\`license: unknown\\` is a placeholder — the releasing operator must set the real SPDX license id in the frontmatter above before publishing.\n\n## Citation\n\n\\`\\`\\`bibtex\n@misc{tangle_rollout_ledger,\n title = {Tangle rollout ledger — agent trajectories},\n author = {{Tangle Network}},\n howpublished = {HuggingFace Datasets},\n note = {Operator: fill in the repository URL, authors, and year before publishing}\n}\n\\`\\`\\`\n`\n}\n","/**\n * Deterministic scrubbing pass over rollout-ledger lines before public release.\n *\n * Every rule is a pure regex rewrite applied to every string value in a line\n * (messages, artifacts, run ids, tool arguments — everywhere), so the scrubbed\n * line is still a valid `tangle.rollout.v1` line. Rules are idempotent:\n * scrub(scrub(x)) === scrub(x), and a second pass counts zero hits — that is\n * the property the release pipeline relies on to prove nothing half-scrubbed\n * ships. Rule order matters: whole `KEY=value` env pairs are redacted before\n * the bare-key rule so one secret is never counted twice.\n */\n\nimport { assertMinted, type MintedRolloutLine } from '../schema'\n\nexport interface ScrubRule {\n name: string\n pattern: RegExp\n /** Rewrite for one match; `g1` is the first capture group when present. */\n rewrite: (match: string, g1?: string) => string\n}\n\nconst SCRUB_RULES: readonly ScrubRule[] = [\n {\n // /home/<user> and /Users/<user> prefixes → $WORK ($HOME-derived paths).\n name: 'home-path',\n pattern: /\\/(?:home|Users)\\/[A-Za-z0-9._-]+/g,\n rewrite: () => '$WORK',\n },\n {\n // Harness stores encode cwd as a dashed path segment (-home-drew-…);\n // strip the leading -home-<user> so the username never ships.\n name: 'home-path-encoded',\n pattern: /(?<=\\/)-(?:home|Users)-[A-Za-z0-9_.]+/g,\n rewrite: () => '$WORK',\n },\n {\n // pytest names its tmpdir after the invoking user (/tmp/pytest-of-drew).\n name: 'tmp-user-dir',\n pattern: /\\/tmp\\/pytest-of-[A-Za-z0-9._-]+/g,\n rewrite: () => '/tmp/pytest-of-$USER',\n },\n {\n // `ls -l` owner/group columns leak the username in captured tool output.\n // The `(?!user user…)` guard keeps a second pass at zero rewrites.\n name: 'ls-owner',\n pattern:\n /([-bcdlps][-rwxsStT]{9}[.+@]?\\s+\\d+\\s+)(?!user user(?=\\s))[A-Za-z0-9._-]+\\s+[A-Za-z0-9._-]+(?=\\s)/g,\n rewrite: (_match, prefix) => `${prefix}user user`,\n },\n {\n // Env-var-shaped secrets: NAME=value where NAME looks credential-bearing.\n // The (?!\\[REDACTED:) guard keeps the rule idempotent on its own output.\n name: 'env-secret',\n pattern:\n /\\b([A-Z][A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?))=(?!\\[REDACTED:)(\"[^\"]*\"|'[^']*'|[^\\s\"']+)/g,\n rewrite: (_match, name) => `${name}=[REDACTED:env]`,\n },\n {\n name: 'bearer-token',\n pattern: /\\b(Bearer|Basic)\\s+(?!\\[REDACTED:)[A-Za-z0-9\\-._~+/=]{8,}/g,\n rewrite: (_match, scheme) => `${scheme} [REDACTED:bearer]`,\n },\n {\n // Bare provider-prefixed keys (OpenAI/Anthropic sk-, GitHub ghp_/gho_/…,\n // fine-grained PATs, HuggingFace hf_, Slack xox*, AWS AKIA).\n name: 'api-key',\n pattern:\n /\\b(?:sk-[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{20,}|hf_[A-Za-z0-9]{16,}|xox[baprs]-[A-Za-z0-9-]{10,}|AKIA[0-9A-Z]{16})\\b/g,\n rewrite: () => '[REDACTED:api-key]',\n },\n {\n // Our infra hostnames → placeholder domain, subdomain preserved\n // (router.tangle.tools → router.internal.example).\n name: 'infra-host',\n pattern: /(?<![A-Za-z0-9.-])((?:[A-Za-z0-9-]+\\.)*)tangle\\.(?:tools|network)(?![A-Za-z0-9-])/g,\n rewrite: (_match, prefix) => `${prefix ?? ''}internal.example`,\n },\n {\n // Known workstation hostnames leak through email Message-IDs and fqdn\n // lookups inside captured test output; extend the list as machines join.\n name: 'machine-host',\n pattern: /\\b[A-Za-z0-9]+-GTR-Pro\\b/g,\n rewrite: () => 'workstation',\n },\n]\n\n/** Rule name → number of matches rewritten. Always carries every rule (0 is data). */\nexport type ScrubCounts = Record<string, number>\n\nexport function emptyScrubCounts(): ScrubCounts {\n return Object.fromEntries(SCRUB_RULES.map((rule) => [rule.name, 0]))\n}\n\nexport function addScrubCounts(into: ScrubCounts, from: ScrubCounts): ScrubCounts {\n for (const [name, count] of Object.entries(from)) into[name] = (into[name] ?? 0) + count\n return into\n}\n\nexport function scrubText(text: string, counts: ScrubCounts): string {\n let out = text\n for (const rule of SCRUB_RULES) {\n out = out.replace(rule.pattern, (match: string, ...rest: unknown[]) => {\n counts[rule.name] = (counts[rule.name] ?? 0) + 1\n return rule.rewrite(match, typeof rest[0] === 'string' ? rest[0] : undefined)\n })\n }\n return out\n}\n\nfunction scrubValue(value: unknown, counts: ScrubCounts): unknown {\n if (typeof value === 'string') return scrubText(value, counts)\n if (Array.isArray(value)) return value.map((item) => scrubValue(item, counts))\n if (value !== null && typeof value === 'object') {\n const out: Record<string, unknown> = {}\n for (const [key, item] of Object.entries(value)) out[key] = scrubValue(item, counts)\n return out\n }\n return value\n}\n\n/**\n * Scrub every string value in a line; structure and key order are preserved.\n *\n * `assertMinted` on the way out rather than a cast: scrubbing rebuilds the\n * object, so the brand has to be re-earned, and re-validating proves the rules\n * did not rewrite a field the schema constrains (`reward` is a number, not a\n * string, so no rule should ever touch it — this is what checks that).\n */\nfunction scrubRolloutLine(line: MintedRolloutLine, counts: ScrubCounts): MintedRolloutLine {\n return assertMinted(scrubValue(line, counts), `scrubbed rollout line ${line.rollout_id}`)\n}\n\nexport function scrubLines(lines: MintedRolloutLine[]): {\n lines: MintedRolloutLine[]\n counts: ScrubCounts\n} {\n const counts = emptyScrubCounts()\n return { lines: lines.map((line) => scrubRolloutLine(line, counts)), counts }\n}\n\n/**\n * A `RolloutScrubber` (text → text) applying the full rule set — the\n * default hook to pass to `mintRolloutRows({ scrub })` so lines are\n * scrubbed at mint time, before they ever reach a ledger file. Release\n * builds re-run `scrubLines` regardless (idempotent), so double-scrubbing\n * is safe and counted as zero.\n */\nexport function defaultRolloutScrubber(text: string): string {\n return scrubText(text, emptyScrubCounts())\n}\n","/**\n * One-command HuggingFace dataset release from rollout ledgers:\n *\n * agent-eval rollout-release <ledger.jsonl...> --out <dir> \\\n * [--formats sft,verifiers,rft,raw] [--include-proposers] [--push <org/name>]\n *\n * Pipeline per input ledger: read + validate → fail-closed filters\n * (trainable split only; proposer sessions dropped unless\n * --include-proposers, they contain improvement-loop harness source) →\n * deterministic scrub → export the requested formats + scrub-report.json +\n * auto-generated README.md card. Deterministic: same inputs and flags →\n * byte-identical output dir.\n *\n * --push uploads the built dir with `huggingface-cli upload` only when the\n * CLI exists on PATH and HF_TOKEN is present in the env; the token is\n * never printed. Everything else runs fully offline.\n */\n\nimport { spawnSync } from 'node:child_process'\nimport { mkdir, writeFile } from 'node:fs/promises'\nimport { basename, dirname, join } from 'node:path'\nimport { toJsonl, toRftItems, toSftRows, toVerifiersRolloutOutputs } from '../exporters'\nimport { readRolloutLedger, writeRolloutLedger } from '../ledger'\nimport { isTrainableSplit, type MintedRolloutLine } from '../schema'\nimport { buildDatasetCard, FORMAT_FILES, RELEASE_FORMATS, type ReleaseFormat } from './card'\nimport {\n assertGateReport,\n FORMAT_GATE_DISPOSITION,\n type GateReport,\n gatedRolloutIds,\n measureFormatGate,\n releaseRowRefs,\n} from './gate-report'\nimport { addScrubCounts, emptyScrubCounts, type ScrubCounts, scrubLines } from './scrub'\n\nexport interface BuildOptions {\n out: string\n formats: ReleaseFormat[]\n includeProposers: boolean\n}\n\nexport interface ScrubReport {\n /** Input ledger path → rule → rewrite count (only shipped lines are scrubbed). */\n files: Record<string, ScrubCounts>\n totals: ScrubCounts\n excluded: { proposers: number; nonTrain: number }\n}\n\nexport interface BuildSummary {\n inputs: string[]\n read: number\n kept: number\n scrub: ScrubReport\n formatCounts: Partial<Record<ReleaseFormat, number>>\n /** Per-format anti-Goodhart accounting, measured on the rows written. */\n gate: GateReport\n files: string[]\n}\n\nexport async function buildHfDataset(\n inputs: string[],\n options: BuildOptions,\n): Promise<BuildSummary> {\n if (inputs.length === 0) throw new Error('no input ledgers given')\n if (options.formats.length === 0) throw new Error('no formats selected')\n\n const report: ScrubReport = {\n files: {},\n totals: emptyScrubCounts(),\n excluded: { proposers: 0, nonTrain: 0 },\n }\n const kept: MintedRolloutLine[] = []\n let read = 0\n\n for (const input of inputs) {\n const lines = await readRolloutLedger(input)\n read += lines.length\n const shippable = lines.filter((line) => {\n if (!isTrainableSplit(line.task.split)) {\n report.excluded.nonTrain += 1\n return false\n }\n if (!options.includeProposers && line.role === 'proposer') {\n report.excluded.proposers += 1\n return false\n }\n return true\n })\n const scrubbed = scrubLines(shippable)\n report.files[input] = scrubbed.counts\n addScrubCounts(report.totals, scrubbed.counts)\n kept.push(...scrubbed.lines)\n }\n\n const formatCounts: Partial<Record<ReleaseFormat, number>> = {}\n const files: string[] = []\n const gated = gatedRolloutIds(kept)\n const gate: GateReport = { gatedLines: gated.size, byFormat: {} }\n\n // Every selected format's rows are exported and gate-measured BEFORE the\n // first byte is written. A build that would ship a gamed run at a positive\n // reward fails with nothing on disk, rather than leaving a poisoned config\n // behind for someone to `--push`.\n const pending: Array<{ path: string; write: () => Promise<void> }> = []\n\n for (const format of options.formats) {\n const path = join(options.out, FORMAT_FILES[format])\n if (format === 'raw') {\n // writeRolloutLedger re-validates every scrubbed line before it lands.\n gate.byFormat.raw = measureFormatGate(gated, releaseRowRefs.raw(kept))\n formatCounts.raw = kept.length\n pending.push({ path, write: () => writeRolloutLedger(path, kept) })\n } else if (format === 'sft') {\n const rows = toSftRows(kept)\n gate.byFormat.sft = measureFormatGate(gated, releaseRowRefs.sft(rows))\n formatCounts.sft = rows.length\n pending.push({ path, write: () => writeFile(path, toJsonl(rows)) })\n } else if (format === 'verifiers') {\n // The declared disposition drives the exporter: 'zero-and-flag' ships\n // gated lines and honest failures as labeled negatives at reward 0.\n const outputs = toVerifiersRolloutOutputs(kept, {\n gatedLines: FORMAT_GATE_DISPOSITION.verifiers,\n })\n gate.byFormat.verifiers = measureFormatGate(gated, releaseRowRefs.verifiers(outputs))\n formatCounts.verifiers = outputs.length\n pending.push({ path, write: () => writeFile(path, toJsonl(outputs)) })\n } else {\n const items = toRftItems(kept, { gatedLines: FORMAT_GATE_DISPOSITION.rft })\n gate.byFormat.rft = measureFormatGate(gated, releaseRowRefs.rft(items))\n formatCounts.rft = items.length\n pending.push({ path, write: () => writeFile(path, toJsonl(items)) })\n }\n }\n\n assertGateReport(gate)\n\n for (const { path, write } of pending) {\n await mkdir(dirname(path), { recursive: true })\n await write()\n files.push(path)\n }\n\n const reportPath = join(options.out, 'scrub-report.json')\n await writeFile(reportPath, `${JSON.stringify(report, null, 2)}\\n`)\n files.push(reportPath)\n\n const cardPath = join(options.out, 'README.md')\n await writeFile(\n cardPath,\n buildDatasetCard({\n lines: kept,\n formats: options.formats,\n includeProposers: options.includeProposers,\n sourceFiles: inputs.map((input) => basename(input)),\n scrubTotals: report.totals,\n excluded: report.excluded,\n formatCounts,\n gate,\n }),\n )\n files.push(cardPath)\n\n return { inputs, read, kept: kept.length, scrub: report, formatCounts, gate, files }\n}\n\nfunction planPushCommand(repo: string, outDir: string): string[] {\n return ['huggingface-cli', 'upload', repo, outDir, '.', '--repo-type', 'dataset']\n}\n\nfunction pushDataset(repo: string, outDir: string): void {\n const found = spawnSync('which', ['huggingface-cli'], { stdio: 'ignore' })\n if (found.status !== 0) {\n throw new Error(\n 'huggingface-cli not found on PATH — install huggingface_hub[cli] before --push',\n )\n }\n if (!process.env.HF_TOKEN) {\n throw new Error('HF_TOKEN not present in env — refusing to push')\n }\n const [command, ...args] = planPushCommand(repo, outDir) as [string, ...string[]]\n // Token stays in the inherited env; it is never echoed or interpolated.\n const run = spawnSync(command, args, { stdio: 'inherit' })\n if (run.status !== 0) throw new Error(`huggingface-cli upload exited ${String(run.status)}`)\n}\n\nexport interface RolloutReleaseCliArgs extends BuildOptions {\n inputs: string[]\n push: string | null\n}\n\nconst ROLLOUT_RELEASE_USAGE =\n 'usage: agent-eval rollout-release <ledger.jsonl...> --out <dir> [--formats sft,verifiers,rft,raw] [--include-proposers] [--push <org/name>]'\n\nfunction parseRolloutReleaseArgs(argv: string[]): RolloutReleaseCliArgs {\n const args: RolloutReleaseCliArgs = {\n inputs: [],\n out: '',\n formats: [...RELEASE_FORMATS],\n includeProposers: false,\n push: null,\n }\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i]!\n if (arg === '--out') {\n args.out = argv[++i] ?? ''\n } else if (arg === '--formats') {\n const raw = (argv[++i] ?? '').split(',').filter(Boolean)\n for (const format of raw) {\n if (!RELEASE_FORMATS.includes(format as ReleaseFormat)) {\n throw new Error(\n `unknown format \"${format}\" — expected one of ${RELEASE_FORMATS.join(',')}`,\n )\n }\n }\n args.formats = raw as ReleaseFormat[]\n } else if (arg === '--include-proposers') {\n args.includeProposers = true\n } else if (arg === '--push') {\n args.push = argv[++i] ?? null\n } else if (arg.startsWith('--')) {\n throw new Error(`unknown flag \"${arg}\"`)\n } else {\n args.inputs.push(arg)\n }\n }\n if (args.inputs.length === 0 || !args.out) {\n throw new Error(ROLLOUT_RELEASE_USAGE)\n }\n if (args.push !== null && !/^[\\w.-]+\\/[\\w.-]+$/.test(args.push)) {\n throw new Error(`--push expects <org/name>, got \"${args.push}\"`)\n }\n return args\n}\n\n/** CLI driver for `agent-eval rollout-release`. Returns the process exit code. */\nexport async function runRolloutReleaseCli(argv: string[]): Promise<number> {\n let args: RolloutReleaseCliArgs\n try {\n args = parseRolloutReleaseArgs(argv)\n } catch (error) {\n process.stderr.write(`${error instanceof Error ? error.message : String(error)}\\n`)\n return 2\n }\n const summary = await buildHfDataset(args.inputs, args)\n process.stdout.write(\n `${JSON.stringify(\n {\n read: summary.read,\n kept: summary.kept,\n formatCounts: summary.formatCounts,\n gate: summary.gate,\n scrub: summary.scrub,\n },\n null,\n 2,\n )}\\n`,\n )\n process.stdout.write(`dataset → ${args.out} (${summary.files.length} files)\\n`)\n if (args.push !== null) {\n pushDataset(args.push, args.out)\n process.stdout.write(`pushed → ${args.push}\\n`)\n }\n return 0\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAoBA,SAAS,UAAU,OAA8B;CAC/C,KAAK,MAAM,CAAC,GAAG,SAAS,MAAM,QAAQ,GAAG,kBAAkB,MAAM,iBAAiB,EAAE,EAAE;CACtF,OAAO,MAAM,KAAK,SAAS,KAAK,UAAU,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,KAAK,MAAM,SAAS,IAAI,OAAO;AAC3F;;AAGA,eAAsB,mBAAmB,MAAc,OAAqC;CAC1F,MAAM,UAAU,UAAU,KAAK;CAC/B,MAAM,MAAM,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;CAC9C,MAAM,UAAU,MAAM,OAAO;AAC/B;;AAGA,eAAsB,mBAAmB,MAAc,OAAqC;CAC1F,IAAI,MAAM,WAAW,GAAG;CACxB,MAAM,UAAU,UAAU,KAAK;CAC/B,MAAM,MAAM,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;CAC9C,MAAM,WAAW,MAAM,OAAO;AAChC;;;;;;;;;;;AAYA,eAAsB,kBAAkB,MAA4C;CAClF,OAAO,UAAU,OAAO,QAAQ,YAAY,aAAa,QAAQ,OAAO,CAAC;AAC3E;AAIA,eAAe,UACb,MACA,OACc;CACd,MAAM,MAAM,MAAM,SAAS,MAAM,MAAM;CACvC,MAAM,QAAa,CAAC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AAY,KAAK,MAAM,KAAK,GAAG;EAC/B,QAAQ,OAAO,MAAM,YAAY,KAAK,KAAK,GAAG;CAChD;CACA,OAAO;AACT"}
@@ -1,5 +1,5 @@
1
1
  import { A as SearchLedgerHash } from "../search-ledger-types-p2xKfiDJ.js";
2
- import { A as admitSearchLedgerBatch, C as SearchLedgerBatchAdmission, D as SearchLedgerHeadSchema, E as SearchLedgerHead, M as searchLedgerArtifactRefs, N as searchLedgerHeadPath, O as SearchRunKind, S as SearchBlobPutResponseSchema, T as SearchLedgerConflictSchema, _ as IngestSearchLedgerRequestSchema, a as createHostedClient, b as SEARCH_LEDGER_INGEST_PATH, c as HOSTED_WIRE_VERSION, d as IngestResponse, f as IngestTracesRequest, g as IngestSearchLedgerRequest, h as AdmitSearchLedgerBatchInput, i as SearchLedgerIngestOutcome, j as searchBlobPath, k as SearchRunKindSchema, l as HostedIngestHeaders, m as UnixNanoTimestamp, n as HostedRequestError, o as hostedClientFromEnv, p as TraceSpanEvent, r as HostedTenant, s as hostedTenantFromEnv, t as HostedClient, u as HostedWireVersion, v as SEARCH_LEDGER_BATCH_MAX_BYTES, w as SearchLedgerConflict, x as SearchBlobPutResponse, y as SEARCH_LEDGER_BATCH_MAX_LINES } from "../client-BzL9niqi.js";
2
+ import { C as SearchLedgerConflictSchema, D as admitSearchLedgerBatch, E as SearchRunKind, S as SearchLedgerConflict, T as SearchLedgerHeadSchema, _ as SEARCH_LEDGER_BATCH_MAX_BYTES, a as hostedClientFromEnv, b as SearchBlobPutResponseSchema, c as HostedIngestHeaders, d as IngestTracesRequest, f as TraceSpanEvent, g as IngestSearchLedgerRequestSchema, h as IngestSearchLedgerRequest, i as createHostedClient, l as HostedWireVersion, m as AdmitSearchLedgerBatchInput, n as HostedTenant, o as hostedTenantFromEnv, p as UnixNanoTimestamp, r as SearchLedgerIngestOutcome, s as HOSTED_WIRE_VERSION, t as HostedClient, u as IngestResponse, v as SEARCH_LEDGER_INGEST_PATH, w as SearchLedgerHead, x as SearchLedgerBatchAdmission, y as SearchBlobPutResponse } from "../client-hwo3cJjR.js";
3
3
  import { z } from "zod";
4
4
  //#region src/hosted/schemas.d.ts
5
5
  export declare const UnixNanoTimestampSchema: z.ZodType<UnixNanoTimestamp>;
@@ -70,5 +70,5 @@ export declare function startSearchShipper(options: SearchShipOptions & {
70
70
  intervalMs?: number;
71
71
  }): SearchShipper;
72
72
  //#endregion
73
- export { type AdmitSearchLedgerBatchInput, HOSTED_WIRE_VERSION, type HostedClient, type HostedIngestHeaders, HostedRequestError, type HostedTenant, type HostedWireVersion, type IngestResponse, type IngestSearchLedgerRequest, IngestSearchLedgerRequestSchema, type IngestTracesRequest, SEARCH_LEDGER_BATCH_MAX_BYTES, SEARCH_LEDGER_BATCH_MAX_LINES, SEARCH_LEDGER_INGEST_PATH, type SearchBlobPutResponse, SearchBlobPutResponseSchema, type SearchLedgerBatchAdmission, type SearchLedgerConflict, SearchLedgerConflictSchema, type SearchLedgerHead, SearchLedgerHeadSchema, type SearchLedgerIngestOutcome, type SearchRunKind, SearchRunKindSchema, type SearchShipMissingBlob, type SearchShipOptions, type SearchShipResult, type SearchShipper, type TraceSpanEvent, type UnixNanoTimestamp, admitSearchLedgerBatch, createHostedClient, hostedClientFromEnv, hostedTenantFromEnv, searchBlobPath, searchLedgerArtifactRefs, searchLedgerHeadPath };
73
+ export { type AdmitSearchLedgerBatchInput, HOSTED_WIRE_VERSION, type HostedClient, type HostedIngestHeaders, type HostedTenant, type HostedWireVersion, type IngestResponse, type IngestSearchLedgerRequest, IngestSearchLedgerRequestSchema, type IngestTracesRequest, SEARCH_LEDGER_BATCH_MAX_BYTES, SEARCH_LEDGER_INGEST_PATH, type SearchBlobPutResponse, SearchBlobPutResponseSchema, type SearchLedgerBatchAdmission, type SearchLedgerConflict, SearchLedgerConflictSchema, type SearchLedgerHead, SearchLedgerHeadSchema, type SearchLedgerIngestOutcome, type SearchRunKind, type SearchShipMissingBlob, type SearchShipOptions, type SearchShipResult, type SearchShipper, type TraceSpanEvent, type UnixNanoTimestamp, admitSearchLedgerBatch, createHostedClient, hostedClientFromEnv, hostedTenantFromEnv };
74
74
  //# sourceMappingURL=index.d.ts.map
@@ -1,2 +1,2 @@
1
- import { C as TraceSpanEventSchema, S as IngestTracesRequestSchema, T as HOSTED_WIRE_VERSION, _ as admitSearchLedgerBatch, a as HostedRequestError, b as searchLedgerHeadPath, c as hostedTenantFromEnv, d as SEARCH_LEDGER_BATCH_MAX_LINES, f as SEARCH_LEDGER_INGEST_PATH, g as SearchRunKindSchema, h as SearchLedgerHeadSchema, i as startSearchShipper, l as IngestSearchLedgerRequestSchema, m as SearchLedgerConflictSchema, o as createHostedClient, p as SearchBlobPutResponseSchema, r as shipSearchLedger, s as hostedClientFromEnv, t as SearchShipConflictError, u as SEARCH_LEDGER_BATCH_MAX_BYTES, v as searchBlobPath, w as UnixNanoTimestampSchema, x as IngestResponseSchema, y as searchLedgerArtifactRefs } from "../search-shipper-BOSD46qv.js";
2
- export { HOSTED_WIRE_VERSION, HostedRequestError, IngestResponseSchema, IngestSearchLedgerRequestSchema, IngestTracesRequestSchema, SEARCH_LEDGER_BATCH_MAX_BYTES, SEARCH_LEDGER_BATCH_MAX_LINES, SEARCH_LEDGER_INGEST_PATH, SearchBlobPutResponseSchema, SearchLedgerConflictSchema, SearchLedgerHeadSchema, SearchRunKindSchema, SearchShipConflictError, TraceSpanEventSchema, UnixNanoTimestampSchema, admitSearchLedgerBatch, createHostedClient, hostedClientFromEnv, hostedTenantFromEnv, searchBlobPath, searchLedgerArtifactRefs, searchLedgerHeadPath, shipSearchLedger, startSearchShipper };
1
+ import { _ as IngestTracesRequestSchema, a as createHostedClient, b as HOSTED_WIRE_VERSION, c as IngestSearchLedgerRequestSchema, d as SearchBlobPutResponseSchema, f as SearchLedgerConflictSchema, g as IngestResponseSchema, h as admitSearchLedgerBatch, i as startSearchShipper, l as SEARCH_LEDGER_BATCH_MAX_BYTES, o as hostedClientFromEnv, p as SearchLedgerHeadSchema, r as shipSearchLedger, s as hostedTenantFromEnv, t as SearchShipConflictError, u as SEARCH_LEDGER_INGEST_PATH, v as TraceSpanEventSchema, y as UnixNanoTimestampSchema } from "../search-shipper-Bg2HW3Uv.js";
2
+ export { HOSTED_WIRE_VERSION, IngestResponseSchema, IngestSearchLedgerRequestSchema, IngestTracesRequestSchema, SEARCH_LEDGER_BATCH_MAX_BYTES, SEARCH_LEDGER_INGEST_PATH, SearchBlobPutResponseSchema, SearchLedgerConflictSchema, SearchLedgerHeadSchema, SearchShipConflictError, TraceSpanEventSchema, UnixNanoTimestampSchema, admitSearchLedgerBatch, createHostedClient, hostedClientFromEnv, hostedTenantFromEnv, shipSearchLedger, startSearchShipper };