@tangle-network/agent-eval 0.217.1 → 0.219.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (258) hide show
  1. package/CHANGELOG.md +57 -1
  2. package/dist/adapters/http.d.ts +3 -3
  3. package/dist/adapters/http.d.ts.map +1 -1
  4. package/dist/adapters/http.js +1 -0
  5. package/dist/adapters/http.js.map +1 -1
  6. package/dist/{agent-profile-DTt8uGP9.d.ts → agent-profile-D01Io2Xw.d.ts} +4 -4
  7. package/dist/{agent-profile-DTt8uGP9.d.ts.map → agent-profile-D01Io2Xw.d.ts.map} +1 -1
  8. package/dist/analyst/index.d.ts +13 -13
  9. package/dist/analyst/index.d.ts.map +1 -1
  10. package/dist/analyst/index.js +10 -10
  11. package/dist/analyst/index.js.map +1 -1
  12. package/dist/{analyze-runs-DyeNcenW.d.ts → analyze-runs-BWAHBDAw.d.ts} +4 -4
  13. package/dist/{analyze-runs-DyeNcenW.d.ts.map → analyze-runs-BWAHBDAw.d.ts.map} +1 -1
  14. package/dist/{benchmark-command-xQK8nOI6.js → benchmark-command-BzmMTnvC.js} +664 -565
  15. package/dist/benchmark-command-BzmMTnvC.js.map +1 -0
  16. package/dist/benchmarks/index.d.ts +5 -5
  17. package/dist/benchmarks/index.js +3 -3
  18. package/dist/benchmarks/index.js.map +1 -1
  19. package/dist/campaign/index.d.ts +8 -8
  20. package/dist/campaign/index.js +11 -11
  21. package/dist/{campaign-CJGkxAQ6.js → campaign-BVPC6ODQ.js} +452 -282
  22. package/dist/campaign-BVPC6ODQ.js.map +1 -0
  23. package/dist/{campaign-evidence-CQYw8_0H.js → campaign-evidence-DunzcJGv.js} +2 -2
  24. package/dist/campaign-evidence-DunzcJGv.js.map +1 -0
  25. package/dist/{chat-client-ldqxYYTN.js → chat-client-CMQ8_h4J.js} +2 -2
  26. package/dist/{chat-client-ldqxYYTN.js.map → chat-client-CMQ8_h4J.js.map} +1 -1
  27. package/dist/{chat-json-call-DavzexSp.js → chat-json-call-BrZKn0L3.js} +2 -2
  28. package/dist/{chat-json-call-DavzexSp.js.map → chat-json-call-BrZKn0L3.js.map} +1 -1
  29. package/dist/cli.js +10 -10
  30. package/dist/{completion-verifier-B_jw6C9p.js → completion-verifier-Cigap8CG.js} +5 -5
  31. package/dist/{completion-verifier-B_jw6C9p.js.map → completion-verifier-Cigap8CG.js.map} +1 -1
  32. package/dist/contract/index.d.ts +11 -11
  33. package/dist/contract/index.js +91 -11
  34. package/dist/contract/index.js.map +1 -1
  35. package/dist/{cost-ledger-D0352Z4d.js → cost-ledger-BGZB6yY2.js} +75 -2
  36. package/dist/cost-ledger-BGZB6yY2.js.map +1 -0
  37. package/dist/{cost-ledger-Jk62OBfF.d.ts → cost-ledger-C1W3ICmP.d.ts} +26 -2
  38. package/dist/cost-ledger-C1W3ICmP.d.ts.map +1 -0
  39. package/dist/{default-registry-ClYjq3QE.js → default-registry-BrKmT01n.js} +310 -278
  40. package/dist/{default-registry-ClYjq3QE.js.map → default-registry-BrKmT01n.js.map} +1 -1
  41. package/dist/{default-registry-DXgLmoDI.d.ts → default-registry-Cwg_QN3d.d.ts} +6 -6
  42. package/dist/{default-registry-DXgLmoDI.d.ts.map → default-registry-Cwg_QN3d.d.ts.map} +1 -1
  43. package/dist/{define-agent-eval-BIkH_gAR.d.ts → define-agent-eval-C2nFhHPu.d.ts} +8 -8
  44. package/dist/{define-agent-eval-BIkH_gAR.d.ts.map → define-agent-eval-C2nFhHPu.d.ts.map} +1 -1
  45. package/dist/{define-agent-eval-BDxNlP3D.js → define-agent-eval-UQY3VbJ2.js} +165 -105
  46. package/dist/define-agent-eval-UQY3VbJ2.js.map +1 -0
  47. package/dist/diagnosis/index.d.ts +2 -2
  48. package/dist/{dspy-rlm-engine-DhdCr1Dc.js → dspy-rlm-engine-Bn_Mt_LW.js} +3 -3
  49. package/dist/{dspy-rlm-engine-DhdCr1Dc.js.map → dspy-rlm-engine-Bn_Mt_LW.js.map} +1 -1
  50. package/dist/{engine-BvZ0R-36.d.ts → engine-BpGGw6cd.d.ts} +3 -3
  51. package/dist/{engine-BvZ0R-36.d.ts.map → engine-BpGGw6cd.d.ts.map} +1 -1
  52. package/dist/eval-campaign-BUMIxKTE.js +393 -0
  53. package/dist/eval-campaign-BUMIxKTE.js.map +1 -0
  54. package/dist/{evaluation-jTjC_QQD.d.ts → evaluation-CBdQt_kr.d.ts} +4 -4
  55. package/dist/{evaluation-jTjC_QQD.d.ts.map → evaluation-CBdQt_kr.d.ts.map} +1 -1
  56. package/dist/evaluation.d.ts +1 -1
  57. package/dist/evaluation.js +1 -1
  58. package/dist/{exact-types-CflbJ9f3.d.ts → exact-types-BYFmYq44.d.ts} +2 -2
  59. package/dist/{exact-types-CflbJ9f3.d.ts.map → exact-types-BYFmYq44.d.ts.map} +1 -1
  60. package/dist/experiment/index.d.ts +24 -1
  61. package/dist/experiment/index.d.ts.map +1 -1
  62. package/dist/experiment/index.js +110 -71
  63. package/dist/experiment/index.js.map +1 -1
  64. package/dist/{exporters-Cl6IeNAu.js → exporters-DWvM16LE.js} +2 -2
  65. package/dist/{exporters-Cl6IeNAu.js.map → exporters-DWvM16LE.js.map} +1 -1
  66. package/dist/{external-optimizer-process-KVFGvYX1.js → external-optimizer-process-wOLfzsCC.js} +2 -2
  67. package/dist/{external-optimizer-process-KVFGvYX1.js.map → external-optimizer-process-wOLfzsCC.js.map} +1 -1
  68. package/dist/{external-optimizer-subprocess-XIHBOSKt.js → external-optimizer-subprocess-D670Oxf2.js} +4 -4
  69. package/dist/{external-optimizer-subprocess-XIHBOSKt.js.map → external-optimizer-subprocess-D670Oxf2.js.map} +1 -1
  70. package/dist/{feedback-trajectory-BWmhRBGu.d.ts → feedback-trajectory-DhB9WzYg.d.ts} +3 -3
  71. package/dist/{feedback-trajectory-BWmhRBGu.d.ts.map → feedback-trajectory-DhB9WzYg.d.ts.map} +1 -1
  72. package/dist/{findings-store-BMVQtEsm.js → findings-store-CvNo712L.js} +6 -6
  73. package/dist/{findings-store-BMVQtEsm.js.map → findings-store-CvNo712L.js.map} +1 -1
  74. package/dist/fuzz.d.ts +1 -1
  75. package/dist/fuzz.js +1 -1
  76. package/dist/{hf-dataset-D9f7-oX7.js → hf-dataset-CKxIJQba.js} +3 -3
  77. package/dist/{hf-dataset-D9f7-oX7.js.map → hf-dataset-CKxIJQba.js.map} +1 -1
  78. package/dist/hosted/index.js +1 -1
  79. package/dist/{index-CX-GAUpw.d.ts → index-CHxwfW5g.d.ts} +2 -2
  80. package/dist/{index-CX-GAUpw.d.ts.map → index-CHxwfW5g.d.ts.map} +1 -1
  81. package/dist/{index-BLGqZ81N.d.ts → index-CVFStrQD.d.ts} +8 -8
  82. package/dist/{index-BLGqZ81N.d.ts.map → index-CVFStrQD.d.ts.map} +1 -1
  83. package/dist/{index-9jJ2fKSX.d.ts → index-CalAsXMR.d.ts} +7 -5
  84. package/dist/index-CalAsXMR.d.ts.map +1 -0
  85. package/dist/{index-CiRwLv2R.d.ts → index-D7fmC-1K.d.ts} +3 -4
  86. package/dist/index-D7fmC-1K.d.ts.map +1 -0
  87. package/dist/{index-BiT6RtNH.d.ts → index-DAXfpVf7.d.ts} +10 -10
  88. package/dist/{index-BiT6RtNH.d.ts.map → index-DAXfpVf7.d.ts.map} +1 -1
  89. package/dist/{index-ZuWx52WG.d.ts → index-Q6DvdcwI.d.ts} +67 -24
  90. package/dist/index-Q6DvdcwI.d.ts.map +1 -0
  91. package/dist/index.d.ts +26 -26
  92. package/dist/index.d.ts.map +1 -1
  93. package/dist/index.js +615 -692
  94. package/dist/index.js.map +1 -1
  95. package/dist/{integrity-DOd9Q86O.js → integrity-C8oUeB0g.js} +322 -197
  96. package/dist/integrity-C8oUeB0g.js.map +1 -0
  97. package/dist/{integrity-_qgZLA5p.d.ts → integrity-CCwvezWS.d.ts} +2 -2
  98. package/dist/{integrity-_qgZLA5p.d.ts.map → integrity-CCwvezWS.d.ts.map} +1 -1
  99. package/dist/{journal-CR4QikYp.js → journal-C7om8Gum.js} +48 -38
  100. package/dist/journal-C7om8Gum.js.map +1 -0
  101. package/dist/judge-gate-Co5tuh57.js.map +1 -1
  102. package/dist/{judge-gate-DsL0yFcb.d.ts → judge-gate-Dc_mXQsL.d.ts} +2 -2
  103. package/dist/judge-gate-Dc_mXQsL.d.ts.map +1 -0
  104. package/dist/{kind-factory-Gy4fXixd.js → kind-factory-BhxbtUsQ.js} +2 -2
  105. package/dist/{kind-factory-Gy4fXixd.js.map → kind-factory-BhxbtUsQ.js.map} +1 -1
  106. package/dist/ledger-core/index.d.ts +1 -1
  107. package/dist/ledger-core/index.js +2 -2
  108. package/dist/ledger-core/lock-holder.d.ts +2 -0
  109. package/dist/ledger-core/lock-holder.js +181 -0
  110. package/dist/ledger-core/lock-holder.js.map +1 -0
  111. package/dist/{ledger-core-DrJhbms9.js → ledger-core-CAxUdDk0.js} +2 -2
  112. package/dist/{ledger-core-DrJhbms9.js.map → ledger-core-CAxUdDk0.js.map} +1 -1
  113. package/dist/{llm-client-BshCREn6.js → llm-client-DXuOTseU.js} +239 -249
  114. package/dist/llm-client-DXuOTseU.js.map +1 -0
  115. package/dist/{llm-judge-C8jMTNNG.js → llm-judge-Cc8vDJh_.js} +648 -459
  116. package/dist/llm-judge-Cc8vDJh_.js.map +1 -0
  117. package/dist/lock-holder-DaJbfpci.d.ts +86 -0
  118. package/dist/lock-holder-DaJbfpci.d.ts.map +1 -0
  119. package/dist/matrix/index.d.ts +2 -2
  120. package/dist/{matrix-DHe-dwVJ.d.ts → matrix-Cf-AGxGh.d.ts} +4 -4
  121. package/dist/{matrix-DHe-dwVJ.d.ts.map → matrix-Cf-AGxGh.d.ts.map} +1 -1
  122. package/dist/meta-eval/index.d.ts +2 -2
  123. package/dist/{mint-zszyYlpA.js → mint-CbdwjTPW.js} +2 -2
  124. package/dist/{mint-zszyYlpA.js.map → mint-CbdwjTPW.js.map} +1 -1
  125. package/dist/{mint-BRZXuwRi.d.ts → mint-CkzpVPdz.d.ts} +3 -3
  126. package/dist/{mint-BRZXuwRi.d.ts.map → mint-CkzpVPdz.d.ts.map} +1 -1
  127. package/dist/multishot/golden/index.d.ts +1 -1
  128. package/dist/multishot/index.d.ts +2 -2
  129. package/dist/multishot/index.js.map +1 -1
  130. package/dist/openapi.json +1 -1
  131. package/dist/{pareto-BzsxidFD.js → pareto-BiBnQXAE.js} +306 -212
  132. package/dist/pareto-BiBnQXAE.js.map +1 -0
  133. package/dist/pipelines/index.d.ts.map +1 -1
  134. package/dist/pipelines/index.js.map +1 -1
  135. package/dist/{prime-protocol-BWG2DQIk.d.ts → prime-protocol-CckHBxGu.d.ts} +3 -3
  136. package/dist/{prime-protocol-BWG2DQIk.d.ts.map → prime-protocol-CckHBxGu.d.ts.map} +1 -1
  137. package/dist/{promotion-gate-DaY95yU6.d.ts → promotion-gate-CkVZHagC.d.ts} +3 -3
  138. package/dist/{promotion-gate-DaY95yU6.d.ts.map → promotion-gate-CkVZHagC.d.ts.map} +1 -1
  139. package/dist/{proposal-findings-BbWidvUk.js → proposal-findings-E1aSC_cU.js} +2 -2
  140. package/dist/{proposal-findings-BbWidvUk.js.map → proposal-findings-E1aSC_cU.js.map} +1 -1
  141. package/dist/{registry-ssNoHzwD.d.ts → registry-B_yG-1jh.d.ts} +5 -5
  142. package/dist/{registry-ssNoHzwD.d.ts.map → registry-B_yG-1jh.d.ts.map} +1 -1
  143. package/dist/{render-C-w2EZ6p.js → render-Cs34y0iX.js} +404 -208
  144. package/dist/render-Cs34y0iX.js.map +1 -0
  145. package/dist/reporting.d.ts +3 -3
  146. package/dist/{researcher-0ABVIdGa.d.ts → researcher-H0p44OYC.d.ts} +5 -5
  147. package/dist/{researcher-0ABVIdGa.d.ts.map → researcher-H0p44OYC.d.ts.map} +1 -1
  148. package/dist/{reward-DrZ71vnf.d.ts → reward-BeUgVVC_.d.ts} +2 -2
  149. package/dist/{reward-DrZ71vnf.d.ts.map → reward-BeUgVVC_.d.ts.map} +1 -1
  150. package/dist/{reward-hacking-E52wq86n.d.ts → reward-hacking-WTxUbtbb.d.ts} +2 -2
  151. package/dist/{reward-hacking-E52wq86n.d.ts.map → reward-hacking-WTxUbtbb.d.ts.map} +1 -1
  152. package/dist/rl.d.ts +8 -8
  153. package/dist/rl.js +4 -4
  154. package/dist/rollout/index.d.ts +3 -3
  155. package/dist/rollout/index.js +5 -5
  156. package/dist/{rollout-D6C50mfA.js → rollout-Dd1ucT_M.js} +5 -5
  157. package/dist/{rollout-D6C50mfA.js.map → rollout-Dd1ucT_M.js.map} +1 -1
  158. package/dist/{rubric-predictive-validity-DiwT8PbL.d.ts → rubric-predictive-validity-noY7uE03.d.ts} +2 -2
  159. package/dist/{rubric-predictive-validity-DiwT8PbL.d.ts.map → rubric-predictive-validity-noY7uE03.d.ts.map} +1 -1
  160. package/dist/{run-record-CaxbLq6Y.d.ts → run-record-C3awiXPf.d.ts} +2 -2
  161. package/dist/{run-record-CaxbLq6Y.d.ts.map → run-record-C3awiXPf.d.ts.map} +1 -1
  162. package/dist/schema-C-ziyJD7.d.ts.map +1 -1
  163. package/dist/{schema-DxcKTzbi.js → schema-CvhfLjtZ.js} +77 -47
  164. package/dist/schema-CvhfLjtZ.js.map +1 -0
  165. package/dist/search/index.d.ts +2 -2
  166. package/dist/search/index.d.ts.map +1 -1
  167. package/dist/search/index.js +2 -2
  168. package/dist/{search-kernel-DxqjBxA-.d.ts → search-kernel-Dloxd6gs.d.ts} +5 -5
  169. package/dist/{search-kernel-DxqjBxA-.d.ts.map → search-kernel-Dloxd6gs.d.ts.map} +1 -1
  170. package/dist/{search-ledger-TUvB5gWH.js → search-ledger-CZRqtFbW.js} +252 -245
  171. package/dist/search-ledger-CZRqtFbW.js.map +1 -0
  172. package/dist/{search-ledger-file-UKCO2r8a.js → search-ledger-file-Bd5Tioq6.js} +3 -3
  173. package/dist/{search-ledger-file-UKCO2r8a.js.map → search-ledger-file-Bd5Tioq6.js.map} +1 -1
  174. package/dist/{search-shipper-Cw2z3-td.js → search-shipper-Dn3NLsuH.js} +3 -3
  175. package/dist/{search-shipper-Cw2z3-td.js.map → search-shipper-Dn3NLsuH.js.map} +1 -1
  176. package/dist/{search-summary-DQIvJsSB.js → search-summary-D4bwYnAE.js} +3 -3
  177. package/dist/{search-summary-DQIvJsSB.js.map → search-summary-D4bwYnAE.js.map} +1 -1
  178. package/dist/{server-DoVbqqtJ.js → server-8TS8XCvg.js} +3 -3
  179. package/dist/{server-DoVbqqtJ.js.map → server-8TS8XCvg.js.map} +1 -1
  180. package/dist/{single-run-lock-U58yf8N6.js → single-run-lock-Dekd8_Wv.js} +7 -7
  181. package/dist/single-run-lock-Dekd8_Wv.js.map +1 -0
  182. package/dist/{skillopt-optimization-method-kyL94-ri.js → skillopt-optimization-method-DLKqdhcR.js} +1384 -1059
  183. package/dist/skillopt-optimization-method-DLKqdhcR.js.map +1 -0
  184. package/dist/{statistical-heldout-C9AbgREN.d.ts → statistical-heldout-3z3I-kJN.d.ts} +3 -3
  185. package/dist/{statistical-heldout-C9AbgREN.d.ts.map → statistical-heldout-3z3I-kJN.d.ts.map} +1 -1
  186. package/dist/{store-otlp-BteDAbHK.js → store-otlp-dyWE3wAG.js} +2 -2
  187. package/dist/{store-otlp-BteDAbHK.js.map → store-otlp-dyWE3wAG.js.map} +1 -1
  188. package/dist/{store-tool-spans-D5l_OfTJ.js → store-tool-spans-DIUgZbzu.js} +3 -3
  189. package/dist/{store-tool-spans-D5l_OfTJ.js.map → store-tool-spans-DIUgZbzu.js.map} +1 -1
  190. package/dist/{store-tool-spans-DZS0HWVf.d.ts → store-tool-spans-DPwXHQkH.d.ts} +7 -7
  191. package/dist/{store-tool-spans-DZS0HWVf.d.ts.map → store-tool-spans-DPwXHQkH.d.ts.map} +1 -1
  192. package/dist/{summary-report-DM7tlml1.d.ts → summary-report-C8V49Jt3.d.ts} +18 -3
  193. package/dist/summary-report-C8V49Jt3.d.ts.map +1 -0
  194. package/dist/supervisor-run/index.d.ts.map +1 -1
  195. package/dist/supervisor-run/index.js +3 -3
  196. package/dist/{systemone-Bp_Ac0p1.d.ts → systemone-DVA7t76V.d.ts} +6 -6
  197. package/dist/{systemone-Bp_Ac0p1.d.ts.map → systemone-DVA7t76V.d.ts.map} +1 -1
  198. package/dist/{systemone-review-CwE6JGIp.d.ts → systemone-review-CUBMuTLi.d.ts} +2 -2
  199. package/dist/{systemone-review-CwE6JGIp.d.ts.map → systemone-review-CUBMuTLi.d.ts.map} +1 -1
  200. package/dist/systemone.d.ts +3 -3
  201. package/dist/{terminal-record-78g6E4vh.js → terminal-record-D4Rv-j1W.js} +241 -193
  202. package/dist/{terminal-record-78g6E4vh.js.map → terminal-record-D4Rv-j1W.js.map} +1 -1
  203. package/dist/{tool-groups-DyNz2JZ_.d.ts → tool-groups-LISbBWCg.d.ts} +3 -3
  204. package/dist/tool-groups-LISbBWCg.d.ts.map +1 -0
  205. package/dist/{trace-questions-xxwgsuMi.d.ts → trace-questions-C42fYEE4.d.ts} +4 -4
  206. package/dist/{trace-questions-xxwgsuMi.d.ts.map → trace-questions-C42fYEE4.d.ts.map} +1 -1
  207. package/dist/trace-repair/index.d.ts +3 -3
  208. package/dist/traces.d.ts +6 -6
  209. package/dist/traces.js +3 -3
  210. package/dist/trajectory-replay/index.d.ts +4 -1
  211. package/dist/trajectory-replay/index.d.ts.map +1 -1
  212. package/dist/trajectory-replay/index.js +854 -823
  213. package/dist/trajectory-replay/index.js.map +1 -1
  214. package/dist/{tree-BGRglkKd.js → tree-DSqwJpL9.js} +122 -14
  215. package/dist/tree-DSqwJpL9.js.map +1 -0
  216. package/dist/{types-CW8ewATZ.d.ts → types-8yQzNm8u.d.ts} +4 -4
  217. package/dist/{types-CW8ewATZ.d.ts.map → types-8yQzNm8u.d.ts.map} +1 -1
  218. package/dist/{types-D8GhJoHk.d.ts → types-CHfn1zg5.d.ts} +70 -72
  219. package/dist/types-CHfn1zg5.d.ts.map +1 -0
  220. package/dist/{types-DtMbFw6U.d.ts → types-D8GXK9Z5.d.ts} +3 -3
  221. package/dist/{types-DtMbFw6U.d.ts.map → types-D8GXK9Z5.d.ts.map} +1 -1
  222. package/dist/{types-D-mgRzlh.d.ts → types-eMhdacVp.d.ts} +2 -2
  223. package/dist/{types-D-mgRzlh.d.ts.map → types-eMhdacVp.d.ts.map} +1 -1
  224. package/dist/wire/index.d.ts +3 -3
  225. package/dist/wire/index.js +1 -1
  226. package/docs/campaign-proposers.md +16 -0
  227. package/docs/concepts.md +31 -0
  228. package/docs/design/statistics-decisions.md +1 -1
  229. package/docs/eval-surface-map.md +1 -0
  230. package/docs/profile-json-identity.md +1 -2
  231. package/docs/public-api.md +100 -88
  232. package/package.json +8 -6
  233. package/dist/benchmark-command-xQK8nOI6.js.map +0 -1
  234. package/dist/campaign-CJGkxAQ6.js.map +0 -1
  235. package/dist/campaign-evidence-CQYw8_0H.js.map +0 -1
  236. package/dist/cost-ledger-D0352Z4d.js.map +0 -1
  237. package/dist/cost-ledger-Jk62OBfF.d.ts.map +0 -1
  238. package/dist/define-agent-eval-BDxNlP3D.js.map +0 -1
  239. package/dist/eval-campaign-BLEfBGbA.js +0 -343
  240. package/dist/eval-campaign-BLEfBGbA.js.map +0 -1
  241. package/dist/index-9jJ2fKSX.d.ts.map +0 -1
  242. package/dist/index-CiRwLv2R.d.ts.map +0 -1
  243. package/dist/index-ZuWx52WG.d.ts.map +0 -1
  244. package/dist/integrity-DOd9Q86O.js.map +0 -1
  245. package/dist/journal-CR4QikYp.js.map +0 -1
  246. package/dist/judge-gate-DsL0yFcb.d.ts.map +0 -1
  247. package/dist/llm-client-BshCREn6.js.map +0 -1
  248. package/dist/llm-judge-C8jMTNNG.js.map +0 -1
  249. package/dist/pareto-BzsxidFD.js.map +0 -1
  250. package/dist/render-C-w2EZ6p.js.map +0 -1
  251. package/dist/schema-DxcKTzbi.js.map +0 -1
  252. package/dist/search-ledger-TUvB5gWH.js.map +0 -1
  253. package/dist/single-run-lock-U58yf8N6.js.map +0 -1
  254. package/dist/skillopt-optimization-method-kyL94-ri.js.map +0 -1
  255. package/dist/summary-report-DM7tlml1.d.ts.map +0 -1
  256. package/dist/tool-groups-DyNz2JZ_.d.ts.map +0 -1
  257. package/dist/tree-BGRglkKd.js.map +0 -1
  258. package/dist/types-D8GhJoHk.d.ts.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"render-C-w2EZ6p.js","names":["round","record","record","round"],"sources":["../src/supervisor-run/patch-stats.ts","../src/supervisor-run/analyze.ts","../src/supervisor-run/coordination-reader.ts","../src/supervisor-run/runtime-source-limits.ts","../src/supervisor-run/runtime-reader.ts","../src/supervisor-run/reader.ts","../src/supervisor-run/render.ts"],"sourcesContent":["/** Unified-diff target, line, and test-file touch counts. */\nimport type { PatchStats } from './types'\n\n/** Unified-diff stats. Counts `+++ b/<path>` targets, body +/- lines, and test-file touches. */\nexport function parsePatch(text: string): PatchStats {\n const files = new Set<string>()\n const testFiles = new Set<string>()\n let added = 0\n let removed = 0\n for (const line of text.split('\\n')) {\n if (line.startsWith('+++ ')) {\n const p = line.slice(4).trim().replace(/^b\\//, '')\n if (p !== '/dev/null') {\n files.add(p)\n if (isTestPath(p)) testFiles.add(p)\n }\n continue\n }\n if (line.startsWith('--- ') || line.startsWith('diff --git') || line.startsWith('index ')) {\n continue\n }\n if (line.startsWith('+')) added += 1\n else if (line.startsWith('-')) removed += 1\n }\n return {\n files: files.size,\n linesAdded: added,\n linesRemoved: removed,\n testFilesTouched: [...testFiles].sort(),\n }\n}\n\nfunction isTestPath(p: string): boolean {\n const base = p.split('/').pop() ?? p\n return (\n /(^|\\/)(tests?|__tests__|testing|spec)(\\/|$)/.test(p) ||\n /\\.(test|spec)\\.[cm]?[jt]sx?$/.test(base) ||\n /^test_.*\\.py$/.test(base) ||\n /_test\\.py$/.test(base)\n )\n}\n","/**\n * The pure analyzer. Takes already-read bytes (`SupervisorRunSources`) and\n * returns the report — every metric derivable from a synthetic journal string\n * with no filesystem, no process, and no network. All I/O lives in a reader\n * (`reader.ts` is one).\n */\n\nimport { roundDecimal as round } from '../math/round-decimal'\nimport { summarizeNumberSeries } from '../statistics'\nimport { parsePatch } from './patch-stats'\nimport {\n asRecord,\n parseJsonRecord,\n parseJsonl,\n parseSupervisorTree,\n type SpawnRow,\n type WorkerLogFacts,\n workerSourceKey,\n} from './source-facts'\nimport { readTerminalRecord } from './terminal-record'\nimport {\n type DecisionMetrics,\n type EconomicsMetrics,\n isUnavailable,\n type Measured,\n type OrchestrationMetrics,\n type OutcomeMetrics,\n type PatchStats,\n type PerWorkerRow,\n type SpendMeasurements,\n type SteerBreakdown,\n SUPERVISOR_RUN_SCHEMA,\n type SupervisorRunReport,\n type SupervisorRunSources,\n type Unavailable,\n unavailable,\n} from './types'\n\nconst NO_CACHE_COUNTERS = 'the journal carries no cache-token counters for this role'\n\nconst NO_CACHE_BREAKDOWN =\n 'Runtime recorded cacheBreakdownKnown:false — the provider reported a total without splitting cache reads from writes'\n\n// ---------------------------------------------------------------------------\n// The analyzer.\n// ---------------------------------------------------------------------------\n\n/**\n * Analyze already-read supervisor-run bytes. Pure and synchronous: same bytes\n * in, same report out (modulo `generatedAt`, which `now` pins in tests).\n */\nexport function analyzeSupervisorRunSources(\n src: SupervisorRunSources,\n now: () => number = Date.now,\n): SupervisorRunReport {\n const gaps: string[] = []\n const gap = (what: string, reason: string): Unavailable => {\n gaps.push(`${what}: ${reason}`)\n return unavailable(reason)\n }\n\n const journalMissing =\n src.journalMissingReason ??\n (src.supRunDir === null ? 'no Runtime supervisor run directory' : 'journal.jsonl absent')\n const haveJournal = src.journal !== null\n const tree = parseSupervisorTree(src)\n const state = tree.state\n const result = parseJsonRecord(src.result)\n const judge = parseJsonRecord(src.judge)\n // Runtime's terminal record is named on the report so a status never arrives unlabeled.\n const terminal = readTerminalRecord({\n state,\n result,\n failure: src.failure === undefined ? undefined : parseJsonRecord(src.failure),\n })\n const { rootId, workerSpawns, workerCloses, startedAt, completedAt } = tree\n const rootSpawn =\n rootId === null ? null : (tree.spawns.find((spawn) => spawn.id === rootId) ?? null)\n const spawnById = new Map(workerSpawns.map((spawn) => [spawn.id, spawn]))\n const spawnsByLabel = new Map<string, SpawnRow[]>()\n for (const spawn of workerSpawns) {\n const matches = spawnsByLabel.get(spawn.label) ?? []\n matches.push(spawn)\n spawnsByLabel.set(spawn.label, matches)\n }\n const spawnsForSource = (\n worker: NonNullable<SupervisorRunSources['workers']>[number],\n ): readonly SpawnRow[] => {\n if (worker.workerId === undefined) return spawnsByLabel.get(worker.label) ?? []\n const spawn = spawnById.get(worker.workerId)\n return spawn === undefined ? [] : [spawn]\n }\n const spawnForSource = (\n worker: NonNullable<SupervisorRunSources['workers']>[number],\n ): SpawnRow | null => {\n const matches = spawnsForSource(worker)\n return matches.length === 1 ? (matches[0] ?? null) : null\n }\n\n // Wall provenance: explicit stamps when the store wrote both; otherwise the\n // journal event span (a lower bound) when there is no completion stamp at\n // all. A present-but-inverted stamp pair is corruption, not absence, and\n // stays unavailable.\n const wallSpanStart = startedAt ?? tree.firstEventAt\n const wallSpanEnd = tree.lastEventAt\n let supervisorWallMs: Measured<number>\n let supervisorWallSource: Measured<'stamps' | 'journal-span'>\n if (startedAt !== null && completedAt !== null && completedAt >= startedAt) {\n supervisorWallMs = completedAt - startedAt\n supervisorWallSource = 'stamps'\n } else if (\n completedAt === null &&\n wallSpanStart !== null &&\n wallSpanEnd !== null &&\n wallSpanEnd >= wallSpanStart\n ) {\n supervisorWallMs = wallSpanEnd - wallSpanStart\n supervisorWallSource = 'journal-span'\n } else {\n const reason = !haveJournal\n ? journalMissing\n : 'no parseable start/complete timestamps in state.json or journal'\n supervisorWallMs = gap('supervisorWallMs', reason)\n supervisorWallSource = unavailable(reason)\n }\n // Where the measured wall ends — the completion stamp, or the last stamped\n // journal event on the journal-span path. Idle and utilization integrate to\n // this bound so their denominator is the wall they are reported against.\n const wallEndAt = completedAt ?? (supervisorWallSource === 'journal-span' ? wallSpanEnd : null)\n\n // ── steers (worker inbox + control events) ─────────────────────────────\n const steerRows: SteerBreakdown[] = []\n let steerQueuedTotal = 0\n let steerDeliveredTotal = 0\n let upLegMessages = 0\n if (src.workers !== null) {\n for (const w of src.workers) {\n const facts = tree.workerLogs.get(workerSourceKey(w))\n const queued = facts?.steersQueued ?? null\n const delivered = facts?.steersDelivered ?? null\n upLegMessages += facts?.questions ?? 0\n if (queued !== null && delivered !== null) {\n steerRows.push({ workerId: w.workerId ?? null, worker: w.label, queued, delivered })\n }\n if (queued !== null) steerQueuedTotal += queued\n if (delivered !== null) steerDeliveredTotal += delivered\n }\n }\n const workersGapReason = src.workersMissingReason ?? 'workers/ directory absent'\n const unavailableReasons = (pick: (facts: WorkerLogFacts) => string | null): string | null => {\n const reasons = tree.workerLogRows\n .map((facts) => pick(facts))\n .filter((reason): reason is string => reason !== null)\n return reasons.length === 0\n ? null\n : `exact steer accounting unavailable for ${reasons.length} worker row(s): ${[...new Set(reasons)].join(' | ')}`\n }\n const queuedGapReason = unavailableReasons((facts) => facts.steersQueuedUnavailable)\n const deliveredGapReason = unavailableReasons((facts) => facts.steersDeliveredUnavailable)\n const workerEventsGapReason = unavailableReasons((facts) =>\n !facts.eventsCaptured\n ? 'events absent'\n : facts.eventsInvalidRows > 0\n ? 'events contain malformed rows'\n : null,\n )\n const steers: Measured<number> =\n src.workers === null\n ? gap('steers', workersGapReason)\n : queuedGapReason === null\n ? steerQueuedTotal\n : gap('steers', queuedGapReason)\n const steersDelivered: Measured<number> =\n src.workers === null\n ? unavailable(workersGapReason)\n : deliveredGapReason === null\n ? steerDeliveredTotal\n : unavailable(deliveredGapReason)\n const steersByWorker: Measured<readonly SteerBreakdown[]> =\n src.workers === null\n ? unavailable(workersGapReason)\n : queuedGapReason === null && deliveredGapReason === null\n ? steerRows\n : unavailable(queuedGapReason ?? deliveredGapReason ?? workersGapReason)\n\n // The `[driver] registered tools: …supervisor_steer…` banner names the verb without\n // invoking it, so banner lines are subtracted from the raw mention count.\n const driverSteerCalls: Measured<number> =\n src.driverLog === null\n ? gap('driverSteerCalls', 'driver.log absent')\n : Math.max(\n 0,\n (src.driverLog.match(/supervisor_steer/g) ?? []).length -\n registrationMentions(src.driverLog),\n )\n\n // ── waves / concurrency / idle ─────────────────────────────────────────\n const timeline: { at: number; delta: 1 | -1 }[] = []\n for (const s of workerSpawns) if (s.at !== null) timeline.push({ at: s.at, delta: 1 })\n for (const c of workerCloses) if (c.at !== null) timeline.push({ at: c.at, delta: -1 })\n timeline.sort((a, b) => a.at - b.at || a.delta - b.delta)\n\n let waves = 0\n const waveSizes: number[] = []\n let closedSinceWaveStart = true\n for (const step of timeline) {\n if (step.delta === 1) {\n if (closedSinceWaveStart) {\n waves += 1\n waveSizes.push(0)\n closedSinceWaveStart = false\n }\n waveSizes[waveSizes.length - 1] = (waveSizes[waveSizes.length - 1] ?? 0) + 1\n } else {\n closedSinceWaveStart = true\n }\n }\n\n let live = 0\n let maxConcurrency = 0\n let idleMs = 0\n let sumWorkerWallMs = 0\n let prev = startedAt\n for (const step of timeline) {\n if (prev !== null && step.at >= prev) {\n const span = step.at - prev\n if (live === 0) idleMs += span\n sumWorkerWallMs += span * live\n }\n live += step.delta\n if (live > maxConcurrency) maxConcurrency = live\n prev = step.at\n }\n if (prev !== null && wallEndAt !== null && wallEndAt >= prev) {\n const span = wallEndAt - prev\n if (live === 0) idleMs += span\n sumWorkerWallMs += span * live\n }\n\n const firstWorkerSpawnAt = workerSpawns.reduce<number | null>(\n (acc, s) => (s.at === null ? acc : acc === null ? s.at : Math.min(acc, s.at)),\n null,\n )\n const closeById = new Map(workerCloses.map((close) => [close.id, close]))\n const childSpawnsByParent = new Map<string, SpawnRow[]>()\n for (const spawn of workerSpawns) {\n if (spawn.parent === null) continue\n const siblings = childSpawnsByParent.get(spawn.parent) ?? []\n siblings.push(spawn)\n childSpawnsByParent.set(spawn.parent, siblings)\n }\n\n let respawns = 0\n let observeThenRespawn = 0\n let respawnWithoutEvidence = 0\n const repeatedLabelSet = new Set<string>()\n for (const siblings of childSpawnsByParent.values()) {\n const labelCounts = new Map<string, number>()\n for (const spawn of siblings) {\n labelCounts.set(spawn.label, (labelCounts.get(spawn.label) ?? 0) + 1)\n }\n for (const [label, count] of labelCounts) {\n if (count > 1) repeatedLabelSet.add(label)\n }\n\n const orderedSpawns = siblings\n .map((spawn, index) => ({ spawn, index }))\n .filter(\n (row): row is { spawn: SpawnRow & { at: number }; index: number } => row.spawn.at !== null,\n )\n .sort((a, b) => a.spawn.at - b.spawn.at || a.index - b.index)\n const directCloseTimes = siblings\n .map((spawn) => closeById.get(spawn.id)?.at ?? null)\n .filter((at): at is number => at !== null)\n .sort((a, b) => a - b)\n const firstDirectClose = directCloseTimes[0] ?? null\n\n for (let i = 1; i < orderedSpawns.length; i += 1) {\n const previous = orderedSpawns[i - 1]?.spawn.at\n const current = orderedSpawns[i]?.spawn.at\n if (previous === undefined || current === undefined) continue\n if (firstDirectClose === null || current <= firstDirectClose) continue\n respawns += 1\n const sawEvidence = hasNumberBetween(directCloseTimes, previous, current)\n if (sawEvidence) observeThenRespawn += 1\n else respawnWithoutEvidence += 1\n }\n }\n const repeatedLabels = [...repeatedLabelSet]\n\n const parentOf = new Map(tree.spawns.map((s) => [s.id, s.parent]))\n let delegationDepth = 0\n for (const s of workerSpawns) {\n let d = 0\n let cur: string | null = s.id\n const seen = new Set<string>()\n while (cur !== null && cur !== rootId && !seen.has(cur)) {\n seen.add(cur)\n d += 1\n cur = parentOf.get(cur) ?? null\n }\n if (d > delegationDepth) delegationDepth = d\n }\n\n const orchestration: OrchestrationMetrics = {\n workersSpawned: haveJournal ? workerSpawns.length : gap('workersSpawned', journalMissing),\n workersSettled: haveJournal\n ? workerCloses.filter((c) => c.kind === 'settled').length\n : unavailable(journalMissing),\n workersCancelled: haveJournal\n ? workerCloses.filter((c) => c.kind === 'cancelled').length\n : unavailable(journalMissing),\n steers,\n steersDelivered,\n steersByWorker,\n driverSteerCalls,\n waves: haveJournal ? waves : unavailable(journalMissing),\n waveSizes: haveJournal ? waveSizes : unavailable(journalMissing),\n maxConcurrency: haveJournal ? maxConcurrency : unavailable(journalMissing),\n respawns: haveJournal ? respawns : unavailable(journalMissing),\n repeatedLabels: haveJournal ? repeatedLabels : unavailable(journalMissing),\n delegationDepth: haveJournal ? delegationDepth : unavailable(journalMissing),\n timeToFirstSpawnMs:\n startedAt !== null && firstWorkerSpawnAt !== null\n ? firstWorkerSpawnAt - startedAt\n : haveJournal\n ? unavailable('no worker spawn timestamps')\n : unavailable(journalMissing),\n supervisorWallMs,\n supervisorWallSource,\n idleMs: isUnavailable(supervisorWallMs) ? unavailable(supervisorWallMs.unavailable) : idleMs,\n idlePct:\n isUnavailable(supervisorWallMs) || supervisorWallMs === 0\n ? isUnavailable(supervisorWallMs)\n ? unavailable(supervisorWallMs.unavailable)\n : unavailable('supervisor wall is 0ms')\n : round((idleMs / supervisorWallMs) * 100, 1),\n workerUtilization:\n isUnavailable(supervisorWallMs) || supervisorWallMs === 0\n ? isUnavailable(supervisorWallMs)\n ? unavailable(supervisorWallMs.unavailable)\n : unavailable('supervisor wall is 0ms')\n : round(sumWorkerWallMs / supervisorWallMs, 3),\n }\n\n // ── decision quality ───────────────────────────────────────────────────\n const settledByStatus: Record<string, number> = {}\n const settledVerdicts: Record<string, number> = {}\n for (const c of workerCloses) {\n const key = c.status ?? 'unknown'\n settledByStatus[key] = (settledByStatus[key] ?? 0) + 1\n if (c.verdict !== null) settledVerdicts[c.verdict] = (settledVerdicts[c.verdict] ?? 0) + 1\n }\n\n // A store with no verify step never says pass or fail. Counting its silent\n // workers as `rejected: 0 / accepted: 0` would read as \"nothing was accepted\".\n const verdictLimit = src.limits.workerVerdicts\n // A store that retains no delivered patch still SETTLES a verdict, and that verdict is\n // the acceptance decision it recorded. Only the split between a green verdict backed by\n // a patch and a green verdict with nothing behind it needs patch bytes, so the\n // deliverables limit takes `emptyPass` and leaves `accepted` measured.\n const deliverablesLimit = src.limits.deliverables\n let accepted = 0\n let emptyPass = 0\n let evidenceBytes = 0\n const sourceVerdicts: boolean[] = []\n for (const w of src.workers ?? []) {\n const f = tree.workerLogs.get(workerSourceKey(w))\n if (f?.finished) evidenceBytes += f.evidenceBytes\n const spawn = spawnForSource(w)\n const close = spawn === null ? null : (closeById.get(spawn.id) ?? null)\n const passed = close?.valid ?? f?.passed ?? null\n if (passed !== null) sourceVerdicts.push(passed)\n if (passed === true) {\n if (deliverablesLimit !== null || (w.patchBytes ?? f?.finishedPatchBytes ?? 0) > 0) {\n accepted += 1\n } else {\n emptyPass += 1\n }\n }\n }\n const settledCloses = workerCloses.filter((close) => close.kind === 'settled')\n const structuredVerdicts = settledCloses\n .map((close) => close.valid)\n .filter((valid): valid is boolean => valid !== null)\n const journalVerdictsComplete =\n settledCloses.length > 0 && structuredVerdicts.length === settledCloses.length\n const sourceVerdictsComplete =\n sourceVerdicts.length > 0 && sourceVerdicts.length >= settledCloses.length\n const rejected = journalVerdictsComplete\n ? structuredVerdicts.filter((valid) => !valid).length\n : sourceVerdictsComplete\n ? sourceVerdicts.filter((valid) => !valid).length\n : 0\n const rejectedLimit =\n journalVerdictsComplete || sourceVerdictsComplete\n ? null\n : settledCloses.length > 0\n ? (verdictLimit ?? 'a settled journal verdict has no validity and no matched worker log')\n : verdictLimit !== null\n ? verdictLimit\n : !haveJournal && src.workers === null\n ? workersGapReason\n : null\n\n const decision: DecisionMetrics = {\n settledByStatus: haveJournal ? settledByStatus : gap('settledByStatus', journalMissing),\n settledVerdicts:\n verdictLimit !== null\n ? unavailable(verdictLimit)\n : haveJournal\n ? settledVerdicts\n : unavailable(journalMissing),\n accepted:\n verdictLimit !== null\n ? gap('accepted', verdictLimit)\n : src.workers === null\n ? unavailable(workersGapReason)\n : accepted,\n rejected: rejectedLimit === null ? rejected : unavailable(rejectedLimit),\n emptyPass:\n verdictLimit !== null\n ? gap('emptyPass', verdictLimit)\n : deliverablesLimit !== null\n ? gap('emptyPass', deliverablesLimit)\n : src.workers === null\n ? unavailable(workersGapReason)\n : emptyPass,\n observeThenRespawn: haveJournal ? observeThenRespawn : unavailable(journalMissing),\n respawnWithoutEvidence: haveJournal ? respawnWithoutEvidence : unavailable(journalMissing),\n reviewActions:\n src.workers === null\n ? unavailable(workersGapReason)\n : queuedGapReason === null\n ? steerQueuedTotal + upLegMessages\n : unavailable(queuedGapReason),\n workerEvidenceBytes:\n src.workers === null\n ? unavailable(workersGapReason)\n : workerEventsGapReason === null\n ? evidenceBytes\n : unavailable(workerEventsGapReason),\n }\n\n // ── economics ──────────────────────────────────────────────────────────\n const rootChildIds = new Set(\n workerSpawns.filter((spawn) => spawn.parent === rootId).map((spawn) => spawn.id),\n )\n const rootChildCloses = workerCloses.filter((close) => rootChildIds.has(close.id))\n // Runtime marks a spend record `usdKnown: false` / `tokensKnown: false` when the work\n // HAPPENED but no provider receipt covered its price or its tokens. Folding such a record\n // in prices unreported work at zero; dropping the whole channel discards every record that\n // DID report. So each channel sums only the reporting records and names the rest.\n const rootChildSpends = rootChildCloses.filter((close) => close.hasSpend)\n const workerUsdUnknownNodes = rootChildSpends\n .filter((close) => !close.spend.usdKnown)\n .map((close) => close.id)\n const workerTokensUnknownNodes = rootChildSpends\n .filter((close) => !close.spend.tokensKnown)\n .map((close) => close.id)\n const workerTokenSpends = rootChildSpends.filter((close) => close.spend.tokensKnown)\n const journalWorkerIn = workerTokenSpends.reduce((a, c) => a + c.spend.tokens.input, 0)\n const journalWorkerOut = workerTokenSpends.reduce((a, c) => a + c.spend.tokens.output, 0)\n const journalWorkerUsd = rootChildSpends\n .filter((close) => close.spend.usdKnown)\n .reduce((a, c) => a + c.spend.usd, 0)\n const usdUnknownIds = new Set(\n workerCloses.filter((close) => close.hasSpend && !close.spend.usdKnown).map((c) => c.id),\n )\n const workerUsdById = new Map<string, number>()\n for (const c of workerCloses) {\n if (usdUnknownIds.has(c.id)) continue\n workerUsdById.set(c.id, (workerUsdById.get(c.id) ?? 0) + c.spend.usd)\n }\n const labelById = new Map(workerSpawns.map((spawn) => [spawn.id, spawn.label]))\n const usdUnknownLabels = new Set(\n [...usdUnknownIds].map((id) => labelById.get(id)).filter((l): l is string => l !== undefined),\n )\n const workerUsdByLabel = new Map<string, number>()\n for (const close of workerCloses) {\n const label = labelById.get(close.id)\n if (label === undefined || usdUnknownLabels.has(label)) continue\n workerUsdByLabel.set(label, (workerUsdByLabel.get(label) ?? 0) + close.spend.usd)\n }\n const brainUsdUnknownNodes =\n tree.brain.usdUnknownCount > 0 && rootId !== null ? ([rootId] as const) : []\n const brainTokensUnknownNodes =\n tree.brain.tokensUnknownCount > 0 && rootId !== null ? ([rootId] as const) : []\n const usdKnownRecords =\n tree.brain.usdKnownCount + rootChildSpends.filter((close) => close.spend.usdKnown).length\n const usdUnknownRecords = tree.brain.usdUnknownCount + workerUsdUnknownNodes.length\n const usdUnknownNodes = [...brainUsdUnknownNodes, ...workerUsdUnknownNodes]\n // The named nodes are what makes the gap actionable, but a fleet run can have hundreds,\n // and this string lands in a report line. Name the first few and count the rest.\n const NAMED_NODE_LIMIT = 5\n const nameNodes = (nodes: readonly string[]): string => {\n if (nodes.length === 0) return ''\n const shown = nodes.slice(0, NAMED_NODE_LIMIT)\n const rest = nodes.length - shown.length\n return ` (${shown.join(', ')}${rest === 0 ? '' : ` +${rest} more`})`\n }\n const unpriced = (unknown: number, total: number, nodes: readonly string[]): string =>\n `Runtime recorded usdKnown:false on ${unknown} of ${total} spend record(s)${nameNodes(nodes)}`\n // A token total is a bare `Measured<number>` with no record denominator beside it, so a\n // partial sum there would be an unlabelled floor — the exact collapse this module refuses.\n // Spend has `SpendMeasurement.records`/`unknownRecords` to carry the split, so it stays\n // partial; tokens go absent with the unreporting nodes named.\n const unreportedTokens = (unknown: number, total: number, nodes: readonly string[]): string =>\n `Runtime recorded tokensKnown:false on ${unknown} of ${total} spend record(s)${nameNodes(nodes)}`\n const usdPartial = usdKnownRecords > 0 && usdUnknownRecords > 0\n const usdAllUnknown = usdKnownRecords === 0 && usdUnknownRecords > 0\n // A role whose records are ALL unreported has nothing measured to report, so it stays\n // unavailable. A role with some of each keeps its sum and labels it in `source`.\n const brainTokensUnreported =\n tree.brain.tokensUnknownCount === 0\n ? null\n : unreportedTokens(\n tree.brain.tokensUnknownCount,\n tree.brain.meteredCount,\n brainTokensUnknownNodes,\n )\n const brainUsdUnreported =\n tree.brain.usdKnownCount > 0 || tree.brain.usdUnknownCount === 0\n ? null\n : unpriced(tree.brain.usdUnknownCount, tree.brain.meteredCount, brainUsdUnknownNodes)\n const workerUsdUnreported =\n workerUsdUnknownNodes.length === 0 || workerUsdUnknownNodes.length < rootChildSpends.length\n ? null\n : unpriced(workerUsdUnknownNodes.length, rootChildSpends.length, workerUsdUnknownNodes)\n const sq = src.harnessWorkerTokens\n const harnessGapReason =\n src.harnessMissingReason ?? 'harness session store unavailable and journal settled spend is 0'\n const workerTokenLimit = src.limits.workerTokens\n const workerTokensUnreported =\n workerTokensUnknownNodes.length === 0\n ? null\n : unreportedTokens(\n workerTokensUnknownNodes.length,\n rootChildSpends.length,\n workerTokensUnknownNodes,\n )\n const workerIn: Measured<number> =\n workerTokenLimit !== null\n ? gap('workers.tokensIn', workerTokenLimit)\n : workerTokensUnreported !== null\n ? gap('workers.tokensIn', workerTokensUnreported)\n : sq !== null\n ? journalWorkerIn + sq.input\n : haveJournal\n ? journalWorkerIn\n : gap('workers.tokensIn', harnessGapReason)\n const workerOut: Measured<number> =\n workerTokenLimit !== null\n ? unavailable(workerTokenLimit)\n : workerTokensUnreported !== null\n ? unavailable(workerTokensUnreported)\n : sq !== null\n ? journalWorkerOut + sq.output\n : haveJournal\n ? journalWorkerOut\n : unavailable(harnessGapReason)\n\n const stateResult = asRecord(state?.result)\n const stateUsd = typeof stateResult.spentUsd === 'number' ? stateResult.spentUsd : null\n const resultSpentTotal = asRecord(result?.spentTotal)\n const resultCloseUsd =\n typeof resultSpentTotal.usd === 'number' && Number.isFinite(resultSpentTotal.usd)\n ? resultSpentTotal.usd\n : null\n // The close record: what the store wrote as settled when the run closed.\n const closeUsd = stateUsd ?? resultCloseUsd\n // A store that logs tokens but never a price yields usd 0 from every sum. That\n // 0 is the store's silence, not a free run, so the limit outranks the sum.\n const usdLimit = src.limits.spendUsd\n // The close record carries its own completeness flag: `spentTotal.usdKnown: false` means\n // Runtime priced part of the run from a catalog, so the number is a floor, not a total.\n const closeUsdUnreported =\n stateUsd === null && resultCloseUsd !== null && resultSpentTotal.usdKnown === false\n const usdUnreportedReason = unpriced(\n usdUnknownRecords,\n usdKnownRecords + usdUnknownRecords,\n usdUnknownNodes,\n )\n // Which numbers may be partial, and which must go absent: a number may be a floor only\n // when its own record carries the known/unknown split beside it — `SpendMeasurement`\n // has `records`/`unknownRecords`, and `RoleSpend` has `source`. `totalUsd` is a bare\n // scalar, so a floor there is an unlabelled understatement and stays unavailable; the\n // partial sum with its denominators lives in `spend.journalDerived`, which this type's\n // own doc already names as the field to prefer.\n const totalUsd: Measured<number> =\n usdLimit !== null\n ? gap('totalUsd', usdLimit)\n : stateUsd !== null\n ? round(stateUsd, 6)\n : !haveJournal\n ? gap('totalUsd', journalMissing)\n : usdUnknownRecords > 0\n ? gap('totalUsd', usdUnreportedReason)\n : round(tree.brain.usd + journalWorkerUsd, 6)\n\n const journalSpendRecords = usdKnownRecords\n // `journalDerived` keeps its partial sum: `records` and `unknownRecords` state exactly\n // how much of the run it covers. Only an all-unreported channel has nothing to report.\n const journalDerivedAvailable = usdLimit === null && haveJournal && !usdAllUnknown\n const closeRecordAvailable = usdLimit === null && closeUsd !== null && !closeUsdUnreported\n const spend: SpendMeasurements = {\n journalDerived: {\n usd: journalDerivedAvailable\n ? round(tree.brain.usd + journalWorkerUsd, 6)\n : unavailable(usdLimit ?? (haveJournal ? usdUnreportedReason : journalMissing)),\n records: journalDerivedAvailable ? journalSpendRecords : 0,\n unknownRecords: usdLimit === null && haveJournal ? usdUnknownRecords : 0,\n partial: journalDerivedAvailable && usdPartial,\n unknownNodes: usdLimit === null && haveJournal ? usdUnknownNodes : [],\n },\n closeRecord: {\n usd: closeRecordAvailable\n ? round(closeUsd as number, 6)\n : unavailable(\n usdLimit ??\n (closeUsdUnreported\n ? 'close record incomplete: result.json spentTotal.usdKnown is false'\n : 'no close record: neither state.json result.spentUsd nor result.json spentTotal.usd is present'),\n ),\n records: closeRecordAvailable ? 1 : 0,\n unknownRecords: closeUsdUnreported ? 1 : 0,\n partial: false,\n unknownNodes: closeUsdUnreported && rootId !== null ? [rootId] : [],\n },\n }\n\n const noteCaptureGaps = (\n owner: string,\n captures: SupervisorRunSources['rootWorkspaceCaptures'],\n ): void => {\n if (captures === null || captures?.length === 0) {\n gaps.push(`${owner} workspaceCapture: no retained output capture evidence`)\n } else if (captures !== undefined) {\n for (const [index, capture] of captures.entries()) {\n const source = `${owner} workspaceCapture[${index + 1}]`\n if (capture.projectionGap !== null) gaps.push(`${source}: ${capture.projectionGap}`)\n if (capture.coverageComplete === false) {\n gaps.push(\n `${source}: ${capture.incompleteReason ?? 'provider reported incomplete coverage'}`,\n )\n }\n if (capture.coverageComplete === null && capture.projectionGap === null) {\n gaps.push(`${source}: capture coverage was not recorded`)\n }\n }\n }\n }\n noteCaptureGaps(`root ${rootId ?? src.runRef}`, src.rootWorkspaceCaptures)\n const perWorker: PerWorkerRow[] = (src.workers ?? []).map((w) => {\n noteCaptureGaps(`worker ${w.workerId ?? w.label}`, w.workspaceCaptures)\n const f = tree.workerLogs.get(workerSourceKey(w))\n const matchingSpawns = spawnsForSource(w)\n const spawn = spawnForSource(w)\n const close = spawn === null ? null : (closeById.get(spawn.id) ?? null)\n const passed = close?.valid ?? f?.passed ?? null\n const matchingRoles = new Set(matchingSpawns.map((candidate) => candidate.role))\n const matchingRuntimes = new Set(matchingSpawns.map((candidate) => candidate.runtime))\n const matchingProfiles = new Set(matchingSpawns.map((candidate) => candidate.profileDigest))\n const journalWallMs =\n spawn?.at !== null &&\n spawn?.at !== undefined &&\n close?.at !== null &&\n close?.at !== undefined &&\n close.at >= spawn.at\n ? close.at - spawn.at\n : null\n return {\n workerId: w.workerId ?? null,\n worker: w.label,\n role: matchingRoles.size === 1 ? (matchingSpawns[0]?.role ?? null) : null,\n runtime: matchingRuntimes.size === 1 ? (matchingSpawns[0]?.runtime ?? null) : null,\n profileDigest:\n matchingProfiles.size === 1 ? (matchingSpawns[0]?.profileDigest ?? null) : null,\n status: close?.status ?? null,\n failure: close?.reason ?? null,\n infra: close?.infra ?? null,\n wallMs: f?.started != null && f.finishedAt != null ? f.finishedAt - f.started : journalWallMs,\n tokensIn:\n w.tokensIn ??\n (close?.hasSpend === true && close.spend.tokensKnown ? close.spend.tokens.input : null),\n tokensOut:\n w.tokensOut ??\n (close?.hasSpend === true && close.spend.tokensKnown ? close.spend.tokens.output : null),\n usd:\n usdLimit !== null\n ? null\n : w.workerId === undefined\n ? (workerUsdByLabel.get(w.label) ?? null)\n : (workerUsdById.get(w.workerId) ?? null),\n patchBytes: w.patchBytes ?? f?.finishedPatchBytes ?? null,\n passed,\n score: close?.score ?? f?.score ?? null,\n workspaceCaptures: w.workspaceCaptures ?? null,\n }\n })\n const wallDistribution = summarizeNumberSeries(\n perWorker.map((w) => w.wallMs).filter((w): w is number => w !== null),\n )\n\n const brainCalls = parseJsonl(src.brainLog)\n const managerTokenLimit = src.limits.managerTokens\n const economics: EconomicsMetrics = {\n resourceRecords:\n src.journal === null && !tree.resourceRecords?.length\n ? unavailable(journalMissing)\n : (tree.resourceRecords ?? []),\n brain: {\n tokensIn:\n managerTokenLimit !== null\n ? gap('brain.tokensIn', managerTokenLimit)\n : !haveJournal\n ? gap('brain.tokensIn', journalMissing)\n : brainTokensUnreported !== null\n ? gap('brain.tokensIn', brainTokensUnreported)\n : tree.brain.tokensIn,\n tokensOut:\n managerTokenLimit !== null\n ? unavailable(managerTokenLimit)\n : !haveJournal\n ? unavailable(journalMissing)\n : brainTokensUnreported !== null\n ? unavailable(brainTokensUnreported)\n : tree.brain.tokensOut,\n usd:\n usdLimit !== null\n ? unavailable(usdLimit)\n : !haveJournal\n ? unavailable(journalMissing)\n : brainUsdUnreported !== null\n ? unavailable(brainUsdUnreported)\n : round(tree.brain.usd, 6),\n cacheRead:\n managerTokenLimit !== null\n ? unavailable(managerTokenLimit)\n : !haveJournal\n ? unavailable(journalMissing)\n : brainTokensUnreported !== null\n ? unavailable(brainTokensUnreported)\n : !tree.brain.hasCache\n ? unavailable(NO_CACHE_COUNTERS)\n : tree.brain.cacheBreakdownKnown\n ? tree.brain.cacheRead\n : unavailable(NO_CACHE_BREAKDOWN),\n cacheWrite:\n managerTokenLimit !== null\n ? unavailable(managerTokenLimit)\n : !haveJournal\n ? unavailable(journalMissing)\n : brainTokensUnreported !== null\n ? unavailable(brainTokensUnreported)\n : !tree.brain.hasCache\n ? unavailable(NO_CACHE_COUNTERS)\n : tree.brain.cacheBreakdownKnown\n ? tree.brain.cacheWrite\n : unavailable(NO_CACHE_BREAKDOWN),\n source:\n managerTokenLimit ??\n (haveJournal\n ? `journal metered events (n=${tree.brain.meteredCount})${\n tree.brain.usdKnownCount > 0 && tree.brain.usdUnknownCount > 0\n ? ` — ${tree.brain.usdUnknownCount} unpriced`\n : ''\n }`\n : journalMissing),\n },\n brainTruncations:\n src.brainLog === null\n ? gap(\n 'brain.brainTruncations',\n src.brainLogMissingReason ??\n (src.supRunDir === null\n ? 'no Runtime supervisor run directory'\n : 'brain.jsonl absent — this source has no brain-call tap, so truncation cannot be ruled out'),\n )\n : brainCalls.filter((c) => c.finish_reason === 'length').length,\n workers: {\n tokensIn: workerIn,\n tokensOut: workerOut,\n cacheRead:\n workerTokenLimit !== null\n ? unavailable(workerTokenLimit)\n : sq?.cacheRead !== undefined\n ? sq.cacheRead\n : unavailable(NO_CACHE_COUNTERS),\n cacheWrite:\n workerTokenLimit !== null\n ? unavailable(workerTokenLimit)\n : sq?.cacheWrite !== undefined\n ? sq.cacheWrite\n : unavailable(NO_CACHE_COUNTERS),\n usd:\n usdLimit !== null\n ? unavailable(usdLimit)\n : !haveJournal\n ? unavailable(journalMissing)\n : workerUsdUnreported !== null\n ? unavailable(workerUsdUnreported)\n : round(journalWorkerUsd, 6),\n source: `${\n workerTokenLimit !== null\n ? workerTokenLimit\n : sq !== null\n ? `journal settled spend + ${sq.store} sessions (n=${sq.sessions})`\n : `journal settled spend only — ${src.harnessMissingReason ?? 'harness session store unavailable'}`\n }${\n workerUsdUnknownNodes.length > 0 && workerUsdUnknownNodes.length < rootChildSpends.length\n ? ` — ${workerUsdUnknownNodes.length} unpriced`\n : ''\n }`,\n },\n spend,\n totalUsd,\n totalUsdSource:\n usdLimit !== null\n ? usdLimit\n : stateUsd !== null\n ? `state.json result.spentUsd${rootChildCloses.length > 0 && journalWorkerUsd === 0 ? ' — brain-priced only; worker CLI inference is unpriced (see worker token counts)' : ''}`\n : !haveJournal\n ? journalMissing\n : usdUnknownRecords > 0\n ? usdUnreportedReason\n : 'journal metered + settled usd',\n costPerAcceptedPatchUsd: isUnavailable(totalUsd)\n ? unavailable(totalUsd.unavailable)\n : isUnavailable(decision.accepted)\n ? unavailable(decision.accepted.unavailable)\n : decision.accepted === 0\n ? unavailable('no accepted worker patch (cost has no denominator)')\n : round(totalUsd / decision.accepted, 6),\n workerWallMsDistribution:\n wallDistribution === null\n ? unavailable(\n src.workers === null ? workersGapReason : 'no worker start/finish pairs captured',\n )\n : wallDistribution,\n perWorker: src.workers === null ? unavailable(workersGapReason) : perWorker,\n }\n\n // ── outcome ────────────────────────────────────────────────────────────\n const patchStats: Measured<PatchStats> =\n src.patch === null\n ? gap('patch', src.limits.deliverables ?? 'delivered patch file absent')\n : parsePatch(src.patch)\n\n const outcome: OutcomeMetrics = {\n supStatus: isUnavailable(terminal.supStatus)\n ? gap('supStatus', terminal.supStatus.unavailable)\n : terminal.supStatus,\n supStatusSource: terminal.supStatusSource,\n supReason: terminal.supReason,\n failure: terminal.failure,\n supVerdict:\n pickString(state, 'verdict') ??\n pickString(result, 'sup_verdict') ??\n unavailable('no state.json / result.json verdict'),\n delivered:\n typeof stateResult.delivered === 'boolean'\n ? stateResult.delivered\n : typeof result?.delivered === 'boolean'\n ? result.delivered\n : unavailable('no delivered flag in state.json or result.json'),\n judgeResolved:\n judge === null\n ? gap('judge', 'judge.json absent')\n : typeof judge.resolved === 'boolean'\n ? judge.resolved\n : null,\n judgeScore:\n judge === null\n ? unavailable('judge.json absent')\n : typeof judge.score === 'number'\n ? judge.score\n : null,\n judgePassed:\n judge === null\n ? unavailable('judge.json absent')\n : typeof judge.passed === 'number'\n ? judge.passed\n : null,\n judgeTotal:\n judge === null\n ? unavailable('judge.json absent')\n : typeof judge.total === 'number'\n ? judge.total\n : null,\n verifyPass:\n typeof result?.verify_pass === 'boolean'\n ? result.verify_pass\n : gap('verifyPass', 'result.json absent or has no verify_pass'),\n verifyRc:\n typeof result?.verify_rc === 'number'\n ? result.verify_rc\n : unavailable('result.json absent or has no verify_rc'),\n patch: patchStats,\n judgeSource: src.judgeSource,\n }\n\n return {\n schema: SUPERVISOR_RUN_SCHEMA,\n runRef: src.runRef,\n instanceId: src.instanceId,\n arm: src.arm,\n supervisorId: rootId !== null ? rootId : unavailable(journalMissing),\n supervisorProfileDigest:\n rootSpawn?.profileDigest !== null && rootSpawn?.profileDigest !== undefined\n ? rootSpawn.profileDigest\n : gap('supervisorProfileDigest', 'root spawned event has no profile digest'),\n generatedAt: new Date(now()).toISOString(),\n orchestration,\n decision,\n economics,\n outcome,\n rootWorkspaceCaptures: src.rootWorkspaceCaptures ?? null,\n gaps,\n traceCommand:\n src.traceCommand ??\n 'npx --yes @tangle-network/traces@latest analyze --harness opencode --cwd <worker-clone-cwd>',\n }\n}\n\n/** Whether sorted values contain one value in the inclusive interval. */\nfunction hasNumberBetween(sorted: readonly number[], low: number, high: number): boolean {\n let left = 0\n let right = sorted.length\n while (left < right) {\n const middle = left + Math.floor((right - left) / 2)\n if ((sorted[middle] as number) < low) left = middle + 1\n else right = middle\n }\n return left < sorted.length && (sorted[left] as number) <= high\n}\n\n/** `[driver] registered tools: …supervisor_steer…` is a banner, not an invocation. */\nfunction registrationMentions(driverLog: string): number {\n let n = 0\n for (const line of driverLog.split('\\n')) {\n if (line.includes('registered tools:') && line.includes('supervisor_steer')) n += 1\n }\n return n\n}\n\nfunction pickString(rec: Record<string, unknown> | null, key: string): string | null {\n const v = rec?.[key]\n return typeof v === 'string' ? v : null\n}\n","/**\n * Optional Runtime run-dir files, read as bytes.\n *\n * `coordination-log.jsonl` is Runtime's JSONL of `{ runId, seq, at, event }`:\n * questions, steers, answers and peer mail between nodes. The `team-shape`\n * analyst reads communication and steer edges from it.\n */\n\nimport { readFile } from 'node:fs/promises'\nimport { join } from 'node:path'\n\nconst COORDINATION_FILE = 'coordination-log.jsonl'\n\n/** File text, or null when the file does not exist. Any other read error throws. */\nexport async function readMaybe(path: string): Promise<string | null> {\n return readFile(path, 'utf8').catch((error: unknown) => {\n if (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code: unknown }).code === 'ENOENT'\n ) {\n return null\n }\n throw error\n })\n}\n\n/** The run's coordination log, or null when Runtime wrote none. */\nexport function readCoordinationLog(runDir: string): Promise<string | null> {\n return readMaybe(join(runDir, COORDINATION_FILE))\n}\n","import { nonEmptyString, recordOrNull as record } from './source-facts'\nimport type { SourceLimits } from './types'\n\nfunction spendRecord(value: unknown): Record<string, unknown> | null {\n const spend = record(value)\n if (spend === null) return null\n const tokens = record(spend.tokens)\n if (\n tokens === null ||\n typeof tokens.input !== 'number' ||\n !Number.isFinite(tokens.input) ||\n tokens.input < 0 ||\n typeof tokens.output !== 'number' ||\n !Number.isFinite(tokens.output) ||\n tokens.output < 0 ||\n typeof spend.usd !== 'number' ||\n !Number.isFinite(spend.usd) ||\n spend.usd < 0 ||\n (spend.usdKnown !== undefined && typeof spend.usdKnown !== 'boolean')\n ) {\n return null\n }\n return spend\n}\n\nexport function sourceLimits(\n root: string,\n events: readonly Record<string, unknown>[],\n workerIds: ReadonlySet<string>,\n): SourceLimits {\n const rootMeters = events.filter((event) => event.kind === 'metered' && event.id === root)\n const invalidRootMeters = rootMeters.filter((event) => spendRecord(event.spend) === null)\n const rootMeterReason =\n rootMeters.length === 0\n ? 'Runtime journal has no root metered event'\n : invalidRootMeters.length > 0\n ? `${invalidRootMeters.length} root metered event(s) lack complete spend`\n : null\n const closes = events.filter(\n (event) =>\n workerIds.has(nonEmptyString(event.id) ?? '') &&\n (event.kind === 'settled' || event.kind === 'cancelled'),\n )\n const settledById = new Map<string, Record<string, unknown>[]>()\n for (const event of closes) {\n const id = nonEmptyString(event.id)\n if (id === null) continue\n const matches = settledById.get(id) ?? []\n matches.push(event)\n settledById.set(id, matches)\n }\n const incompleteWorkers = [...workerIds].filter((id) => {\n const terminal = settledById.get(id)\n return (\n terminal?.length !== 1 ||\n terminal[0]?.kind !== 'settled' ||\n spendRecord(terminal[0]?.spent) === null\n )\n })\n const missingVerdicts = [...workerIds].filter((id) => {\n const terminal = settledById.get(id)?.[0]\n if (terminal?.kind !== 'settled') return true\n const verdict = record(terminal.verdict)\n return typeof verdict?.valid !== 'boolean'\n })\n\n return {\n managerTokens: rootMeterReason,\n workerTokens:\n incompleteWorkers.length === 0\n ? null\n : `${incompleteWorkers.length}/${workerIds.size} child invocation(s) lack one settled spend record`,\n // `usdKnown: false` on ONE record is not a limit of this store: the store priced every\n // other record, and a limit here discards them all. The analyzer folds the flag per\n // record instead, and reports a partial total with the unpriced nodes named.\n spendUsd:\n rootMeterReason !== null\n ? rootMeterReason\n : incompleteWorkers.length > 0\n ? 'at least one child invocation lacks a settled spend record'\n : null,\n workerVerdicts:\n missingVerdicts.length === 0\n ? null\n : `${missingVerdicts.length}/${workerIds.size} child invocation(s) lack a structured validity verdict`,\n deliverables:\n workerIds.size === 0\n ? null\n : 'Runtime FileRunContext does not retain per-child delivered patches',\n }\n}\n","/**\n * Reader for agent-runtime's file-backed supervision context.\n *\n * Runtime stores multiple recursive trees in one `spawn-journal.jsonl`.\n * Each line is an envelope whose `root` identifies the local tree. A journal\n * can connect a nested tree with `spawned.ownedTreeRoot`. It can also use the\n * spawned child id as the nested root when no owned tree is recorded. Either\n * way the nested tree may repeat its owner's spawn as a parentless marker: the\n * owner's id, not the tree key, identifies it (an owned tree's key is a path\n * such as `root/root:s0`). Descendant spawns must occur in the tree their\n * parent owns. This reader removes a duplicate marker and preserves the other\n * envelopes for the supervisor-run analyzer. Runtime stores profile\n * identity below `identity` and does not emit Eval's role field. This boundary\n * projects those fields without changing Runtime's dialect.\n *\n * Transcripts come from Runtime's own records too: `root-stream.jsonl` is the root's, each\n * worker's turn outputs and native-session receipt are read from the journal, and every blob\n * a record names is checked on disk (see `nodeTranscripts`).\n *\n * The run's terminal record is Runtime's own: `result.json` is the\n * `SupervisedResult` that `supervise()` returned, verbatim, and its `kind`\n * (`winner`, `no-winner`, or whatever a later arm is called) is the status.\n * `failure.json` (`{ runId, pursuitId, at, error: { name, message } }`) is the\n * record Runtime writes when `supervise()` threw before a result landed. Both\n * pass through as bytes; `terminal-record.ts` reads them. The reader does not\n * decide which kinds count: a kind it refuses is a run that recorded its\n * outcome and got reported as having none. The reader does not synthesize status fields. The analyzer names the Runtime\n * record that supplied a status, so status provenance cannot be mislabelled.\n *\n * `usdKnown: false` / `tokensKnown: false` on ONE record is not a limit of this\n * store. The store recorded every other record completely, so the flags travel\n * through to the analyzer per record, which reports the measured nodes and\n * names the unreported ones.\n */\n\nimport { readFile, stat } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { hashCanonical } from '../ledger-core/canonical'\nimport type { RolloutWorkspaceCapture } from '../rollout/schema'\nimport { readCoordinationLog, readMaybe } from './coordination-reader'\nimport { sourceLimits } from './runtime-source-limits'\nimport { nonEmptyString, recordOrNull as record } from './source-facts'\nimport {\n NO_SOURCE_LIMITS,\n type SupervisorRunSources,\n type WorkerLogSource,\n type WorkerNativeSession,\n} from './types'\n\nconst JOURNAL_FILE = 'spawn-journal.jsonl'\nconst OBSERVER_FILE = 'observer.jsonl'\nconst ROOT_STREAM_FILE = 'root-stream.jsonl'\nconst BLOB_DIR = 'blobs'\nconst RESULT_FILE = 'result.json'\nconst FAILURE_FILE = 'failure.json'\n\n/**\n * The files only Runtime's durable layer writes. Any one of them marks a\n * Runtime run directory: `supervise()` opens the spawn journal on its first\n * event, and `supervisePursuit` appends the observer's `before` event and, on\n * a throw, the failure record before any spawn.\n *\n * Measured motive (discovery-lab recursive smoke r1, 2026-09-06): the first\n * attempt threw on a caller input error 16 minutes before the corrected attempt\n * opened the spawn journal. At that instant the directory held `observer.jsonl`\n * (2 records) and the failure record and no journal, so a journal-only test\n * routed it to an unrelated reader, which reads neither file, and the recorded\n * throw was reported as no run at all.\n */\nconst RUNTIME_RUN_DIR_MARKERS: readonly string[] = [JOURNAL_FILE, OBSERVER_FILE, FAILURE_FILE]\n\ninterface BeginRecord {\n readonly root: string\n readonly at: string\n readonly line: number\n}\n\ninterface EventRecord {\n readonly root: string\n readonly event: Record<string, unknown>\n readonly line: number\n}\n\ninterface NormalizedRuntimeJournal {\n readonly root: string\n readonly startedAt: string\n readonly journal: string\n readonly events: readonly Record<string, unknown>[]\n}\n\nfunction profileDigest(event: Record<string, unknown>): string | null {\n const direct = nonEmptyString(event.profileDigest)\n if (direct !== null) return direct\n const identity = record(event.identity)\n return identity === null ? null : nonEmptyString(identity.profileDigest)\n}\n\nfunction formatError(path: string, line: number, detail: string): Error {\n return new Error(`${path}:${line}: invalid Runtime spawn journal: ${detail}`)\n}\n\nfunction parseEnvelopeJournal(text: string, path: string): NormalizedRuntimeJournal {\n const begins: BeginRecord[] = []\n const events: EventRecord[] = []\n const begun = new Map<string, BeginRecord>()\n\n for (const [index, sourceLine] of text.split('\\n').entries()) {\n const line = index + 1\n const trimmed = sourceLine.trim()\n if (trimmed.length === 0) continue\n let parsed: unknown\n try {\n parsed = JSON.parse(trimmed)\n } catch {\n throw formatError(path, line, 'line is not JSON')\n }\n const envelope = record(parsed)\n if (envelope === null) throw formatError(path, line, 'line is not an object')\n const kind = nonEmptyString(envelope.kind)\n const root = nonEmptyString(envelope.root)\n if (root === null) throw formatError(path, line, 'root must be a non-empty string')\n\n if (kind === 'begin') {\n const at = nonEmptyString(envelope.at)\n if (at === null || !Number.isFinite(Date.parse(at))) {\n throw formatError(path, line, 'begin.at must be an ISO timestamp')\n }\n if (begun.has(root)) throw formatError(path, line, `tree ${JSON.stringify(root)} began twice`)\n const begin = { root, at, line }\n begun.set(root, begin)\n begins.push(begin)\n continue\n }\n\n if (kind !== 'event') {\n throw formatError(path, line, \"kind must be 'begin' or 'event'\")\n }\n if (!begun.has(root)) {\n throw formatError(path, line, `event for tree ${JSON.stringify(root)} precedes begin`)\n }\n const event = record(envelope.event)\n if (event === null) throw formatError(path, line, 'event must be an object')\n if (nonEmptyString(event.kind) === null) {\n throw formatError(path, line, 'event.kind must be a non-empty string')\n }\n events.push({ root, event: { ...event }, line })\n }\n\n if (begins.length === 0) throw formatError(path, 1, 'no begin record')\n\n const parentSpawnsById = new Map<string, EventRecord[]>()\n const parentSpawnsByOwnedTreeRoot = new Map<string, EventRecord[]>()\n for (const entry of events) {\n if (entry.event.kind !== 'spawned') continue\n const id = nonEmptyString(entry.event.id)\n if (id === null) continue\n if (nonEmptyString(entry.event.parent) !== null) {\n const ownedTreeRoot = nonEmptyString(entry.event.ownedTreeRoot)\n if (ownedTreeRoot !== null) {\n const owners = parentSpawnsByOwnedTreeRoot.get(ownedTreeRoot) ?? []\n owners.push(entry)\n parentSpawnsByOwnedTreeRoot.set(ownedTreeRoot, owners)\n } else {\n const matches = parentSpawnsById.get(id) ?? []\n matches.push(entry)\n parentSpawnsById.set(id, matches)\n }\n }\n }\n\n const nestedRoots = new Set<string>()\n const nestedParentSpawns = new Map<string, EventRecord>()\n for (const begin of begins) {\n const parentSpawns = [\n ...new Set([\n ...(parentSpawnsByOwnedTreeRoot.get(begin.root) ?? []),\n ...(parentSpawnsById.get(begin.root) ?? []),\n ]),\n ].filter((entry) => entry.root !== begin.root)\n if (parentSpawns.length > 1) {\n throw formatError(\n path,\n begin.line,\n `tree ${JSON.stringify(begin.root)} has ${parentSpawns.length} parent spawns`,\n )\n }\n if (parentSpawns.length === 1) {\n nestedRoots.add(begin.root)\n nestedParentSpawns.set(begin.root, parentSpawns[0] as EventRecord)\n }\n }\n\n const topRoots = begins.filter((begin) => !nestedRoots.has(begin.root))\n if (topRoots.length !== 1) {\n throw formatError(\n path,\n topRoots[0]?.line ?? 1,\n `expected one top-level tree, found ${topRoots.length}`,\n )\n }\n const top = topRoots[0] as BeginRecord\n\n // A tree's root marker is a parentless spawn of the node that owns the tree: the top root\n // itself, or the parent spawn that owns a nested tree. An owned tree's key is a path, so\n // the owner's id is compared, never the tree key.\n const ownerIdByTree = new Map<string, string>([[top.root, top.root]])\n for (const [nestedRoot, parentSpawn] of nestedParentSpawns) {\n const ownerId = nonEmptyString(parentSpawn.event.id)\n if (ownerId !== null) ownerIdByTree.set(nestedRoot, ownerId)\n }\n const isRootMarker = (entry: EventRecord): boolean =>\n entry.event.kind === 'spawned' &&\n (entry.event.parent === undefined || entry.event.parent === null) &&\n nonEmptyString(entry.event.id) !== null &&\n entry.event.id === ownerIdByTree.get(entry.root)\n const rootMarkersByTree = new Map<string, EventRecord[]>()\n for (const entry of events) {\n if (!isRootMarker(entry)) continue\n const markers = rootMarkersByTree.get(entry.root) ?? []\n markers.push(entry)\n rootMarkersByTree.set(entry.root, markers)\n }\n\n for (const nestedRoot of nestedRoots) {\n const markers = rootMarkersByTree.get(nestedRoot) ?? []\n if (markers.length > 1) {\n throw formatError(\n path,\n begun.get(nestedRoot)?.line ?? 1,\n `nested tree ${JSON.stringify(nestedRoot)} contains ${markers.length} root markers`,\n )\n }\n const parentSpawn = nestedParentSpawns.get(nestedRoot)\n if (parentSpawn === undefined) {\n throw formatError(\n path,\n begun.get(nestedRoot)?.line ?? 1,\n `nested tree ${JSON.stringify(nestedRoot)} has no parent spawn`,\n )\n }\n const markerDigest = profileDigest(markers[0]?.event ?? {})\n const parentDigest = profileDigest(parentSpawn.event)\n if (markerDigest !== null && parentDigest !== null && markerDigest !== parentDigest) {\n throw formatError(\n path,\n markers[0]?.line ?? 1,\n `nested tree ${JSON.stringify(nestedRoot)} disagrees with its parent profile digest`,\n )\n }\n if (parentDigest === null && markerDigest !== null) {\n parentSpawn.event.profileDigest = markerDigest\n }\n }\n\n const ownedTreeBySupervisorId = new Map<string, string>([[top.root, top.root]])\n for (const [nestedRoot, parentSpawn] of nestedParentSpawns) {\n const supervisorId = nonEmptyString(parentSpawn.event.id)\n if (supervisorId === null) continue\n const priorTree = ownedTreeBySupervisorId.get(supervisorId)\n if (priorTree !== undefined && priorTree !== nestedRoot) {\n throw formatError(\n path,\n parentSpawn.line,\n `spawn ${JSON.stringify(supervisorId)} owns both ${JSON.stringify(priorTree)} and ${JSON.stringify(nestedRoot)}`,\n )\n }\n ownedTreeBySupervisorId.set(supervisorId, nestedRoot)\n }\n for (const entry of events) {\n if (entry.event.kind !== 'spawned') continue\n const parentId = nonEmptyString(entry.event.parent)\n if (parentId === null) continue\n const parentTree = ownedTreeBySupervisorId.get(parentId)\n if (parentTree === undefined) {\n throw formatError(\n path,\n entry.line,\n `spawn ${JSON.stringify(entry.event.id)} names parent ${JSON.stringify(parentId)}, which owns no journal tree`,\n )\n }\n if (entry.root !== parentTree) {\n throw formatError(\n path,\n entry.line,\n `spawn ${JSON.stringify(entry.event.id)} is in tree ${JSON.stringify(entry.root)}, but parent ${JSON.stringify(parentId)} owns tree ${JSON.stringify(parentTree)}`,\n )\n }\n }\n\n // Runtime's recursive atom has no supervisor/worker role field. A tree root\n // is a supervisor; a child without its own tree is a worker.\n const supervisorIds = new Set([\n top.root,\n ...[...nestedParentSpawns.values()]\n .map((entry) => nonEmptyString(entry.event.id))\n .filter((id): id is string => id !== null),\n ])\n const normalized = events\n .filter((entry) => !(nestedRoots.has(entry.root) && isRootMarker(entry)))\n .map((entry) => {\n const event = { ...entry.event }\n if (event.kind === 'spawned') {\n const digest = profileDigest(event)\n if (event.profileDigest === undefined && digest !== null) {\n event.profileDigest = digest\n }\n if (event.role === undefined) {\n event.role = supervisorIds.has(nonEmptyString(event.id) ?? '') ? 'supervisor' : 'worker'\n }\n }\n return { root: entry.root, event }\n })\n\n const rootMarkers = rootMarkersByTree.get(top.root) ?? []\n if (rootMarkers.length !== 1) {\n throw formatError(\n path,\n top.line,\n `top-level tree ${JSON.stringify(top.root)} must contain one root marker`,\n )\n }\n\n return {\n root: top.root,\n startedAt: top.at,\n // Keep Runtime's event envelope intact. The pure source parser uses the envelope to\n // distinguish an understood-but-unmodeled Runtime event from an unreadable flat record.\n journal: `${normalized\n .map((entry) => JSON.stringify({ kind: 'event', root: entry.root, event: entry.event }))\n .join('\\n')}\\n`,\n events: normalized.map((entry) => entry.event),\n }\n}\n\nfunction parseOptionalRecord(text: string | null, path: string): Record<string, unknown> | null {\n if (text === null) return null\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n throw new Error(`${path}: invalid JSON`)\n }\n const value = record(parsed)\n if (value === null) throw new Error(`${path}: expected a JSON object`)\n return value\n}\n\n/**\n * Refuse a `result.json` that belongs to another run. Runtime's result carries\n * its own `tree.root`; a settled record with a different root is a copied or\n * misplaced file, and reading its status onto this journal misreports the run.\n */\nfunction assertResultMatchesJournal(\n root: string,\n result: Record<string, unknown> | null,\n resultPath: string,\n): void {\n const resultKind = result === null ? null : nonEmptyString(result.kind)\n if (resultKind === null || result === null) return\n const resultRoot = nonEmptyString(record(result.tree)?.root)\n if (resultRoot === null) {\n throw new Error(`${resultPath}: Runtime ${resultKind} result has no tree.root`)\n }\n if (resultRoot !== root) {\n throw new Error(\n `${resultPath}: root ${JSON.stringify(resultRoot)} does not match journal root ${JSON.stringify(root)}`,\n )\n }\n}\n\n/**\n * Refuse a `failure.json` that is not a failure record. Runtime writes\n * `{ runId, pursuitId, at, error: { name, message } }`; a document without an\n * `error` object is not one, and reading it as a failure invents a terminal\n * state the run never recorded. The record carries no tree root, so its\n * identity is not checked against the journal.\n */\nfunction assertFailureRecord(failure: Record<string, unknown> | null, failurePath: string): void {\n if (failure === null) return\n if (record(failure.error) === null) {\n throw new Error(`${failurePath}: Runtime failure record has no error object`)\n }\n}\n\n/**\n * The journal's begin stamp in the analyzer's state-document shape. It carries\n * the run identity and start instant only; the terminal status lives in\n * Runtime's own `result.json` / `failure.json`, which the analyzer reads by\n * name, so no synthetic status field is fabricated here.\n */\nfunction runtimeBeginState(root: string, startedAt: string): string {\n return JSON.stringify({ id: root, startedAt })\n}\n\n/**\n * The file Runtime's `FileResultBlobStore` writes for one content address\n * (`sha256:<hex>` → `blobs/sha256-<hex>.json`), or null for anything that is not one.\n */\nfunction blobFile(runDir: string, ref: unknown): string | null {\n return typeof ref === 'string' && /^sha256:[0-9a-f]{64}$/u.test(ref)\n ? join(runDir, BLOB_DIR, `${ref.replace(':', '-')}.json`)\n : null\n}\n\ntype NodeTranscript = Pick<\n WorkerLogSource,\n 'transcriptRef' | 'turns' | 'nativeSession' | 'workspaceCaptures'\n>\n\ninterface NodeTranscriptFacts {\n dispatched: number\n readonly outputRefs: { value: unknown; turn: boolean }[]\n readonly outputPositions: Map<string, number>\n receipt: Record<string, unknown> | null\n}\n\n/** A later receipt replaces an earlier one, except that an absence never replaces an available one. */\nfunction keepReceipt(fact: NodeTranscriptFacts, receipt: Record<string, unknown> | null): void {\n if (receipt === null) return\n if (fact.receipt?.status === 'available' && receipt.status !== 'available') return\n fact.receipt = receipt\n}\n\n/**\n * The files each harness writes its conversation to. A receipt can be available and complete\n * while holding none of them: on the 2026-10-04 trace proof a Pi worker that never wrote a session\n * stored only `.pi/agent/models-store.json`, and this summary counted it as a transcript.\n */\nconst HARNESS_SESSION_FILE: Readonly<Record<string, RegExp>> = {\n 'claude-code': /(^|\\/)\\.claude\\/projects\\/.+\\.jsonl$/u,\n codex: /(^|\\/)\\.codex\\/sessions\\/.+\\.jsonl$/u,\n pi: /(^|\\/)\\.pi\\/agent\\/sessions\\/.+\\.jsonl$/u,\n opencode:\n /(^|\\/)(\\.local\\/share\\/opencode\\/(opencode\\.db|storage\\/session\\/.+\\.json|export\\/.+\\.json)|\\.opencode\\/sessions\\/.+)$/u,\n}\n\n/** Session files the receipt's transcript blob lists, or undefined when it cannot say. */\nasync function receiptSessionFiles(file: string): Promise<number | undefined> {\n let descriptor: unknown\n try {\n descriptor = JSON.parse(await readFile(file, 'utf8'))\n } catch {\n return undefined\n }\n const harness = record(descriptor)?.harness\n const files = record(descriptor)?.files\n const pattern = typeof harness === 'string' ? HARNESS_SESSION_FILE[harness] : undefined\n if (pattern === undefined || !Array.isArray(files)) return undefined\n return files.filter((entry) => {\n const path = record(entry)?.path\n return typeof path === 'string' && pattern.test(path)\n }).length\n}\n\ntype NativeSessionState = 'complete' | 'partial' | 'no-session-file' | 'unavailable' | 'none'\n\nfunction nativeSessionState(session: WorkerNativeSession | null | undefined): NativeSessionState {\n if (session === null || session === undefined) return 'none'\n if (session.status !== 'available') return 'unavailable'\n if (session.coverageComplete === false) return 'partial'\n if (session.sessionFiles === 0) return 'no-session-file'\n return 'complete'\n}\n\n/**\n * What this reader can say about harness-session traces. Every spawned worker counts, including\n * one that recorded nothing; the root is reported apart because its receipt lives in result.json\n * (`rootHarnessTranscript`), not on a worker. Runtime records the session identity on each\n * receipt, so the sessions are read per node, not through one command. A receipt counts as a\n * session only when its copy is complete and holds a file the harness writes its conversation to.\n */\nfunction nativeTraceSummary(\n workers: readonly WorkerLogSource[],\n root: NodeTranscript | undefined,\n): string {\n const states = workers.map((worker) => nativeSessionState(worker.nativeSession))\n const count = (state: NativeSessionState): number => states.filter((s) => s === state).length\n const rootSession = root?.nativeSession ?? null\n const rootState = nativeSessionState(rootSession)\n const rootText =\n rootSession === null\n ? 'no receipt'\n : rootSession.status === 'unavailable'\n ? `unavailable (${rootSession.reason})`\n : rootState === 'complete'\n ? 'complete'\n : rootState === 'partial'\n ? 'partial copy'\n : 'no session file'\n if (rootSession === null && states.every((state) => state === 'none'))\n return 'unavailable — no node carries a Runtime harness transcript receipt'\n const gaps = [\n count('partial') > 0 ? `${count('partial')} only a partial copy` : null,\n count('no-session-file') > 0\n ? `${count('no-session-file')} a receipt with no session file`\n : null,\n ].filter((gap): gap is string => gap !== null)\n return `per node — ${count('complete')} of ${workers.length} workers carry a complete native session receipt (workers[].nativeSession)${gaps.length > 0 ? `; ${gaps.join('; ')}` : ''}; root: ${rootText} (result.json rootHarnessTranscript)`\n}\n\nasync function workspaceCapturesFromOutput(\n runDir: string,\n ref: unknown,\n): Promise<RolloutWorkspaceCapture[]> {\n const outRef = typeof ref === 'string' ? ref : null\n const blobPath = blobFile(runDir, ref)\n const missing = (projectionGap: string): RolloutWorkspaceCapture => ({\n outRef,\n blobPath,\n receiptPointer: null,\n receipt: null,\n attempts: null,\n coverageComplete: null,\n incompleteReason: null,\n projectionGap,\n })\n if (blobPath === null) return [missing('Runtime output has no valid content address')]\n if (!(await isFile(blobPath))) return [missing('Runtime output blob is missing or not a file')]\n const raw = await readMaybe(blobPath)\n if (raw === null) return [missing('Runtime output blob is missing')]\n let output: unknown\n try {\n output = JSON.parse(raw)\n } catch {\n return [missing('Runtime output blob is not JSON')]\n }\n let addressGap: string | null = null\n try {\n if (hashCanonical(output) !== outRef) {\n addressGap = 'Runtime output content address does not match output blob'\n }\n } catch {\n addressGap = 'Runtime output cannot be canonically hashed'\n }\n const project = (rawReceipt: unknown, receiptPointer: string | null): RolloutWorkspaceCapture => {\n const receipt = record(rawReceipt)\n if (receipt === null) {\n return {\n ...missing(\n `workspaceCapture receipt is absent or malformed${addressGap === null ? '' : `; ${addressGap}`}`,\n ),\n receiptPointer,\n receipt: rawReceipt,\n }\n }\n const provenance = record(receipt.provenance)\n const attempts = Array.isArray(provenance?.attempts) ? provenance.attempts : null\n const coverageComplete =\n typeof receipt.coverageComplete === 'boolean' ? receipt.coverageComplete : null\n const incompleteReason =\n typeof receipt.incompleteReason === 'string' ? receipt.incompleteReason : null\n const gaps: string[] = []\n if (addressGap !== null) gaps.push(addressGap)\n if (coverageComplete === null) gaps.push('workspaceCapture.coverageComplete is absent')\n if (record(receipt.snapshot) === null) gaps.push('workspaceCapture.snapshot is absent')\n if (provenance === null) gaps.push('workspaceCapture.provenance is absent')\n if (attempts === null) gaps.push('workspaceCapture.provenance.attempts is absent')\n else if (attempts.length === 0 || attempts.some((attempt) => record(attempt) === null)) {\n gaps.push('workspaceCapture.provenance.attempts is empty or malformed')\n }\n return {\n outRef,\n blobPath,\n receiptPointer,\n receipt,\n attempts,\n coverageComplete,\n incompleteReason,\n projectionGap: gaps.length > 0 ? gaps.join('; ') : null,\n }\n }\n const result = record(output)\n const captures: RolloutWorkspaceCapture[] = []\n // Use the record's field order and each array's order so every retained source stays ordered.\n for (const key of Object.keys(result ?? {})) {\n if (key === 'workspaceCapture') {\n captures.push(project(result?.[key], '/workspaceCapture'))\n } else if (key === 'workspaceCaptures') {\n const receipts = result?.[key]\n if (Array.isArray(receipts) && receipts.length > 0) {\n for (const [index, receipt] of receipts.entries()) {\n captures.push(project(receipt, `/workspaceCaptures/${index}`))\n }\n } else {\n captures.push({\n ...missing(\n `workspaceCaptures is empty or malformed${addressGap === null ? '' : `; ${addressGap}`}`,\n ),\n receiptPointer: '/workspaceCaptures',\n receipt: receipts ?? null,\n })\n }\n }\n }\n return captures.length > 0 ? captures : [project(null, null)]\n}\n\n/**\n * What Runtime retained of each node's decisions, from its own records.\n *\n * - A turn is one `execution-admitted` event in the `dispatched` phase. Its `execution-result`\n * names an output blob holding that turn's provider event stream (reasoning, tool calls and\n * results as the harness reported them). A dispatched turn with no retained output lost its\n * record, which is how a worker that went down mid-turn shows up.\n * - Every event's `outRef` enters the same collector, once per node and address. Terminal\n * records retain ordinary and steerable results; they are not counted as dispatched turns.\n * - The terminal event's `harnessTranscript` receipt covers the harness's native session files.\n * Those are the only record of the harness's own subagents, so an unavailable receipt is a\n * separate gap from a missing turn, and its reason is Runtime's, verbatim. `settled`,\n * `cancelled` and `reconciled` all carry one; an available receipt is never replaced by a later\n * absence. The root has no terminal event, so its receipt is the settle record's\n * `rootHarnessTranscript`.\n *\n * Blob files are checked on disk: a receipt that names a blob the directory no longer holds is\n * not a retained transcript.\n */\nasync function nodeTranscripts(\n runDir: string,\n events: readonly Record<string, unknown>[],\n nodeIds: ReadonlySet<string>,\n root?: { readonly id: string; readonly receipt: Record<string, unknown> | null },\n): Promise<Map<string, NodeTranscript>> {\n const facts = new Map<string, NodeTranscriptFacts>()\n const entry = (id: string): NodeTranscriptFacts => {\n let found = facts.get(id)\n if (found === undefined) {\n found = { dispatched: 0, outputRefs: [], outputPositions: new Map(), receipt: null }\n facts.set(id, found)\n }\n return found\n }\n for (const event of events) {\n const id = nonEmptyString(event.id)\n if (id === null || !nodeIds.has(id)) continue\n if (Object.hasOwn(event, 'outRef')) {\n const fact = entry(id)\n const ref = event.outRef\n const position = typeof ref === 'string' ? fact.outputPositions.get(ref) : undefined\n if (position !== undefined) {\n if (event.kind === 'execution-result') fact.outputRefs[position]!.turn = true\n } else {\n if (typeof ref === 'string') fact.outputPositions.set(ref, fact.outputRefs.length)\n fact.outputRefs.push({ value: ref, turn: event.kind === 'execution-result' })\n }\n }\n if (event.kind === 'execution-admitted' && record(event.admission)?.phase === 'dispatched') {\n entry(id).dispatched += 1\n } else if (\n event.kind === 'settled' ||\n event.kind === 'cancelled' ||\n event.kind === 'reconciled'\n ) {\n // A reconciled node carries its receipt on `reconciled`, which 15 available transcripts of\n // the 2026-10-04 Discovery archives did and this reader once skipped.\n keepReceipt(entry(id), record(event.harnessTranscript))\n }\n }\n if (root !== undefined && nodeIds.has(root.id)) keepReceipt(entry(root.id), root.receipt)\n const out = new Map<string, NodeTranscript>()\n for (const [id, fact] of facts) {\n const retained: string[] = []\n let retainedTurns = 0\n const workspaceCaptures: RolloutWorkspaceCapture[] = []\n for (const { value: ref, turn } of fact.outputRefs) {\n const file = blobFile(runDir, ref)\n if (file !== null && (await isFile(file))) {\n retained.push(file)\n if (turn) retainedTurns += 1\n }\n workspaceCaptures.push(...(await workspaceCapturesFromOutput(runDir, ref)))\n }\n let nativeSession: WorkerNativeSession | null = null\n if (fact.receipt !== null) {\n if (fact.receipt.status === 'available') {\n const file = blobFile(runDir, fact.receipt.transcriptRef)\n if (file !== null && (await isFile(file))) {\n const sessionFiles = await receiptSessionFiles(file)\n const coverageComplete = fact.receipt.coverageComplete\n nativeSession = {\n status: 'available',\n ref: file,\n ...(typeof coverageComplete === 'boolean' ? { coverageComplete } : {}),\n ...(sessionFiles === undefined ? {} : { sessionFiles }),\n }\n } else {\n nativeSession = { status: 'unavailable', reason: 'receipt-blob-missing' }\n }\n } else {\n nativeSession = {\n status: 'unavailable',\n reason: nonEmptyString(fact.receipt.reason) ?? 'unavailable',\n }\n }\n }\n out.set(id, {\n // The native session is the fuller record; the newest turn output is the next best.\n transcriptRef:\n nativeSession?.status === 'available' ? nativeSession.ref : (retained.at(-1) ?? null),\n turns: { dispatched: fact.dispatched, retained: retainedTurns },\n nativeSession,\n workspaceCaptures: workspaceCaptures.length > 0 ? workspaceCaptures : null,\n })\n }\n return out\n}\n\nexport interface RuntimeReaderOptions {\n /**\n * Throw on a missing spawn journal instead of returning absent-shaped\n * sources. The default (false) models a journal-less run dir — a\n * pre-supervise death, a backfilled zombie — as a readable absence.\n */\n readonly strict?: boolean\n}\n\n/**\n * Sources for a run dir whose spawn journal does not exist. Mirrors the\n * absent shape the reader returns for a missing store: every\n * journal-dependent metric downstream reads `unavailable`, never 0.\n */\n/**\n * The run identity a terminal record names when no journal exists yet: the\n * settle record's `tree.root`, else the failure record's `runId`. Both are\n * Runtime's own `runId`, so the report names the run the record is about\n * instead of `?`.\n */\nfunction recordedRunId(\n result: Record<string, unknown> | null,\n failure: Record<string, unknown> | null,\n): string | null {\n return nonEmptyString(record(result?.tree)?.root) ?? nonEmptyString(failure?.runId)\n}\n\nfunction absentRuntimeSupervisorRun(\n runDir: string,\n resultText: string | null,\n failureText: string | null,\n instanceId: string | null,\n): SupervisorRunSources {\n const reason = `no Runtime spawn journal (${JOURNAL_FILE}) under ${runDir}`\n return {\n runRef: runDir,\n instanceId,\n arm: null,\n supRunDir: null,\n journal: null,\n journalMissingReason: reason,\n brainLog: null,\n brainLogMissingReason:\n 'Runtime FileRunContext records spend but not model completion finish reasons',\n state: null,\n progress: null,\n workers: null,\n workersMissingReason: reason,\n result: resultText,\n failure: failureText,\n judge: null,\n judgeSource: null,\n patch: null,\n driverLog: null,\n harnessWorkerTokens: null,\n harnessMissingReason: 'Runtime FileRunContext has no external worker-token join',\n limits: NO_SOURCE_LIMITS,\n rootTranscriptRef: null,\n rootWorkspaceCaptures: null,\n traceCommand: 'unavailable — Runtime FileRunContext records no provider-session trace identity',\n }\n}\n\n/**\n * Read one agent-runtime `createFileRunContext(dir)` directory.\n *\n * A run dir without `spawn-journal.jsonl` returns the same absent-shaped\n * sources the reader returns for a missing store: `journal` and\n * `workers` null, each with its reason, so every dependent metric reads\n * `unavailable` — never 0 and never a throw. Its `result.json` and\n * `failure.json` are still read, so a run that died before its first spawn\n * reports the failure Runtime recorded. Pass `strict: true` to throw on the\n * missing journal instead. A journal, result, or failure document that exists\n * but cannot be parsed always throws: a corrupt record is a defect, not an\n * absence.\n *\n * The reader translates storage envelopes only. It does not assign research\n * roles, interpret artifacts, or turn process completion into a quality\n * verdict.\n */\nexport async function readRuntimeSupervisorRun(\n runDir: string,\n opts: RuntimeReaderOptions = {},\n): Promise<SupervisorRunSources> {\n const journalPath = join(runDir, JOURNAL_FILE)\n const rawJournal =\n opts.strict === true ? await readFile(journalPath, 'utf8') : await readMaybe(journalPath)\n const resultPath = join(runDir, RESULT_FILE)\n const failurePath = join(runDir, FAILURE_FILE)\n const resultText = await readMaybe(resultPath)\n const failureText = await readMaybe(failurePath)\n const failure = parseOptionalRecord(failureText, failurePath)\n assertFailureRecord(failure, failurePath)\n const result = parseOptionalRecord(resultText, resultPath)\n if (rawJournal === null) {\n return absentRuntimeSupervisorRun(\n runDir,\n resultText,\n failureText,\n recordedRunId(result, failure),\n )\n }\n const normalized = parseEnvelopeJournal(rawJournal, journalPath)\n assertResultMatchesJournal(normalized.root, result, resultPath)\n\n const spawns = normalized.events.filter(\n (event) => event.kind === 'spawned' && nonEmptyString(event.id) !== null,\n )\n const childSpawns = spawns.filter((event) => event.id !== normalized.root)\n const workerIds = new Set(\n childSpawns.map((event) => nonEmptyString(event.id)).filter((id): id is string => id !== null),\n )\n const transcripts = await nodeTranscripts(\n runDir,\n normalized.events,\n new Set([normalized.root, ...workerIds]),\n { id: normalized.root, receipt: record(result?.rootHarnessTranscript) },\n )\n const workers: WorkerLogSource[] = childSpawns.map((event) => {\n const workerId = nonEmptyString(event.id) as string\n const transcript = transcripts.get(workerId)\n return {\n workerId,\n label: nonEmptyString(event.label) ?? String(event.id),\n events: null,\n inbox: null,\n patchBytes: null,\n transcriptRef: transcript?.transcriptRef ?? null,\n turns: transcript?.turns ?? { dispatched: 0, retained: 0 },\n nativeSession: transcript?.nativeSession ?? null,\n workspaceCaptures: transcript?.workspaceCaptures ?? null,\n patchPath: null,\n }\n })\n // Runtime appends every root provider event to the root stream as it arrives.\n const rootStream = join(runDir, ROOT_STREAM_FILE)\n\n return {\n runRef: runDir,\n instanceId: normalized.root,\n arm: null,\n supRunDir: runDir,\n journal: normalized.journal,\n brainLog: null,\n brainLogMissingReason:\n 'Runtime FileRunContext records spend but not model completion finish reasons',\n state: runtimeBeginState(normalized.root, normalized.startedAt),\n progress: null,\n workers,\n workersMissingReason: null,\n result: resultText,\n failure: failureText,\n judge: null,\n judgeSource: null,\n patch: null,\n driverLog: null,\n coordinationLog: await readCoordinationLog(runDir),\n harnessWorkerTokens: null,\n harnessMissingReason: 'Runtime FileRunContext has no external worker-token join',\n limits: sourceLimits(normalized.root, normalized.events, workerIds),\n rootTranscriptRef: (await isFile(rootStream)) ? rootStream : null,\n rootWorkspaceCaptures: transcripts.get(normalized.root)?.workspaceCaptures ?? null,\n traceCommand: nativeTraceSummary(workers, transcripts.get(normalized.root)),\n }\n}\n\n\n\n/**\n * True when a directory holds any file only Runtime's durable layer writes:\n * the spawn journal, the observer journal, or the failure record. A run that\n * threw before its first spawn has no journal yet and is still a Runtime run.\n */\nexport async function isRuntimeSupervisorRunDir(runDir: string): Promise<boolean> {\n for (const marker of RUNTIME_RUN_DIR_MARKERS) {\n if (await isFile(join(runDir, marker))) return true\n }\n return false\n}\n\nasync function isFile(path: string): Promise<boolean> {\n return stat(path)\n .then((entry) => entry.isFile())\n .catch((error: unknown) => {\n if (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n ((error as { code: unknown }).code === 'ENOENT' ||\n (error as { code: unknown }).code === 'ENOTDIR')\n ) {\n return false\n }\n throw error\n })\n}\n","/**\n * Runtime supervisor-run reader and report writers.\n *\n * Runtime's file-backed supervision context is the only live on-disk contract.\n * Other stores implement `SupervisorRunReader` and feed the same pure analyzer;\n * this module owns path discovery and report output for Runtime runs.\n */\n\nimport { readdir } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { analyzeSupervisorRunSources } from './analyze'\n\nimport { isRuntimeSupervisorRunDir, readRuntimeSupervisorRun } from './runtime-reader'\nimport type { SupervisorRunReader, SupervisorRunReport, SupervisorRunSources } from './types'\n\n/**\n * Analyze a supervisor run. Accepts a Runtime run directory, any\n * `SupervisorRunReader`, or already-read source bytes — so a\n * caller with its own store never has to touch the filesystem layout.\n */\nexport async function analyzeSupervisorRun(\n input: string | SupervisorRunReader | SupervisorRunSources,\n): Promise<SupervisorRunReport> {\n if (typeof input === 'string') {\n return analyzeSupervisorRunSources(await readRuntimeSupervisorRun(input))\n }\n if (isReader(input)) return analyzeSupervisorRunSources(await input.read())\n return analyzeSupervisorRunSources(input)\n}\n\nfunction isReader(input: SupervisorRunReader | SupervisorRunSources): input is SupervisorRunReader {\n return typeof (input as SupervisorRunReader).read === 'function'\n}\n\nexport interface WriteSupervisorRunOptions {\n /** Append the headline block here (the experiment's run log). */\n readonly appendHeadlineTo?: string\n /** Also console.log the headline (default true). */\n readonly echo?: boolean\n /**\n * Write `run-report.{json,md}` here instead of into the run dir. Set when\n * reporting over a run directory that must stay READ-ONLY (a live run, an\n * archived generation).\n */\n readonly reportDir?: string\n}\n\n\n\n\n\n\n\n/**\n * Every Runtime supervisor run below `root`.\n *\n * When `root` itself is one run, return no children so callers can distinguish\n * a single report from a parent-directory rollup.\n */\nexport async function findSupervisorRunDirs(root: string): Promise<string[]> {\n if (await isRuntimeSupervisorRunDir(root)) {\n return []\n }\n const found: string[] = []\n const walk = async (dir: string, depth: number): Promise<void> => {\n if (depth > 8) return\n const entries = await readdir(dir, { withFileTypes: true }).catch(() => [])\n for (const e of entries) {\n if (!e.isDirectory()) continue\n if (e.name === 'node_modules' || e.name === '.git') continue\n const full = join(dir, e.name)\n if (await isRuntimeSupervisorRunDir(full)) {\n found.push(full)\n continue\n }\n await walk(full, depth + 1)\n }\n }\n await walk(root, 0)\n return found.sort()\n}\n","/**\n * Human-readable renderings of a supervisor-run report. Zero and unavailable\n * render differently on purpose (`0` vs `unavailable — <reason>`), because the\n * two have driven opposite conclusions about the same architecture.\n */\n\nimport { roundDecimal as round } from '../math/round-decimal'\nimport {\n isUnavailable,\n type Measured,\n type ResourceSpendRecord,\n type SupervisorRunReport,\n type SupervisorRunRollup,\n showMeasured,\n type TerminalFailure,\n} from './types'\n\n/**\n * The block appended to a run log after every run — the answers an operator asks\n * for, in the log tail, with no extra command.\n */\nexport function renderSupervisorRunHeadline(r: SupervisorRunReport): string {\n const o = r.orchestration\n const steerNote = isUnavailable(o.steers)\n ? `unavailable — ${o.steers.unavailable}`\n : o.steers === 0\n ? '0 (spawn→wait→respawn only; no mid-task steering)'\n : `${o.steers} queued / ${showMeasured(o.steersDelivered)} delivered`\n return [\n `RUN-REPORT ${r.instanceId ?? '?'} [${r.arm ?? '?'}]`,\n ` status=${showMeasured(r.outcome.supStatus)} source=${showMeasured(r.outcome.supStatusSource)}` +\n ` reason=${showMeasured(r.outcome.supReason)} failure=${fmtFailure(r.outcome.failure)}`,\n ` steers=${steerNote}`,\n ` waves=${showMeasured(o.waves)} sizes=${isUnavailable(o.waveSizes) ? `unavailable — ${o.waveSizes.unavailable}` : `[${o.waveSizes.join(',')}]`}` +\n ` workers=${showMeasured(o.workersSpawned)} settled=${showMeasured(o.workersSettled)} cancelled=${showMeasured(o.workersCancelled)}`,\n ` concurrency max=${showMeasured(o.maxConcurrency)} utilization=${showMeasured(o.workerUtilization)}` +\n ` idle=${fmtMs(o.idleMs)} (${showMeasured(o.idlePct)}%) wall=${fmtMs(o.supervisorWallMs)}` +\n `${o.supervisorWallSource === 'journal-span' ? ' (journal-span lower bound)' : ''}`,\n ` respawns=${showMeasured(o.respawns)} evidence→respawn=${showMeasured(r.decision.observeThenRespawn)}` +\n ` blind-respawn=${showMeasured(r.decision.respawnWithoutEvidence)} depth=${showMeasured(o.delegationDepth)}`,\n ` accepted=${showMeasured(r.decision.accepted)} rejected=${showMeasured(r.decision.rejected)} empty-pass=${showMeasured(r.decision.emptyPass)}`,\n ` brain=$${showMeasured(r.economics.brain.usd)} total=$${showMeasured(r.economics.totalUsd)}` +\n ` judge.resolved=${showMeasured(r.outcome.judgeResolved)} score=${showMeasured(r.outcome.judgeScore)}` +\n ` verify=${showMeasured(r.outcome.verifyPass)}`,\n r.gaps.length > 0 ? ` gaps(${r.gaps.length}): ${r.gaps.join('; ')}` : ' gaps: none',\n ].join('\\n')\n}\n\n/**\n * The recorded error on one line; `none recorded` and `unavailable` stay\n * distinct, and a throw the run outlived is labeled so it is not read as the\n * outcome of the settled result beside it.\n */\nfunction fmtFailure(v: Measured<TerminalFailure | null>): string {\n if (isUnavailable(v)) return `unavailable — ${v.unavailable}`\n if (v === null) return 'none recorded'\n const name = v.name ?? 'unavailable — record has no error.name'\n const message = v.message ?? 'unavailable — record has no error.message'\n const attempt = v.earlierAttempt ? ', earlier attempt' : ''\n return `${name}: ${message} [${v.source}${v.at === null ? '' : ` at ${v.at}`}${attempt}]`\n}\n\nfunction resourceRows(records: Measured<readonly ResourceSpendRecord[]>): string[] {\n if (isUnavailable(records)) return [`unavailable — ${records.unavailable}`, '']\n const out = [\n 'Receipts are source records, not additive totals.',\n 'A false completeness flag means the amount is a recorded subtotal, not complete usage.',\n '',\n '| Node | Source | Resource | Unit | Amount | Known |',\n '|---|---|---|---|---:|---|',\n ]\n const cell = (value: string) => value.replace(/\\|/g, '\\\\|').replace(/\\r?\\n/g, ' ')\n for (const record of records) {\n const prefix = `| ${cell(record.nodeId ?? 'unavailable')} | ${cell(record.source)} |`\n if (isUnavailable(record.resources)) {\n out.push(`${prefix} ${cell(showMeasured(record.resources))} | — | — | — |`)\n } else if (record.resources.length === 0) {\n out.push(`${prefix} recorded empty map | — | — | — |`)\n } else {\n for (const receipt of record.resources) {\n out.push(\n `${prefix} ${cell(showMeasured(receipt.name))} | ${cell(showMeasured(receipt.unit))} | ${cell(showMeasured(receipt.amount))} | ${cell(showMeasured(receipt.known))} |`,\n )\n }\n }\n }\n if (!records.length) out.push('| — | — | no spend records | — | — | — |')\n out.push('')\n return out\n}\n\nfunction fmtMs(v: Measured<number>): string {\n if (isUnavailable(v)) return `unavailable — ${v.unavailable}`\n if (v < 1000) return `${v}ms`\n const s = v / 1000\n if (s < 120) return `${round(s, 1)}s`\n return `${round(s / 60, 1)}min`\n}\n\nexport function renderSupervisorRunMarkdown(r: SupervisorRunReport): string {\n const o = r.orchestration\n const d = r.decision\n const e = r.economics\n const out: string[] = []\n out.push(`# Run report — ${r.instanceId ?? 'unknown instance'} [${r.arm ?? 'unknown arm'}]`)\n out.push('')\n out.push('```')\n out.push(renderSupervisorRunHeadline(r))\n out.push('```')\n out.push('')\n out.push(`- Run: \\`${r.runRef}\\``)\n out.push(`- Supervisor: \\`${showMeasured(r.supervisorId)}\\``)\n out.push(`- Supervisor profile: \\`${showMeasured(r.supervisorProfileDigest)}\\``)\n out.push(`- Generated: ${r.generatedAt}`)\n out.push('')\n\n out.push('## Orchestration')\n out.push('')\n out.push('| Metric | Value |')\n out.push('|---|---|')\n out.push(`| Workers spawned | ${showMeasured(o.workersSpawned)} |`)\n out.push(`| Workers settled | ${showMeasured(o.workersSettled)} |`)\n out.push(`| Workers cancelled | ${showMeasured(o.workersCancelled)} |`)\n out.push(`| **Steers (mid-task messages to live workers)** | **${showMeasured(o.steers)}** |`)\n out.push(`| Steers delivered | ${showMeasured(o.steersDelivered)} |`)\n out.push(`| Outer-driver \\`supervisor_steer\\` calls | ${showMeasured(o.driverSteerCalls)} |`)\n out.push(`| Spawn waves | ${showMeasured(o.waves)} |`)\n out.push(\n `| Wave sizes | ${isUnavailable(o.waveSizes) ? showMeasured(o.waveSizes) : `[${o.waveSizes.join(', ')}]`} |`,\n )\n out.push(`| Max concurrency | ${showMeasured(o.maxConcurrency)} |`)\n out.push(`| Respawns (after same parent's first settle) | ${showMeasured(o.respawns)} |`)\n out.push(\n `| Repeated labels | ${isUnavailable(o.repeatedLabels) ? showMeasured(o.repeatedLabels) : o.repeatedLabels.length === 0 ? 'none' : o.repeatedLabels.join(', ')} |`,\n )\n out.push(`| Delegation depth | ${showMeasured(o.delegationDepth)} |`)\n out.push(`| Time to first spawn | ${fmtMs(o.timeToFirstSpawnMs)} |`)\n out.push(\n `| Supervisor wall | ${fmtMs(o.supervisorWallMs)}${isUnavailable(o.supervisorWallSource) ? '' : ` (source: ${o.supervisorWallSource}${o.supervisorWallSource === 'journal-span' ? ', lower bound' : ''})`} |`,\n )\n out.push(`| Idle (zero live workers) | ${fmtMs(o.idleMs)} (${showMeasured(o.idlePct)}%) |`)\n out.push(\n `| Worker utilization (Σ worker wall ÷ supervisor wall) | ${showMeasured(o.workerUtilization)} |`,\n )\n out.push('')\n\n if (!isUnavailable(o.steersByWorker) && o.steersByWorker.length > 0) {\n out.push('### Steers per worker')\n out.push('')\n out.push('| Worker id | Label | Queued | Delivered |')\n out.push('|---|---|---:|---:|')\n for (const s of o.steersByWorker) {\n out.push(\n `| ${s.workerId === null ? 'unavailable — worker id absent; label join used' : `\\`${s.workerId}\\``} | \\`${s.worker}\\` | ${s.queued} | ${s.delivered} |`,\n )\n }\n out.push('')\n } else if (isUnavailable(o.steersByWorker)) {\n out.push(`### Steers per worker\\n\\nunavailable — ${o.steersByWorker.unavailable}\\n`)\n }\n\n out.push('## Decision quality')\n out.push('')\n out.push('| Metric | Value |')\n out.push('|---|---|')\n out.push(`| Settled by status | ${fmtCounts(d.settledByStatus)} |`)\n out.push(`| Settled verdicts | ${fmtCounts(d.settledVerdicts)} |`)\n out.push(`| Accepted (verify green + patch bytes) | ${showMeasured(d.accepted)} |`)\n out.push(`| Rejected (verify red) | ${showMeasured(d.rejected)} |`)\n out.push(`| Empty pass (green, no patch) | ${showMeasured(d.emptyPass)} |`)\n out.push(`| Evidence → respawn sequences | ${showMeasured(d.observeThenRespawn)} |`)\n out.push(\n `| Respawn with no same-parent settled evidence in front | ${showMeasured(d.respawnWithoutEvidence)} |`,\n )\n out.push(`| Review actions (steers + worker questions) | ${showMeasured(d.reviewActions)} |`)\n out.push(\n `| Worker evidence returned | ${isUnavailable(d.workerEvidenceBytes) ? showMeasured(d.workerEvidenceBytes) : `${d.workerEvidenceBytes} bytes`} |`,\n )\n out.push('')\n\n out.push('## Economics')\n out.push('')\n out.push('| Role | Tokens in | Tokens out | Cache read | Cache write | USD | Source |')\n out.push('|---|---:|---:|---:|---:|---:|---|')\n out.push(\n `| brain | ${showMeasured(e.brain.tokensIn)} | ${showMeasured(e.brain.tokensOut)} | ${showMeasured(e.brain.cacheRead)} | ${showMeasured(e.brain.cacheWrite)} | ${showMeasured(e.brain.usd)} | ${e.brain.source} |`,\n )\n out.push(\n `| workers | ${showMeasured(e.workers.tokensIn)} | ${showMeasured(e.workers.tokensOut)} | ${showMeasured(e.workers.cacheRead)} | ${showMeasured(e.workers.cacheWrite)} | ${showMeasured(e.workers.usd)} | ${e.workers.source} |`,\n )\n out.push('')\n if (!isUnavailable(e.brainTruncations) && e.brainTruncations > 0) {\n out.push(\n `- **BRAIN OUTPUT TRUNCATED: ${e.brainTruncations} completion(s) hit \\`finish_reason: \"length\"\\`** — the supervisor ` +\n 'acted on a half-written plan. Its output ceiling is too low; see `brain.jsonl` for the per-call `req_max_tokens`.',\n )\n } else {\n out.push(\n `- Brain completions truncated (finish_reason=length): ${showMeasured(e.brainTruncations)}`,\n )\n }\n out.push(`- Total USD: ${showMeasured(e.totalUsd)} (source: ${e.totalUsdSource})`)\n out.push(\n `- Spend measured two ways: journal-derived $${showMeasured(e.spend.journalDerived.usd)} over ${e.spend.journalDerived.records} journal record(s) (execution accounting) · ` +\n `close-record $${showMeasured(e.spend.closeRecord.usd)} over ${e.spend.closeRecord.records} close record(s) (billing-shaped). Divergence is a signal, not an error.`,\n )\n out.push(`- Cost per accepted patch: ${showMeasured(e.costPerAcceptedPatchUsd)}`)\n if (isUnavailable(e.workerWallMsDistribution)) {\n out.push(`- Worker wall distribution: unavailable — ${e.workerWallMsDistribution.unavailable}`)\n } else {\n const w = e.workerWallMsDistribution\n out.push(\n `- Worker wall (n=${w.n}): min ${fmtMs(w.min)} / p50 ${fmtMs(w.p50)} / p90 ${fmtMs(w.p90)} / max ${fmtMs(w.max)} / Σ ${fmtMs(w.sum)}`,\n )\n }\n out.push('')\n if (!isUnavailable(e.perWorker) && e.perWorker.length > 0) {\n out.push(\n '| Worker id | Label | Role | Runtime | Profile digest | Status | Failure | Infra | Wall | Tokens in | Tokens out | Patch bytes | Verify passed | Score |',\n )\n out.push('|---|---|---|---|---|---|---|---|---:|---:|---:|---:|---|---:|')\n for (const w of e.perWorker) {\n out.push(\n `| ${w.workerId === null ? 'unavailable — worker id absent; label join used' : `\\`${w.workerId}\\``} | \\`${w.worker}\\` | ${w.role ?? 'unavailable — source recorded no role'} | ${w.runtime ?? 'unavailable — source recorded no runtime'} | ${w.profileDigest === null ? 'unavailable — source recorded no profile digest' : `\\`${w.profileDigest}\\``} | ${w.status ?? 'unavailable — no terminal event'} | ${w.failure ?? 'none recorded'} | ${w.infra ?? 'unavailable'} | ${w.wallMs === null ? 'unavailable — no spawn/finish pair' : fmtMs(w.wallMs)} | ${w.tokensIn ?? 'unavailable — store does not attribute tokens per worker'} | ${w.tokensOut ?? 'unavailable — store does not attribute tokens per worker'} | ${w.patchBytes ?? 'unavailable — no worker patch file'} | ${w.passed === null ? 'unavailable — no verdict' : String(w.passed)} | ${w.score ?? 'unavailable — no numeric score'} |`,\n )\n }\n out.push('')\n }\n\n if (e.resourceRecords !== undefined) {\n out.push('## Named resource receipts', '', ...resourceRows(e.resourceRecords))\n }\n\n out.push('## Outcome')\n out.push('')\n out.push('| Metric | Value |')\n out.push('|---|---|')\n out.push(`| Supervisor status | ${showMeasured(r.outcome.supStatus)} |`)\n out.push(`| Status source | ${showMeasured(r.outcome.supStatusSource)} |`)\n out.push(`| Terminal reason | ${showMeasured(r.outcome.supReason)} |`)\n out.push(`| Failure | ${fmtFailure(r.outcome.failure)} |`)\n out.push(`| Supervisor verdict | ${showMeasured(r.outcome.supVerdict)} |`)\n out.push(`| Delivered | ${showMeasured(r.outcome.delivered)} |`)\n out.push(`| Judge resolved | ${showMeasured(r.outcome.judgeResolved)} |`)\n out.push(`| Judge score | ${showMeasured(r.outcome.judgeScore)} |`)\n out.push(\n `| Judge passed / total | ${showMeasured(r.outcome.judgePassed)} / ${showMeasured(r.outcome.judgeTotal)} |`,\n )\n out.push(\n `| Judge source | ${r.outcome.judgeSource ?? 'unavailable — no judge.json and no ledger row'} |`,\n )\n out.push(\n `| Verify gate | pass=${showMeasured(r.outcome.verifyPass)} rc=${showMeasured(r.outcome.verifyRc)} |`,\n )\n if (isUnavailable(r.outcome.patch)) {\n out.push(`| Patch | unavailable — ${r.outcome.patch.unavailable} |`)\n } else {\n const p = r.outcome.patch\n out.push(\n `| Patch | ${p.files} file(s), +${p.linesAdded}/-${p.linesRemoved}, test files touched: ${p.testFilesTouched.length === 0 ? 'none' : p.testFilesTouched.join(', ')} |`,\n )\n }\n out.push('')\n out.push('## Gaps')\n out.push('')\n if (r.gaps.length === 0) out.push('None — every metric above is backed by a present artifact.')\n else for (const g of r.gaps) out.push(`- ${g}`)\n out.push('')\n out.push(\n `> Harness-session view of the same run (model calls, stuck loops, tool errors): \\`${r.traceCommand}\\``,\n )\n out.push('')\n return out.join('\\n')\n}\n\nfunction fmtCounts(v: Measured<Record<string, number>>): string {\n if (isUnavailable(v)) return showMeasured(v as unknown as Measured<string>)\n const entries = Object.entries(v)\n return entries.length === 0 ? 'none' : entries.map(([k, n]) => `${k}=${n}`).join(', ')\n}\n\nexport function renderSupervisorRollupMarkdown(\n rollup: SupervisorRunRollup,\n title = 'Round rollup',\n): string {\n const out: string[] = []\n out.push(`# ${title}`)\n out.push('')\n out.push(`- Cells: ${rollup.cells}`)\n out.push(\n `- **Steers across all cells: ${showMeasured(rollup.steersTotal)}** (cells with ≥1 steer: ${showMeasured(rollup.cellsWithSteers)}; cells where the steer count is unavailable: ${rollup.cellsWithUnavailableSteers})`,\n )\n out.push(`- Waves per cell (mean): ${showMeasured(rollup.wavesMean)}`)\n out.push(`- Max concurrency observed: ${showMeasured(rollup.maxConcurrencyMax)}`)\n out.push(`- Worker utilization (mean): ${showMeasured(rollup.utilizationMean)}`)\n out.push(`- Idle share (mean): ${showMeasured(rollup.idlePctMean)}%`)\n out.push(\n `- Workers spawned: ${showMeasured(rollup.workersSpawnedTotal)} · accepted: ${showMeasured(rollup.acceptedTotal)}`,\n )\n out.push(\n `- Spend: $${showMeasured(rollup.usdTotal)} · judged resolved: ${showMeasured(rollup.resolvedCount)}/${rollup.cells}`,\n )\n out.push(\n `- Spend measured two ways: journal-derived $${showMeasured(rollup.spendUsd.journalDerived.value)} over ${rollup.spendUsd.journalDerived.runs}/${rollup.cells} runs (execution accounting) · ` +\n `close-record $${showMeasured(rollup.spendUsd.closeRecord.value)} over ${rollup.spendUsd.closeRecord.runs}/${rollup.cells} runs (billing-shaped)`,\n )\n out.push('')\n out.push('| Instance | Arm | Steers | Waves | Utilization | Idle % | Resolved | USD |')\n out.push('|---|---|---:|---:|---:|---:|---|---:|')\n for (const c of rollup.perCell) {\n out.push(\n `| ${c.instanceId ?? '?'} | ${c.arm ?? '?'} | ${showMeasured(c.steers)} | ${showMeasured(c.waves)} | ${showMeasured(c.utilization)} | ${showMeasured(c.idlePct)} | ${showMeasured(c.resolved)} | ${showMeasured(c.usd)} |`,\n )\n }\n out.push('')\n for (const cell of rollup.perCell) {\n if (cell.resourceRecords !== undefined) {\n out.push(\n `## Resource receipts — ${cell.instanceId ?? '?'} [${cell.arm ?? '?'}]`,\n '',\n ...resourceRows(cell.resourceRecords),\n )\n }\n }\n return out.join('\\n')\n}\n"],"mappings":";;;;;;;;AAIA,SAAgB,WAAW,MAA0B;CACnD,MAAM,wBAAQ,IAAI,IAAY;CAC9B,MAAM,4BAAY,IAAI,IAAY;CAClC,IAAI,QAAQ;CACZ,IAAI,UAAU;CACd,KAAK,MAAM,QAAQ,KAAK,MAAM,IAAI,GAAG;EACnC,IAAI,KAAK,WAAW,MAAM,GAAG;GAC3B,MAAM,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,QAAQ,QAAQ,EAAE;GACjD,IAAI,MAAM,aAAa;IACrB,MAAM,IAAI,CAAC;IACX,IAAI,WAAW,CAAC,GAAG,UAAU,IAAI,CAAC;GACpC;GACA;EACF;EACA,IAAI,KAAK,WAAW,MAAM,KAAK,KAAK,WAAW,YAAY,KAAK,KAAK,WAAW,QAAQ,GACtF;EAEF,IAAI,KAAK,WAAW,GAAG,GAAG,SAAS;OAC9B,IAAI,KAAK,WAAW,GAAG,GAAG,WAAW;CAC5C;CACA,OAAO;EACL,OAAO,MAAM;EACb,YAAY;EACZ,cAAc;EACd,kBAAkB,CAAC,GAAG,SAAS,CAAC,CAAC,KAAK;CACxC;AACF;AAEA,SAAS,WAAW,GAAoB;CACtC,MAAM,OAAO,EAAE,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK;CACnC,OACE,8CAA8C,KAAK,CAAC,KACpD,+BAA+B,KAAK,IAAI,KACxC,gBAAgB,KAAK,IAAI,KACzB,aAAa,KAAK,IAAI;AAE1B;;;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AQ,OAAO,SAAS,YAAY,KAAK,GAAG,OAAO,MAAM,uBAC9H;CACA,IAAI,KAAK,EAAE;CACX,IAAI,KAAK,6EAA6E;CACtF,IAAI,KAAK,wCAAwC;CACjD,KAAK,MAAM,KAAK,OAAO,SACrB,IAAI,KACF,KAAK,EAAE,cAAc,IAAI,KAAK,EAAE,OAAO,IAAI,KAAK,aAAa,EAAE,MAAM,EAAE,KAAK,aAAa,EAAE,KAAK,EAAE,KAAK,aAAa,EAAE,WAAW,EAAE,KAAK,aAAa,EAAE,OAAO,EAAE,KAAK,aAAa,EAAE,QAAQ,EAAE,KAAK,aAAa,EAAE,GAAG,EAAE,GACzN;CAEF,IAAI,KAAK,EAAE;CACX,KAAK,MAAM,QAAQ,OAAO,SACxB,IAAI,KAAK,oBAAoB,KAAA,GAC3B,IAAI,KACF,0BAA0B,KAAK,cAAc,IAAI,IAAI,KAAK,OAAO,IAAI,IACrE,IACA,GAAG,aAAa,KAAK,eAAe,CACtC;CAGJ,OAAO,IAAI,KAAK,IAAI;AACtB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"schema-DxcKTzbi.js","names":[],"sources":["../src/rollout/gate-checks.ts","../src/rollout/schema.ts"],"sourcesContent":["/**\n * THE canonical list of anti-Goodhart gate checks, plus the TOTAL policy every\n * entry point has to declare over it.\n *\n * Four rounds of adversarial review found the same defect four times, and it\n * was never the check itself: it was the COMPOSITION. `validateRolloutLine`\n * composed one check, `assertMinted` composed two, `assertRewardGate` composed\n * two of the three, `assertGateReport` composed its own pair — each by hand, in\n * its own file. So a check added to the package applied wherever its author\n * happened to remember, and the guard that forgot it looked exactly like the\n * guard that didn't. The last leak was literally that: `assertRewardGate`\n * composed `reward-relationship` + `gated-evidence` and not `unscreened-reward`,\n * so a never-screened positive reward that `assertMinted` correctly REFUSED\n * walked through all four waist exporters at full value.\n *\n * The fix is to make hand-composition impossible rather than to add a third\n * call to the two places that had two:\n *\n * - `GATE_CHECKS` is a TOTAL map over `GateCheckId`. A new id with no\n * implementation does not compile.\n * - `GatePolicy` is a TOTAL map over `GateCheckId`. Every entry point\n * declares one, so a new id makes EVERY entry point's policy a type error\n * until it is wired. Wiring it means writing `enforced`, `repairedBy(...)`\n * or `omittedBecause(...)` — and the last two force a written reason, so a\n * silent gap is not expressible.\n * - every check carries a `tripwire`: the minimal outcome it must refuse.\n * `gate-checks.test.ts` feeds each tripwire to every entry point that\n * declares `enforced` and requires a rejection, so wiring a check to the\n * wrong disposition is a TEST failure even when it type-checks.\n *\n * Adding a check is therefore: append the id, write the check, and the compiler\n * enumerates every place that has to decide about it.\n */\n\nimport type { GatedEvidence, RolloutOutcome, RolloutStep } from './schema'\n\n/**\n * Every gate check in the package, in the order they are applied.\n *\n * Order is load-bearing only for which message a caller sees first: a line that\n * trips two checks reports the earlier one, and `reward-relationship` is first\n * because it is the invariant the other three protect.\n */\nexport const GATE_CHECK_IDS = [\n 'reward-relationship',\n 'gated-evidence',\n 'undeclared-step-payload',\n 'unscreened-reward',\n] as const\n\nexport type GateCheckId = (typeof GATE_CHECK_IDS)[number]\n\n/**\n * An outcome as it reaches a check.\n *\n * Deliberately accepts a raw record as well as the typed shape: the checks are\n * the RUNTIME half of the gate, and the callers they exist for — JSON off a\n * ledger, a plain-JavaScript consumer of the published package — arrive with no\n * types at all. `Partial` because a tripwire states only the fields it trips on.\n */\nexport type GateCheckedOutcome = Partial<RolloutOutcome> | Readonly<Record<string, unknown>>\n\n/**\n * What a gate check reads: the reward-bearing surface of ONE LINE.\n *\n * For three rounds the subject was the OUTCOME alone, and that assumption is\n * what produced the next leak rather than any missing check: `steps[]` sits on\n * the LINE, outside `outcome`, so a per-step reward on a gated line was read by\n * no check at all while `toRewardRows` copied it out verbatim — through the\n * MINTED door, not merely the raw one. Widening the subject is what makes\n * \"somewhere else on the line\" a place the checks can see.\n *\n * `outcome` is REQUIRED, and that is the point: a bare `RolloutOutcome` is then\n * not assignable to a subject, so every call site that used to pass one is a\n * COMPILE error until it passes the line instead. A subject with an optional\n * `outcome` would have let the old call sites keep compiling while silently\n * checking nothing — the exact failure this module exists to make impossible.\n */\ninterface GateSubject {\n outcome: GateCheckedOutcome\n /** The line's trajectory steps, when it carries any. */\n steps?: unknown\n}\n\n/** One untyped field read off the outcome, so every check narrows from the same place. */\nconst field = (subject: GateSubject, name: string): unknown =>\n (subject.outcome as Readonly<Record<string, unknown>>)?.[name]\n\nexport interface GateCheck {\n id: GateCheckId\n /** One sentence: what this check refuses. */\n refuses: string\n /** One dotted-path message per defect; `[]` when the line is clean. */\n errors: (subject: GateSubject) => string[]\n /**\n * Every minimal subject that MUST trip `errors` — the executable form of\n * `refuses`, and the reason a check cannot be added without being provable.\n * The calibration test feeds each one to every entry point declaring\n * `enforced`.\n *\n * A LIST rather than one case: a check that refuses two distinct populations\n * (a positive reward AND a reward it cannot read as a number) proved able to\n * hold for the first while silently passing the second, so each population\n * states its own tripwire and each is exercised separately.\n */\n tripwires: GateSubject[]\n}\n\n// ---------------------------------------------------------------------------\n// Total readers. Every \"is this positive?\" / \"is this populated?\" question the\n// checks ask goes through one of these.\n// ---------------------------------------------------------------------------\n\n/**\n * How the gate reads one `outcome.reward`.\n *\n * TOTAL over `unknown`, with an explicit `unreadable` case, because the\n * recurring defect across four rounds was a hand-written type test whose\n * NEGATIVE branch silently passed: `typeof reward !== 'number' || !(reward > 0)`\n * returned \"clean\" for `reward: \"0.95\"`, so a plain-JavaScript producer that\n * stringifies its numbers — the exact population the runtime backstop exists\n * for — shipped a gamed run at full value through three waist exporters.\n *\n * A value the gate cannot read as a number is not evidence the reward is\n * cleared; it is the absence of that evidence, and the gate fails closed on it.\n */\ntype RewardReading =\n /** `null`/`undefined` — a labeled gap, which is never a positive signal. */\n | { kind: 'absent' }\n /** A number at or below zero: the gate's own verdict, applied. */\n | { kind: 'cleared' }\n /** A number above zero, `Infinity` and the 5e-324 denormal included. */\n | { kind: 'positive'; shown: string }\n /** Anything the wire format does not permit here, plus `NaN`. */\n | { kind: 'unreadable'; shown: string }\n\nexport function readReward(value: unknown): RewardReading {\n if (value === null || value === undefined) return { kind: 'absent' }\n if (typeof value === 'number') {\n if (Number.isNaN(value)) return { kind: 'unreadable', shown: 'NaN' }\n return value > 0 ? { kind: 'positive', shown: String(value) } : { kind: 'cleared' }\n }\n return {\n kind: 'unreadable',\n shown: `${JSON.stringify(value) ?? String(value)} (${typeof value})`,\n }\n}\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/**\n * Whether a reward-derived field carries anything at all.\n *\n * The previous emptiness test was `Object.keys(value).length > 0`, which reads\n * `[]` for a NUMBER, a BOOLEAN and the empty string — so `metrics: 0.95` on a\n * gated line counted as empty and shipped verbatim in the verifiers format's\n * per-rubric score dict. `Object.keys` being total over primitives is not the\n * same property as being CORRECT over them.\n *\n * The rule that has no such hole: only `undefined`, `null` and a record with no\n * keys are empty. Everything else is payload, whatever its type.\n */\nexport function payloadIsPopulated(value: unknown): boolean {\n if (value === undefined || value === null) return false\n if (isPlainRecord(value)) return Object.keys(value).length > 0\n return true\n}\n\n/**\n * Every key `tangle.rollout.v1` declares on a step, as a TOTAL map over the\n * interface: a field added to `RolloutStep` and not to this list does not\n * compile, so the list cannot silently fall behind the schema it mirrors.\n *\n * This is the producer's OWN classification, which is the only partition\n * `gatedEvidenceOf` accepts — a key-name heuristic (\"strip anything matching\n * /reward|score/\") holds until someone names a field `credit` and the next\n * per-step signal ships at full value.\n */\nconst DECLARED_STEP_KEYS: { readonly [K in keyof Required<RolloutStep>]: true } = {\n kind: true,\n name: true,\n input: true,\n output: true,\n status: true,\n durationMs: true,\n llm_call_count: true,\n prompt_token_ids: true,\n completion_token_ids: true,\n logprobs: true,\n}\n\n/**\n * The part of `steps` the wire format has no name for — a per-step reward, a\n * per-step score, whatever a producer decided to hang there.\n *\n * `undefined` when the steps carry nothing undeclared.\n */\nexport function undeclaredStepPayload(steps: unknown): unknown {\n if (steps === undefined || steps === null) return undefined\n // The format says `steps` is a list. Anything else is wholly unclassified.\n if (!Array.isArray(steps)) return steps\n const extras: Array<Record<string, unknown>> = []\n let found = false\n for (const step of steps) {\n const extra: Record<string, unknown> = {}\n if (isPlainRecord(step)) {\n for (const [key, value] of Object.entries(step)) {\n if (key in DECLARED_STEP_KEYS) continue\n extra[key] = value\n found = true\n }\n } else if (step !== undefined && step !== null) {\n // A step that is not even a record carries no declared key to keep.\n extras.push({ step } as Record<string, unknown>)\n found = true\n continue\n }\n extras.push(extra)\n }\n return found ? extras : undefined\n}\n\n/** `steps` projected down to the keys the wire format declares. */\nexport function declaredSteps(steps: unknown): RolloutStep[] | undefined {\n if (!Array.isArray(steps)) return undefined\n const kept: RolloutStep[] = []\n for (const step of steps) {\n if (!isPlainRecord(step)) continue\n const projected: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(step)) {\n if (key in DECLARED_STEP_KEYS) projected[key] = value\n }\n kept.push(projected as unknown as RolloutStep)\n }\n return kept\n}\n\n/**\n * THE anti-Goodhart invariant, checked as a RELATIONSHIP between two fields\n * rather than as two independent type checks.\n *\n * Everything upstream of a training export is allowed to be wrong; this is the\n * one thing that cannot be. `realness_gated: true` means the run faked its\n * success signal, so its reward is a fabrication, and a fabrication above zero\n * is precisely what a trainer would learn to reproduce. Validating only that\n * `reward` is a number and `realness_gated` is a boolean is what let a line\n * claiming `{reward: 0.95, realness_gated: true}` validate clean and walk\n * through every exporter.\n */\nconst rewardRelationship: GateCheck = {\n id: 'reward-relationship',\n refuses: 'a positive — or unreadable — reward on a line the authenticity screen flagged as gamed',\n tripwires: [\n { outcome: { reward: 0.95, realness_gated: true } },\n // The second population, stated separately because the check held for the\n // first while passing this one for a full round.\n { outcome: { reward: '0.95' as unknown as number, realness_gated: true } },\n ],\n errors: (subject) => {\n if (field(subject, 'realness_gated') !== true) return []\n const reading = readReward(field(subject, 'reward'))\n if (reading.kind === 'absent' || reading.kind === 'cleared') return []\n if (reading.kind === 'unreadable') {\n return [\n `outcome.reward: ${reading.shown} with outcome.realness_gated: true — the wire format ` +\n 'declares this field `number | null`, so the gate cannot read this value as a number ' +\n 'and cannot establish that the reward was cleared. On a run flagged as gamed that is ' +\n 'not evidence of a zero, it is the absence of it, and a consumer that coerces the ' +\n 'value (`\"0.95\"`, `\"2\"`) reads a positive reward off a faked success. Emit a number ' +\n 'or null — `trainingReward` / `trainingScore` from `rollout/reward.ts` produce one.',\n ]\n }\n return [\n `outcome.reward: ${reading.shown} with outcome.realness_gated: true — a run flagged as ` +\n 'gamed may not carry a positive reward. The anti-Goodhart gate forces the reward to 0 (a ' +\n 'real verdict: the gate decided) before the line is written, so a fine-tune cannot learn ' +\n 'from a faked success. Derive the reward with `trainingReward` / `trainingScore` from ' +\n '`rollout/reward.ts`, or drop the line.',\n ]\n },\n}\n\n/**\n * The reward-bearing outcome fields that are NOT the scalar: the numbers the\n * reward was computed from, and the verdict record that claimed it.\n *\n * Returned as one block rather than filtered key-by-key. A key-name heuristic\n * (\"zero anything matching `layer.*` or `/score/`\") is the same defect shape as\n * the line-oriented regex the AST score guard replaced: it holds until someone\n * names a metric `pass_fraction`, and the next reward-shaped key ships at full\n * value. The producer's OWN classification — \"this is the scalar, that is\n * everything else\" — is the only partition that cannot be out-guessed.\n */\nexport function gatedEvidenceOf(subject: GateSubject): GatedEvidence | undefined {\n const evidence: GatedEvidence = {}\n // `payloadIsPopulated`, not an inline key count: a plain-JavaScript caller can\n // hand any value here, and a non-record `metrics` is still reward-derived\n // payload. See that function for the primitives an `Object.keys` test missed.\n const metrics = field(subject, 'metrics')\n if (payloadIsPopulated(metrics)) evidence.metrics = metrics as Record<string, unknown>\n const verdict = field(subject, 'verdict')\n if (verdict !== null && verdict !== undefined) evidence.verdict = verdict\n const steps = undeclaredStepPayload(subject.steps)\n if (steps !== undefined) evidence.steps = steps\n return evidence.metrics === undefined && evidence.verdict === undefined && steps === undefined\n ? undefined\n : evidence\n}\n\n/**\n * The invariant is about the OUTCOME, not about one field of it.\n *\n * `mintRolloutRows` bulk-copied `RunRecord.outcome.raw` into `outcome.metrics`\n * with no gate, so a gated run exported `reward: 0` (correct) while the\n * deterministic per-layer scores that reward was COMPUTED FROM — the `layer.*`\n * keys `rl/verifiable-reward.ts` calls the RL training signal — shipped at 1.0,\n * in the top-level `metrics` dict of the Prime Intellect verifiers format, which\n * IS that format's per-rubric score dict. `verdict` leaks the same way into\n * `toRftItem`'s `reference.verdict`, where a grader author reads\n * `resolved: true` off a run that faked it.\n */\nconst gatedEvidence: GateCheck = {\n id: 'gated-evidence',\n refuses: 'the numbers a fabricated reward was computed from, riding along at reward 0',\n tripwires: [\n { outcome: { reward: 0, realness_gated: true, metrics: { 'layer.tests': 1 } } },\n // A PRIMITIVE `metrics`: `Object.keys(0.95)` is `[]`, so the emptiness test\n // this check used to run reported it clean and the verifiers format shipped\n // it as its per-rubric score dict.\n { outcome: { reward: 0, realness_gated: true, metrics: 0.95 as unknown as never } },\n ],\n errors: (subject) => {\n if (field(subject, 'realness_gated') !== true) return []\n const evidence = gatedEvidenceOf(subject)\n if (evidence === undefined) return []\n // Each check reports only the fields it owns; `steps` is `undeclared-step-payload`.\n if (evidence.metrics === undefined && evidence.verdict === undefined) return []\n const path = evidence.metrics !== undefined ? 'outcome.metrics' : 'outcome.verdict'\n return [\n `${path} is populated with outcome.realness_gated: true — a run flagged as gamed may not ` +\n 'ship the numbers its fabricated reward was computed from, even at reward 0. The ' +\n 'per-layer scores in `metrics` ARE the reward signal in the verifiers format, and ' +\n '`verdict` is the record that claimed the success. Mint through `assertMinted`, which ' +\n 'relocates both to `provenance.gated_evidence` (see `gateGamedOutcome`), or drop the line.',\n ]\n },\n}\n\n/**\n * A reward-bearing field hung on `steps[]`, where the gate was not looking.\n *\n * The first three checks all read `outcome`, so the whole apparatus was blind to\n * anything a producer wrote elsewhere on the line — and `toRewardRows` emits\n * `steps` verbatim beside the scalar it just forced to 0. A generated corpus\n * found it in twenty cases: a gated line carrying\n * `steps: [{kind, name, reward: 0.86}]` exported `{\"reward\": 0, \"steps\":\n * [{\"reward\": 0.86}]}`, which is the per-step credit assignment of a run that\n * faked its success, at full value, through the MINTED door.\n *\n * `RolloutStep` declares ten keys and none of them is a reward, so the partition\n * needs no judgement call: whatever the format does not name is unclassified\n * payload, and on a gated line unclassified payload is exactly what the gate\n * refuses. `assertMinted` relocates it rather than rejecting, like the sibling\n * check, so an already-published ledger stays readable.\n */\nconst undeclaredStepPayloadCheck: GateCheck = {\n id: 'undeclared-step-payload',\n refuses: 'per-step reward signal hung on a gated line’s steps, outside every field the gate read',\n tripwires: [\n {\n outcome: { reward: 0, realness_gated: true },\n steps: [{ kind: 'tool', name: 'edit', reward: 0.9 }],\n },\n ],\n errors: (subject) => {\n if (field(subject, 'realness_gated') !== true) return []\n const extra = undeclaredStepPayload(subject.steps)\n if (extra === undefined) return []\n return [\n `steps[] carries fields \\`${ROLLOUT_SCHEMA_NAME}\\` does not declare (${JSON.stringify(extra).slice(0, 120)}) ` +\n 'with outcome.realness_gated: true — a per-step reward is training signal exactly like ' +\n 'the scalar, and the exporters copy `steps` through verbatim, so zeroing `outcome.reward` ' +\n 'while leaving it in place ships the gamed run’s step-level credit assignment at full ' +\n 'value. Mint through `assertMinted`, which projects the steps down to the declared keys ' +\n 'and relocates the rest to `provenance.gated_evidence.steps` (see `gateGamedOutcome`).',\n ]\n },\n}\n\n/** Named here rather than imported, so `gate-checks` stays free of schema cycles. */\nconst ROLLOUT_SCHEMA_NAME = 'tangle.rollout.v1'\n\n/**\n * A positive reward whose producer DECLARED that no authenticity screen exists.\n *\n * `realness_gated: false` is the screen's VERDICT, so writing it with no screen\n * behind it claims \"we looked and nothing fired\" about a reward nobody looked\n * at. `realness_screened: false` is the producer saying so out loud, and a\n * positive reward carrying it is exactly the signal the gate exists to qualify\n * with nothing having qualified it.\n */\nconst unscreenedReward: GateCheck = {\n id: 'unscreened-reward',\n refuses: 'a positive reward whose producer declares that no authenticity screen ever ran',\n tripwires: [\n { outcome: { reward: 1, realness_gated: false, realness_screened: false } },\n {\n outcome: {\n reward: '2' as unknown as number,\n realness_gated: false,\n realness_screened: false,\n },\n },\n ],\n errors: (subject) => {\n if (field(subject, 'realness_screened') !== false) return []\n const reading = readReward(field(subject, 'reward'))\n if (reading.kind === 'absent' || reading.kind === 'cleared') return []\n return [\n `outcome.reward: ${reading.shown} with outcome.realness_screened: false — this producer declares ` +\n 'that NO authenticity screen ran on this reward, so nothing has established the success ' +\n 'is real, and an unscreened positive reward is exactly the signal the anti-Goodhart gate ' +\n 'exists to qualify. Screen the run and write the verdict (`rolloutRewardFields` from a ' +\n '`RunRecord` carrying `outcome.realness`), or emit `reward: null` — an unqualified ' +\n 'verdict is a labeled gap, not a measured success.',\n ]\n },\n}\n\n/**\n * The registry. Total over `GateCheckId`, so an id with no check does not\n * compile, and `GATE_CHECK_IDS` stays the single enumeration everything\n * iterates.\n */\nexport const GATE_CHECKS: { readonly [K in GateCheckId]: GateCheck } = {\n 'reward-relationship': rewardRelationship,\n 'gated-evidence': gatedEvidence,\n 'undeclared-step-payload': undeclaredStepPayloadCheck,\n 'unscreened-reward': unscreenedReward,\n}\n\n/**\n * What ONE entry point does about ONE check.\n *\n * `repair` and `omit` both carry a mandatory sentence, which is the mechanism\n * that keeps a legitimate omission distinguishable from a forgotten one: you\n * cannot skip a check without writing down why, and the reasons are readable\n * side by side in `GATE_POLICIES`.\n */\nexport type GateCheckDisposition =\n | { readonly kind: 'enforce' }\n /** Resolved by TRANSFORMING the line instead of rejecting it; `by` names the function. */\n | { readonly kind: 'repair'; readonly by: string }\n /** Deliberately not applied here; `because` states the reason. */\n | { readonly kind: 'omit'; readonly because: string }\n\nconst enforced: GateCheckDisposition = { kind: 'enforce' }\nconst repairedBy = (by: string): GateCheckDisposition => ({ kind: 'repair', by })\nconst omittedBecause = (because: string): GateCheckDisposition => ({\n kind: 'omit',\n because,\n})\n\n/** Total over `GateCheckId`: a new check makes every policy literal a type error. */\nexport type GatePolicy = { readonly [K in GateCheckId]: GateCheckDisposition }\n\n/**\n * Every entry point that decides about the gate, and what it decides.\n *\n * Read this as the package's gate policy in one screen. The four entry points\n * are not interchangeable — a validator that rejects, a mint funnel that\n * repairs, a runtime backstop for untyped callers, and a release certifier over\n * emitted rows — and the dispositions say which is which.\n */\nexport const GATE_POLICIES = {\n /**\n * The schema validator. Rejects the reward relationship and NOTHING ELSE, on\n * purpose: it runs on every line read off disk, and the other two conditions\n * describe artifacts that already exist.\n */\n validateRolloutLine: {\n // Stays a REJECTION rather than a transformation. A caller emitting\n // `{reward: 0.95, realness_gated: true}` is a producer defect and has to\n // fail loudly; laundering it into `reward: 0` here would hide the producer,\n // which is the actual bug.\n 'reward-relationship': enforced,\n 'gated-evidence': omittedBecause(\n 'a ledger written before the relocation existed carries `metrics` on its gated lines; ' +\n 'rejecting those would make every already-published artifact unreadable. The condition ' +\n 'is REPAIRED at `assertMinted` (`gateGamedOutcome`) instead, which is the only door into ' +\n 'the training path, so the artifact stays readable and the leak still closes.',\n ),\n 'undeclared-step-payload': omittedBecause(\n 'identical reasoning to `gated-evidence`, one field over: a foreign or pre-unification ' +\n 'ledger may carry producer-invented keys on its steps, and refusing to READ those files ' +\n 'buys nothing the relocation at `assertMinted` does not already buy. Promotion into ' +\n 'training is where it closes.',\n ),\n 'unscreened-reward': omittedBecause(\n 'supervision-journal rows legitimately carry an unscreened positive reward (there is no ' +\n '`RunRecord.outcome.realness` behind them) and must stay writable, readable and ' +\n 'reportable. Only PROMOTION into training is closed, at `assertMinted`.',\n ),\n },\n /**\n * The mint funnel — the single door every `MintedRolloutLine` passes. Validates\n * first (so the reward relationship has already been rejected), then refuses\n * what cannot be repaired, then repairs what can.\n */\n assertMinted: {\n // Re-run after `assertRolloutLine`, which already rejected it. Cheap, and it\n // makes this entry point independently complete rather than complete only\n // because of what it happens to call first.\n 'reward-relationship': enforced,\n 'gated-evidence': repairedBy('gateGamedOutcome'),\n 'undeclared-step-payload': repairedBy('gateGamedOutcome'),\n 'unscreened-reward': enforced,\n },\n /**\n * The runtime backstop, and the one entry point with no license to omit\n * anything: it exists for callers the type system never saw (plain JavaScript\n * handing an object literal to a published exporter), so a check it skips is a\n * check that does not run at all for them. This is where the fourth leak was.\n */\n assertRewardGate: {\n 'reward-relationship': enforced,\n 'gated-evidence': enforced,\n 'undeclared-step-payload': enforced,\n 'unscreened-reward': enforced,\n },\n /**\n * The release certifier. Same checks, measured over the rows a release is\n * ABOUT TO WRITE rather than over one line's outcome — see `REPORT_MEASURES`\n * in `release/gate-report.ts`, which is the second total map this policy\n * drives.\n */\n assertGateReport: {\n 'reward-relationship': enforced,\n 'gated-evidence': enforced,\n 'undeclared-step-payload': enforced,\n 'unscreened-reward': enforced,\n },\n} as const satisfies Record<string, GatePolicy>\n\n/** Every entry point that declares a gate policy. */\nexport type GateEntryPoint = keyof typeof GATE_POLICIES\n\n/**\n * Run the checks one entry point enforces. The ONLY way an entry point should\n * obtain gate errors — hand-composing two of the three is the bug this module\n * exists to remove.\n */\nexport function gateErrors(subject: GateSubject, policy: GatePolicy): string[] {\n const errors: string[] = []\n for (const id of GATE_CHECK_IDS) {\n if (policy[id].kind !== 'enforce') continue\n errors.push(...GATE_CHECKS[id].errors(subject))\n }\n return errors\n}\n","/**\n * `tangle.rollout.v1` — THE canonical rollout serialization, owned by\n * agent-eval. One JSONL line per agent invocation (a solo eval run, a\n * supervisor episode, a worker session, a proposer shot, a judge call, an\n * analyst pass), labeled with its task/split coordinates and a single\n * scalar reward, carrying the FULL message transcript inline.\n *\n * This schema is the reconciliation of two prior producers:\n * - agent-eval's RunRecord-joined rollout rows (PR #410): identity,\n * provenance hashes, the realness gate travelling into the reward,\n * trace-derived steps.\n * - the bench rollout-ledger (agent-runtime PR #591): the wire shape —\n * role, task.split/rep, parent_rollout_id, policy provenance, capture\n * provenance, inline canonical chat-with-tools messages.\n * Where the two conflicted, RunRecord-derived semantics won; the wire\n * field names follow the ledger (snake_case). See `docs/rollout.md` for\n * the field-by-field decision table.\n *\n * Messages are inlined — never referenced — because every harness store a\n * rollout can be recovered from is mutable or garbage-collected. A line\n * must stay a complete training/eval example on its own.\n *\n * `outcome.reward` is THE single scalar (null = no verdict exists — a\n * labeled gap, never 0). `outcome.realness_gated` is the anti-Goodhart\n * flag: a gated line must never export as a positive training example.\n *\n * That last sentence is enforced here, by `validateRolloutLine`, not merely\n * documented. Validating `reward` and `realness_gated` independently — each a\n * well-typed field, their COMBINATION unchecked — is what let a line claiming\n * `{reward: 0.95, realness_gated: true}` validate clean and walk into every\n * training export. The relationship between the two IS the invariant, so it is\n * checked where every other structural claim about a line is checked.\n *\n * The invariant is about the OUTCOME, not about one field of it. Zeroing\n * `reward` while `outcome.metrics` still carried the per-layer scores that\n * reward was computed from exported the gamed signal anyway, in the dict the\n * verifiers format reads as its per-rubric scores. So `gateGamedOutcome`\n * transforms the whole outcome once, at `assertMinted` — the funnel every\n * minted line passes — and the reward-bearing components are relocated to\n * `provenance.gated_evidence`, which no exporter projects.\n *\n * WHICH checks each door applies is not decided in this file. `./gate-checks`\n * owns the canonical list and the total per-entry-point policy; the three doors\n * below (`validateRolloutLine`, `assertRewardGate`, `assertMinted`) each call\n * `gateErrors` with their declared policy, so a check added to that list applies\n * here without anyone editing this file, and a check deliberately skipped has to\n * name itself there.\n */\n\nimport { declaredSteps, GATE_POLICIES, gatedEvidenceOf, gateErrors } from './gate-checks'\n\nimport { isRecord } from '../llm-client/json'\nexport const ROLLOUT_SCHEMA = 'tangle.rollout.v1'\n\n/** `agent` = a solo evaluation run (no multi-agent topology). */\nexport type RolloutRole = 'agent' | 'supervisor' | 'worker' | 'proposer' | 'judge' | 'analyst'\nexport const ROLLOUT_ROLES: readonly RolloutRole[] = [\n 'agent',\n 'supervisor',\n 'worker',\n 'proposer',\n 'judge',\n 'analyst',\n]\n\n/** Split vocabulary follows `RunRecord.splitTag`, extended with `canary`. */\nexport type RolloutSplit = 'search' | 'dev' | 'holdout' | 'canary'\nexport const ROLLOUT_SPLITS: readonly RolloutSplit[] = ['search', 'dev', 'holdout', 'canary']\n/** Splits that may ship in training exports. Everything else is fail-closed excluded. */\nconst TRAINABLE_SPLITS: readonly RolloutSplit[] = ['search']\n\nexport function isTrainableSplit(split: RolloutSplit): boolean {\n return TRAINABLE_SPLITS.includes(split)\n}\n\n/** 'mint' = joined live from RunRecord + trace by `mintRolloutRows`. */\nexport type RolloutCapture = 'mint' | 'settle-time' | 'backfill'\nexport const ROLLOUT_CAPTURES: readonly RolloutCapture[] = ['mint', 'settle-time', 'backfill']\n\n// ---------------------------------------------------------------------------\n// Canonical message format — OpenAI chat-with-tools, full fidelity.\n// ---------------------------------------------------------------------------\n\nexport type ChatRole = 'system' | 'user' | 'assistant' | 'tool'\nconst CHAT_ROLES: readonly ChatRole[] = ['system', 'user', 'assistant', 'tool']\n\nexport interface ChatToolCall {\n id: string\n type: 'function'\n function: {\n name: string\n /** JSON-encoded argument object, exactly as the model emitted it. */\n arguments: string\n }\n}\n\nexport interface ChatMessage {\n role: ChatRole\n content: string | null\n /** Reasoning/thinking channel where the harness captured it (full fidelity). */\n reasoning_content?: string\n tool_calls?: ChatToolCall[]\n /** Required on role:\"tool\" — the ChatToolCall this result answers. */\n tool_call_id?: string\n name?: string\n /**\n * Harbor ATIF `is_copied_context` (RFC 0001 rule 7): this turn was COPIED IN\n * from another trajectory's context, not produced by the agent on this line.\n * The RFC makes excluding it from SFT a MUST, and `toSftRows` does — training\n * on it teaches the model to author text it never authored, and credits this\n * run for another one's work. Absent = false (authored here).\n */\n is_copied_context?: boolean\n}\n\nexport interface ToolDef {\n type: 'function'\n function: {\n name: string\n description?: string\n parameters?: Record<string, unknown>\n }\n}\n\n/**\n * Compact trace-span projection (llm/tool step) carried alongside the\n * conversation when the line was minted from a trace. Optional: lines\n * recovered from harness stores have no span structure.\n */\nexport interface RolloutStep {\n kind: string\n name: string\n /** llm: last-message summary · tool: stringified args. Scrubbed. */\n input?: string\n /** llm: output text · tool: stringified result. Scrubbed. */\n output?: string\n status?: 'ok' | 'error'\n durationMs?: number\n // The four fields below are lifted verbatim from Harbor ATIF's per-step\n // `metrics` (see `interchange/harbor.ts`); the wire names stay snake_case to\n // match that spec exactly, which is why they differ from `durationMs`.\n // All optional and never back-filled: an absent field means \"not captured\",\n // which is not the same claim as an empty array.\n /**\n * LLM inferences this span represents. 0 = deterministic dispatch with no\n * model call — distinct from absent, which means the producer did not track it.\n */\n llm_call_count?: number\n /** Exact prompt tokenization. Removes the ambiguity of re-tokenizing text at train time. */\n prompt_token_ids?: number[]\n /** Exact completion tokenization; aligns index-wise with `logprobs`. */\n completion_token_ids?: number[]\n /**\n * Per-completion-token log probabilities under the sampling policy. Required\n * for off-policy correction (importance weighting) when the rollout was\n * generated by a policy other than the one being trained.\n */\n logprobs?: number[]\n}\n\n// ---------------------------------------------------------------------------\n// Ledger line sections.\n// ---------------------------------------------------------------------------\n\nexport interface RolloutTask {\n /** Benchmark/suite id (e.g. \"swe-bench-verified\") or the experiment id. */\n suite: string\n instance_id: string\n split: RolloutSplit\n /** Sampling seed the campaign pinned; null = not recorded. */\n seed: number | null\n /** Replicate index (0-based). */\n rep: number\n}\n\nexport interface RolloutPolicy {\n /** Harness that drove the invocation (e.g. \"opencode\", \"claude\", \"pi-loops\"). */\n harness: string | null\n harness_version: string | null\n model: string | null\n provider: string | null\n /** Commit of the agent profile / candidate under evaluation. */\n profile_commit: string | null\n /** sha256 of the effective prompt (post-steering), when recorded. */\n prompt_hash?: string | null\n /** sha256 of the effective run config, when recorded. */\n config_hash?: string | null\n /** Canonical agent-profile cell identity, when the run carries one. */\n agent_profile_cell_id?: string | null\n /** Sampling params (temperature, top_p, max_tokens…); null = not recorded. */\n sampling: Record<string, unknown> | null\n}\n\nexport interface RolloutOutcome {\n /**\n * THE single scalar training signal — the official verdict.\n * null = no verdict exists for this invocation (a labeled gap, never 0).\n */\n reward: number | null\n /** Where the reward came from (judge id; \"/inherited\" = parent episode's). */\n reward_source: string | null\n /** Raw judge verdict record, verbatim. */\n verdict: unknown\n /** Everything that is NOT the scalar reward. */\n metrics: Record<string, unknown>\n is_completed: boolean\n is_truncated: boolean\n error: string | null\n /**\n * Anti-Goodhart flag from `RunRecord.outcome.realness.gated`: the run faked\n * its success signal. `true` requires `reward` to be 0 or null — the\n * validator rejects the line otherwise — and the line never qualifies for\n * SFT. Required on the wire: a line that does not state the flag does not\n * validate, so no producer can dodge the gate by omitting it.\n *\n * `true` ALSO requires `metrics` to be empty and `verdict` to be null: the\n * numbers the reward was computed from are relocated to\n * `provenance.gated_evidence` by `gateGamedOutcome`. See that function for\n * why zeroing the scalar alone was not enough.\n */\n realness_gated: boolean\n /**\n * Whether an authenticity SCREEN ever RAN on this reward — a different claim\n * from `realness_gated`, which is the screen's VERDICT.\n *\n * `realness_gated: false` reads as \"we looked and nothing fired\". A producer\n * with no screen at all was emitting exactly that, so a never-screened reward\n * was indistinguishable on the wire from a screened-clean one, and the whole\n * anti-Goodhart apparatus silently treated the first as the second. The two\n * claims are now separable:\n *\n * - `true` — a screen ran; `realness_gated` is its verdict.\n * - `false` — the producer declares it HAS no screen (`unscreenedRewardFields`).\n * `assertMinted` REFUSES such a line when its reward is above\n * zero: an unscreened positive reward is precisely the signal\n * the gate exists to qualify, and nothing has qualified it.\n * - absent — not stated. Pre-unification ledgers land here, as does a\n * `RunRecord` carrying no `outcome.realness` at all. Absent is\n * read as \"unknown\", never as `false` (which would refuse most\n * of the existing corpus) and never as `true`.\n */\n realness_screened?: boolean\n}\n\nexport interface RolloutCostBlock {\n usd: number | null\n tokens_in: number | null\n tokens_out: number | null\n tokens_reasoning: number | null\n cache_read: number | null\n cache_write: number | null\n wall_s: number | null\n /**\n * Total LLM inferences across the invocation (ATIF `llm_call_count`,\n * aggregated). Optional and additive: absent = not tracked, never 0.\n */\n llm_call_count?: number | null\n}\n\nexport interface RolloutArtifacts {\n patch_path: string | null\n run_dir: string | null\n /** Source-of-truth transcript pointer (session id / jsonl path) for audit.\n * Minted lines point at the run's trace as `trace:<traceId>`. */\n transcript_ref: string | null\n}\n\n/**\n * The reward-bearing half of a GATED line's outcome, moved off `outcome` and\n * parked here verbatim. Diagnostics, never training input — see\n * `gateGamedOutcome`.\n */\nexport interface GatedEvidence {\n /** `outcome.metrics` exactly as the producer measured it. */\n metrics?: Record<string, unknown>\n /** `outcome.verdict` verbatim — the judge record that claimed the success. */\n verdict?: unknown\n /**\n * The per-step fields `tangle.rollout.v1` does not declare, parked here when\n * the gate projected `steps[]` down to the schema's own key set.\n *\n * A per-step reward is training signal exactly like the scalar, and `steps`\n * rides through `toRewardRows` verbatim — so a gated line was shipping its\n * step-level credit assignment at full value beside a `reward` of 0.\n */\n steps?: unknown\n}\n\nexport interface RolloutEvidenceAttempt {\n executionId: string\n ordinal: number\n providerSessionId: string | null\n nativeSessionIds: string[]\n processIds: string[]\n outcome: 'succeeded' | 'failed' | 'cancelled' | 'unknown'\n missingReasons: string[]\n}\n\n/** One Runtime result blob and its unmodified provider capture receipt. */\nexport interface RolloutWorkspaceCapture {\n readonly outRef: string | null\n readonly blobPath: string | null\n /** JSON pointer to the receipt within its Runtime result. */\n readonly receiptPointer: string | null\n readonly receipt: unknown | null\n readonly attempts: readonly unknown[] | null\n /** The provider's claim, not an Eval verification of the archive bytes. */\n readonly coverageComplete: boolean | null\n readonly incompleteReason: string | null\n readonly projectionGap: string | null\n}\n\nexport interface RolloutProvenance {\n captured_at: string\n capture: RolloutCapture\n /** Exact search-cell attempt; absent outside a search. */\n search?: { searchId: string; nodeId: string; cellId: string; attempt: number }\n /** Run-bound provider attempts; absent means this source was not observed. */\n attempts?: RolloutEvidenceAttempt[]\n /** Exact per-result receipts in source order. Null means Runtime had no result evidence. */\n workspace_captures?: readonly RolloutWorkspaceCapture[] | null\n /** A known lossy semantic projection. Training sinks refuse this line. */\n lossy_projection?: true\n /**\n * Why this line is incomplete. Required when `messages` is empty and set\n * for lossy last-context or capped-step projections. Importers also use it to\n * name a MISSING LABEL — an imported trajectory carries no verdict, so\n * `outcome.reward` is null and this says why.\n */\n gap?: string\n /**\n * Present only on a realness-gated line: the outcome fields the gate\n * relocated, kept so an auditor can still see WHY the run was gated and what\n * it claimed. Deliberately OUTSIDE `outcome`, because every training exporter\n * reads `outcome` and none reads `provenance`.\n */\n gated_evidence?: GatedEvidence\n}\n\nexport interface RolloutLine {\n schema: typeof ROLLOUT_SCHEMA\n rollout_id: string\n /** Spawning invocation within the same episode (worker → supervisor); for a\n * nested search run, the run of the cell that contains the search. */\n parent_rollout_id: string | null\n run_id: string\n /** Logical experiment grouping from `RunRecord.experimentId`; null = not recorded. */\n experiment_id: string | null\n /** Stable candidate identity from `RunRecord.candidateId`; null = not recorded. */\n candidate_id: string | null\n /** Search depth of the run's node (0 = the search root); null = not a search run. */\n generation: number | null\n /** Registration order of the run's node in its search (0 = the root); null = not a search run. */\n candidate_index: number | null\n role: RolloutRole\n task: RolloutTask\n policy: RolloutPolicy\n /** Inline conversation projection. Check provenance.gap before treating it as complete. */\n messages: ChatMessage[]\n tool_defs: ToolDef[]\n /** Trace-span projections, when minted from a trace. */\n steps?: RolloutStep[]\n outcome: RolloutOutcome\n cost: RolloutCostBlock\n artifacts: RolloutArtifacts\n provenance: RolloutProvenance\n}\n\n// ---------------------------------------------------------------------------\n// Validation — pure TS, no runtime schema dependency, mirroring the\n// run-record validator's fail-loud discipline. Returns [] when the value\n// is a valid RolloutLine; otherwise one dotted-path error per defect.\n// ---------------------------------------------------------------------------\n\nconst isNumberOrNull = (v: unknown): boolean => v === null || typeof v === 'number'\nconst isNumberArray = (v: unknown): boolean =>\n Array.isArray(v) && v.every((n) => typeof n === 'number' && Number.isFinite(n))\nconst isIntegerArray = (v: unknown): boolean =>\n Array.isArray(v) && v.every((n) => Number.isInteger(n))\nconst isStringOrNull = (v: unknown): boolean => v === null || typeof v === 'string'\nconst isIntegerOrNull = (v: unknown): boolean => v === null || Number.isInteger(v)\n\nfunction validateChatMessage(value: unknown, path: string, errors: string[]): void {\n if (!isRecord(value)) {\n errors.push(`${path}: not an object`)\n return\n }\n if (!CHAT_ROLES.includes(value.role as ChatRole))\n errors.push(`${path}.role: invalid role ${String(value.role)}`)\n if (!isStringOrNull(value.content)) errors.push(`${path}.content: must be string|null`)\n if (value.reasoning_content !== undefined && typeof value.reasoning_content !== 'string') {\n errors.push(`${path}.reasoning_content: must be string when present`)\n }\n if (value.tool_call_id !== undefined && typeof value.tool_call_id !== 'string') {\n errors.push(`${path}.tool_call_id: must be string when present`)\n }\n if (value.role === 'tool' && typeof value.tool_call_id !== 'string') {\n errors.push(`${path}.tool_call_id: required on role:\"tool\"`)\n }\n if (value.is_copied_context !== undefined && typeof value.is_copied_context !== 'boolean') {\n errors.push(`${path}.is_copied_context: must be boolean when present`)\n }\n if (value.tool_calls !== undefined) {\n if (!Array.isArray(value.tool_calls)) {\n errors.push(`${path}.tool_calls: must be an array when present`)\n } else {\n value.tool_calls.forEach((call, i) => {\n if (!isRecord(call) || typeof call.id !== 'string' || call.type !== 'function') {\n errors.push(`${path}.tool_calls[${i}]: must be {id, type:\"function\", function}`)\n return\n }\n const fn = call.function\n if (!isRecord(fn) || typeof fn.name !== 'string' || typeof fn.arguments !== 'string') {\n errors.push(\n `${path}.tool_calls[${i}].function: must be {name: string, arguments: string}`,\n )\n }\n })\n }\n }\n}\n\nfunction validateSection(\n value: unknown,\n path: string,\n fields: Array<[name: string, check: (v: unknown) => boolean, expect: string]>,\n errors: string[],\n): void {\n if (!isRecord(value)) {\n errors.push(`${path}: not an object`)\n return\n }\n for (const [name, check, expect] of fields) {\n if (!check(value[name])) errors.push(`${path}.${name}: expected ${expect}`)\n }\n}\n\n/**\n * THE anti-Goodhart gate, applied to the WHOLE outcome as a TRANSFORMATION.\n *\n * Two prior rounds enforced the gate as a CHECK ON ONE FIELD at N call sites,\n * and each round the next reward-bearing field leaked. The one that shipped:\n * `mintRolloutRows` bulk-copied `RunRecord.outcome.raw` into `outcome.metrics`\n * with no gate, so a gated run exported `reward: 0` (correct) while the\n * deterministic per-layer scores that reward was COMPUTED FROM — the\n * `layer.*` keys `rl/verifiable-reward.ts` calls the RL training signal —\n * shipped at 1.0, in the top-level `metrics` dict of the Prime Intellect\n * verifiers format, which IS that format's per-rubric score dict. `verdict`\n * leaks the same way into `toRftItem`'s `reference.verdict`, where a grader\n * author reads `resolved: true` off a run that faked it.\n *\n * So the rule is no longer \"zero the field we remembered\". It is: if the gate\n * fired, the outcome that leaves here carries NOTHING positive that was derived\n * from the reward, whichever field a present or future exporter decides to\n * read. `reward` is already forced to 0 upstream (`trainingReward`) and\n * REJECTED here if it is not; `metrics` and `verdict` are relocated.\n *\n * WHERE they go, and why relocation rather than deletion: zeroing destroys the\n * audit trail that shows why the run was gated and what it claimed, which is\n * the row an auditor most wants and the labeled example a gaming DETECTOR\n * trains on. `provenance.gated_evidence` keeps every byte, at a path no\n * training exporter reads — all four release configs and every `rl/exporters`\n * shape project from `outcome`, `messages`, `cost` and `task`; none projects\n * `provenance`. Auditability preserved, training signal removed, and a future\n * exporter that reads a field nobody thought of is safe by construction because\n * the field is empty rather than because the exporter remembered to check.\n *\n * Idempotent: a second application finds nothing left to move and returns the\n * line unchanged, so re-minting a line read back off a ledger cannot clobber\n * the evidence it already carries.\n */\nexport function gateGamedOutcome(line: RolloutLine): RolloutLine {\n if (line.outcome.realness_gated !== true) return line\n const moved = gatedEvidenceOf(line)\n if (moved === undefined) return line\n const kept = line.provenance.gated_evidence\n const evidence: GatedEvidence = {}\n const metrics = { ...kept?.metrics, ...moved.metrics }\n if (Object.keys(metrics).length > 0) evidence.metrics = metrics\n if (moved.verdict !== undefined) evidence.verdict = moved.verdict\n else if (kept?.verdict !== undefined) evidence.verdict = kept.verdict\n if (moved.steps !== undefined) evidence.steps = moved.steps\n else if (kept?.steps !== undefined) evidence.steps = kept.steps\n // The trajectory itself STAYS: a gamed transcript is the labeled example a\n // gaming detector trains on, and the exporters are meant to ship it. Only the\n // fields the wire format does not declare come off, which is the same\n // partition `gatedEvidenceOf` applies to `metrics` — the producer's own,\n // never a key-name guess.\n const steps = moved.steps === undefined ? line.steps : declaredSteps(line.steps)\n return {\n ...line,\n ...(steps === undefined ? {} : { steps }),\n outcome: { ...line.outcome, metrics: {}, verdict: null },\n provenance: { ...line.provenance, gated_evidence: evidence },\n }\n}\n\n/**\n * EVERY gate check, for the export path — the runtime backstop.\n *\n * `validateRolloutLine` checks the reward relationship too, but an exporter\n * cannot afford to re-validate every field of every line, and more importantly\n * it is not the exporter's job to re-check the schema — it is its job never to\n * emit a signal it was told is fabricated. Thrown rather than filtered: an\n * exporter silently dropping a poisoned line would hide the producer that made\n * it, and the producer is the actual defect.\n *\n * This is the third layer, and it exists for exactly one caller: JavaScript.\n * The brand stops TypeScript callers at compile time and `assertMinted` fixes\n * data arriving from disk, but neither is present for a plain JS consumer of\n * the published package handing an object literal to `toRewardRows`. Which is\n * exactly why this entry point's policy omits nothing: a check it skips is a\n * check that never runs for those callers at all. It composed two of the three\n * for one round, and a never-screened positive reward walked through all four\n * waist exporters at full value. `GATE_POLICIES.assertRewardGate` is now the\n * only place that list is written down.\n */\nexport function assertRewardGate(line: RolloutLine, context: string): void {\n const errors = gateErrors(line, GATE_POLICIES.assertRewardGate)\n if (errors.length > 0) {\n throw new Error(`${context}: rollout ${line.rollout_id} — ${errors[0]}`)\n }\n}\n\nexport function validateRolloutLine(value: unknown): string[] {\n const errors: string[] = []\n if (!isRecord(value)) return ['line: not an object']\n\n if (value.schema !== ROLLOUT_SCHEMA) errors.push(`schema: expected \"${ROLLOUT_SCHEMA}\"`)\n if (typeof value.rollout_id !== 'string' || value.rollout_id.length === 0)\n errors.push('rollout_id: expected non-empty string')\n if (!isStringOrNull(value.parent_rollout_id))\n errors.push('parent_rollout_id: expected string|null')\n if (typeof value.run_id !== 'string' || value.run_id.length === 0)\n errors.push('run_id: expected non-empty string')\n if (!isStringOrNull(value.experiment_id)) errors.push('experiment_id: expected string|null')\n if (!isStringOrNull(value.candidate_id)) errors.push('candidate_id: expected string|null')\n if (!isIntegerOrNull(value.generation)) errors.push('generation: expected integer|null')\n if (!isIntegerOrNull(value.candidate_index)) errors.push('candidate_index: expected integer|null')\n if (!ROLLOUT_ROLES.includes(value.role as RolloutRole))\n errors.push(`role: invalid role ${String(value.role)}`)\n\n validateSection(\n value.task,\n 'task',\n [\n ['suite', (v) => typeof v === 'string' && v.length > 0, 'non-empty string'],\n ['instance_id', (v) => typeof v === 'string' && v.length > 0, 'non-empty string'],\n [\n 'split',\n (v) => ROLLOUT_SPLITS.includes(v as RolloutSplit),\n `one of ${ROLLOUT_SPLITS.join('|')}`,\n ],\n ['seed', isNumberOrNull, 'number|null'],\n ['rep', (v) => Number.isInteger(v), 'integer'],\n ],\n errors,\n )\n\n validateSection(\n value.policy,\n 'policy',\n [\n ['harness', isStringOrNull, 'string|null'],\n ['harness_version', isStringOrNull, 'string|null'],\n ['model', isStringOrNull, 'string|null'],\n ['provider', isStringOrNull, 'string|null'],\n ['profile_commit', isStringOrNull, 'string|null'],\n ['sampling', (v) => v === null || isRecord(v), 'object|null'],\n ],\n errors,\n )\n if (isRecord(value.policy)) {\n for (const key of ['prompt_hash', 'config_hash', 'agent_profile_cell_id'] as const) {\n if (value.policy[key] !== undefined && !isStringOrNull(value.policy[key])) {\n errors.push(`policy.${key}: expected string|null when present`)\n }\n }\n }\n\n if (!Array.isArray(value.messages)) {\n errors.push('messages: expected array')\n } else {\n for (const [i, m] of value.messages.entries()) validateChatMessage(m, `messages[${i}]`, errors)\n }\n\n if (!Array.isArray(value.tool_defs)) {\n errors.push('tool_defs: expected array')\n } else {\n value.tool_defs.forEach((d, i) => {\n if (\n !isRecord(d) ||\n d.type !== 'function' ||\n !isRecord(d.function) ||\n typeof d.function.name !== 'string'\n ) {\n errors.push(`tool_defs[${i}]: must be {type:\"function\", function:{name}}`)\n }\n })\n }\n\n if (value.steps !== undefined) {\n if (!Array.isArray(value.steps)) {\n errors.push('steps: expected array when present')\n } else {\n value.steps.forEach((s, i) => {\n if (!isRecord(s) || typeof s.kind !== 'string' || typeof s.name !== 'string') {\n errors.push(`steps[${i}]: must be {kind: string, name: string, …}`)\n return\n }\n // ATIF-lifted optionals: absent on every line written before they\n // existed, so they are checked only when present — old ledgers stay valid.\n if (s.llm_call_count !== undefined && !Number.isInteger(s.llm_call_count)) {\n errors.push(`steps[${i}].llm_call_count: expected integer when present`)\n }\n for (const key of ['prompt_token_ids', 'completion_token_ids'] as const) {\n if (s[key] !== undefined && !isIntegerArray(s[key])) {\n errors.push(`steps[${i}].${key}: expected integer[] when present`)\n }\n }\n if (s.logprobs !== undefined && !isNumberArray(s.logprobs)) {\n errors.push(`steps[${i}].logprobs: expected number[] when present`)\n }\n })\n }\n }\n\n validateSection(\n value.outcome,\n 'outcome',\n [\n ['reward', isNumberOrNull, 'number|null'],\n ['reward_source', isStringOrNull, 'string|null'],\n ['metrics', isRecord, 'object'],\n ['is_completed', (v) => typeof v === 'boolean', 'boolean'],\n ['is_truncated', (v) => typeof v === 'boolean', 'boolean'],\n ['error', isStringOrNull, 'string|null'],\n ],\n errors,\n )\n if (isRecord(value.outcome)) {\n if (!('verdict' in value.outcome)) errors.push('outcome.verdict: field required (may be null)')\n if (typeof value.outcome.realness_gated !== 'boolean') {\n errors.push('outcome.realness_gated: expected boolean')\n }\n if (\n value.outcome.realness_screened !== undefined &&\n typeof value.outcome.realness_screened !== 'boolean'\n ) {\n errors.push('outcome.realness_screened: expected boolean when present')\n }\n errors.push(\n ...gateErrors(\n { outcome: value.outcome, steps: value.steps },\n GATE_POLICIES.validateRolloutLine,\n ),\n )\n }\n\n validateSection(\n value.cost,\n 'cost',\n [\n ['usd', isNumberOrNull, 'number|null'],\n ['tokens_in', isNumberOrNull, 'number|null'],\n ['tokens_out', isNumberOrNull, 'number|null'],\n ['tokens_reasoning', isNumberOrNull, 'number|null'],\n ['cache_read', isNumberOrNull, 'number|null'],\n ['cache_write', isNumberOrNull, 'number|null'],\n ['wall_s', isNumberOrNull, 'number|null'],\n ],\n errors,\n )\n if (\n isRecord(value.cost) &&\n value.cost.llm_call_count !== undefined &&\n !(value.cost.llm_call_count === null || Number.isInteger(value.cost.llm_call_count))\n ) {\n errors.push('cost.llm_call_count: expected integer|null when present')\n }\n\n validateSection(\n value.artifacts,\n 'artifacts',\n [\n ['patch_path', isStringOrNull, 'string|null'],\n ['run_dir', isStringOrNull, 'string|null'],\n ['transcript_ref', isStringOrNull, 'string|null'],\n ],\n errors,\n )\n\n validateSection(\n value.provenance,\n 'provenance',\n [\n [\n 'captured_at',\n (v) => typeof v === 'string' && !Number.isNaN(Date.parse(v)),\n 'ISO-8601 timestamp',\n ],\n [\n 'capture',\n (v) => ROLLOUT_CAPTURES.includes(v as RolloutCapture),\n `one of ${ROLLOUT_CAPTURES.join('|')}`,\n ],\n ],\n errors,\n )\n if (isRecord(value.provenance)) {\n if (\n value.provenance.lossy_projection !== undefined &&\n value.provenance.lossy_projection !== true\n ) {\n errors.push('provenance.lossy_projection: expected true when present')\n }\n if (\n value.provenance.lossy_projection === true &&\n (typeof value.provenance.gap !== 'string' || value.provenance.gap.length === 0)\n ) {\n errors.push('provenance.gap: required for a lossy projection')\n }\n const search = value.provenance.search\n if (search !== undefined) {\n if (\n !isRecord(search) ||\n typeof search.searchId !== 'string' ||\n !search.searchId ||\n typeof search.nodeId !== 'string' ||\n !search.nodeId ||\n typeof search.cellId !== 'string' ||\n !search.cellId ||\n !Number.isSafeInteger(search.attempt) ||\n (search.attempt as number) < 1\n ) {\n errors.push('provenance.search: expected exact search, node, cell and positive attempt')\n }\n }\n const captures = value.provenance.workspace_captures\n if (captures !== undefined && captures !== null) {\n if (!Array.isArray(captures)) {\n errors.push('provenance.workspace_captures: expected array|null when present')\n } else {\n for (const [i, capture] of captures.entries()) {\n if (\n !isRecord(capture) ||\n !isStringOrNull(capture.outRef) ||\n !isStringOrNull(capture.blobPath) ||\n !isStringOrNull(capture.receiptPointer) ||\n !('receipt' in capture) ||\n (capture.attempts !== null && !Array.isArray(capture.attempts)) ||\n (capture.coverageComplete !== null && typeof capture.coverageComplete !== 'boolean') ||\n !isStringOrNull(capture.incompleteReason) ||\n !isStringOrNull(capture.projectionGap)\n ) {\n errors.push(`provenance.workspace_captures[${i}]: invalid capture evidence`)\n }\n }\n }\n }\n const attempts = value.provenance.attempts\n if (attempts !== undefined) {\n if (!Array.isArray(attempts)) {\n errors.push('provenance.attempts: expected array when present')\n } else {\n const ordinalsByExecution = new Map<string, Set<number>>()\n for (const [i, attempt] of attempts.entries()) {\n if (\n !isRecord(attempt) ||\n typeof attempt.executionId !== 'string' ||\n !attempt.executionId ||\n !Number.isSafeInteger(attempt.ordinal) ||\n (attempt.ordinal as number) < 1 ||\n !isStringOrNull(attempt.providerSessionId) ||\n !Array.isArray(attempt.nativeSessionIds) ||\n !attempt.nativeSessionIds.every((id) => typeof id === 'string' && id.length > 0) ||\n !Array.isArray(attempt.processIds) ||\n !attempt.processIds.every((id) => typeof id === 'string' && id.length > 0) ||\n !['succeeded', 'failed', 'cancelled', 'unknown'].includes(attempt.outcome as string) ||\n !Array.isArray(attempt.missingReasons) ||\n !attempt.missingReasons.every(\n (reason) => typeof reason === 'string' && reason.length > 0,\n )\n ) {\n errors.push(`provenance.attempts[${i}]: invalid attempt evidence`)\n continue\n }\n const executionId = attempt.executionId as string\n const ordinal = attempt.ordinal as number\n const seen = ordinalsByExecution.get(executionId) ?? new Set<number>()\n if (seen.has(ordinal)) {\n errors.push(`provenance.attempts[${i}]: duplicate execution/ordinal`)\n }\n seen.add(ordinal)\n ordinalsByExecution.set(executionId, seen)\n }\n for (const [executionId, ordinals] of ordinalsByExecution) {\n for (let ordinal = 1; ordinal <= ordinals.size; ordinal++) {\n if (!ordinals.has(ordinal)) {\n errors.push(`provenance.attempts: ${executionId} is missing ordinal ${ordinal}`)\n }\n }\n }\n }\n }\n if (value.provenance.gap !== undefined && typeof value.provenance.gap !== 'string') {\n errors.push('provenance.gap: must be string when present')\n }\n const evidence = value.provenance.gated_evidence\n if (evidence !== undefined) {\n if (!isRecord(evidence)) {\n errors.push('provenance.gated_evidence: must be an object when present')\n } else if (evidence.metrics !== undefined && !isRecord(evidence.metrics)) {\n errors.push('provenance.gated_evidence.metrics: must be an object when present')\n }\n }\n }\n\n // A gap line must say WHY it is a gap; a full line must not carry a gap note.\n if (Array.isArray(value.messages) && isRecord(value.provenance)) {\n if (value.messages.length === 0 && typeof value.provenance.gap !== 'string') {\n errors.push('provenance.gap: required when messages is empty')\n }\n }\n\n return errors\n}\n\nexport function assertRolloutLine(\n value: unknown,\n context = 'rollout line',\n): asserts value is RolloutLine {\n const errors = validateRolloutLine(value)\n if (errors.length > 0) {\n throw new Error(`invalid ${context}:\\n ${errors.join('\\n ')}`)\n }\n}\n\nexport function isRolloutLine(value: unknown): value is RolloutLine {\n return validateRolloutLine(value).length === 0\n}\n\n// ---------------------------------------------------------------------------\n// The minted brand — the COMPILE-TIME half of the anti-Goodhart gate.\n// ---------------------------------------------------------------------------\n\n/**\n * Phantom property. `declare const` means it exists only in the type system:\n * nothing is written at runtime, so a branded line still serializes to exactly\n * the same JSON as a plain one.\n */\ndeclare const MINTED_ROLLOUT: unique symbol\n\n/**\n * A minted outcome states the gate verdict — it is not allowed to stay silent —\n * and, when that verdict is `true`, carries nothing else the reward was derived\n * from (`gateGamedOutcome` has run).\n */\nexport interface MintedRolloutOutcome extends RolloutOutcome {\n realness_gated: boolean\n}\n\n/**\n * A `RolloutLine` whose reward has been checked against the anti-Goodhart\n * invariant. The type every training-data exporter takes.\n *\n * Why a brand and not just the interface: `RolloutLine` is structural, so any\n * hand-built object literal of the right shape IS one — which is how a line\n * declaring `{reward: 0.95, realness_gated: true}` reached the exporters\n * despite them \"only accepting a minted line\". The phantom symbol makes the\n * type nominal: it cannot be produced by writing an object literal, only by\n * `mintRolloutRows` (which applies the gate), `readRolloutLedger` (which\n * validates every line off disk), or an explicit, greppable `assertMinted`.\n *\n * Belt and braces on purpose. The brand closes first-party call sites at\n * COMPILE time; `validateRolloutLine` closes data arriving at RUNTIME (ledger\n * files, foreign imports, JSON from another process) where types are absent.\n * Neither alone is enough.\n *\n * Assignable to `RolloutLine` in one direction only: readers, analysis, and\n * the ledger writer keep taking the plain type.\n */\nexport type MintedRolloutLine = Omit<RolloutLine, 'outcome'> & {\n readonly [MINTED_ROLLOUT]: true\n outcome: MintedRolloutOutcome\n}\n\n/**\n * Promote a line to the type the training exporters accept, applying the\n * anti-Goodhart gate to the WHOLE outcome on the way through. THE escape hatch\n * — grep `assertMinted` to enumerate every place a line enters the training\n * path without coming from mint or a ledger.\n *\n * The gate runs HERE, once, rather than at each producer, because this is the\n * single funnel every minted line passes: `mintRolloutRows` calls it,\n * `readRolloutLedger` calls it per line off disk, `scrubLines` calls it on the\n * way out of a release, and a hand-built line has no other door. One\n * transformation at the funnel means an already-published ledger holding a\n * gated line with populated `metrics` is RE-GATED when it is read, instead of\n * being rejected (which would make every such artifact unreadable) or trusted\n * (which is the leak). Three steps, in this order:\n *\n * 1. VALIDATE the schema.\n * 2. REFUSE every check `GATE_POLICIES.assertMinted` marks `enforce` — today\n * the reward relationship (which stays a REJECTION: a caller claiming\n * `{reward: 0.95, realness_gated: true}` is a producer defect and must fail\n * loudly, since laundering it into `reward: 0` here would hide the\n * producer) and a positive reward the producer declared it never screened.\n * 3. TRANSFORM the one check that policy marks `repair` — relocate the\n * reward's components off `outcome` (`gateGamedOutcome`), so no exporter\n * can leak them whichever field it reads.\n *\n * Step 2 enumerates nothing by hand: a check added to `GATE_CHECKS` is enforced\n * here the moment its disposition in that policy says so.\n *\n * Also normalizes the optional wire flag to an explicit boolean.\n * `realness_gated` is absent on pre-unification ledgers and absent means \"not\n * flagged\" per the schema, so filling it in states a claim the line was already\n * making, and makes the flag readable on every published row instead of most of\n * them. `realness_screened` is NOT filled in: absent means \"unknown\", and\n * inventing either value there would be the same overclaim this round removed.\n */\nexport function assertMinted(value: unknown, context = 'rollout line'): MintedRolloutLine {\n assertRolloutLine(value, context)\n const refused = gateErrors(value, GATE_POLICIES.assertMinted)\n if (refused.length > 0) {\n throw new Error(`invalid ${context}: rollout ${value.rollout_id} — ${refused[0]}`)\n }\n const gated = gateGamedOutcome(value)\n if (gated.outcome.realness_gated === undefined) {\n return {\n ...gated,\n outcome: { ...gated.outcome, realness_gated: false },\n } as MintedRolloutLine\n }\n return gated as MintedRolloutLine\n}\n\n/** `assertMinted` over a batch, naming the offending index in the error. */\nexport function assertMintedLines(\n values: readonly unknown[],\n context = 'rollout line',\n): MintedRolloutLine[] {\n return values.map((value, i) => assertMinted(value, `${context} [${i}]`))\n}\n"],"mappings":";;;;;;;;;AA2CA,MAAa,iBAAiB;CAC5B;CACA;CACA;CACA;AACF;;AAqCA,MAAM,SAAS,SAAsB,SAClC,QAAQ,UAAgD;AAkD3D,SAAgB,WAAW,OAA+B;CACxD,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO,EAAE,MAAM,SAAS;CACnE,IAAI,OAAO,UAAU,UAAU;EAC7B,IAAI,OAAO,MAAM,KAAK,GAAG,OAAO;GAAE,MAAM;GAAc,OAAO;EAAM;EACnE,OAAO,QAAQ,IAAI;GAAE,MAAM;GAAY,OAAO,OAAO,KAAK;EAAE,IAAI,EAAE,MAAM,UAAU;CACpF;CACA,OAAO;EACL,MAAM;EACN,OAAO,GAAG,KAAK,UAAU,KAAK,KAAK,OAAO,KAAK,EAAE,IAAI,OAAO,MAAM;CACpE;AACF;AAEA,MAAM,iBAAiB,UACrB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;;;;;;;;;;;;;AAcrE,SAAgB,mBAAmB,OAAyB;CAC1D,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO;CAClD,IAAI,cAAc,KAAK,GAAG,OAAO,OAAO,KAAK,KAAK,CAAC,CAAC,SAAS;CAC7D,OAAO;AACT;;;;;;;;;;;AAYA,MAAM,qBAA4E;CAChF,MAAM;CACN,MAAM;CACN,OAAO;CACP,QAAQ;CACR,QAAQ;CACR,YAAY;CACZ,gBAAgB;CAChB,kBAAkB;CAClB,sBAAsB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