@tangle-network/agent-eval 0.163.2 → 0.171.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 (249) hide show
  1. package/CHANGELOG.md +127 -0
  2. package/README.md +2 -0
  3. package/dist/adapters/http.d.ts +108 -0
  4. package/dist/adapters/http.d.ts.map +1 -0
  5. package/dist/adapters/http.js +208 -0
  6. package/dist/adapters/http.js.map +1 -0
  7. package/dist/analyst/index.d.ts +40 -70
  8. package/dist/analyst/index.d.ts.map +1 -1
  9. package/dist/analyst/index.js +18 -311
  10. package/dist/analyst/index.js.map +1 -1
  11. package/dist/{backend-integrity-DxuQCu_A.d.ts → backend-integrity-e79K3UPD.d.ts} +3 -3
  12. package/dist/{backend-integrity-DxuQCu_A.d.ts.map → backend-integrity-e79K3UPD.d.ts.map} +1 -1
  13. package/dist/{benchmark-BhT16ep9.js → benchmark-C4wk_Sjr.js} +10 -3
  14. package/dist/benchmark-C4wk_Sjr.js.map +1 -0
  15. package/dist/{benchmark-command-CF-4GEWZ.js → benchmark-command-D8k3Gf0J.js} +236 -251
  16. package/dist/benchmark-command-D8k3Gf0J.js.map +1 -0
  17. package/dist/{benchmark-CGPp-kDC.d.ts → benchmark-h-h4bfqj.d.ts} +3 -3
  18. package/dist/{benchmark-CGPp-kDC.d.ts.map → benchmark-h-h4bfqj.d.ts.map} +1 -1
  19. package/dist/benchmarks/index.d.ts +5 -5
  20. package/dist/benchmarks/index.js +3 -3
  21. package/dist/builder-eval/index.d.ts +3 -3
  22. package/dist/builder-eval/index.js +1 -1
  23. package/dist/campaign/index.d.ts +8 -8
  24. package/dist/campaign/index.js +7 -7
  25. package/dist/{campaign-DQZmc2Dq.js → campaign-B72njjHj.js} +15 -14
  26. package/dist/campaign-B72njjHj.js.map +1 -0
  27. package/dist/{canonical-IL-Bu-14.js → canonical-DPyQ_rpt.js} +22 -2
  28. package/dist/{canonical-IL-Bu-14.js.map → canonical-DPyQ_rpt.js.map} +1 -1
  29. package/dist/{chat-client-DlMlAeYI.js → chat-client-DEtybj5i.js} +5 -5
  30. package/dist/{chat-client-DlMlAeYI.js.map → chat-client-DEtybj5i.js.map} +1 -1
  31. package/dist/cli.js +2 -2
  32. package/dist/{client-CX7KqIdB.js → client-BvwNkIRN.js} +2 -2
  33. package/dist/{client-CX7KqIdB.js.map → client-BvwNkIRN.js.map} +1 -1
  34. package/dist/{client-L9VVPkim.d.ts → client-CDtcZ3p9.d.ts} +4 -4
  35. package/dist/{client-L9VVPkim.d.ts.map → client-CDtcZ3p9.d.ts.map} +1 -1
  36. package/dist/contract/index.d.ts +12 -703
  37. package/dist/contract/index.js +11 -11
  38. package/dist/{counterfactual-BaFUWK3H.d.ts → counterfactual-Bee5_BIn.d.ts} +4 -4
  39. package/dist/{counterfactual-BaFUWK3H.d.ts.map → counterfactual-Bee5_BIn.d.ts.map} +1 -1
  40. package/dist/{default-registry-G9CKMNkc.d.ts → default-registry-B0s2zU-s.d.ts} +6 -6
  41. package/dist/{default-registry-G9CKMNkc.d.ts.map → default-registry-B0s2zU-s.d.ts.map} +1 -1
  42. package/dist/{define-agent-eval-Dx1JnPEa.d.ts → define-agent-eval-Cjy2yhqP.d.ts} +7 -7
  43. package/dist/{define-agent-eval-Dx1JnPEa.d.ts.map → define-agent-eval-Cjy2yhqP.d.ts.map} +1 -1
  44. package/dist/{define-agent-eval-D08pWIJb.js → define-agent-eval-Dy8QgxAI.js} +20 -8
  45. package/dist/{define-agent-eval-D08pWIJb.js.map → define-agent-eval-Dy8QgxAI.js.map} +1 -1
  46. package/dist/{dspy-rlm-engine-DhA9qKIm.js → dspy-rlm-engine-CS3qcCEk.js} +3 -10
  47. package/dist/dspy-rlm-engine-CS3qcCEk.js.map +1 -0
  48. package/dist/{emitter-D_jYSGRd.d.ts → emitter-Bvnu0VzL.d.ts} +3 -3
  49. package/dist/{emitter-D_jYSGRd.d.ts.map → emitter-Bvnu0VzL.d.ts.map} +1 -1
  50. package/dist/{engine-Cu5qD5Fc.d.ts → engine-CAmTUk52.d.ts} +7 -7
  51. package/dist/{engine-Cu5qD5Fc.d.ts.map → engine-CAmTUk52.d.ts.map} +1 -1
  52. package/dist/{eval-campaign-BfohKmzx.js → eval-campaign-JDTeE6Pl.js} +4 -4
  53. package/dist/{eval-campaign-BfohKmzx.js.map → eval-campaign-JDTeE6Pl.js.map} +1 -1
  54. package/dist/{exact-types-qnexxJ1Z.d.ts → exact-types-BEecmnWm.d.ts} +2 -2
  55. package/dist/{exact-types-qnexxJ1Z.d.ts.map → exact-types-BEecmnWm.d.ts.map} +1 -1
  56. package/dist/experiment/index.d.ts +5 -5
  57. package/dist/experiment/index.js +4 -4
  58. package/dist/{experiment-tracker-DCO6Cz4s.d.ts → experiment-tracker-Dm8yQMqb.d.ts} +2 -2
  59. package/dist/{experiment-tracker-DCO6Cz4s.d.ts.map → experiment-tracker-Dm8yQMqb.d.ts.map} +1 -1
  60. package/dist/{external-optimizer-process-BFmh36vW.js → external-optimizer-process-CQxylYeG.js} +4 -11
  61. package/dist/external-optimizer-process-CQxylYeG.js.map +1 -0
  62. package/dist/{external-optimizer-subprocess-CqLMW3nh.js → external-optimizer-subprocess-Cex8Da2i.js} +25 -11
  63. package/dist/external-optimizer-subprocess-Cex8Da2i.js.map +1 -0
  64. package/dist/{failure-cluster-CXL8NbEw.d.ts → failure-cluster-6YSvsKlp.d.ts} +3 -3
  65. package/dist/{failure-cluster-CXL8NbEw.d.ts.map → failure-cluster-6YSvsKlp.d.ts.map} +1 -1
  66. package/dist/{feedback-trajectory-B3ZHaHV_.d.ts → feedback-trajectory-DIqpCyF0.d.ts} +6 -6
  67. package/dist/{feedback-trajectory-B3ZHaHV_.d.ts.map → feedback-trajectory-DIqpCyF0.d.ts.map} +1 -1
  68. package/dist/fuzz.d.ts +1 -1
  69. package/dist/{skillopt-optimization-method-x7TTF23P.d.ts → heldout-gate-Dh2b62w8.d.ts} +111 -111
  70. package/dist/heldout-gate-Dh2b62w8.d.ts.map +1 -0
  71. package/dist/hosted/index.d.ts +2 -2
  72. package/dist/hosted/index.js +1 -1
  73. package/dist/{index-D-V8gCs_.d.ts → index-8VIogTyS.d.ts} +30 -22
  74. package/dist/index-8VIogTyS.d.ts.map +1 -0
  75. package/dist/{index-D-IiQIBB.d.ts → index-DMoxLG8P.d.ts} +3 -3
  76. package/dist/{index-D-IiQIBB.d.ts.map → index-DMoxLG8P.d.ts.map} +1 -1
  77. package/dist/{index-D_P7Ye43.d.ts → index-DNgf5gyG.d.ts} +2 -2
  78. package/dist/{index-D_P7Ye43.d.ts.map → index-DNgf5gyG.d.ts.map} +1 -1
  79. package/dist/{index-CGtH1piv.d.ts → index-DT73JraI.d.ts} +7 -38
  80. package/dist/index-DT73JraI.d.ts.map +1 -0
  81. package/dist/index-fNXZMCzX.d.ts +704 -0
  82. package/dist/index-fNXZMCzX.d.ts.map +1 -0
  83. package/dist/index.d.ts +197 -38
  84. package/dist/index.d.ts.map +1 -1
  85. package/dist/index.js +736 -28
  86. package/dist/index.js.map +1 -1
  87. package/dist/{insight-report-DRe8LB6d.d.ts → insight-report-08F022xN.d.ts} +4 -4
  88. package/dist/{insight-report-DRe8LB6d.d.ts.map → insight-report-08F022xN.d.ts.map} +1 -1
  89. package/dist/{integrity-DUNX9Fao.d.ts → integrity-B_EDELom.d.ts} +2 -2
  90. package/dist/{integrity-DUNX9Fao.d.ts.map → integrity-B_EDELom.d.ts.map} +1 -1
  91. package/dist/internal-BMFSR8Ns.js.map +1 -1
  92. package/dist/{kind-factory-DY8FdoXf.js → kind-factory-DMeEoMQZ.js} +3 -10
  93. package/dist/kind-factory-DMeEoMQZ.js.map +1 -0
  94. package/dist/ledger-core/index.js +2 -2
  95. package/dist/{ledger-core-BOzlRygb.js → ledger-core-PIfjCbKn.js} +2 -2
  96. package/dist/{ledger-core-BOzlRygb.js.map → ledger-core-PIfjCbKn.js.map} +1 -1
  97. package/dist/{llm-judge-Du7WQPh7.js → llm-judge-BtJ2Sfk_.js} +101 -20
  98. package/dist/llm-judge-BtJ2Sfk_.js.map +1 -0
  99. package/dist/matrix/index.d.ts +2 -2
  100. package/dist/{matrix-eXKRMHnL.d.ts → matrix-DiHmUobV.d.ts} +3 -3
  101. package/dist/{matrix-eXKRMHnL.d.ts.map → matrix-DiHmUobV.d.ts.map} +1 -1
  102. package/dist/meta-eval/index.d.ts +3 -3
  103. package/dist/meta-eval/index.js +1 -1
  104. package/dist/{mint-DfODW1KW.js → mint-DjfDUMHr.js} +2 -2
  105. package/dist/{mint-DfODW1KW.js.map → mint-DjfDUMHr.js.map} +1 -1
  106. package/dist/multishot/golden/index.d.ts +1 -1
  107. package/dist/multishot/index.d.ts +2 -2
  108. package/dist/openapi.json +4 -4
  109. package/dist/pipelines/index.d.ts +5 -5
  110. package/dist/pipelines/index.js +3 -3
  111. package/dist/{pareto-BqNW3LJR.d.ts → power-preflight-Ptse_Kq7.d.ts} +43 -43
  112. package/dist/power-preflight-Ptse_Kq7.d.ts.map +1 -0
  113. package/dist/{pre-registration-KN9jkh58.js → pre-registration-D94b7Of5.js} +2 -2
  114. package/dist/{pre-registration-KN9jkh58.js.map → pre-registration-D94b7Of5.js.map} +1 -1
  115. package/dist/{pre-registration-CzFCcwYk.d.ts → pre-registration-DHz6P_6f.d.ts} +2 -2
  116. package/dist/{pre-registration-CzFCcwYk.d.ts.map → pre-registration-DHz6P_6f.d.ts.map} +1 -1
  117. package/dist/{produced-state-Be0BK3RN.js → produced-state-Cm6DU_Ao.js} +4 -4
  118. package/dist/{produced-state-Be0BK3RN.js.map → produced-state-Cm6DU_Ao.js.map} +1 -1
  119. package/dist/profile-cell.js +1 -1
  120. package/dist/{promotion-policy-DtnOIZvk.d.ts → promotion-policy-WSXtBgBb.d.ts} +3 -3
  121. package/dist/{promotion-policy-DtnOIZvk.d.ts.map → promotion-policy-WSXtBgBb.d.ts.map} +1 -1
  122. package/dist/{run-score-lDzV0X8j.js → proposal-findings-bko3GGy-.js} +2 -31
  123. package/dist/proposal-findings-bko3GGy-.js.map +1 -0
  124. package/dist/{transient-failure-DKF5Mofa.d.ts → provenance-CafMdZKM.d.ts} +895 -891
  125. package/dist/provenance-CafMdZKM.d.ts.map +1 -0
  126. package/dist/{query-_5g6re3_.js → query-BPGMVlbM.js} +3 -3
  127. package/dist/{query-_5g6re3_.js.map → query-BPGMVlbM.js.map} +1 -1
  128. package/dist/{query-CwnHlu5p.d.ts → query-Na5gEIGd.d.ts} +3 -3
  129. package/dist/{query-CwnHlu5p.d.ts.map → query-Na5gEIGd.d.ts.map} +1 -1
  130. package/dist/{registry-8You7OK1.d.ts → registry-xEb_xfns.d.ts} +3 -3
  131. package/dist/{registry-8You7OK1.d.ts.map → registry-xEb_xfns.d.ts.map} +1 -1
  132. package/dist/{release-confidence-nGDJiiwc.js → release-confidence-CzUHc4z4.js} +3 -3
  133. package/dist/{release-confidence-nGDJiiwc.js.map → release-confidence-CzUHc4z4.js.map} +1 -1
  134. package/dist/{release-confidence-Dqt0NFep.d.ts → release-confidence-D6lQw_o7.d.ts} +4 -4
  135. package/dist/{release-confidence-Dqt0NFep.d.ts.map → release-confidence-D6lQw_o7.d.ts.map} +1 -1
  136. package/dist/reporting.d.ts +3 -3
  137. package/dist/reporting.js +2 -2
  138. package/dist/{researcher-Cz565b7D.d.ts → researcher-CMUTQXD7.d.ts} +6 -6
  139. package/dist/{researcher-Cz565b7D.d.ts.map → researcher-CMUTQXD7.d.ts.map} +1 -1
  140. package/dist/{reward-hacking-MBf7qpSB.d.ts → reward-hacking-CgPRUesA.d.ts} +2 -2
  141. package/dist/{reward-hacking-MBf7qpSB.d.ts.map → reward-hacking-CgPRUesA.d.ts.map} +1 -1
  142. package/dist/{reward-hacking-O5zKDANP.js → reward-hacking-SkxYgT0x.js} +2 -2
  143. package/dist/{reward-hacking-O5zKDANP.js.map → reward-hacking-SkxYgT0x.js.map} +1 -1
  144. package/dist/rl.d.ts +8 -8
  145. package/dist/rl.d.ts.map +1 -1
  146. package/dist/rl.js +6 -5
  147. package/dist/rl.js.map +1 -1
  148. package/dist/rollout/index.d.ts +1 -1
  149. package/dist/rollout/index.js +2 -2
  150. package/dist/{rollout-Dm2tSdiQ.js → rollout-Crypdx8s.js} +2 -2
  151. package/dist/{rollout-Dm2tSdiQ.js.map → rollout-Crypdx8s.js.map} +1 -1
  152. package/dist/{rubric-predictive-validity-CxycqzX5.d.ts → rubric-predictive-validity-DluJLCKQ.d.ts} +2 -2
  153. package/dist/{rubric-predictive-validity-CxycqzX5.d.ts.map → rubric-predictive-validity-DluJLCKQ.d.ts.map} +1 -1
  154. package/dist/{run-record-BC0ebuRP.js → run-record-DLORoL7t.js} +2 -2
  155. package/dist/{run-record-BC0ebuRP.js.map → run-record-DLORoL7t.js.map} +1 -1
  156. package/dist/{run-record-VVy4T9OW.d.ts → run-record-DQjRcYwA.d.ts} +3 -3
  157. package/dist/{run-record-VVy4T9OW.d.ts.map → run-record-DQjRcYwA.d.ts.map} +1 -1
  158. package/dist/{schema-k6ZBftVv.js → schema-CdIX2aHu.js} +5 -1
  159. package/dist/{schema-k6ZBftVv.js.map → schema-CdIX2aHu.js.map} +1 -1
  160. package/dist/{schema-Bjgdsn73.d.ts → schema-DID1Cqct.d.ts} +7 -3
  161. package/dist/{schema-Bjgdsn73.d.ts.map → schema-DID1Cqct.d.ts.map} +1 -1
  162. package/dist/{semantic-concept-judge-BsDMOwJr.js → semantic-concept-judge-I36eejJx.js} +2 -2
  163. package/dist/{semantic-concept-judge-BsDMOwJr.js.map → semantic-concept-judge-I36eejJx.js.map} +1 -1
  164. package/dist/{sequential-BLMbdrD7.js → sequential-B51qAYE4.js} +2 -2
  165. package/dist/{sequential-BLMbdrD7.js.map → sequential-B51qAYE4.js.map} +1 -1
  166. package/dist/{server-BjYiJHoJ.js → server-CCEnywOR.js} +26 -18
  167. package/dist/server-CCEnywOR.js.map +1 -0
  168. package/dist/{skillopt-optimization-method-UArRo-nr.js → skillopt-optimization-method-DzlF2RM7.js} +9 -9
  169. package/dist/{skillopt-optimization-method-UArRo-nr.js.map → skillopt-optimization-method-DzlF2RM7.js.map} +1 -1
  170. package/dist/{statistical-heldout-Cy3EhjlC.d.ts → statistical-heldout-UhiexnjU.d.ts} +3 -3
  171. package/dist/{statistical-heldout-Cy3EhjlC.d.ts.map → statistical-heldout-UhiexnjU.d.ts.map} +1 -1
  172. package/dist/{store-B06JdC56.d.ts → store-Cq9oOrI1.d.ts} +2 -2
  173. package/dist/{store-B06JdC56.d.ts.map → store-Cq9oOrI1.d.ts.map} +1 -1
  174. package/dist/{store-otlp-C_Rq5I4D.js → store-otlp-CHjBvWQY.js} +2 -2
  175. package/dist/{store-otlp-C_Rq5I4D.js.map → store-otlp-CHjBvWQY.js.map} +1 -1
  176. package/dist/{store-tool-spans-BVga3c37.js → store-tool-spans-B9o6tU8f.js} +3 -3
  177. package/dist/{store-tool-spans-BVga3c37.js.map → store-tool-spans-B9o6tU8f.js.map} +1 -1
  178. package/dist/{store-tool-spans-DPUG7UUY.d.ts → store-tool-spans-D_qMl2__.d.ts} +102 -36
  179. package/dist/store-tool-spans-D_qMl2__.d.ts.map +1 -0
  180. package/dist/storyboard/index.d.ts +1 -1
  181. package/dist/{summary-report-BXeQ5Ues.js → summary-report-Bgh8CpNK.js} +2 -2
  182. package/dist/{summary-report-BXeQ5Ues.js.map → summary-report-Bgh8CpNK.js.map} +1 -1
  183. package/dist/{summary-report-CC07PhEL.d.ts → summary-report-DRstQNBX.d.ts} +3 -3
  184. package/dist/{summary-report-CC07PhEL.d.ts.map → summary-report-DRstQNBX.d.ts.map} +1 -1
  185. package/dist/{task-failure-attributes-DTl-7-Kw.js → task-failure-attributes-CBGtLS_H.js} +3 -3
  186. package/dist/{task-failure-attributes-DTl-7-Kw.js.map → task-failure-attributes-CBGtLS_H.js.map} +1 -1
  187. package/dist/{tool-groups-Ci8i9ErB.d.ts → tool-groups-RGYfVWpc.d.ts} +3 -3
  188. package/dist/tool-groups-RGYfVWpc.d.ts.map +1 -0
  189. package/dist/{tool-waste-CKc7bYIg.d.ts → tool-waste-BrmLKxMw.d.ts} +4 -4
  190. package/dist/{tool-waste-CKc7bYIg.d.ts.map → tool-waste-BrmLKxMw.d.ts.map} +1 -1
  191. package/dist/{tool-waste-8BQiUc8K.js → tool-waste-CwGHzBzX.js} +2 -2
  192. package/dist/{tool-waste-8BQiUc8K.js.map → tool-waste-CwGHzBzX.js.map} +1 -1
  193. package/dist/trace-repair/index.d.ts +3 -3
  194. package/dist/trace-repair/index.d.ts.map +1 -1
  195. package/dist/trace-repair/index.js +4 -3
  196. package/dist/trace-repair/index.js.map +1 -1
  197. package/dist/traces.d.ts +59 -61
  198. package/dist/traces.d.ts.map +1 -1
  199. package/dist/traces.js +7 -7
  200. package/dist/{trajectory-Bi157Gun.d.ts → trajectory-r1bQqvBQ.d.ts} +3 -3
  201. package/dist/{trajectory-Bi157Gun.d.ts.map → trajectory-r1bQqvBQ.d.ts.map} +1 -1
  202. package/dist/trajectory-replay/index.d.ts +3 -3
  203. package/dist/trajectory-replay/index.js +1 -1
  204. package/dist/{types-BPb2Kf_C.d.ts → types-CMyW4GnH.d.ts} +3 -3
  205. package/dist/{types-BPb2Kf_C.d.ts.map → types-CMyW4GnH.d.ts.map} +1 -1
  206. package/dist/{types-BI4fT3HN.js → types-CiWITkGo.js} +11 -2
  207. package/dist/types-CiWITkGo.js.map +1 -0
  208. package/dist/{types-D9ssmxKL.d.ts → types-DMoNFDWi.d.ts} +6 -3
  209. package/dist/{types-D9ssmxKL.d.ts.map → types-DMoNFDWi.d.ts.map} +1 -1
  210. package/dist/{types-D4s7Z6nq.d.ts → types-JHMOqZI4.d.ts} +13 -3
  211. package/dist/types-JHMOqZI4.d.ts.map +1 -0
  212. package/dist/{verdict-B0xltqu6.js → verdict-BQ3pCFf8.js} +2 -2
  213. package/dist/{verdict-B0xltqu6.js.map → verdict-BQ3pCFf8.js.map} +1 -1
  214. package/dist/{verdict-cache-CdVVTVmn.js → verdict-cache-B3eCVQtY.js} +2 -2
  215. package/dist/{verdict-cache-CdVVTVmn.js.map → verdict-cache-B3eCVQtY.js.map} +1 -1
  216. package/dist/wire/index.d.ts +26 -11
  217. package/dist/wire/index.d.ts.map +1 -1
  218. package/dist/wire/index.js +2 -2
  219. package/docs/campaign-proposers.md +4 -0
  220. package/docs/code-agent-intake.md +64 -0
  221. package/docs/concepts.md +1 -1
  222. package/docs/design/statistics-decisions.md +1 -1
  223. package/docs/distributed-driver.md +3 -6
  224. package/docs/public-api.md +122 -106
  225. package/docs/wire-protocol.md +5 -3
  226. package/package.json +27 -19
  227. package/dist/benchmark-BhT16ep9.js.map +0 -1
  228. package/dist/benchmark-command-CF-4GEWZ.js.map +0 -1
  229. package/dist/campaign-DQZmc2Dq.js.map +0 -1
  230. package/dist/capture-fetch-CqwsJkkG.d.ts +0 -68
  231. package/dist/capture-fetch-CqwsJkkG.d.ts.map +0 -1
  232. package/dist/contract/index.d.ts.map +0 -1
  233. package/dist/dspy-rlm-engine-DhA9qKIm.js.map +0 -1
  234. package/dist/external-optimizer-process-BFmh36vW.js.map +0 -1
  235. package/dist/external-optimizer-subprocess-CqLMW3nh.js.map +0 -1
  236. package/dist/index-CGtH1piv.d.ts.map +0 -1
  237. package/dist/index-D-V8gCs_.d.ts.map +0 -1
  238. package/dist/index-vrJugRal.d.ts +0 -1
  239. package/dist/kind-factory-DY8FdoXf.js.map +0 -1
  240. package/dist/llm-judge-Du7WQPh7.js.map +0 -1
  241. package/dist/pareto-BqNW3LJR.d.ts.map +0 -1
  242. package/dist/run-score-lDzV0X8j.js.map +0 -1
  243. package/dist/server-BjYiJHoJ.js.map +0 -1
  244. package/dist/skillopt-optimization-method-x7TTF23P.d.ts.map +0 -1
  245. package/dist/store-tool-spans-DPUG7UUY.d.ts.map +0 -1
  246. package/dist/tool-groups-Ci8i9ErB.d.ts.map +0 -1
  247. package/dist/transient-failure-DKF5Mofa.d.ts.map +0 -1
  248. package/dist/types-BI4fT3HN.js.map +0 -1
  249. package/dist/types-D4s7Z6nq.d.ts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"chat-client-DlMlAeYI.js","names":["ANALYST_ID","ACTOR_PROMPT","ACTOR_PROMPT","ACTOR_PROMPT","ACTOR_PROMPT"],"sources":["../src/feedback-trajectory-review.ts","../src/trace-analyst/behavioral-metrics.ts","../src/analyst/behavioral-analyst.ts","../src/analyst/kinds/control-integrity.ts","../src/analyst/kinds/failure-mode.ts","../src/analyst/kinds/improvement.ts","../src/analyst/kinds/intent-divergence.ts","../src/analyst/kinds/knowledge-gap.ts","../src/analyst/kinds/knowledge-poisoning.ts","../src/analyst/kinds/index.ts","../src/analyst/registry.ts","../src/analyst/default-registry.ts","../src/analyst/chat-client.ts"],"sourcesContent":["import { type ExactAnalystRunResult, snapshotExactExecutionPlan } from './analyst/exact-types'\nimport type {\n AnalystFinding,\n AnalystRunResult,\n AnalystUsageReceipt,\n EvidenceRef,\n} from './analyst/types'\nimport { assertValidAnalystUsageReceipt } from './analyst/usage-receipt'\nimport type { FeedbackLabelSource, FeedbackTrajectory } from './feedback-trajectory'\nimport { canonicalString, hashCanonical } from './ledger-core/canonical'\nimport { deepFreezeCanonicalJson } from './ledger-core/deep-freeze'\n\nexport type AnalystReviewSource = Exclude<FeedbackLabelSource, 'system'>\nexport type AnalystFindingDigest = `sha256:${string}`\nexport type AnalystRunDigest = `sha256:${string}`\n\nexport interface AnalystMissedIssue {\n id: string\n reason: string\n evidence?: EvidenceRef[]\n}\n\ninterface AnalystReviewDecisionBase {\n runDigest: AnalystRunDigest\n source: AnalystReviewSource\n reviewerId: string\n reviewId: string\n reason: string\n decidedAt: string\n}\n\nexport type AnalystReviewDecision =\n | (AnalystReviewDecisionBase & {\n findingId: string\n findingDigest: AnalystFindingDigest\n verdict: 'confirmed' | 'rejected'\n missedIssues?: never\n })\n | (AnalystReviewDecisionBase & {\n verdict: 'completeness_assessed'\n missedIssues: AnalystMissedIssue[]\n findingId?: never\n findingDigest?: never\n })\n\nexport interface AnalystReviewCounts {\n emitted: number\n confirmed: number\n rejected: number\n missed: number\n}\n\nexport interface AnalystReviewQuality {\n precision: number\n recall: number\n f1: number\n counts: AnalystReviewCounts\n}\n\nexport interface StoredAnalystReview {\n runId: string\n runDigest: AnalystRunDigest\n findings: AnalystFinding[]\n findingIds: string[]\n analystIds: string[]\n reviewDecisions: AnalystReviewDecision[]\n}\n\n/** Bind an analyst finding's complete canonical JSON content to a stable digest. */\nexport function analystFindingDigest(finding: AnalystFinding): AnalystFindingDigest {\n return hashCanonical(snapshotAnalystFinding(finding, 'analyst finding'))\n}\n\n/** Bind the complete analyst result to one immutable review target. */\nexport function analystRunDigest(run: AnalystRunResult): AnalystRunDigest {\n return hashCanonical(snapshotAnalystRun(run, 'analyst run'))\n}\n\nexport function snapshotAnalystRun(value: unknown, context = 'analyst run'): AnalystRunResult {\n const snapshot = snapshotAnalystRunRecord(value, context)\n if (snapshot.execution_plan !== undefined) {\n return sealExactAnalystRunReceipt(snapshot, context)\n }\n if (snapshot.completion !== undefined) {\n throw new TypeError(`${context} completion is valid only for an exact run`)\n }\n return snapshot as unknown as AnalystRunResult\n}\n\n/** Canonicalize, validate, and deeply freeze one complete or failed exact-run receipt. */\nexport function snapshotExactAnalystRunReceipt(\n value: unknown,\n context = 'exact analyst run receipt',\n): ExactAnalystRunResult {\n return sealExactAnalystRunReceipt(snapshotAnalystRunRecord(value, context), context)\n}\n\nfunction snapshotAnalystRunRecord(value: unknown, context: string): Record<string, unknown> {\n let snapshot: unknown\n try {\n snapshot = JSON.parse(canonicalString(value)) as unknown\n } catch (cause) {\n throw new TypeError(`${context} must have a canonical JSON representation`, { cause })\n }\n if (!isRecord(snapshot)) throw new TypeError(`${context} must be an object`)\n assertOnlyKeys(\n snapshot,\n [\n 'run_id',\n 'correlation_id',\n 'started_at',\n 'ended_at',\n 'findings',\n 'per_analyst',\n 'total_cost_usd',\n 'total_cost_provenance',\n 'execution_plan',\n 'completion',\n ],\n context,\n )\n requiredString(snapshot.run_id, `${context} run_id`)\n requiredString(snapshot.correlation_id, `${context} correlation_id`)\n canonicalTimestamp(snapshot.started_at, `${context} started_at`)\n canonicalTimestamp(snapshot.ended_at, `${context} ended_at`)\n snapshot.findings = snapshotAnalystFindings(snapshot.findings, `${context} findings`)\n if (!Array.isArray(snapshot.per_analyst)) {\n throw new TypeError(`${context} per_analyst must be an array`)\n }\n for (const [index, summary] of snapshot.per_analyst.entries()) {\n assertAnalystRunSummary(summary, `${context} per_analyst ${index}`)\n }\n if (\n typeof snapshot.total_cost_usd !== 'number' ||\n !Number.isFinite(snapshot.total_cost_usd) ||\n snapshot.total_cost_usd < 0\n ) {\n throw new TypeError(`${context} total_cost_usd must be a finite non-negative number`)\n }\n if (snapshot.total_cost_provenance !== undefined) {\n assertCostProvenance(snapshot.total_cost_provenance, `${context} total_cost_provenance`)\n }\n return snapshot\n}\n\nfunction assertAnalystRunSummary(value: unknown, context: string): void {\n if (!isRecord(value)) throw new TypeError(`${context} must be an object`)\n assertOnlyKeys(\n value,\n [\n 'analyst_id',\n 'status',\n 'reason',\n 'findings_count',\n 'latency_ms',\n 'usage',\n 'allocated_budget_usd',\n 'error',\n ],\n context,\n )\n requiredString(value.analyst_id, `${context} analyst_id`)\n if (value.status !== 'ok' && value.status !== 'skipped' && value.status !== 'failed') {\n throw new TypeError(`${context} status is invalid`)\n }\n if (value.reason !== undefined) requiredString(value.reason, `${context} reason`)\n if (value.status === 'skipped' && value.reason === undefined) {\n throw new TypeError(`${context} skipped summary requires reason`)\n }\n nonnegativeSafeInteger(value.findings_count, `${context} findings_count`)\n finiteNonnegative(value.latency_ms, `${context} latency_ms`)\n assertAnalystUsageReceipt(value.usage, `${context} usage`)\n if (value.allocated_budget_usd !== undefined && value.allocated_budget_usd !== null) {\n finiteNonnegative(value.allocated_budget_usd, `${context} allocated_budget_usd`)\n }\n if (value.error !== undefined) {\n if (value.status !== 'failed' || !isRecord(value.error)) {\n throw new TypeError(`${context} error is valid only for failed summaries`)\n }\n assertOnlyKeys(value.error, ['class', 'message'], `${context} error`)\n requiredString(value.error.class, `${context} error class`)\n requiredString(value.error.message, `${context} error message`)\n } else if (value.status === 'failed') {\n throw new TypeError(`${context} failed summary requires error`)\n }\n}\n\nfunction assertAnalystUsageReceipt(value: unknown, context: string): void {\n if (!isRecord(value)) throw new TypeError(`${context} must be an object`)\n assertOnlyKeys(value, ['calls', 'tokens', 'cost', 'knownCostUsd'], context)\n for (const field of ['calls', 'tokens', 'cost'] as const) {\n if (!Object.hasOwn(value, field)) {\n throw new TypeError(`${context} ${field} is required`)\n }\n }\n if (value.tokens !== null) {\n if (!isRecord(value.tokens)) throw new TypeError(`${context} tokens must be an object or null`)\n assertOnlyKeys(\n value.tokens,\n ['input', 'output', 'reasoning', 'cached', 'cacheWrite'],\n `${context} tokens`,\n )\n }\n assertCostProvenance(value.cost, `${context} cost`)\n assertValidAnalystUsageReceipt(value as unknown as AnalystUsageReceipt, context)\n}\n\nfunction assertCostProvenance(value: unknown, context: string): void {\n if (!isRecord(value)) throw new TypeError(`${context} must be an object`)\n assertOnlyKeys(value, ['kind', 'usd'], context)\n if (value.kind === 'uncaptured') {\n if (value.usd !== null) throw new TypeError(`${context} uncaptured usd must be null`)\n return\n }\n if (value.kind !== 'observed' && value.kind !== 'estimated') {\n throw new TypeError(`${context} kind is invalid`)\n }\n finiteNonnegative(value.usd, `${context} usd`)\n}\n\nfunction sealExactAnalystRunReceipt(\n run: Record<string, unknown>,\n context: string,\n): ExactAnalystRunResult {\n if (run.execution_plan === undefined) {\n throw new TypeError(`${context} exact run requires execution_plan`)\n }\n const plan = snapshotExactExecutionPlan(run.execution_plan, `${context} execution_plan`)\n const completion = snapshotExactRunCompletion(run.completion, `${context} completion`)\n run.execution_plan = plan\n run.completion = completion\n const summaries = run.per_analyst as Array<{\n analyst_id: string\n status: 'ok' | 'skipped' | 'failed'\n findings_count: number\n usage: { cost: { kind: string; usd: number | null }; knownCostUsd?: number }\n allocated_budget_usd?: number | null\n }>\n const findings = run.findings as AnalystFinding[]\n const planned = plan.analysts.map((analyst) => analyst.id)\n const completed = summaries.map((summary) => summary.analyst_id)\n const ordered = completed.every((analystId, index) => analystId === planned[index])\n if (!ordered || (completion.status === 'complete' && completed.length !== planned.length)) {\n throw new TypeError(\n completion.status === 'complete'\n ? `${context} complete receipt must contain every execution_plan analyst in exact order`\n : `${context} failed receipt per_analyst must be an execution_plan prefix`,\n )\n }\n const completedIds = new Set(completed)\n for (const finding of findings) {\n if (!completedIds.has(finding.analyst_id)) {\n throw new TypeError(`${context} finding names an analyst absent from per_analyst`)\n }\n }\n for (const summary of summaries) {\n const actual = findings.filter((finding) => finding.analyst_id === summary.analyst_id).length\n if (summary.findings_count !== actual) {\n throw new TypeError(\n `${context} findings_count does not match findings for \"${summary.analyst_id}\"`,\n )\n }\n const hasAllocation = Object.hasOwn(summary, 'allocated_budget_usd')\n if (summary.status === 'skipped') {\n if (hasAllocation) {\n throw new TypeError(\n `${context} skipped summary \"${summary.analyst_id}\" cannot report an allocated budget`,\n )\n }\n continue\n }\n const allocation = summary.allocated_budget_usd\n const validAllocation =\n hasAllocation &&\n (plan.policy.budget.kind === 'none'\n ? allocation === null\n : typeof allocation === 'number' &&\n plan.policy.budget.allocations_usd[summary.analyst_id] !== null &&\n plan.policy.budget.allocations_usd[summary.analyst_id] !== undefined &&\n allocation <= plan.policy.budget.allocations_usd[summary.analyst_id]!)\n if (!validAllocation) {\n throw new TypeError(\n `${context} summary \"${summary.analyst_id}\" allocation does not match its execution plan`,\n )\n }\n }\n let knownCost = 0\n for (const summary of summaries) {\n const amount =\n summary.usage.cost.kind === 'uncaptured'\n ? (summary.usage.knownCostUsd ?? 0)\n : (summary.usage.cost.usd ?? 0)\n knownCost = finiteNonnegative(knownCost + amount, `${context} aggregate known cost`)\n }\n if (run.total_cost_usd !== knownCost) {\n throw new TypeError(`${context} total_cost_usd does not match per_analyst usage`)\n }\n if (run.total_cost_provenance === undefined) {\n throw new TypeError(`${context} exact run requires total_cost_provenance`)\n }\n const costs = summaries.map((summary) => summary.usage.cost)\n const expectedProvenance = costs.some((cost) => cost.kind === 'uncaptured')\n ? { kind: 'uncaptured', usd: null }\n : {\n kind: costs.some((cost) => cost.kind === 'estimated') ? 'estimated' : 'observed',\n usd: costs.reduce(\n (sum, cost) =>\n finiteNonnegative(sum + (cost.usd ?? 0), `${context} aggregate captured cost`),\n 0,\n ),\n }\n if (hashCanonical(run.total_cost_provenance) !== hashCanonical(expectedProvenance)) {\n throw new TypeError(`${context} total_cost_provenance does not match per_analyst usage`)\n }\n return deepFreezeCanonicalJson(run as unknown as ExactAnalystRunResult)\n}\n\nfunction snapshotExactRunCompletion(\n value: unknown,\n context: string,\n): ExactAnalystRunResult['completion'] {\n if (!isRecord(value)) throw new TypeError(`${context} must be an object`)\n if (value.status === 'complete') {\n assertOnlyKeys(value, ['status'], context)\n return value as ExactAnalystRunResult['completion']\n }\n if (value.status !== 'failed') {\n throw new TypeError(`${context} status must be complete or failed`)\n }\n assertOnlyKeys(value, ['status', 'error'], context)\n if (!isRecord(value.error)) throw new TypeError(`${context} failed receipt requires error`)\n assertOnlyKeys(value.error, ['class', 'message'], `${context} error`)\n requiredString(value.error.class, `${context} error class`)\n requiredString(value.error.message, `${context} error message`)\n return value as unknown as ExactAnalystRunResult['completion']\n}\n\nfunction finiteNonnegative(value: unknown, context: string): number {\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {\n throw new TypeError(`${context} must be a non-negative finite number`)\n }\n return value\n}\n\nfunction nonnegativeSafeInteger(value: unknown, context: string): number {\n if (!Number.isSafeInteger(value) || (value as number) < 0) {\n throw new TypeError(`${context} must be a non-negative safe integer`)\n }\n return value as number\n}\n\nexport function snapshotAnalystFindings(\n value: unknown,\n context = 'analyst run findings',\n): AnalystFinding[] {\n if (!Array.isArray(value)) {\n throw new TypeError(`${context} must be an array`)\n }\n const findings = value.map((finding, index) =>\n snapshotAnalystFinding(finding, `${context} finding ${index}`),\n )\n assertUniqueFindingIds(findings.map((finding) => finding.finding_id))\n return findings\n}\n\nexport function readAnalystReview(trajectory: FeedbackTrajectory): StoredAnalystReview | undefined {\n const analystAttempts = trajectory.attempts.filter(\n (attempt) => isRecord(attempt.artifact) && attempt.artifact.type === 'analyst-run',\n )\n const analysis = isRecord(trajectory.metadata?.analysis)\n ? trajectory.metadata.analysis\n : undefined\n if (analystAttempts.length === 0) {\n if (analysis?.kind === 'analyst-run') {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: analyst trajectory \"${trajectory.id}\" is missing its archived run`,\n )\n }\n return undefined\n }\n if (analystAttempts.length !== 1) {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: analyst trajectory \"${trajectory.id}\" must contain exactly one archived run`,\n )\n }\n if (analysis?.kind !== 'analyst-run') {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: analyst trajectory \"${trajectory.id}\" is missing review state`,\n )\n }\n\n const artifact = analystAttempts[0]!.artifact\n if (!isRecord(artifact)) {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: analyst trajectory \"${trajectory.id}\" has an invalid archived run`,\n )\n }\n const runId = requiredString(\n artifact.analystRunId,\n `analyst trajectory \"${trajectory.id}\" run id`,\n )\n if (analysis.runId !== runId) {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: analyst trajectory \"${trajectory.id}\" run identity does not match its review state`,\n )\n }\n const artifactRunDigest = requiredDigest(\n artifact.runDigest,\n `analyst trajectory \"${trajectory.id}\" archived run digest`,\n )\n const storedRunDigest = requiredDigest(\n analysis.runDigest,\n `analyst trajectory \"${trajectory.id}\" review run digest`,\n )\n if (artifactRunDigest !== storedRunDigest) {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: analyst trajectory \"${trajectory.id}\" run digest does not match its review state`,\n )\n }\n const findings = snapshotAnalystFindings(\n artifact.findings,\n `analyst trajectory \"${trajectory.id}\"`,\n )\n const findingIds = findings.map((finding) => finding.finding_id)\n const analystIds = stringArray(\n artifact.analystIds,\n `analyst trajectory \"${trajectory.id}\" analyst ids`,\n )\n const attemptMetadata = analystAttempts[0]!.metadata\n if (!isRecord(attemptMetadata)) {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: analyst trajectory \"${trajectory.id}\" is missing archived run metadata`,\n )\n }\n const archivedRun = snapshotAnalystRun(\n {\n run_id: runId,\n correlation_id: artifact.correlationId,\n started_at: analysis.startedAt,\n ended_at: analysis.endedAt,\n findings,\n per_analyst: attemptMetadata.perAnalyst,\n total_cost_usd: analysis.knownCostUsd,\n ...(analysis.costProvenance === undefined\n ? {}\n : { total_cost_provenance: analysis.costProvenance }),\n ...(artifact.executionPlan === undefined\n ? {}\n : {\n execution_plan: artifact.executionPlan,\n completion: artifact.completion,\n }),\n },\n `analyst trajectory \"${trajectory.id}\" archived run`,\n )\n const knownAnalystIds = new Set(analystIds)\n for (const [index, finding] of findings.entries()) {\n if (!knownAnalystIds.has(finding.analyst_id)) {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: analyst trajectory \"${trajectory.id}\" omits generating analyst \"${finding.analyst_id}\" at finding ${index}`,\n )\n }\n }\n const reviewDecisions = validateAnalystReviewDecisions({\n runId,\n runDigest: storedRunDigest,\n findings,\n analystIds,\n decisions: analysis.reviewDecisions,\n requireComplete: true,\n })\n const expectedRunDigest = analystRunDigest(archivedRun)\n if (storedRunDigest !== expectedRunDigest) {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: analyst trajectory \"${trajectory.id}\" archived run digest mismatch`,\n )\n }\n return {\n runId,\n runDigest: expectedRunDigest,\n findings,\n findingIds,\n analystIds,\n reviewDecisions,\n }\n}\n\nexport function completedAnalystReviewQuality(review: StoredAnalystReview): AnalystReviewQuality {\n const findingDecisions = review.reviewDecisions.filter(\n (decision): decision is Extract<AnalystReviewDecision, { verdict: 'confirmed' | 'rejected' }> =>\n decision.verdict !== 'completeness_assessed',\n )\n const completeness = review.reviewDecisions.filter(\n (decision): decision is Extract<AnalystReviewDecision, { verdict: 'completeness_assessed' }> =>\n decision.verdict === 'completeness_assessed',\n )\n if (completeness.length !== 1) {\n throw new TypeError(\n 'feedbackTrajectoryToOptimizerRow: analyst run requires exactly one independent completeness_assessed decision',\n )\n }\n\n const confirmed = findingDecisions.filter((decision) => decision.verdict === 'confirmed').length\n const rejected = findingDecisions.length - confirmed\n const emitted = review.findingIds.length\n const missed = completeness[0]!.missedIssues.length\n const precision = emitted === 0 ? 1 : confirmed / emitted\n const recallDenominator = confirmed + missed\n const recall = recallDenominator === 0 ? 1 : confirmed / recallDenominator\n const f1 = precision + recall === 0 ? 0 : (2 * precision * recall) / (precision + recall)\n return {\n precision,\n recall,\n f1,\n counts: { emitted, confirmed, rejected, missed },\n }\n}\n\nexport function validateAnalystReviewDecisions(input: {\n runId: string\n runDigest: AnalystRunDigest\n findings: readonly AnalystFinding[]\n analystIds: readonly string[]\n decisions: unknown\n requireComplete?: boolean\n}): AnalystReviewDecision[] {\n if (!Array.isArray(input.decisions)) {\n throw new TypeError('analyst review decisions must be an array')\n }\n const findings = snapshotAnalystFindings(input.findings)\n const expectedRunDigest = requiredDigest(input.runDigest, 'analyst review run digest')\n const findingsById = new Map(findings.map((finding) => [finding.finding_id, finding]))\n const generatingAnalystIds = new Set(input.analystIds)\n const seenFindingIds = new Set<string>()\n let completenessCount = 0\n\n const decisions = input.decisions.map((value, index): AnalystReviewDecision => {\n if (!isRecord(value)) {\n throw new TypeError(`analyst review decision ${index} must be an object`)\n }\n const source = requiredString(value.source, `analyst review decision ${index} source`)\n if (!isAnalystReviewSource(source)) {\n throw new TypeError(\n `analyst review decision ${index} source must be user, judge, environment, metric, or policy`,\n )\n }\n const reviewerId = requiredString(\n value.reviewerId,\n `analyst review decision ${index} reviewerId`,\n )\n if (generatingAnalystIds.has(reviewerId)) {\n throw new TypeError(\n `analyst review decision ${index} reviewerId must differ from the generating analyst`,\n )\n }\n const reviewId = requiredString(value.reviewId, `analyst review decision ${index} reviewId`)\n if (reviewId === input.runId) {\n throw new TypeError(\n `analyst review decision ${index} reviewId must identify an independent review`,\n )\n }\n const reason = requiredString(value.reason, `analyst review decision ${index} reason`)\n const decidedAt = canonicalTimestamp(\n value.decidedAt,\n `analyst review decision ${index} decidedAt`,\n )\n const runDigest = requiredDigest(value.runDigest, `analyst review decision ${index} runDigest`)\n if (runDigest !== expectedRunDigest) {\n throw new TypeError(`analyst review decision ${index} run digest mismatch`)\n }\n\n if (value.verdict === 'completeness_assessed') {\n assertOnlyKeys(\n value,\n [\n 'runDigest',\n 'verdict',\n 'missedIssues',\n 'source',\n 'reviewerId',\n 'reviewId',\n 'reason',\n 'decidedAt',\n ],\n `analyst review decision ${index}`,\n )\n completenessCount += 1\n if (completenessCount > 1) {\n throw new TypeError('duplicate completeness_assessed analyst review decision')\n }\n return {\n runDigest,\n verdict: 'completeness_assessed',\n missedIssues: validateMissedIssues(\n value.missedIssues,\n findingsById,\n `analyst review decision ${index}`,\n ),\n source,\n reviewerId,\n reviewId,\n reason,\n decidedAt,\n }\n }\n\n if (value.verdict !== 'confirmed' && value.verdict !== 'rejected') {\n throw new TypeError(\n `analyst review decision ${index} verdict must be confirmed, rejected, or completeness_assessed`,\n )\n }\n assertOnlyKeys(\n value,\n [\n 'runDigest',\n 'findingId',\n 'findingDigest',\n 'verdict',\n 'source',\n 'reviewerId',\n 'reviewId',\n 'reason',\n 'decidedAt',\n ],\n `analyst review decision ${index}`,\n )\n const findingId = requiredString(value.findingId, `analyst review decision ${index} findingId`)\n const finding = findingsById.get(findingId)\n if (!finding) {\n throw new TypeError(`analyst review decision references unknown finding id \"${findingId}\"`)\n }\n if (seenFindingIds.has(findingId)) {\n throw new TypeError(`duplicate analyst review decision for finding id \"${findingId}\"`)\n }\n seenFindingIds.add(findingId)\n const findingDigest = requiredString(\n value.findingDigest,\n `analyst review decision ${index} findingDigest`,\n )\n const expectedDigest = analystFindingDigest(finding)\n if (findingDigest !== expectedDigest) {\n throw new TypeError(\n `analyst review decision ${index} digest mismatch for finding id \"${findingId}\"`,\n )\n }\n return {\n runDigest,\n findingId,\n findingDigest: expectedDigest,\n verdict: value.verdict,\n source,\n reviewerId,\n reviewId,\n reason,\n decidedAt,\n }\n })\n\n if (input.requireComplete) {\n const missing = findings\n .map((finding) => finding.finding_id)\n .filter((findingId) => !seenFindingIds.has(findingId))\n if (missing.length > 0) {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: missing independent decisions for finding ids: ${missing.join(', ')}`,\n )\n }\n if (completenessCount !== 1) {\n throw new TypeError(\n 'feedbackTrajectoryToOptimizerRow: analyst run requires exactly one independent completeness_assessed decision',\n )\n }\n }\n return decisions\n}\n\nexport function assertUniqueFindingIds(findingIds: readonly string[]): void {\n const seen = new Set<string>()\n for (const findingId of findingIds) {\n if (findingId.trim().length === 0) throw new TypeError('analyst finding id must not be empty')\n if (seen.has(findingId)) {\n throw new TypeError(`analyst run contains duplicate finding id \"${findingId}\"`)\n }\n seen.add(findingId)\n }\n}\n\nfunction snapshotAnalystFinding(value: unknown, context: string): AnalystFinding {\n let snapshot: unknown\n try {\n snapshot = JSON.parse(canonicalString(value)) as unknown\n } catch (cause) {\n throw new TypeError(`${context} must have a canonical JSON representation`, { cause })\n }\n assertAnalystFinding(snapshot, context)\n return snapshot\n}\n\nfunction assertAnalystFinding(value: unknown, context: string): asserts value is AnalystFinding {\n if (!isRecord(value)) throw new TypeError(`${context} must be an object`)\n assertOnlyKeys(\n value,\n [\n 'schema_version',\n 'finding_id',\n 'analyst_id',\n 'produced_at',\n 'severity',\n 'area',\n 'claim',\n 'rationale',\n 'evidence_refs',\n 'recommended_action',\n 'validation_plan',\n 'confidence',\n 'subject',\n 'derived_from_judge',\n 'metadata',\n ],\n context,\n )\n if (value.schema_version !== '1.0.0') {\n throw new TypeError(`${context} schema_version must be \"1.0.0\"`)\n }\n requiredString(value.finding_id, `${context} finding_id`)\n requiredString(value.analyst_id, `${context} analyst_id`)\n canonicalTimestamp(value.produced_at, `${context} produced_at`)\n if (\n value.severity !== 'critical' &&\n value.severity !== 'high' &&\n value.severity !== 'medium' &&\n value.severity !== 'low' &&\n value.severity !== 'info'\n ) {\n throw new TypeError(`${context} severity is invalid`)\n }\n requiredString(value.area, `${context} area`)\n requiredString(value.claim, `${context} claim`)\n optionalString(value.rationale, `${context} rationale`)\n value.evidence_refs = validateEvidenceRefs(value.evidence_refs, `${context} evidence_refs`)\n optionalString(value.recommended_action, `${context} recommended_action`)\n optionalString(value.validation_plan, `${context} validation_plan`)\n if (\n typeof value.confidence !== 'number' ||\n !Number.isFinite(value.confidence) ||\n value.confidence < 0 ||\n value.confidence > 1\n ) {\n throw new TypeError(`${context} confidence must be a finite number from 0 through 1`)\n }\n optionalString(value.subject, `${context} subject`)\n if (value.derived_from_judge !== undefined && typeof value.derived_from_judge !== 'boolean') {\n throw new TypeError(`${context} derived_from_judge must be a boolean`)\n }\n if (value.metadata !== undefined && !isRecord(value.metadata)) {\n throw new TypeError(`${context} metadata must be an object`)\n }\n}\n\nfunction validateMissedIssues(\n value: unknown,\n findingsById: ReadonlyMap<string, AnalystFinding>,\n context: string,\n): AnalystMissedIssue[] {\n if (!Array.isArray(value)) {\n throw new TypeError(`${context} missedIssues must be an array`)\n }\n const seen = new Set<string>()\n return value.map((issue, index) => {\n const issueContext = `${context} missedIssues ${index}`\n if (!isRecord(issue)) throw new TypeError(`${issueContext} must be an object`)\n assertOnlyKeys(issue, ['id', 'reason', 'evidence'], issueContext)\n const id = requiredString(issue.id, `${issueContext} id`)\n if (findingsById.has(id)) {\n throw new TypeError(`${issueContext} id \"${id}\" is already an emitted finding id`)\n }\n if (seen.has(id)) {\n throw new TypeError(`duplicate missed issue id \"${id}\"`)\n }\n seen.add(id)\n const reason = requiredString(issue.reason, `${issueContext} reason`)\n return {\n id,\n reason,\n ...(issue.evidence === undefined\n ? {}\n : { evidence: validateEvidenceRefs(issue.evidence, `${issueContext} evidence`) }),\n }\n })\n}\n\nfunction validateEvidenceRefs(value: unknown, context: string): EvidenceRef[] {\n if (!Array.isArray(value)) throw new TypeError(`${context} must be an array`)\n return value.map((evidence, index) => {\n const evidenceContext = `${context} ${index}`\n if (!isRecord(evidence)) throw new TypeError(`${evidenceContext} must be an object`)\n assertOnlyKeys(evidence, ['kind', 'uri', 'excerpt'], evidenceContext)\n if (\n evidence.kind !== 'span' &&\n evidence.kind !== 'event' &&\n evidence.kind !== 'artifact' &&\n evidence.kind !== 'finding' &&\n evidence.kind !== 'metric'\n ) {\n throw new TypeError(`${evidenceContext} kind is invalid`)\n }\n const uri = requiredString(evidence.uri, `${evidenceContext} uri`)\n const excerpt = evidence.excerpt\n optionalString(excerpt, `${evidenceContext} excerpt`)\n return {\n kind: evidence.kind,\n uri,\n ...(excerpt === undefined ? {} : { excerpt: excerpt as string }),\n }\n })\n}\n\nfunction assertOnlyKeys(\n value: Record<string, unknown>,\n allowed: readonly string[],\n name: string,\n): void {\n const allowedKeys = new Set(allowed)\n const unexpected = Object.keys(value).filter((key) => !allowedKeys.has(key))\n if (unexpected.length > 0) {\n throw new TypeError(`${name} contains unknown fields: ${unexpected.sort().join(', ')}`)\n }\n}\n\nfunction stringArray(value: unknown, name: string): string[] {\n if (!Array.isArray(value) || value.some((item) => typeof item !== 'string')) {\n throw new TypeError(`${name} must be an array of strings`)\n }\n const strings = value.map((item) => requiredString(item, name))\n if (new Set(strings).size !== strings.length) {\n throw new TypeError(`${name} must contain unique values`)\n }\n return strings\n}\n\nfunction requiredString(value: unknown, name: string): string {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new TypeError(`${name} must be a non-empty string`)\n }\n return value\n}\n\nfunction requiredDigest(value: unknown, name: string): AnalystRunDigest {\n const digest = requiredString(value, name)\n if (!/^sha256:[a-f0-9]{64}$/.test(digest)) {\n throw new TypeError(`${name} must be a sha256 digest`)\n }\n return digest as AnalystRunDigest\n}\n\nfunction optionalString(value: unknown, name: string): void {\n if (value !== undefined && typeof value !== 'string') {\n throw new TypeError(`${name} must be a string`)\n }\n}\n\nfunction canonicalTimestamp(value: unknown, name: string): string {\n const timestamp = requiredString(value, name)\n const parsed = new Date(timestamp)\n if (Number.isNaN(parsed.valueOf()) || parsed.toISOString() !== timestamp) {\n throw new TypeError(`${name} must be a canonical ISO 8601 UTC timestamp`)\n }\n return timestamp\n}\n\nfunction isAnalystReviewSource(value: string): value is AnalystReviewSource {\n return (\n value === 'user' ||\n value === 'judge' ||\n value === 'environment' ||\n value === 'metric' ||\n value === 'policy'\n )\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n","/**\n * Deterministic behavioral metrics over OTLP spans — pure arithmetic, no LLM.\n *\n * It computes token growth, output decay, tool monoculture, and missing\n * self-verification once in TypeScript with no model judgment.\n *\n * General, not trace-specific: the detectors key off token trajectories and\n * tool usage present in any agentic OTLP trace, not any one benchmark.\n */\n\nimport { LLM_CONTEXT_TOKENS } from '../trace/attribute-vocabulary'\nimport { executionTrackByLane } from '../trace/execution-tracks'\nimport {\n LLM_INPUT_TOKEN_ATTR_KEYS,\n LLM_OUTPUT_TOKEN_ATTR_KEYS,\n TOOL_NAME_ATTR_KEYS,\n} from '../trace/otlp-attributes'\nimport { spanEpochMillis } from './otlp-span'\nimport type { TraceAnalystSpan } from './types'\n\nexport type SuboptimalCode =\n | 'monotonic-input-growth'\n | 'output-length-decay'\n | 'single-tool-dependency'\n | 'no-self-verification'\n\nexport interface SuboptimalSignal {\n code: SuboptimalCode\n severity: 'high' | 'medium' | 'low'\n /** Human-readable claim, with the backing numbers inlined. */\n detail: string\n /** The exact figures the detector fired on — auditable, no model in the loop. */\n evidence: Record<string, number | string | boolean>\n}\n\nexport interface BehavioralMetrics {\n /** The only trace represented by these metrics; null when spans are empty. */\n traceId: string | null\n llmCallCount: number\n /** Causally serial LLM timelines. Parallel branches are never joined. */\n tokenSequences: BehavioralTokenSequence[]\n /** Token values from the longest serial timeline, retained for convenience. */\n inputTokenTrajectory: number[]\n outputTokenTrajectory: number[]\n toolHistogram: Record<string, number>\n totalToolCalls: number\n distinctTools: number\n /** distinct/total tool calls; 1.0 when there are no tool calls. */\n toolDiversityRatio: number\n hasSelfVerification: boolean\n signals: SuboptimalSignal[]\n}\n\nexport interface BehavioralTokenSequence {\n scopeId: string\n spanIds: string[]\n inputTokenTrajectory: Array<number | null>\n outputTokenTrajectory: Array<number | null>\n}\n\ninterface TokenSample {\n span: TraceAnalystSpan\n input: number | null\n output: number | null\n step: number | null\n}\n\n/** ≥ this input-token growth ratio across a run, with no compression, fires. */\nconst INPUT_GROWTH_FACTOR = 3\n/** Tool-usage signals need at least this many calls to be meaningful. */\nconst MIN_TOOL_CALLS = 3\n/**\n * Serial calls required before a strictly-decreasing output run counts as decay.\n *\n * A run of n independent lengths is strictly decreasing by chance with\n * probability 1/n!, so the old minimum of 3 fired on roughly one sequence in\n * six. The paired `inputIsMonotonic && inputGrew` guard does not offset that:\n * context accumulates by construction in a serial agent loop, so input growth\n * is very nearly free evidence. At 5 calls chance alone accounts for under 1%,\n * which is the bar a signal reported at full confidence has to clear.\n */\nconst OUTPUT_DECAY_MINIMUM_CALLS = 5\n/**\n * The last output must fall to at most this fraction of the first.\n *\n * Length wanders between turns for reasons that are not degradation, so\n * direction alone is not a finding — an observed 784 → 646 run (18%) was\n * reported as decay and was noise. Requiring the response to lose most of its\n * length keeps the signal on the failure it names: late steps that quietly\n * stop doing the work.\n */\nconst OUTPUT_DECAY_MAXIMUM_RETAINED_FRACTION = 0.6\n/** Tool names that read or check state count as self-verification, not mutation.\n * Covers the inspect verbs plus the read/search tools real harnesses use to\n * verify (Claude Code Read/Grep/Glob, codex read_file/ls/cat, git status/diff,\n * test/lint). A pure shell tool (Bash/exec_command) is intentionally NOT matched\n * — its name can't tell a `pytest` from an `rm`. */\nconst VERIFY_RE =\n /verif|eval|inspect|check|assert|validat|review|confirm|read|grep|glob|search|view|\\blist\\b|\\bls\\b|\\bcat\\b|\\bfind\\b|diff|status|\\btest|lint|typecheck/i\n\nfunction num(v: unknown): number | null {\n return typeof v === 'number' && Number.isFinite(v) ? v : null\n}\nfunction numAttr(attrs: Record<string, unknown>, keys: readonly string[]): number | null {\n for (const key of keys) {\n const value = num(attrs[key])\n if (value !== null) return value\n }\n return null\n}\nfunction inputTokensOf(s: TraceAnalystSpan): number | null {\n const exactContext = num(s.attributes[LLM_CONTEXT_TOKENS])\n if (exactContext !== null) return exactContext\n // Foreign producers disagree on whether prompt includes cached tokens.\n // Without an exact total, retain the reported prompt instead of guessing.\n return (\n numAttr(s.attributes, LLM_INPUT_TOKEN_ATTR_KEYS) ?? num(s.attributes['llm.usage.input_tokens'])\n )\n}\nfunction outputTokensOf(s: TraceAnalystSpan): number | null {\n return (\n numAttr(s.attributes, LLM_OUTPUT_TOKEN_ATTR_KEYS) ??\n num(s.attributes['llm.usage.output_tokens'])\n )\n}\nfunction stepOf(s: TraceAnalystSpan): number | null {\n return num(s.attributes.step)\n}\nfunction toolNameOf(s: TraceAnalystSpan): string | null {\n if (s.tool_name) return s.tool_name\n for (const key of TOOL_NAME_ATTR_KEYS) {\n const t = s.attributes[key]\n if (typeof t === 'string' && t.length > 0) return t\n }\n return null\n}\n\n/**\n * Reduce a span list to behavioral metrics + fired suboptimality signals.\n * Pure + deterministic: same spans → same output, on any machine, no model.\n */\nexport function computeTraceMetrics(spans: readonly TraceAnalystSpan[]): BehavioralMetrics {\n const traceIds = new Set(spans.map((span) => span.trace_id))\n if (traceIds.size > 1) {\n throw new Error(\n `computeTraceMetrics: expected spans from one trace, received ${traceIds.size} traces`,\n )\n }\n const traceId = traceIds.values().next().value ?? null\n\n const samples: TokenSample[] = spans.map((span) => ({\n span,\n input: inputTokensOf(span),\n output: outputTokensOf(span),\n step: stepOf(span),\n }))\n const llmSamples = samples.filter((sample) => sample.span.kind === 'LLM')\n const tokenSamples =\n llmSamples.length > 0\n ? llmSamples\n : samples.filter((sample) => sample.input !== null || sample.output !== null)\n const tokenSequences = buildTokenSequences(tokenSamples, spans)\n const primarySequence = tokenSequences[0]\n const inputTokenTrajectory =\n primarySequence?.inputTokenTrajectory.filter((value): value is number => value !== null) ?? []\n const outputTokenTrajectory =\n primarySequence?.outputTokenTrajectory.filter((value): value is number => value !== null) ?? []\n const toolHistogram: Record<string, number> = {}\n let hasSelfVerification = false\n\n for (const s of spans) {\n const tool = toolNameOf(s)\n if (tool) {\n toolHistogram[tool] = (toolHistogram[tool] ?? 0) + 1\n if (VERIFY_RE.test(tool)) hasSelfVerification = true\n }\n }\n\n const totalToolCalls = Object.values(toolHistogram).reduce((a, b) => a + b, 0)\n const distinctTools = Object.keys(toolHistogram).length\n const toolDiversityRatio = totalToolCalls === 0 ? 1 : distinctTools / totalToolCalls\n\n const signals: SuboptimalSignal[] = []\n const seenTokenSignals = new Set<SuboptimalCode>()\n for (const sequence of tokenSequences) {\n for (const signal of tokenSignals(sequence)) {\n if (seenTokenSignals.has(signal.code)) continue\n seenTokenSignals.add(signal.code)\n signals.push(signal)\n }\n }\n\n if (totalToolCalls >= MIN_TOOL_CALLS && distinctTools === 1) {\n const only = Object.keys(toolHistogram)[0]!\n signals.push({\n code: 'single-tool-dependency',\n severity: 'medium',\n detail: `All ${totalToolCalls} observed tool calls are \\`${only}\\`; no alternate tool call was observed.`,\n evidence: { tool: only, calls: totalToolCalls, distinct_tools: 1 },\n })\n }\n\n if (totalToolCalls >= MIN_TOOL_CALLS && !hasSelfVerification) {\n signals.push({\n code: 'no-self-verification',\n severity: 'medium',\n detail: `${totalToolCalls} tool calls were observed without a verification-named tool call.`,\n evidence: { tool_calls: totalToolCalls, verification_calls: 0 },\n })\n }\n\n return {\n traceId,\n llmCallCount: tokenSamples.length,\n tokenSequences,\n inputTokenTrajectory,\n outputTokenTrajectory,\n toolHistogram,\n totalToolCalls,\n distinctTools,\n toolDiversityRatio,\n hasSelfVerification,\n signals,\n }\n}\n\nfunction buildTokenSequences(\n samples: readonly TokenSample[],\n spans: readonly TraceAnalystSpan[],\n): BehavioralTokenSequence[] {\n const spansById = new Map(spans.map((span) => [span.span_id, span]))\n const executionScopeFor = createTokenExecutionScopeResolver(spansById)\n const scopedSamples = samples.map((sample) => ({\n sample,\n ...executionScopeFor(sample.span),\n }))\n const trackByLane = executionTrackByLane(scopedSamples)\n const byTrack = new Map<string, { scopeId: string; samples: TokenSample[] }>()\n for (const scoped of scopedSamples) {\n const trackId = trackByLane.get(scoped.key)!\n const track = byTrack.get(trackId) ?? { scopeId: scoped.scopeId, samples: [] }\n track.samples.push(scoped.sample)\n byTrack.set(trackId, track)\n }\n\n const sequences: BehavioralTokenSequence[] = []\n for (const { scopeId, samples: tracked } of byTrack.values()) {\n const runs = serialTokenRuns([...tracked].sort(compareTokenSamples))\n runs.forEach((run, index) => {\n sequences.push({\n scopeId: runs.length === 1 ? scopeId : `${scopeId}#${index + 1}`,\n spanIds: run.map((sample) => sample.span.span_id),\n inputTokenTrajectory: run.map((sample) => sample.input),\n outputTokenTrajectory: run.map((sample) => sample.output),\n })\n })\n }\n\n return sequences.sort(\n (a, b) =>\n b.spanIds.length - a.spanIds.length ||\n a.scopeId.localeCompare(b.scopeId) ||\n a.spanIds[0]!.localeCompare(b.spanIds[0]!),\n )\n}\n\ninterface AncestorScope {\n agentId: string | null\n rootId: string | null\n missingParentId: string | null\n laneSpanId: string | null\n}\n\nfunction createTokenExecutionScopeResolver(spansById: ReadonlyMap<string, TraceAnalystSpan>): (\n span: TraceAnalystSpan,\n) => {\n key: string\n scopeKey: string\n scopeId: string\n start: number | null\n end: number | null\n} {\n const cache = new Map<string, AncestorScope>()\n return (span) => {\n const ancestry = resolveAncestorScope(span.parent_span_id, spansById, cache)\n const rootId = ancestry.rootId\n const scopeId = ancestry.agentId\n ? `span:${ancestry.agentId}`\n : ancestry.missingParentId\n ? `parent:${ancestry.missingParentId}`\n : rootId\n ? `root:${rootId}`\n : span.agent_name\n ? `agent:${span.agent_name}`\n : `trace:${span.trace_id}`\n const scopeSpanId = ancestry.agentId ?? ancestry.missingParentId ?? rootId\n const laneSpan = ancestry.laneSpanId ? spansById.get(ancestry.laneSpanId) : undefined\n const direct = scopeSpanId === null || ancestry.laneSpanId === scopeSpanId\n const timedSpan = direct ? span : laneSpan\n return {\n key: JSON.stringify([scopeId, direct ? span.span_id : ancestry.laneSpanId]),\n scopeKey: scopeId,\n scopeId,\n start: timedSpan ? spanEpochMillis(timedSpan.start_time) : null,\n end: timedSpan ? spanEpochMillis(timedSpan.end_time) : null,\n }\n }\n}\n\nfunction resolveAncestorScope(\n startId: string | null,\n spansById: ReadonlyMap<string, TraceAnalystSpan>,\n cache: Map<string, AncestorScope>,\n): AncestorScope {\n const empty: AncestorScope = {\n agentId: null,\n rootId: null,\n missingParentId: null,\n laneSpanId: null,\n }\n if (!startId) return empty\n\n const path: string[] = []\n const pathIndex = new Map<string, number>()\n let currentId: string | null = startId\n let resolved = empty\n while (currentId) {\n const cached = cache.get(currentId)\n if (cached) {\n resolved = cached\n break\n }\n const cycleStart = pathIndex.get(currentId)\n if (cycleStart !== undefined) {\n resolved = {\n agentId: null,\n rootId: [...path.slice(cycleStart)].sort()[0]!,\n missingParentId: null,\n laneSpanId: [...path.slice(cycleStart)].sort()[0]!,\n }\n break\n }\n const current = spansById.get(currentId)\n if (!current) {\n resolved = {\n agentId: null,\n rootId: null,\n missingParentId: currentId,\n laneSpanId: currentId,\n }\n break\n }\n if (current.kind === 'AGENT') {\n resolved = {\n agentId: current.span_id,\n rootId: null,\n missingParentId: null,\n laneSpanId: current.span_id,\n }\n break\n }\n pathIndex.set(currentId, path.length)\n path.push(currentId)\n currentId = current.parent_span_id\n }\n\n for (let index = path.length - 1; index >= 0; index -= 1) {\n if (resolved.agentId === null && resolved.rootId === null) {\n resolved = { ...resolved, rootId: path[index]!, laneSpanId: path[index]! }\n } else if (\n resolved.laneSpanId === (resolved.agentId ?? resolved.missingParentId ?? resolved.rootId)\n ) {\n resolved = { ...resolved, laneSpanId: path[index]! }\n }\n cache.set(path[index]!, resolved)\n }\n return resolved\n}\n\nfunction compareTokenSamples(a: TokenSample, b: TokenSample): number {\n const aStart = spanEpochMillis(a.span.start_time)\n const bStart = spanEpochMillis(b.span.start_time)\n if (aStart === null && bStart !== null) return 1\n if (aStart !== null && bStart === null) return -1\n if (aStart !== null && bStart !== null && aStart !== bStart) return aStart - bStart\n if (a.step !== null && b.step !== null && a.step !== b.step) return a.step - b.step\n return a.span.span_id.localeCompare(b.span.span_id)\n}\n\nfunction serialTokenRuns(ordered: readonly TokenSample[]): TokenSample[][] {\n const runs: TokenSample[][] = []\n let serial: TokenSample[] = []\n let overlap: TokenSample[] = []\n let overlapEnd = Number.NEGATIVE_INFINITY\n\n const flushSerial = () => {\n if (serial.length > 0) runs.push(serial)\n serial = []\n }\n const flushOverlap = () => {\n if (overlap.length === 1) {\n serial.push(overlap[0]!)\n } else if (overlap.length > 1) {\n flushSerial()\n for (const sample of overlap) runs.push([sample])\n }\n overlap = []\n overlapEnd = Number.NEGATIVE_INFINITY\n }\n\n for (const sample of ordered) {\n const start = spanEpochMillis(sample.span.start_time)\n const end = spanEpochMillis(sample.span.end_time)\n if (start === null || end === null || sample.span.duration_ms <= 0 || end < start) {\n flushOverlap()\n flushSerial()\n runs.push([sample])\n continue\n }\n if (overlap.length > 0 && start >= overlapEnd) flushOverlap()\n overlap.push(sample)\n overlapEnd = Math.max(overlapEnd, end)\n }\n flushOverlap()\n flushSerial()\n return runs\n}\n\nfunction tokenSignals(sequence: BehavioralTokenSequence): SuboptimalSignal[] {\n const signals: SuboptimalSignal[] = []\n const inputs = sequence.inputTokenTrajectory\n const outputs = sequence.outputTokenTrajectory\n if (inputs.length >= 3 && inputs.every((value): value is number => value !== null)) {\n const first = inputs[0]!\n const last = inputs[inputs.length - 1]!\n const isMonotonic = everyAdjacent(inputs, (previous, current) => current >= previous)\n const growthFromZero = first === 0 && last > 0\n const growth = growthFromZero ? Infinity : first > 0 ? last / first : 0\n if (isMonotonic && last > first && growth >= INPUT_GROWTH_FACTOR) {\n const growthLabel = growthFromZero ? '0→nonzero (unbounded)' : `${growth.toFixed(1)}x`\n signals.push({\n code: 'monotonic-input-growth',\n severity: 'high',\n detail: `LLM input tokens grew ${growthLabel} (${first}→${last}) across ${inputs.length} serial calls without an intervening decrease.`,\n evidence: {\n first,\n last,\n growth_x: growthFromZero ? 'unbounded' : Number(growth.toFixed(2)),\n calls: inputs.length,\n scope: sequence.scopeId,\n first_span_id: sequence.spanIds[0]!,\n last_span_id: sequence.spanIds[sequence.spanIds.length - 1]!,\n },\n })\n }\n }\n\n if (\n inputs.length >= OUTPUT_DECAY_MINIMUM_CALLS &&\n inputs.length === outputs.length &&\n inputs.every((value): value is number => value !== null) &&\n outputs.every((value): value is number => value !== null)\n ) {\n const first = outputs[0]!\n const last = outputs[outputs.length - 1]!\n const inputIsMonotonic = everyAdjacent(inputs, (previous, current) => current >= previous)\n const outputIsMonotonic = everyAdjacent(outputs, (previous, current) => current <= previous)\n const inputGrew = inputs[inputs.length - 1]! > inputs[0]!\n const decayIsMaterial = last <= first * OUTPUT_DECAY_MAXIMUM_RETAINED_FRACTION\n if (inputIsMonotonic && inputGrew && outputIsMonotonic && decayIsMaterial) {\n signals.push({\n code: 'output-length-decay',\n severity: 'medium',\n detail: `LLM output tokens shrank ${first}→${last} over ${outputs.length} serial calls while input tokens increased monotonically.`,\n evidence: {\n first,\n last,\n calls: outputs.length,\n scope: sequence.scopeId,\n first_span_id: sequence.spanIds[0]!,\n last_span_id: sequence.spanIds[sequence.spanIds.length - 1]!,\n },\n })\n }\n }\n return signals\n}\n\nfunction everyAdjacent(\n values: readonly number[],\n predicate: (previous: number, current: number) => boolean,\n): boolean {\n return values.slice(1).every((current, index) => predicate(values[index]!, current))\n}\n","/**\n * Deterministic behavioral analysis over arithmetic in trace spans.\n * This pass is cheap and repeatable; semantic analysis remains the job of\n * model-backed analysts. Relative quality requires a labeled comparison.\n */\n\nimport {\n type BehavioralMetrics,\n computeTraceMetrics,\n type SuboptimalCode,\n} from '../trace-analyst/behavioral-metrics'\nimport type { TraceAnalysisStore } from '../trace-analyst/store'\nimport type { ExactCapableAnalyst } from './exact-types'\nimport { type AnalystFinding, makeFinding } from './types'\n\nconst RECOMMENDED_ACTION: Record<SuboptimalCode, string> = {\n 'monotonic-input-growth':\n 'Inspect context assembly; if prior history is repeatedly included, summarize completed work before the next model call.',\n 'output-length-decay':\n 'Check late-step completeness; if shorter responses omit required work, add explicit completion criteria to the agent instructions.',\n 'single-tool-dependency':\n 'Test whether an inspect or verification tool improves outcomes after the repeated call fails or returns no progress.',\n 'no-self-verification':\n 'After state-changing actions, require an observable check before the agent proceeds.',\n}\n\nconst ANALYST_ID = 'efficiency-behavioral'\nconst DEFAULT_MAX_TRACES = 1_000\nconst DEFAULT_MAX_EVIDENCE_REFS = 20\nconst TRACE_PAGE_SIZE = 200\n\nexport interface BehavioralAnalystOptions {\n /** Refuse larger unfiltered datasets instead of sampling them silently. Default 1,000. */\n maxTraces?: number\n /** Evidence locations retained per finding. Counts still cover every analyzed trace. Default 20. */\n maxEvidenceRefsPerFinding?: number\n}\n\nconst AGGREGATE_CLAIM: Record<SuboptimalCode, (observed: number, analyzed: number) => string> = {\n 'monotonic-input-growth': (observed, analyzed) =>\n `${observed}/${analyzed} analyzed traces showed input tokens grow from zero to nonzero or to at least 3x their initial value across at least 3 serial model calls without a decrease.`,\n 'output-length-decay': (observed, analyzed) =>\n `${observed}/${analyzed} analyzed traces showed output tokens decrease while input tokens increased monotonically across at least 3 serial model calls.`,\n 'single-tool-dependency': (observed, analyzed) =>\n `${observed}/${analyzed} analyzed traces used only one named tool across at least 3 tool calls.`,\n 'no-self-verification': (observed, analyzed) =>\n `${observed}/${analyzed} analyzed traces had at least 3 tool calls without a verification-named tool call.`,\n}\n\nasync function listTraceIds(\n store: TraceAnalysisStore,\n maxTraces: number,\n signal?: AbortSignal,\n): Promise<string[]> {\n const traceIds = new Set<string>()\n let offset = 0\n let expectedTotal: number | undefined\n\n while (true) {\n signal?.throwIfAborted()\n const page = await store.queryTraces({ limit: TRACE_PAGE_SIZE, offset })\n if (expectedTotal === undefined) expectedTotal = page.total\n if (page.total !== expectedTotal) {\n throw new Error(\n `behavioralAnalyst: trace count changed during pagination (${expectedTotal} to ${page.total})`,\n )\n }\n if (page.total > maxTraces) {\n throw new RangeError(\n `behavioralAnalyst: ${page.total} traces exceed maxTraces=${maxTraces}; filter the store or raise the explicit limit`,\n )\n }\n for (const trace of page.traces) traceIds.add(trace.trace_id)\n if (traceIds.size > maxTraces) {\n throw new RangeError(\n `behavioralAnalyst: more than maxTraces=${maxTraces} unique traces were returned`,\n )\n }\n if (!page.has_more) break\n if (page.traces.length === 0) {\n throw new Error('behavioralAnalyst: trace store returned an empty page with has_more=true')\n }\n offset += page.traces.length\n }\n\n if (traceIds.size !== expectedTotal) {\n throw new Error(\n `behavioralAnalyst: pagination returned ${traceIds.size}/${expectedTotal ?? 0} unique traces`,\n )\n }\n\n return [...traceIds].sort()\n}\n\n/**\n * Map computed signals → structured AnalystFindings. Pure: no LLM, no clock\n * dependence beyond `produced_at` (overridable for deterministic tests).\n */\nexport function deriveEfficiencyFindings(\n metrics: BehavioralMetrics,\n opts: { analystId?: string; producedAt?: string } = {},\n): AnalystFinding[] {\n const analystId = opts.analystId ?? ANALYST_ID\n const traceId = metrics.traceId\n return metrics.signals.map((sig) =>\n makeFinding({\n analyst_id: analystId,\n area: 'efficiency',\n subject: sig.code,\n claim: sig.detail,\n severity: sig.severity,\n // Deterministic arithmetic over spans, not a model judgment → certain.\n confidence: 1,\n evidence_refs: [\n {\n kind: 'metric',\n uri: traceId\n ? `metric://trace/${encodeURIComponent(traceId)}/efficiency/${sig.code}`\n : `metric://efficiency/${sig.code}`,\n excerpt: JSON.stringify(sig.evidence),\n },\n ],\n recommended_action: RECOMMENDED_ACTION[sig.code],\n metadata: {\n deterministic: true,\n evidence: sig.evidence,\n ...(traceId ? { trace_id: traceId } : {}),\n },\n id_basis: sig.code,\n ...(opts.producedAt ? { produced_at: opts.producedAt } : {}),\n }),\n )\n}\n\n/** The deterministic behavioral/efficiency analyst (no LLM, any-model). */\nexport function behavioralAnalyst(\n options: BehavioralAnalystOptions = {},\n): ExactCapableAnalyst<TraceAnalysisStore> {\n const maxTraces = positiveInteger(options.maxTraces ?? DEFAULT_MAX_TRACES, 'maxTraces')\n const maxEvidenceRefsPerFinding = positiveInteger(\n options.maxEvidenceRefsPerFinding ?? DEFAULT_MAX_EVIDENCE_REFS,\n 'maxEvidenceRefsPerFinding',\n )\n return {\n id: ANALYST_ID,\n description:\n 'Deterministic behavioral/efficiency findings over OTLP spans — token-growth, output-decay, tool-monoculture, missing self-verification. Zero LLM; model-agnostic by construction.',\n inputKind: 'trace-store',\n cost: { kind: 'deterministic' },\n version: '2.0.0',\n executionConfig: {\n kind: 'behavioral-efficiency',\n max_traces: maxTraces,\n max_evidence_refs_per_finding: maxEvidenceRefsPerFinding,\n },\n async analyze(store, context) {\n const analyzedTraceIds = await listTraceIds(store, maxTraces, context.signal)\n const findingsById = new Map<\n string,\n {\n finding: AnalystFinding\n observedTraceCount: number\n evidenceTraceIds: string[]\n evidence: AnalystFinding['evidence_refs']\n }\n >()\n for (const traceId of analyzedTraceIds) {\n context.signal?.throwIfAborted()\n const viewed = await store.viewTrace({ trace_id: traceId })\n if (viewed.trace_id !== traceId) {\n throw new Error(\n `behavioralAnalyst: requested trace '${traceId}', received '${viewed.trace_id}'`,\n )\n }\n if (!viewed.spans) {\n throw new Error(\n `behavioralAnalyst: trace '${traceId}' is oversized; complete spans are required`,\n )\n }\n const metrics = computeTraceMetrics(viewed.spans)\n if (metrics.traceId !== null && metrics.traceId !== traceId) {\n throw new Error(\n `behavioralAnalyst: requested trace '${traceId}', received '${metrics.traceId}'`,\n )\n }\n for (const finding of deriveEfficiencyFindings(metrics)) {\n const current = findingsById.get(finding.finding_id)\n if (!current) {\n findingsById.set(finding.finding_id, {\n finding,\n observedTraceCount: 1,\n evidenceTraceIds: [traceId],\n evidence: [...finding.evidence_refs],\n })\n continue\n }\n current.observedTraceCount += 1\n if (current.evidence.length < maxEvidenceRefsPerFinding) {\n current.evidenceTraceIds.push(traceId)\n current.evidence.push(...finding.evidence_refs)\n }\n }\n }\n return [...findingsById.values()].map(\n ({ finding, observedTraceCount, evidenceTraceIds, evidence }) => ({\n ...finding,\n claim: AGGREGATE_CLAIM[finding.subject as SuboptimalCode](\n observedTraceCount,\n analyzedTraceIds.length,\n ),\n rationale: `${observedTraceCount}/${analyzedTraceIds.length} analyzed traces exhibited this pattern.`,\n evidence_refs: evidence,\n metadata: {\n deterministic: true,\n evidence_trace_ids: evidenceTraceIds,\n omitted_evidence_trace_count: observedTraceCount - evidenceTraceIds.length,\n observed_trace_count: observedTraceCount,\n analyzed_trace_count: analyzedTraceIds.length,\n },\n }),\n )\n },\n }\n}\n\nfunction positiveInteger(value: number, name: string): number {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new RangeError(`behavioralAnalyst: ${name} must be a positive safe integer`)\n }\n return value\n}\n","import {\n analyzeSupervisorRunIntegrity,\n type SupervisorRunIntegrityEvidence,\n} from '../../supervisor-run/integrity'\nimport type { SupervisorRunSources, SupervisorRunTree } from '../../supervisor-run/types'\nimport type { ExactCapableAnalyst } from '../exact-types'\nimport { type AnalystContext, type AnalystFinding, type EvidenceRef, makeFinding } from '../types'\n\nconst ANALYST_ID = 'control-integrity'\n\nfunction shown(value: unknown): string {\n if (value === undefined) return '<absent>'\n const encoded = JSON.stringify(value)\n return encoded === undefined ? String(value) : encoded\n}\n\nfunction evidenceRef(namespace: string, value: SupervisorRunIntegrityEvidence): EvidenceRef {\n return {\n kind: 'metric',\n uri: `supervisor-run://${encodeURIComponent(namespace)}/${value.path}`,\n excerpt: shown(value.value),\n }\n}\n\n/** Translate typed supervisor-run integrity issues into the shared analyst envelope. */\nexport function emitControlIntegrityFindings(\n input: SupervisorRunSources | SupervisorRunTree,\n producedAt: string,\n): AnalystFinding[] {\n const report = analyzeSupervisorRunIntegrity(input, { capturedAt: producedAt })\n return report.issues.map((issue) =>\n makeFinding({\n analyst_id: ANALYST_ID,\n produced_at: producedAt,\n area: issue.area,\n severity: issue.severity,\n subject: `${report.runRef}/${issue.subject}`,\n claim: issue.claim,\n rationale: issue.detail,\n evidence_refs: issue.evidence.map((value) => evidenceRef(report.runRef, value)),\n recommended_action: issue.recommendedAction,\n validation_plan:\n 'Re-run this deterministic analyst on the retained SupervisorRunSources or SupervisorRunTree after correcting the producer.',\n confidence: 1,\n metadata: {\n integrity_code: issue.code,\n integrity_input: report.input,\n integrity_run_ref: report.runRef,\n integrity_subject: issue.subject,\n ...issue.metadata,\n },\n }),\n )\n}\n\n/** Deterministic Analyst adapter for `SupervisorRunSources | SupervisorRunTree`. */\nexport class ControlIntegrityAnalyst\n implements ExactCapableAnalyst<SupervisorRunSources | SupervisorRunTree>\n{\n readonly id = ANALYST_ID\n readonly description =\n 'Deterministic supervisor-run integrity checks with explicit unavailable evidence.'\n readonly inputKind = 'custom' as const\n readonly cost = { kind: 'deterministic' as const, est_usd_per_run: 0 }\n readonly version = '2.0.0'\n readonly executionConfig = {\n kind: 'control-integrity',\n produced_at_source: 'tags.producedAt-or-system-clock',\n } as const\n\n async analyze(\n input: SupervisorRunSources | SupervisorRunTree,\n ctx: AnalystContext,\n ): Promise<AnalystFinding[]> {\n const producedAt = ctx.tags?.producedAt ?? new Date().toISOString()\n const findings = emitControlIntegrityFindings(input, producedAt)\n ctx.log?.(`control-integrity: ${findings.length} finding(s)`, {\n input: 'nodes' in input ? 'SupervisorRunTree' : 'SupervisorRunSources',\n })\n return findings\n }\n}\n\nexport const CONTROL_INTEGRITY_ANALYST = new ControlIntegrityAnalyst()\n","/**\n * Failure-mode analyst — prices each failure by the work it burned.\n *\n * Brief: for every failure worth reporting, find the span where it\n * started, find the span where the agent resumed productive work, and\n * report the distance between them as the cost. Severity follows that\n * measured cost. Frequency does not set severity.\n *\n * Why the reframe: counting is already free. `getDatasetOverview`\n * returns `errors.trace_count`, `errors.span_count`, and an\n * `error_clusters[]` array carrying each signature's tool, trace and\n * span counts, prevalence, and exemplar ids — deterministically, before\n * a single model call. The 1.x prompt spent a recursive investigation\n * re-deriving exactly that and answered with \"Bash tool calls are the\n * dominant failure surface (54 error spans across 47 distinct\n * signatures)\" and \"79/5260 tool calls ended in errors\". Both numbers\n * were true, both were already on the overview, and neither told an\n * operator which failure to fix first.\n *\n * What is NOT free is attributing waste. An error the agent shrugged\n * off on the next span cost approximately nothing. An error that sent\n * it down a wrong path for twenty spans, or that ended with a human\n * typing the correction, cost real wall-clock and real tokens. Only a\n * reader that follows the trace forward from the error to the point of\n * resumption can measure that, and that walk is what the model is paid\n * for here.\n *\n * The bounding pair is enforced structurally rather than by prompt\n * alone: `minimumEvidenceCitations: 2` rejects any finding that cannot\n * cite both the error span and the span that closed it, so an\n * unmeasured cost claim cannot reach the registry.\n *\n * Eight bounded model subqueries let the actor adjudicate the one\n * genuine judgement call — is a given post-error span real progress or\n * more flailing? — over excerpts it has already loaded.\n */\n\nimport { findingSubjectGrammarPromptFor } from '../finding-subject'\nimport type { TraceAnalystDefinition } from '../kind-factory'\n\nconst subjectGrammar = findingSubjectGrammarPromptFor('failure-mode')\n\nconst ACTOR_PROMPT = `You are a failure-cost analyst for an OTLP trace dataset. Your job is to find the failures that **burned the most agent work** and to price each one in spans, model calls, and wall-clock. How often an error occurred is not its cost and is not your output.\n\n${subjectGrammar}\n\nUse a lowercase cluster label that names the cost shape, not the error string: \"human-corrected-file-overwrite\", \"unrecovered-auth-loop\", \"long-detour-schema-guess\".\n\nWORKLIST → RECOVERY BOUNDARY → PRICE → CITE protocol:\n\n1. \\`getDatasetOverview({})\\` first. Read \\`errors.trace_count\\`, \\`errors.span_count\\`, and \\`error_clusters[]\\` — each cluster carries \\`signature\\`, \\`tool_name\\`, \\`trace_count\\`, \\`span_count\\`, \\`prevalence\\`, \\`exemplar_trace_ids\\`, and \\`exemplar_span_ids\\`. This is the deterministic analyzer's output, already computed for free. It is your WORKLIST: the exemplar ids name the spans you go price. It is never your findings.\n2. Reach error-bearing traces the exemplars miss with \\`queryTraces(filters={\"has_errors\": true}, limit=...)\\`. Prefer long traces and traces whose errors sit early: a failure has room to be expensive only when work followed it.\n3. Take one candidate error span E and read its trace in order. \\`viewTrace\\` returns that trace's spans sorted by \\`start_time\\`, which is the ordering every distance below is counted in. When \\`viewTrace\\` returns \\`oversized\\` instead of spans, locate candidates with \\`searchTrace\\` and pull the exact ids with \\`viewSpans\\`; use \\`searchSpan\\` when one span's payload is truncated.\n4. Find the RECOVERY BOUNDARY R — the first span after E in which the agent resumed productive work. Productive means a different, task-advancing action. A retry of the same call with the same arguments, a re-read of the same file, a re-plan of the same step, and an apology are all still inside the failure. Then price it:\n - spans_burned: spans strictly between E and R\n - model_calls_burned: how many of those spans have kind \\`LLM\\`\n - wall_clock_ms: R \\`end_time\\` minus E \\`start_time\\`\n Report all three. If the agent never resumed, R is the trace's last span and the failure is UNRECOVERED.\n5. Set severity from what ENDED the failure and from the measured distance, never from how many times the signature appears:\n - HUMAN-CORRECTED — a human turn after E supplies the correction. This is the most expensive class at any span count, because the failure escaped the agent entirely and reached the user: severity critical. Detect it as a new user-role message in a later \\`LLM\\` span's input attributes, or a new root-level \\`AGENT\\` span in which the user restates or repairs the task. Search with patterns like \\`\"role\"\\\\s*:\\\\s*\"user\"\\`, \\`(that|this) is (wrong|not what)\\`, \\`I (said|asked|told you)\\`, \\`stop\\`, \\`undo\\`, \\`revert\\`, \\`you (deleted|broke|missed|ignored)\\`, \\`try again\\`. Quote the human's words exactly.\n - UNRECOVERED — the trace ends without resumption: severity critical.\n - LONG DETOUR — 10 or more spans burned, or 3 or more \\`LLM\\` spans burned: severity high.\n - SHORT DETOUR — 2 to 9 spans burned: severity medium.\n - SELF-RECOVERED ON THE NEXT SPAN — cost is approximately zero. Do not emit it. That is resilience, and reporting it dilutes the ranking.\n One error that cost 20 spans outranks 50 errors that each cost one retry. Frequency may appear in a finding only as a multiplier on a measured per-instance cost, never as the reason for its severity.\n6. **Cluster, do not enumerate.** Errors sharing a root cause AND a recovery shape are ONE finding: report the summed cost across instances, state how many instances it covers, and cite the bounding pair of the single most expensive instance. Two errors with the same signature but different recovery shapes — one shrugged off, one human-corrected — are NOT the same finding; the expensive one is the finding and the cheap one is noise.\n\nFORBIDDEN OUTPUT. Each of the following duplicates the deterministic pass, and a duplicate finding is worse than no finding because it costs a reviewer the same attention while carrying no new information:\n - a count of errors by tool (\"Bash is the dominant failure surface, 54 error spans\")\n - a count or inventory of error signatures (\"47 distinct error signatures\")\n - an error rate (\"79 of 5260 tool calls ended in errors\")\n - any restatement of \\`prevalence\\`, \\`trace_count\\`, or \\`span_count\\` from \\`error_clusters[]\\`\nEvery finding MUST state its measured cost — spans burned, model calls burned, wall-clock — in the claim, and MUST cite the two spans that bound it: the error span and the recovery span, or the escaping human turn, or the trace's last span when unrecovered. A failure you cannot bound with two spans is one you did not measure: drop it.\n\n**Adjudicate boundaries with subqueries.** The single judgement call in this protocol is whether a post-error span is genuine resumption or more flailing. Load E, the spans between, and the candidate R, then send one bounded \\`llm_query\\` per candidate carrying those exact excerpts and asking which span first advances the task. Subqueries cannot call trace tools, so a trace id tells them nothing — paste the excerpts. Accept a boundary only when the excerpts you loaded support the answer.\n\nConfidence 0.9+ when both bounding spans are quoted and the spans between them were counted directly; 0.6-0.8 when an oversized trace forced you to sample the interval and the distance is an estimate; below 0.5 does not belong in this analyst, because an unmeasurable cost is not a finding. Keep the recommended action a short imperative; the improvement analyst expands it.\n\nIf every error in this dataset was recovered on the next span, return an empty findings array. That is the correct answer for a dataset whose failures were all cheap. Do not backfill it with the counts listed above and do not pad it with speculation.`\n\nexport const FAILURE_MODE_KIND_SPEC: TraceAnalystDefinition = {\n id: 'failure-mode',\n description:\n 'Ranks failures by the work each one burned — spans, model calls, and wall-clock between the error and the span where the agent resumed — and treats a failure that reached a human as the most expensive class.',\n area: 'failure-mode',\n version: '2.0.0',\n instructions: ACTOR_PROMPT,\n toolGroup: 'all',\n // Pricing one failure costs a bounded trace read plus a span-pair read,\n // where counting cost a single overview call; the read budget is sized for\n // that walk, not for the recount it replaces.\n limits: { maxLlmCalls: 8, maxIterations: 24, maxToolCalls: 80 },\n // The error span and the span that closed it. A cost claim that cannot cite\n // both was never measured.\n minimumEvidenceCitations: 2,\n}\n","/**\n * Improvement analyst — actionable self-improvement findings.\n *\n * Brief: read findings from upstream analysts (failure-mode,\n * knowledge-gap, knowledge-poisoning) AND the trace dataset itself,\n * then propose **concrete edits** to the agent's runtime: prompt\n * additions, RAG documents to ingest, tool descriptions to rewrite,\n * scaffolding changes to make, memory entries to invalidate. Each\n * finding is one proposed edit with the locus, the diff, and the\n * expected effect.\n *\n * This is the self-improvement loop's last mile: the prior\n * kinds describe *what's wrong*; this kind describes *what to change*.\n *\n * Eight bounded model subqueries let the actor compare competing fix\n * directions over the same cited evidence before recommending one.\n */\n\nimport { findingSubjectGrammarPromptFor } from '../finding-subject'\nimport type { TraceAnalystDefinition } from '../kind-factory'\n\nconst subjectGrammar = findingSubjectGrammarPromptFor('improvement')\n\nconst ACTOR_PROMPT = `You are a self-improvement analyst. Your job is to propose **concrete, locus-named edits** the agent's runtime should adopt to fix the failure modes, knowledge gaps, and poisonings present in this dataset.\n\nUpstream analysts have already classified the problems. Your job is to convert each problem into a *change to make* and grade its expected leverage. Each finding is one proposed edit.\n\n${subjectGrammar}\n\nDISCOVERY → CANDIDATE-FIXES → COMPETE → CITE protocol:\n\n1. \\`getDatasetOverview({})\\` first. Note the agents, tools, and any system-prompt fingerprints (look for the prompt text echoed in early spans).\n2. For each high-severity failure pattern, generate 2-3 candidate fixes. Real candidate axes:\n - **System-prompt edit** — add an instruction, remove a misleading one, restructure precedence\n - **Tool description edit** — rewrite a tool's description so the agent picks it correctly / passes valid args\n - **New tool** — add a tool the agent kept emulating in code\n - **RAG ingestion** — add a document or correct a stale one\n - **Memory invalidation** — clear cached prior-run decisions that no longer apply\n - **Scaffolding** — add a precondition check, a retry policy, a turn budget, a verification step\n - **Output schema** — narrow the agent's output to forbid the failure shape\n - **Skill / MCP / hook / subagent** — change the reusable profile component responsible for the behavior\n - **Workflow / rollout policy** — change orchestration, budget, sampling, or stopping behavior\n - **Code** — change an implementation path when profile edits cannot repair the behavior\n3. **Compare candidate fixes with bounded subqueries.** Load the representative failure excerpts, then send one \\`llm_query\\` per candidate-fix axis the same evidence. Ask for likely effect, side effects, and implementation scope. Subqueries cannot call trace tools; trace ids alone are insufficient context.\n4. After the comparisons return, **pick the winning candidate per cluster** based on expected effect and risk, then emit ONE finding. Keep the alternatives and rejection reasons in the rationale so the recommendation is auditable.\n5. **Cross-reference upstream findings.** Cite prior failure-mode or knowledge-gap findings as \\`finding://<prior-finding-id>\\`. This builds the dependency graph that lets the dashboard show \"fix #X resolves failure modes A, B, C.\"\n\nFor each winning recommendation, emit ONE finding. Use one exact locus from the subject grammar and state the edit in one sentence. Match leverage to the source failure's severity; use medium for quality-of-life changes and info for cleanup with no behavioral effect. Cite the targeted \\`finding://<id>\\` when available and the most representative span when useful. Quote the problem being fixed. Use confidence 0.85+ for a mechanical fix to a well-evidenced failure, 0.6-0.8 when judgment is required, and <0.5 for speculation. Explain in at most two sentences why this candidate beat its alternatives. The recommended action must be the literal diff, quoted replacement, tool description, or setting change.\n\nIf no upstream failure findings exist in this run, derive your own from the trace dataset using the failure-mode protocol inline (\\`searchTrace\\` for STATUS_CODE_ERROR / MaxTurnsExceeded / etc.). Prefer upstream findings when present because the analysts are designed to chain.\n\nDo NOT propose a fix you cannot defend with evidence. \"Tighten the prompt\" is not a finding; \"Add 'When the user asks for X, always Y' to the system prompt section \"request-classification\"\" is.`\n\nexport const IMPROVEMENT_KIND_SPEC: TraceAnalystDefinition = {\n id: 'improvement',\n description:\n 'Converts upstream failure / gap / poisoning findings into concrete locus-named edits (prompt, tool-doc, RAG, scaffolding) with leverage grades.',\n area: 'improvement',\n version: '1.2.0',\n instructions: ACTOR_PROMPT,\n toolGroup: 'all',\n limits: {\n maxLlmCalls: 8,\n maxIterations: 30,\n maxToolCalls: 80,\n maxOutputChars: 12_000,\n },\n}\n","/**\n * Intent-divergence analyst — was the agent doing what the user asked,\n * and how early was the drift knowable?\n *\n * Brief: unlike every other kind, this one has free ground truth sitting\n * in the trace. A corrective human turn (\"no, I meant…\", \"stop doing X\",\n * \"why are you still asking\") is an *observed, labelled* divergence\n * event — the user themself marked the moment the agent was off target.\n * The analyst takes that label and works BACKWARD to the earliest\n * assistant turn where the divergence was already detectable, names the\n * signal in the user's stated intent that turn contradicted, and counts\n * the turns burned in between.\n *\n * \"The user corrected the agent\" is counting, and the deterministic\n * behavioral pass already counts it. The finding this kind owes is the\n * backward-looking one: at turn N the agent did X against stated intent\n * Y, the user corrected at turn N+K, so K turns were burned. A finding\n * with no earliest-detectable turn and no burned-turn count carries no\n * cost estimate and no place to put the fix, so it is not emitted.\n *\n * Second locus: turns where the *user's own* request was ambiguous or\n * self-contradictory, evidenced by the user later clarifying rather than\n * correcting. Nothing misbehaved there — the fix is a clarifying-question\n * policy that spends one turn up front instead of K turns of rework, so\n * those findings target `scaffolding:*` rather than the agent's\n * instructions.\n *\n * Six bounded model subqueries let the actor test competing\n * earliest-detectable anchors against the same loaded turn excerpts.\n */\n\nimport { findingSubjectGrammarPromptFor } from '../finding-subject'\nimport type { TraceAnalystDefinition } from '../kind-factory'\n\nconst subjectGrammar = findingSubjectGrammarPromptFor('intent-divergence')\n\nconst ACTOR_PROMPT = `You are an intent-divergence analyst for an OTLP trace dataset. Your job is to find where the agent stopped doing what the user asked, and to establish **how early that was knowable**.\n\nThis dataset carries ground truth the other analysts do not have. When a human turn corrects the agent — \"no, I meant…\", \"stop doing X\", \"why are you still asking\" — the user has labelled a divergence for you. That label marks the END of the divergence, not its start. Your finding is the start: the earliest assistant turn already off-intent, the signal in the user's stated intent it contradicted, and the number of turns burned before the correction landed.\n\n${subjectGrammar}\n\nDISCOVERY → BACKTRACK → QUANTIFY → CITE protocol:\n\n1. \\`getDatasetOverview({})\\` first. Note the agent names and \\`sample_trace_ids\\`; conversational datasets carry several human turns per trace and those are the ones worth pulling.\n2. **DISCOVERY — find the corrective human turns.** Use \\`searchTrace\\` for user-authored corrections:\n Every pattern MUST begin with \\`(?i)\\`. The trace store compiles a search pattern case-sensitively unless it opens with that flag, and corrections are overwhelmingly sentence-initial and capitalised (\"Stop\", \"No,\", \"I said\"), so a lowercase pattern silently returns zero hits.\n - Imperative stops: \\`(?i)\\\\bstop\\\\b\\`, \\`(?i)\\\\b(don'?t|do not)\\\\b\\`, \\`(?i)^\\\\s*no[,.!]\\`, \\`(?i)\\\\bnot what I (wanted|asked|meant)\\\\b\\`, \\`(?i)\\\\bthat'?s not what\\\\b\\`, \\`(?i)\\\\brevert\\\\b\\`, \\`(?i)\\\\bstart over\\\\b\\`\n - Repetition and frustration: \\`(?i)\\\\bI (said|asked|told you)\\\\b\\`, \\`(?i)\\\\balready told you\\\\b\\`, \\`(?i)\\\\bwhy are you (still )?\\\\w+ing\\\\b\\`, \\`(?i)\\\\bjust (do|use|write|make)\\\\b\\`, \\`(?i)\\\\bagain\\\\b\\`\n - Clarification markers (second-order, see step 6): \\`(?i)\\\\bI mean(t)?\\\\b\\`, \\`(?i)\\\\bto be clear\\\\b\\`, \\`(?i)\\\\bactually,? I (want|need)\\\\b\\`, \\`(?i)\\\\bwhat I meant\\\\b\\`, \\`(?i)\\\\blet me rephrase\\\\b\\`\n Attribute every match to a role before using it. The same phrases inside an assistant turn are hedging, not correction.\n3. **BACKTRACK — walk the trace backward from the correction.** Read the ordered turns preceding it with \\`viewTrace\\` / \\`viewSpans\\`. Locate the user's ORIGINAL statement of intent (usually the first human turn, sometimes a constraint added mid-run), then locate the FIRST assistant turn that contradicts it. That turn, not the correction, anchors the finding. Name the concrete signal already available at that turn: an explicit constraint the agent violated, a scope it exceeded, a different question it answered, a file or target the user never named, a decision the user had already made.\n4. **QUANTIFY — count the burned turns.** K = (index of the corrective human turn) − (index of the earliest detectable assistant turn). Report both indices and K. If you cannot locate an earliest-detectable turn, you have a correction and not a divergence: drop it.\n5. **CLUSTER.** Repeated corrections about the same misread intent are ONE finding citing all of them, not one finding per corrective turn. Corrections about genuinely different intents in the same trace are separate findings.\n6. **Second-order — the request itself was ambiguous.** When the user CLARIFIES rather than corrects (\"I mean the staging config, not prod\"), the agent's reading was defensible and the request was underspecified or self-contradictory. Emit those against a \\`scaffolding:*\\` locus — a clarifying-question policy or a plan checkpoint — because the fix is one sharp question before acting, priced against the K turns the ambiguity cost. Do not charge the agent's instructions for a request that could not be resolved from its own text.\n\n**Test competing anchors with subqueries.** After the backward walk, load the excerpts for the original intent turn, your candidate earliest-detectable turn, and the turn before it. Send one bounded \\`llm_query\\` per candidate anchor asking whether the divergence is already present in that turn's text alone. Subqueries cannot call trace tools, and a turn index alone is insufficient context. Take the EARLIEST candidate the loaded excerpts support.\n\nFor each cluster, emit ONE finding. Use an exact locus from the subject grammar — the surface whose edit prevents the divergence, not the surface where it surfaced. State the claim in the shape \"turn N did X against stated intent Y; user corrected at turn N+K, burning K turns.\" Rate it critical when the divergence produced a user-visible or irreversible action, high when K is 3 or more or the run ended without the intent satisfied, medium for one or two burned turns, and low for a cosmetic correction. Cite BOTH spans with exact quotes: the earliest-detectable assistant turn and the corrective human turn. Use confidence 0.85+ when the stated intent and the diverging turn are both quotable and the contradiction is explicit, and 0.6-0.8 when the earliest-detectable turn is inferred from surrounding context. The recommended action must be the literal instruction, question, or checkpoint to add.\n\nDo NOT report a divergence the agent noticed and reversed inside the same turn — that is self-correction and it cost the user nothing. Do NOT report a human turn that adds NEW scope; a changed mind is not a divergence. If the dataset holds no corrective or clarifying human turns, return an empty findings array instead of grading tone.`\n\nexport const INTENT_DIVERGENCE_KIND_SPEC: TraceAnalystDefinition = {\n id: 'intent-divergence',\n description:\n 'Anchors each corrective human turn to the earliest assistant turn where the divergence from stated intent was already detectable, and prices it in burned turns.',\n area: 'intent-divergence',\n version: '1.0.0',\n instructions: ACTOR_PROMPT,\n // Backtracking reads the ordered turns BEFORE the correction, so the\n // search-only group cannot serve this kind: discovery finds the label,\n // viewTrace / viewSpans find the anchor.\n toolGroup: 'all',\n limits: { maxLlmCalls: 6, maxIterations: 22, maxToolCalls: 64 },\n // Both ends of the divergence must be quoted — the anchor turn alone is an\n // unlabelled guess, the corrective turn alone is the counting the\n // deterministic pass already does.\n minimumEvidenceCitations: 2,\n}\n","/**\n * Knowledge-gap analyst — what did the agent NOT know that it needed?\n *\n * Brief: find moments in the trace where the agent had to guess, ask\n * the user to fill in context, recover from a wrong assumption, or\n * loop on a retrieval. Each finding names a *missing or outdated piece\n * of knowledge* the agent's curated knowledge base should have held —\n * or a downstream lookup (web, docs, tool description) that surfaced\n * stale or outdated information.\n *\n * The primary expected store is `@tangle-network/agent-knowledge`: a\n * Karpathy-style wiki the agent maintains with raw ↔ curated pages,\n * source anchors, and claim/relation triples. A gap is anything the\n * agent had to discover at run-time that should already have lived\n * there. Secondary loci: web-search results that returned outdated\n * pages, tool descriptions that omitted critical behavior, system-\n * prompt sections that didn't cover the case.\n *\n * Distinct from failure-mode: failure-mode classifies *how* it broke;\n * knowledge-gap names the *information* whose absence (or staleness)\n * caused the break. One failure-mode often maps to several gaps.\n *\n * Five bounded model subqueries let the actor compare candidate gaps\n * across source layers after it has loaded the relevant excerpts.\n */\n\nimport { findingSubjectGrammarPromptFor } from '../finding-subject'\nimport type { TraceAnalystDefinition } from '../kind-factory'\n\nconst subjectGrammar = findingSubjectGrammarPromptFor('knowledge-gap')\n\nconst ACTOR_PROMPT = `You are a knowledge-gap analyst for an OTLP trace dataset. Your job is to identify the **specific pieces of information the agent lacked, or that were stale**, that caused poor decisions.\n\nThe agent under analysis maintains a curated knowledge base via \\`@tangle-network/agent-knowledge\\` — a wiki of \\`KnowledgePage\\`s with raw source anchors, claims, and relations. The primary expected store of agent-knowable facts IS that wiki. A \"knowledge gap\" is anything the agent had to discover or guess at run-time that the wiki should have held — or an outdated/contradictory fact the agent picked up from a non-wiki source.\n\n${subjectGrammar}\n\nDISCOVERY → ATTRIBUTE-TO-LAYER → CITE protocol:\n\n1. \\`getDatasetOverview({})\\` first. Note which agents, tools, and models appear.\n2. Pull traces where the agent shows gap signals. The strongest signals are:\n - Self-correction turns (\"I assumed X but…\", \"let me re-check\", \"actually,\")\n - Clarifying-question turns where the agent asked the user something the runtime should have surfaced\n - Repeated retrieval / lookup calls for the same artifact with slightly varied queries\n - Tool errors that name a missing argument or unknown resource\n - Web-search calls returning pages dated before a known cutoff for content that changes (versioned APIs, schemas, policies)\n - Agent quoting a tool's docs / system prompt incorrectly because the actual text was insufficient\n - Fabricated identifiers that don't appear in dataset \\`sample_trace_ids\\`\n Use \\`searchTrace\\` with patterns like \\`I (don.?t|do not) know\\`, \\`assumed\\`, \\`unclear\\`, \\`could you (clarify|tell me|provide)\\`, \\`not found\\`, \\`undefined\\`, \\`unknown\\`, \\`null\\`, dates older than the analysis window, or the agent's specific clarification phrases.\n3. For each gap, identify the **layer of the runtime that should have prevented it** and use its exact locus from the subject grammar above.\n4. For each defensible gap, emit ONE finding. Use an exact locus from the subject grammar and name the missing or stale knowledge (for example, \"wiki has no page on invoice line-item shape; agent re-derived it from raw spans\"). Rate it high when it caused failure or a clarifying question, medium for unnecessary turns, and low for minor inefficiency. Cite the span where the question, correction, retrieval miss, or stale result surfaced and quote it exactly. Use confidence 0.85+ when the agent articulated the gap and 0.6-0.8 when inferred. Recommend a concrete wiki edit for an agent-knowledge locus or a prompt/tool-description edit otherwise.\n\n**Compare layers over loaded evidence.** After the first scan, load the exact excerpts behind candidates across \\`agent-knowledge:*\\`, \\`websearch:outdated\\`, \\`tool-doc:*\\`, \\`system-prompt:*\\`, and \\`memory:*\\`. Use one bounded \\`llm_query\\` per layer to classify those excerpts. Subqueries cannot call trace tools. Merge their classifications into the final finding set only when the source excerpts support them.\n\nDo NOT report a gap that the agent later recovered from cleanly within the same turn. That is resilience, not a gap. Cite the non-recovery version when both exist.`\n\nexport const KNOWLEDGE_GAP_KIND_SPEC: TraceAnalystDefinition = {\n id: 'knowledge-gap',\n description:\n 'Identifies missing or stale pieces of knowledge — primarily against the agent-knowledge wiki — and attributes each to the runtime layer (wiki page, claim, raw source, websearch, tool-doc, system-prompt, memory) that should have held it.',\n area: 'knowledge-gap',\n version: '1.2.0',\n instructions: ACTOR_PROMPT,\n toolGroup: 'discoveryAndSearch',\n limits: { maxLlmCalls: 5, maxIterations: 18, maxToolCalls: 48 },\n}\n","/**\n * Knowledge-poisoning analyst — what FALSE information misled the agent?\n *\n * Brief: find moments where the agent acted on information that was\n * *wrong* — stale memory, RAG documents that contradicted ground truth,\n * tool descriptions that lied about return shapes, system-prompt\n * instructions that no longer matched reality, prior-run summaries that\n * cached a wrong decision.\n *\n * Distinct from knowledge-gap: a gap is \"the agent didn't know X\"; a\n * poisoning is \"the agent confidently used X, but X was wrong.\" Gaps\n * surface as questions / self-correction; poisonings surface as\n * confident-but-wrong actions that downstream evidence contradicts.\n *\n * Eight bounded model subqueries let the actor independently assess\n * the action and contradiction excerpts for candidate poisonings.\n */\n\nimport { findingSubjectGrammarPromptFor } from '../finding-subject'\nimport type { TraceAnalystDefinition } from '../kind-factory'\n\nconst subjectGrammar = findingSubjectGrammarPromptFor('knowledge-poisoning')\n\nconst ACTOR_PROMPT = `You are a knowledge-poisoning analyst for an OTLP trace dataset. Your job is to identify cases where the agent **confidently used wrong information** — not where it lacked information (that's the knowledge-gap analyst).\n\n${subjectGrammar}\n\nDISCOVERY → DUAL-VERIFY → CITE protocol:\n\n1. \\`getDatasetOverview({})\\` first. Identify the agents, models, and tools.\n2. Pull traces where the agent's confident action was later contradicted. Strongest signals:\n - Agent stated a fact in one span; a later span surfaced contradictory evidence; the agent then proceeded anyway or fabricated reconciliation.\n - Tool call with stale arguments (an id that no longer exists, an API shape that changed).\n - Agent cited an \\`agent-knowledge\\` wiki page or claim whose content contradicts the trace's own evidence — the wiki itself drifted.\n - Web-search result the agent cited that returned an outdated page; agent treated it as canonical.\n - System-prompt instruction the agent followed that ground-truth evidence in the trace contradicts (e.g. prompt says \"use endpoint A\"; tool reply says \"endpoint A deprecated, use B\").\n - Repeated wrong-shape parsing despite the tool's actual output proving the shape.\n3. Use \\`searchTrace\\` with regex on phrases like \\`actually\\`, \\`turns out\\`, \\`previously assumed\\`, \\`old version\\`, \\`deprecated\\`, \\`updated to\\`, \\`now uses\\`, or specific entity names you suspect have changed.\n4. For each candidate poisoning, **DUAL-VERIFY**:\n - Confirm the agent actually acted on the false belief (cite the span where it did)\n - Confirm the belief is actually false in this trace's own evidence (cite the span that contradicts it)\n Only emit a finding when both halves are supported. If you can only support one, drop it because single-evidence poisoning findings are too speculative to be useful.\n\n**Independently assess both halves.** Load the action excerpt and contradicting excerpt yourself, then send bounded \\`llm_query\\` calls the exact evidence for \"did the agent act?\" and \"does the trace contradict the belief?\" Subqueries cannot call trace tools. Accept a poisoning only when both assessments and the source excerpts support it.\n\nFor each confirmed poisoning, emit ONE finding. Use the source of the false belief as the exact subject. State \"agent believed X (from source S); trace evidence shows X is false.\" Rate it critical for a wrong user-visible action, high when caught internally after significant waste, and medium for inefficiency. Cite BOTH the action span and the contradicting span with exact quotes. Use confidence 0.85+ when both halves have exact quotes and 0.6-0.8 when one half is inferred. Recommend the literal source correction: update the wiki claim, invalidate and re-curate the raw source, or replace the stale prompt/tool instruction.\n\nDo NOT report a finding if the agent caught and corrected the false belief in the same turn. Reserve poisoning for cases where the false belief shaped downstream action.`\n\nexport const KNOWLEDGE_POISONING_KIND_SPEC: TraceAnalystDefinition = {\n id: 'knowledge-poisoning',\n description:\n 'Identifies confident-but-wrong actions caused by stale memory, contradicting RAG, deprecated tool docs, or outdated system-prompt instructions.',\n area: 'knowledge-poisoning',\n version: '1.2.0',\n instructions: ACTOR_PROMPT,\n toolGroup: 'all',\n limits: { maxLlmCalls: 8, maxIterations: 20, maxToolCalls: 64 },\n minimumEvidenceCitations: 2,\n}\n","/**\n * Default analyst kinds focused on agent failure + recursive\n * self-improvement.\n *\n * The five kinds chain. Two independent classifiers partition the\n * outcome surface: failure-mode names how a run broke, intent-divergence\n * names where it drifted from what the user asked and how many turns\n * that cost. Knowledge-gap and knowledge-poisoning then explain *why* in\n * two orthogonal ways — missing information versus false information.\n * Improvement proposes the concrete edits. Register all five against the\n * same trace store in this order and run the registry with\n * `chainFindings: true` to pass each completed kind's findings to the\n * kinds that follow it.\n */\n\nexport {\n CONTROL_INTEGRITY_ANALYST,\n ControlIntegrityAnalyst,\n emitControlIntegrityFindings,\n} from './control-integrity'\nexport { FAILURE_MODE_KIND_SPEC } from './failure-mode'\nexport { IMPROVEMENT_KIND_SPEC } from './improvement'\nexport { INTENT_DIVERGENCE_KIND_SPEC } from './intent-divergence'\nexport { KNOWLEDGE_GAP_KIND_SPEC } from './knowledge-gap'\nexport { KNOWLEDGE_POISONING_KIND_SPEC } from './knowledge-poisoning'\n\nimport type { TraceAnalystDefinition } from '../kind-factory'\nimport { FAILURE_MODE_KIND_SPEC } from './failure-mode'\nimport { IMPROVEMENT_KIND_SPEC } from './improvement'\nimport { INTENT_DIVERGENCE_KIND_SPEC } from './intent-divergence'\nimport { KNOWLEDGE_GAP_KIND_SPEC } from './knowledge-gap'\nimport { KNOWLEDGE_POISONING_KIND_SPEC } from './knowledge-poisoning'\n\n/**\n * The default kind suite. Order is the run order operators should use:\n * failure-mode and intent-divergence first (neither reads upstream\n * findings), gap + poisoning next (both explain the problems those two\n * found), improvement last (chains all four). Intent-divergence sits\n * ahead of improvement deliberately — a proposed edit should be able to\n * act on a priced divergence, and it is the only kind whose findings\n * carry a burned-turn cost to rank against.\n */\nexport const DEFAULT_TRACE_ANALYST_KINDS: readonly TraceAnalystDefinition[] = [\n FAILURE_MODE_KIND_SPEC,\n INTENT_DIVERGENCE_KIND_SPEC,\n KNOWLEDGE_GAP_KIND_SPEC,\n KNOWLEDGE_POISONING_KIND_SPEC,\n IMPROVEMENT_KIND_SPEC,\n] as const\n","/**\n * AnalystRegistry — orchestrate N analysts against one run.\n *\n * Owns three responsibilities and only three:\n * 1. Registration — ids must be unique; bad registrations fail loudly\n * at register-time, not run-time.\n * 2. Routing — each analyst declares its `inputKind`; the registry\n * picks the matching field from AnalystRunInputs and skips the\n * analyst with a logged reason if it's missing.\n * 3. Isolation — one analyst's exception MUST NOT stop other analysts.\n * Failed analysts produce zero findings + a 'failed' summary row.\n *\n * Cross-cutting concerns (telemetry, error → finding conversion, cost\n * ingestion, storage rotation) live in `AnalystHooks`. Budget shaping\n * (equal split vs weighted vs custom) lives in `BudgetPolicy`. Both\n * have sensible defaults; consumers override only what they need.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { z } from 'zod'\nimport { combineAbortSignals } from '../abort-signal'\nimport type { CostLedgerHandle } from '../cost-ledger'\nimport {\n snapshotAnalystFindings,\n snapshotExactAnalystRunReceipt,\n} from '../feedback-trajectory-review'\nimport { canonicalString, hashCanonical } from '../ledger-core/canonical'\nimport { deepFreezeCanonicalJson } from '../ledger-core/deep-freeze'\nimport type { RunCostProvenance, RunTokenUsage } from '../run-record'\nimport type { ChatClient } from './chat-client'\nimport type {\n ExactAnalystExecutionPlanSnapshot,\n ExactAnalystRunEvent,\n ExactAnalystRunResult,\n ExactCapableAnalyst,\n ExactExecutionComponentIdentity,\n ExactExecutionComponentSnapshot,\n} from './exact-types'\nimport { snapshotExactExecutionComponentIdentity, snapshotExactExecutionPlan } from './exact-types'\nimport type {\n Analyst,\n AnalystContext,\n AnalystFinding,\n AnalystRunEvent,\n AnalystRunInputs,\n AnalystRunResult,\n AnalystRunSummary,\n AnalystUsageReceipt,\n} from './types'\nimport { assertValidAnalystUsageReceipt, validateUsageSettlementTimeout } from './usage-receipt'\n\n// ── Hook + policy surfaces ─────────────────────────────────────────\n\nexport interface AnalystHooks {\n /** Legacy runs may mutate ctx; exact runs provide a frozen observational context. */\n onBeforeAnalyze?(args: {\n analyst: Analyst\n ctx: AnalystContext\n runId: string\n }): void | Promise<void>\n /** After every analyst (ok | failed | skipped). Use for telemetry, ingestion, rotation. */\n onAfterAnalyze?(args: {\n analyst: Analyst\n summary: AnalystRunSummary\n findings: AnalystFinding[]\n runId: string\n }): void | Promise<void>\n /**\n * On analyst exception. Hook MAY return findings to convert the\n * error into structured findings; the summary still reports 'failed'.\n * Return void to keep the default empty-findings behavior.\n */\n onError?(args: {\n analyst: Analyst\n error: Error\n runId: string\n }): AnalystFinding[] | undefined | Promise<AnalystFinding[] | undefined>\n /** Once after registry.run() completes. Use for final aggregation, persistence. */\n onComplete?(args: { result: AnalystRunResult }): void | Promise<void>\n}\n\nexport interface BudgetPolicy {\n /** Overall USD cap across the registry.run(). */\n totalUsd?: number\n /** Per-analyst weight for the default allocator. Missing ids get weight 1. */\n weights?: Record<string, number>\n /**\n * Custom allocator — receives the analyst, remaining/total budget, and\n * the count of analysts that will run. Returns the per-analyst budget\n * (or undefined only when the run has no overall cap). Overrides weights\n * when set.\n */\n allocate?: (args: {\n analyst: Analyst\n totalUsd: number | undefined\n remainingUsd: number | undefined\n runningCount: number\n }) => number | undefined\n}\n\nexport interface AnalystRegistryOptions {\n /** Shared chat client passed to every LLM analyst via AnalystContext. */\n chat?: ChatClient\n /** Logger callback. Defaults to a no-op. */\n log?: (msg: string, fields?: Record<string, unknown>) => void\n /** Hooks invoked around analyze() — observability + customization seam. */\n hooks?: AnalystHooks\n /** Required identity/config when `runExact` applies `hooks`. */\n hooksIdentity?: ExactExecutionComponentIdentity\n /** Default budget when run() doesn't override. */\n defaultBudget?: BudgetPolicy\n /** Required identity/config when `runExact` provides `chat`. */\n chatIdentity?: ExactExecutionComponentIdentity\n}\n\nexport interface RegistryRunOpts {\n /** Restrict to a subset of registered analysts by id. */\n only?: string[]\n /** Skip these analysts even if registered. Useful for cheap iteration. */\n skip?: string[]\n /** Budget policy — totalUsd + optional weights/allocator. Falls back to options.defaultBudget. */\n budget?: BudgetPolicy\n /** Active-work cap for the complete registry run. Model receipt settlement may follow. */\n timeoutMs?: number\n /** Abort signal — forwarded into every analyst's context. */\n signal?: AbortSignal\n /** Shared paid-call account forwarded to every analyst. */\n costLedger?: CostLedgerHandle\n /** Attribution phase for calls written to `costLedger`. */\n costPhase?: string\n /** Tags echoed into AnalystContext.tags — useful for tracking environment/version in findings. */\n tags?: Record<string, string>\n /**\n * Prior-run findings made available as retrieval context to every\n * analyst via `ctx.priorFindings`. The registry forwards the slice\n * whose `analyst_id` matches each registered analyst so a kind sees\n * only its own history. Pass `{ '*': findings }` to broadcast to\n * every analyst (useful when several kinds share the same historical\n * context). For findings from this run, use `chainFindings` instead.\n */\n priorFindings?: ReadonlyArray<AnalystFinding> | Record<string, ReadonlyArray<AnalystFinding>>\n /**\n * Pass findings produced earlier in this registry run to each later analyst\n * via `ctx.upstreamFindings`. Registration order is dependency order.\n * Disabled by default because independent analyst suites must opt in.\n */\n chainFindings?: boolean\n}\n\n/** A caller-selected allocation rule for an exact analyst run. */\nexport type ExactAnalystBudgetPolicy =\n | {\n readonly kind: 'equal'\n readonly totalUsd: number\n }\n | {\n readonly kind: 'weighted'\n readonly totalUsd: number\n /** One explicit weight for every selected analyst id. */\n readonly weights: Readonly<Record<string, number>>\n }\n\n/**\n * Complete per-run analyst policy.\n *\n * Every field is required. `null` explicitly disables an optional resource or context channel.\n * `analystIds` is execution order; it is not filtered through registry insertion order.\n * Missing-input behavior is explicit so callers cannot accidentally inherit it by omission.\n * Exact runs are serial; more elaborate scheduling belongs in the caller's runtime.\n */\nexport interface ExactRegistryRunOpts {\n readonly analystIds: readonly string[]\n readonly budget: ExactAnalystBudgetPolicy | null\n readonly totalTimeoutMs: number | null\n readonly signal: AbortSignal | null\n readonly costLedger: CostLedgerHandle | null\n readonly costLedgerIdentity: ExactExecutionComponentIdentity | null\n readonly costPhase: string | null\n readonly tags: Readonly<Record<string, string>> | null\n readonly priorFindings:\n | ReadonlyArray<AnalystFinding>\n | Readonly<Record<string, ReadonlyArray<AnalystFinding>>>\n | null\n readonly chainFindings: boolean\n readonly missingInputMode: 'skip' | 'abort'\n readonly applyRegistryHooks: boolean\n readonly useRegistryChat: boolean\n}\n\ntype NormalizedBudgetPlan =\n | { readonly kind: 'none' }\n | { readonly kind: 'dynamic'; readonly policy: BudgetPolicy }\n\ninterface PreparedAnalyst {\n readonly analyst: Analyst\n readonly input:\n | { readonly kind: 'present'; readonly value: unknown }\n | { readonly kind: 'missing' }\n}\n\ninterface AnalystExecutionPlan {\n readonly runId: string\n readonly prepared: readonly PreparedAnalyst[]\n readonly budget: NormalizedBudgetPlan\n readonly totalTimeoutMs: number | null\n readonly signal: AbortSignal | null\n readonly costLedger: CostLedgerHandle | null\n readonly costPhase: string | null\n readonly tags: Readonly<Record<string, string>> | null\n readonly priorFindings:\n | ReadonlyArray<AnalystFinding>\n | Readonly<Record<string, ReadonlyArray<AnalystFinding>>>\n | null\n readonly chainFindings: boolean\n readonly hooks: AnalystHooks\n readonly chat: ChatClient | undefined\n readonly log: (msg: string, fields?: Record<string, unknown>) => void\n readonly executionSnapshot: ExactAnalystExecutionPlanSnapshot | undefined\n}\n\ntype InternalAnalystRunEvent = AnalystRunEvent\n\n/** A post-start exact-run failure; completed work remains attached for accounting and review. */\nexport class ExactAnalystRunExecutionError extends Error {\n readonly name: string = 'ExactAnalystRunExecutionError'\n readonly result: ExactAnalystRunResult\n\n constructor(message: string, result: ExactAnalystRunResult, options?: ErrorOptions) {\n super(message, options)\n const snapshot = snapshotExactAnalystRunReceipt(result, 'ExactAnalystRunExecutionError result')\n if (snapshot.completion.status !== 'failed') {\n throw new TypeError('ExactAnalystRunExecutionError result must be a failed receipt')\n }\n this.result = snapshot\n }\n}\n\nexport class AnalystRegistry {\n private readonly analysts = new Map<string, Analyst>()\n private readonly options: AnalystRegistryOptions\n\n constructor(options: AnalystRegistryOptions = {}) {\n this.options = options\n }\n\n register(analyst: Analyst): void {\n const id = analyst.id\n const version = analyst.version\n const cost = analyst.cost\n if (!id) throw new Error('AnalystRegistry.register: analyst.id is required')\n if (this.analysts.has(id)) {\n throw new Error(`AnalystRegistry.register: duplicate analyst id \"${id}\"`)\n }\n if (!version) {\n throw new Error(`AnalystRegistry.register: analyst \"${id}\" must declare a version`)\n }\n if (cost.kind === 'deterministic' && cost.settlement_timeout_ms !== undefined) {\n throw new TypeError(\n `AnalystRegistry.register: deterministic analyst \"${id}\" cannot declare settlement_timeout_ms`,\n )\n }\n if (cost.settlement_timeout_ms !== undefined) {\n validateUsageSettlementTimeout(cost.settlement_timeout_ms)\n }\n this.analysts.set(id, analyst)\n }\n\n list(): ReadonlyArray<{\n id: string\n description: string\n version: string\n cost: Analyst['cost']\n }> {\n return Array.from(this.analysts.values()).map((a) => ({\n id: a.id,\n description: a.description,\n version: a.version,\n cost: a.cost,\n }))\n }\n\n async run(\n runId: string,\n inputs: AnalystRunInputs,\n runOpts: RegistryRunOpts = {},\n ): Promise<AnalystRunResult> {\n // Thin collector over `runStream`. Both surfaces share the same\n // loop body so they cannot drift on isolation / hook order / cost.\n for await (const ev of this.runStream(runId, inputs, runOpts)) {\n if (ev.type === 'run-completed') return ev.result\n }\n throw new Error('AnalystRegistry.run: stream completed without run-completed event')\n }\n\n /** Run exactly the ordered analysts and complete policy supplied by the caller. */\n async runExact(\n runId: string,\n inputs: AnalystRunInputs,\n runOpts: ExactRegistryRunOpts,\n ): Promise<ExactAnalystRunResult> {\n for await (const ev of this.runExactStream(runId, inputs, runOpts)) {\n if (ev.type === 'run-completed') return ev.result\n }\n throw new Error('AnalystRegistry.runExact: stream completed without run-completed event')\n }\n\n /** Streaming counterpart to {@link runExact}. */\n async *runExactStream(\n runId: string,\n inputs: AnalystRunInputs,\n runOpts: ExactRegistryRunOpts,\n ): AsyncGenerator<ExactAnalystRunEvent, void, void> {\n for await (const event of this.executePlanStream(\n this.normalizeExactPlan(runId, inputs, runOpts),\n )) {\n yield event as ExactAnalystRunEvent\n }\n }\n\n /**\n * Streaming counterpart to `run()`. Emits `AnalystRunEvent` values\n * in real time — `run-started`, then per-analyst `skipped` /\n * `started` / `completed`, then a terminal `run-completed` whose\n * payload is the full `AnalystRunResult`. UIs use this to render\n * progress; persistence consumers use `run()` and read the result.\n *\n * Hooks (`onBeforeAnalyze` / `onAfterAnalyze` / `onError` /\n * `onComplete`) fire as before — streaming is additive, not a hook\n * replacement.\n */\n async *runStream(\n runId: string,\n inputs: AnalystRunInputs,\n runOpts: RegistryRunOpts = {},\n ): AsyncGenerator<AnalystRunEvent, void, void> {\n yield* this.executePlanStream(this.normalizeLegacyPlan(runId, inputs, runOpts))\n }\n\n private normalizeLegacyPlan(\n runId: string,\n inputs: AnalystRunInputs,\n runOpts: RegistryRunOpts,\n ): AnalystExecutionPlan {\n const timeoutMs = validateTimeout(runOpts.timeoutMs) ?? null\n const budget = runOpts.budget ?? this.options.defaultBudget\n validateBudgetPolicy(budget)\n const selected = this.selectAnalysts(runOpts)\n return {\n runId,\n prepared: selected.map((analyst) => ({\n analyst,\n input: this.routeInput(analyst, inputs),\n })),\n budget: budget ? { kind: 'dynamic', policy: budget } : { kind: 'none' },\n totalTimeoutMs: timeoutMs,\n signal: runOpts.signal ?? null,\n costLedger: runOpts.costLedger ?? null,\n costPhase: runOpts.costPhase ?? null,\n tags: runOpts.tags ?? null,\n priorFindings: runOpts.priorFindings ?? null,\n chainFindings: runOpts.chainFindings ?? false,\n hooks: this.options.hooks ?? {},\n chat: this.options.chat,\n log: this.options.log ?? (() => {}),\n executionSnapshot: undefined,\n }\n }\n\n private normalizeExactPlan(\n runId: string,\n inputs: AnalystRunInputs,\n runOpts: ExactRegistryRunOpts,\n ): AnalystExecutionPlan {\n const exactRunId = snapshotExactRunId(runId)\n const exact = snapshotExactRegistryRunOpts(runOpts)\n const selected = normalizeExactAnalysts(this.selectExactAnalysts(exact.analystIds))\n const registryChat = this.options.chat\n const registryChatIdentity = this.options.chatIdentity\n const registryHooks = this.options.hooks\n const registryHooksIdentity = this.options.hooksIdentity\n if (exact.useRegistryChat && registryChat === undefined) {\n throw new TypeError(\n 'ExactRegistryRunOpts.useRegistryChat is true but the registry has no chat client',\n )\n }\n if (exact.applyRegistryHooks && !hasRegistryHooks(registryHooks)) {\n throw new TypeError(\n 'ExactRegistryRunOpts.applyRegistryHooks is true but the registry has no lifecycle hooks',\n )\n }\n const inputSnapshot = snapshotAnalystRunInputChannels(inputs)\n const prepared = selected.map((analyst) => ({\n analyst,\n input: this.routeInput(analyst, inputSnapshot),\n }))\n if (exact.missingInputMode === 'abort') {\n const missing = prepared.find((candidate) => candidate.input.kind === 'missing')?.analyst\n if (missing) {\n throw new TypeError(\n `ExactRegistryRunOpts.missingInputMode abort preflight found no \"${missing.inputKind}\" input for \"${missing.id}\"`,\n )\n }\n }\n const hooksIdentity =\n exact.applyRegistryHooks && registryHooks\n ? requireExactComponentIdentity(registryHooksIdentity, 'registry hooks')\n : null\n const chatIdentity = exact.useRegistryChat\n ? requireExactComponentIdentity(registryChatIdentity, 'registry chat')\n : null\n const costLedgerIdentity =\n exact.costLedger === null\n ? null\n : requireExactComponentIdentity(exact.costLedgerIdentity ?? undefined, 'cost ledger')\n const allocations = exactFixedBudgets(\n exact.budget,\n prepared\n .filter(\n (\n candidate,\n ): candidate is {\n analyst: ExactCapableAnalyst\n input: { kind: 'present'; value: unknown }\n } => candidate.input.kind === 'present',\n )\n .map((candidate) => candidate.analyst),\n selected,\n )\n const executionSnapshot = exactExecutionSnapshot(\n selected,\n exact,\n allocations,\n costLedgerIdentity,\n hooksIdentity,\n chatIdentity,\n )\n return {\n runId: exactRunId,\n prepared,\n budget: { kind: 'none' },\n totalTimeoutMs: exact.totalTimeoutMs,\n signal: exact.signal,\n costLedger: exact.costLedger,\n costPhase: exact.costPhase,\n tags: exact.tags,\n priorFindings: exact.priorFindings,\n chainFindings: exact.chainFindings,\n hooks: exact.applyRegistryHooks && registryHooks ? snapshotHooks(registryHooks) : {},\n chat: exact.useRegistryChat && registryChat ? snapshotChat(registryChat) : undefined,\n // Exact runs expose live events and versioned hooks. An inherited logger is intentionally\n // excluded because an anonymous callback can throw, block, or mutate shared state.\n log: () => {},\n executionSnapshot,\n }\n }\n\n private async *executePlanStream(\n plan: AnalystExecutionPlan,\n ): AsyncGenerator<InternalAnalystRunEvent, void, void> {\n const exact = plan.executionSnapshot !== undefined\n if (exact && plan.signal?.aborted) throw abortReason(plan.signal)\n\n const correlationId = `ar_${randomUUID().slice(0, 12)}`\n const log = plan.log\n const startedAt = new Date().toISOString()\n const started = Date.now()\n const timeoutSignal =\n plan.totalTimeoutMs === null ? undefined : AbortSignal.timeout(plan.totalTimeoutMs)\n const runSignal = combineAbortSignals(plan.signal ?? undefined, timeoutSignal)\n const deadlineMs = plan.totalTimeoutMs === null ? undefined : started + plan.totalTimeoutMs\n const runnable = plan.prepared\n .filter(\n (\n candidate,\n ): candidate is {\n analyst: Analyst\n input: { kind: 'present'; value: unknown }\n } => candidate.input.kind === 'present',\n )\n .map((candidate) => candidate.analyst)\n let remainingUsd = plan.budget.kind === 'dynamic' ? plan.budget.policy.totalUsd : undefined\n const weights = plan.budget.kind === 'dynamic' ? plan.budget.policy.weights : undefined\n const totalWeight =\n weights &&\n plan.budget.kind === 'dynamic' &&\n plan.budget.policy.totalUsd != null &&\n !plan.budget.policy.allocate &&\n runnable.length > 0\n ? runnable.reduce((sum, analyst) => sum + analystWeight(weights, analyst.id), 0)\n : undefined\n if (totalWeight === 0) {\n throw new Error('BudgetPolicy.weights must allocate positive weight to a runnable analyst')\n }\n const upstreamFindings: AnalystFinding[] = []\n\n yield snapshotExecutionEvent(\n {\n type: 'run-started',\n run_id: plan.runId,\n correlation_id: correlationId,\n started_at: startedAt,\n analyst_ids: plan.prepared.map(({ analyst }) => analyst.id),\n ...(plan.executionSnapshot === undefined ? {} : { execution_plan: plan.executionSnapshot }),\n },\n exact,\n )\n\n const executions: AnalystExecution[] = []\n let executionFailure: unknown\n\n for (const { analyst, input } of plan.prepared) {\n const t0 = Date.now()\n if (runSignal?.aborted) {\n const summary = abortedBeforeStartSummary(analyst, runSignal)\n executions.push({ summary, findings: [], budgetDebitUsd: 0 })\n log(`[analyst] skip ${analyst.id} — run aborted`, {\n runId: plan.runId,\n reason: summary.reason,\n })\n yield snapshotExecutionEvent({ type: 'analyst-skipped', summary }, exact)\n if (exact) {\n executionFailure = abortReason(runSignal)\n break\n }\n continue\n }\n\n if (input.kind === 'missing') {\n const summary: AnalystRunSummary = {\n analyst_id: analyst.id,\n status: 'skipped',\n reason: `missing input of kind '${analyst.inputKind}'`,\n findings_count: 0,\n latency_ms: 0,\n usage: zeroUsage(),\n }\n const execution = { summary, findings: [], budgetDebitUsd: 0 } satisfies AnalystExecution\n executions.push(execution)\n log(`[analyst] skip ${analyst.id} — missing input`, {\n runId: plan.runId,\n kind: analyst.inputKind,\n })\n const hookValues = snapshotAfterHookValues(summary, [], exact)\n try {\n await waitForHook(\n plan.hooks.onAfterAnalyze\n ? () =>\n plan.hooks.onAfterAnalyze?.({\n analyst,\n summary: hookValues.summary,\n findings: hookValues.findings,\n runId: plan.runId,\n })\n : undefined,\n runSignal,\n )\n } catch (error) {\n if (!exact) throw error\n executionFailure = error\n }\n yield snapshotExecutionEvent({ type: 'analyst-skipped', summary }, exact)\n if (executionFailure !== undefined) break\n continue\n }\n\n const allocatedUsd =\n plan.executionSnapshot === undefined\n ? allocateBudget(plan.budget.kind === 'dynamic' ? plan.budget.policy : undefined, {\n analyst,\n remainingUsd,\n runningCount: runnable.length,\n totalWeight,\n })\n : exactPlannedAllocation(plan.executionSnapshot, analyst.id)\n const budgetCeilingUsd = plan.executionSnapshot === undefined ? remainingUsd : allocatedUsd\n const usageReceipts: AnalystUsageReceipt[] = []\n const contextTags = plan.tags === null ? undefined : { ...plan.tags }\n const priorFindings = selectPriorFindings(plan.priorFindings ?? undefined, analyst.id)\n const chainedFindings =\n plan.chainFindings && upstreamFindings.length > 0 ? [...upstreamFindings] : undefined\n const ctx: AnalystContext = {\n runId: plan.runId,\n correlationId,\n deadlineMs,\n budgetUsd: allocatedUsd,\n costLedger: plan.costLedger ?? undefined,\n costPhase: plan.costPhase ?? undefined,\n chat: plan.chat,\n tags: contextTags,\n log: (message, fields) =>\n log(`[${analyst.id}] ${message}`, {\n runId: plan.runId,\n correlationId,\n ...fields,\n }),\n signal: runSignal,\n priorFindings,\n upstreamFindings: chainedFindings,\n recordUsage: (receipt) => {\n if (!exact) {\n assertValidAnalystUsageReceipt(receipt)\n usageReceipts.push(receipt)\n return\n }\n usageReceipts.push(\n snapshotUsageReceiptOnce(\n receipt,\n `AnalystRegistry.runExact analyst \"${analyst.id}\" usage`,\n ),\n )\n },\n }\n if (exact) {\n if (contextTags) deepFreezeCanonicalJson(contextTags)\n if (priorFindings) deepFreezeCanonicalJson(priorFindings)\n if (chainedFindings) deepFreezeCanonicalJson(chainedFindings)\n Object.freeze(ctx)\n }\n\n try {\n await waitForHook(\n plan.hooks.onBeforeAnalyze\n ? () => plan.hooks.onBeforeAnalyze?.({ analyst, ctx, runId: plan.runId })\n : undefined,\n runSignal,\n )\n } catch (error) {\n if (!exact) throw error\n executionFailure = error\n break\n }\n if (runSignal?.aborted) {\n const summary = abortedBeforeStartSummary(analyst, runSignal, Date.now() - t0)\n executions.push({ summary, findings: [], budgetDebitUsd: 0 })\n yield snapshotExecutionEvent({ type: 'analyst-skipped', summary }, exact)\n if (exact) {\n executionFailure = abortReason(runSignal)\n break\n }\n continue\n }\n let effectiveBudget: number | undefined\n try {\n effectiveBudget = validateEffectiveBudget(ctx.budgetUsd, budgetCeilingUsd, analyst.id)\n } catch (error) {\n if (!exact) throw error\n executionFailure = error\n break\n }\n const analystContext: AnalystContext = exact ? ctx : { ...ctx }\n const executionSignal = exact ? ctx.signal : runSignal\n yield snapshotExecutionEvent(\n {\n type: 'analyst-started',\n analyst_id: analyst.id,\n started_at: new Date(t0).toISOString(),\n },\n exact,\n )\n\n let findings: AnalystFinding[]\n let summary: AnalystRunSummary\n let lifecycleFailure: unknown\n let analysisFailure: Error | undefined\n try {\n if (runSignal?.aborted) throw abortReason(runSignal)\n const analyzed = await waitForOperation(\n (analyst as Analyst<unknown>).analyze(input.value, analystContext),\n executionSignal,\n analystAbortGraceMs(analyst),\n )\n findings = snapshotExecutionFindings(\n analyzed,\n exact,\n `AnalystRegistry.runExact analyst \"${analyst.id}\" findings`,\n )\n } catch (error) {\n const cause = error instanceof Error ? error : new Error(String(error))\n analysisFailure = cause\n let hookFindings: AnalystFinding[] = []\n if (!executionSignal?.aborted) {\n try {\n const rawHookFindings =\n (await waitForHook(\n plan.hooks.onError\n ? () =>\n plan.hooks.onError?.({\n analyst,\n error: cause,\n runId: plan.runId,\n })\n : undefined,\n executionSignal,\n )) ?? []\n hookFindings = snapshotExecutionFindings(\n rawHookFindings,\n exact,\n `AnalystRegistry.runExact analyst \"${analyst.id}\" onError findings`,\n )\n } catch (error) {\n lifecycleFailure = error\n }\n }\n findings = hookFindings\n }\n\n let usage: AnalystUsageReceipt\n try {\n usage = resolveUsage(analyst, usageReceipts, exact)\n } catch (error) {\n if (!exact) throw error\n executionFailure = error\n break\n }\n if (analysisFailure === undefined) {\n summary = {\n analyst_id: analyst.id,\n status: 'ok',\n findings_count: findings.length,\n latency_ms: Date.now() - t0,\n usage,\n ...(exact ? { allocated_budget_usd: effectiveBudget ?? null } : {}),\n }\n log(`[analyst] ok ${analyst.id}`, {\n runId: plan.runId,\n findings: findings.length,\n latency_ms: summary.latency_ms,\n cost_usd: knownCostUsd(usage),\n cost_kind: usage.cost.kind,\n input_tokens: usage.tokens?.input ?? null,\n output_tokens: usage.tokens?.output ?? null,\n })\n } else {\n const errorClass = analysisFailure.constructor.name || 'Error'\n const errorMessage =\n exact && analysisFailure.message.length === 0\n ? 'Analyst failed without an error message'\n : analysisFailure.message\n summary = {\n analyst_id: analyst.id,\n status: 'failed',\n findings_count: findings.length,\n latency_ms: Date.now() - t0,\n usage,\n ...(exact ? { allocated_budget_usd: effectiveBudget ?? null } : {}),\n error: { class: errorClass, message: errorMessage },\n }\n log(`[analyst] FAIL ${analyst.id}`, {\n runId: plan.runId,\n error_class: errorClass,\n error: errorMessage,\n cost_usd: knownCostUsd(usage),\n cost_kind: usage.cost.kind,\n })\n }\n logUncapturedBudgetWarning({\n analyst,\n runId: plan.runId,\n budgetUsd: effectiveBudget,\n usage,\n log,\n })\n\n const execution = {\n summary,\n findings,\n budgetDebitUsd: budgetDebit(summary.usage, effectiveBudget),\n } satisfies AnalystExecution\n if (exact) {\n try {\n executionCost([...executions, execution], true)\n } catch (error) {\n executionFailure = error\n break\n }\n }\n executions.push(execution)\n if (plan.budget.kind === 'dynamic' && remainingUsd !== undefined) {\n remainingUsd = Math.max(0, remainingUsd - execution.budgetDebitUsd)\n }\n if (plan.chainFindings) upstreamFindings.push(...findings)\n if (lifecycleFailure !== undefined) {\n if (!exact) throw lifecycleFailure\n executionFailure = lifecycleFailure\n break\n }\n\n const hookValues = snapshotAfterHookValues(summary, findings, exact)\n try {\n await waitForHook(\n plan.hooks.onAfterAnalyze\n ? () =>\n plan.hooks.onAfterAnalyze?.({\n analyst,\n summary: hookValues.summary,\n findings: hookValues.findings,\n runId: plan.runId,\n })\n : undefined,\n executionSignal,\n )\n } catch (error) {\n if (!exact) throw error\n executionFailure = error\n break\n }\n yield snapshotExecutionEvent({ type: 'analyst-completed', summary, findings }, exact)\n if (exact && runSignal?.aborted) {\n executionFailure = abortReason(runSignal)\n break\n }\n }\n\n const summaries = executions.map(({ summary }) => summary)\n const findings = executions.flatMap((execution) => execution.findings)\n const cost = executionCost(executions, exact)\n const baseResult: AnalystRunResult = {\n run_id: plan.runId,\n correlation_id: correlationId,\n started_at: startedAt,\n ended_at: new Date().toISOString(),\n findings,\n per_analyst: summaries,\n total_cost_usd: cost.known,\n total_cost_provenance: cost.provenance,\n }\n if (plan.executionSnapshot === undefined) {\n await waitForHook(\n plan.hooks.onComplete ? () => plan.hooks.onComplete?.({ result: baseResult }) : undefined,\n runSignal,\n )\n yield { type: 'run-completed', result: baseResult }\n return\n }\n\n let completeResult: ExactAnalystRunResult | undefined\n if (executionFailure === undefined) {\n try {\n completeResult = snapshotExactAnalystRunReceipt(\n {\n ...baseResult,\n execution_plan: plan.executionSnapshot,\n completion: { status: 'complete' },\n },\n 'AnalystRegistry.runExact result',\n )\n await waitForHook(\n plan.hooks.onComplete\n ? () => plan.hooks.onComplete?.({ result: completeResult! })\n : undefined,\n runSignal,\n )\n } catch (error) {\n executionFailure = error\n }\n }\n if (runSignal?.aborted) executionFailure ??= abortReason(runSignal)\n if (executionFailure === undefined && completeResult) {\n yield snapshotExecutionEvent({ type: 'run-completed', result: completeResult }, true)\n return\n }\n\n const cause =\n executionFailure instanceof Error ? executionFailure : new Error(String(executionFailure))\n const errorClass = cause.constructor.name || 'Error'\n const errorMessage =\n cause.message.trim().length === 0\n ? 'Exact analyst run failed without a message'\n : cause.message\n throw new ExactAnalystRunExecutionError(\n `exact analyst run failed after starting: ${errorMessage}; partial result is attached`,\n {\n ...baseResult,\n execution_plan: plan.executionSnapshot,\n completion: {\n status: 'failed',\n error: { class: errorClass, message: errorMessage },\n },\n },\n { cause },\n )\n }\n\n private selectAnalysts(opts: RegistryRunOpts): Analyst[] {\n let candidates = Array.from(this.analysts.values())\n if (opts.only?.length) {\n const only = new Set(opts.only)\n candidates = candidates.filter((a) => only.has(a.id))\n }\n if (opts.skip?.length) {\n const skip = new Set(opts.skip)\n candidates = candidates.filter((a) => !skip.has(a.id))\n }\n return candidates\n }\n\n private selectExactAnalysts(\n ids: readonly string[],\n ): ReadonlyArray<{ readonly registeredId: string; readonly analyst: Analyst }> {\n return ids.map((id) => {\n const analyst = this.analysts.get(id)\n if (!analyst) throw new Error(`ExactRegistryRunOpts.analystIds names unknown analyst \"${id}\"`)\n return { registeredId: id, analyst }\n })\n }\n\n private routeInput(\n analyst: Analyst,\n inputs: AnalystRunInputs,\n ): { kind: 'present'; value: unknown } | { kind: 'missing' } {\n switch (analyst.inputKind) {\n case 'trace-store': {\n const value = inputs.traceStore\n return value ? { kind: 'present', value } : { kind: 'missing' }\n }\n case 'artifact-dir': {\n const value = inputs.artifactDir\n return value ? { kind: 'present', value } : { kind: 'missing' }\n }\n case 'run-record': {\n const value = inputs.runRecord\n return value ? { kind: 'present', value } : { kind: 'missing' }\n }\n case 'judge-input': {\n const value = inputs.judgeInput\n return value ? { kind: 'present', value } : { kind: 'missing' }\n }\n case 'custom': {\n const custom = inputs.custom\n const value = custom?.[analyst.id]\n return value !== undefined ? { kind: 'present', value } : { kind: 'missing' }\n }\n }\n }\n}\n\nconst exactRunFields = [\n 'analystIds',\n 'budget',\n 'totalTimeoutMs',\n 'signal',\n 'costLedger',\n 'costLedgerIdentity',\n 'costPhase',\n 'tags',\n 'priorFindings',\n 'chainFindings',\n 'missingInputMode',\n 'applyRegistryHooks',\n 'useRegistryChat',\n] as const\n\nconst exactNonEmptyString = z.string().min(1)\nconst exactFiniteNonnegative = z.number().finite().nonnegative()\nconst exactBudgetSchema = z.discriminatedUnion('kind', [\n z.strictObject({\n kind: z.literal('equal'),\n totalUsd: exactFiniteNonnegative,\n }),\n z.strictObject({\n kind: z.literal('weighted'),\n totalUsd: exactFiniteNonnegative,\n weights: z.record(exactNonEmptyString, exactFiniteNonnegative),\n }),\n])\nconst exactRunDataSchema = z\n .strictObject({\n analystIds: z.array(exactNonEmptyString).min(1),\n budget: exactBudgetSchema.nullable(),\n totalTimeoutMs: z.number().int().positive().max(2_147_483_647).nullable(),\n costLedgerIdentity: z.unknown().nullable(),\n costPhase: exactNonEmptyString.nullable(),\n tags: z.record(z.string(), z.string()).nullable(),\n chainFindings: z.boolean(),\n missingInputMode: z.enum(['skip', 'abort']),\n applyRegistryHooks: z.boolean(),\n useRegistryChat: z.boolean(),\n })\n .superRefine((policy, context) => {\n const issue = (path: PropertyKey[], message: string): void =>\n context.addIssue({ code: 'custom', path, message })\n if (new Set(policy.analystIds).size !== policy.analystIds.length) {\n issue(['analystIds'], 'must not contain duplicates')\n }\n if (\n policy.budget?.kind === 'weighted' &&\n Object.values(policy.budget.weights).every((weight) => weight === 0)\n ) {\n issue(['budget', 'weights'], 'must allocate positive weight to at least one analyst')\n }\n if (policy.budget?.kind === 'weighted') {\n const selected = [...policy.analystIds].sort()\n const weighted = Object.keys(policy.budget.weights).sort()\n if (\n selected.length !== weighted.length ||\n selected.some((id, index) => id !== weighted[index])\n ) {\n issue(['budget', 'weights'], 'must name every selected analyst and no others')\n }\n }\n })\n\nfunction snapshotExactRunId(value: unknown): string {\n if (typeof value !== 'string' || value.length === 0) {\n throw new TypeError('AnalystRegistry.runExact: runId must be a non-empty string')\n }\n return canonicalJsonSnapshot(value, 'AnalystRegistry.runExact runId')\n}\n\nfunction snapshotAnalystRunInputChannels(inputs: AnalystRunInputs): AnalystRunInputs {\n if (!inputs || typeof inputs !== 'object' || Array.isArray(inputs)) {\n throw new TypeError('AnalystRegistry.runExact: inputs must be an object')\n }\n const traceStore = inputs.traceStore\n const artifactDir = inputs.artifactDir\n const runRecord = inputs.runRecord\n const judgeInput = inputs.judgeInput\n const custom = inputs.custom\n return Object.freeze({\n traceStore,\n artifactDir,\n runRecord,\n judgeInput,\n custom,\n })\n}\n\n/**\n * Read the untrusted caller object once, then validate and execute only this frozen snapshot.\n * Functions and resource handles retain identity; all data fields are copied canonically.\n */\nfunction snapshotExactRegistryRunOpts(value: unknown): ExactRegistryRunOpts {\n const captured = readOwnFields(value, exactRunFields, 'ExactRegistryRunOpts')\n const missing = exactRunFields.find((field) => !Object.hasOwn(captured, field))\n if (missing) {\n throw new TypeError(`ExactRegistryRunOpts.${missing} must be supplied explicitly`)\n }\n const { signal, costLedger, priorFindings, ...rawData } = captured\n const data = canonicalJsonSnapshot(rawData, 'ExactRegistryRunOpts')\n const parsed = exactRunDataSchema.safeParse(data)\n if (!parsed.success) {\n const issue = parsed.error.issues[0]\n if (issue?.code === 'unrecognized_keys' && issue.path.join('.') === 'budget') {\n const required =\n isPlainRecord(data.budget) && data.budget.kind === 'weighted'\n ? 'kind, totalUsd, weights'\n : 'kind, totalUsd'\n throw new TypeError(`ExactRegistryRunOpts.budget must contain exactly ${required}`)\n }\n const path = issue?.path.length ? `.${issue.path.join('.')}` : ''\n throw new TypeError(`ExactRegistryRunOpts${path}: ${issue?.message ?? 'is invalid'}`)\n }\n if (\n signal !== null &&\n (!signal ||\n typeof signal !== 'object' ||\n typeof (signal as AbortSignal).addEventListener !== 'function')\n ) {\n throw new TypeError('ExactRegistryRunOpts.signal must be an AbortSignal or null')\n }\n if (costLedger !== null && (!costLedger || typeof costLedger !== 'object')) {\n throw new TypeError('ExactRegistryRunOpts.costLedger must be a CostLedgerHandle or null')\n }\n if (costLedger === null && parsed.data.costLedgerIdentity !== null) {\n throw new TypeError('ExactRegistryRunOpts.costLedgerIdentity must be null without costLedger')\n }\n if (costLedger !== null && parsed.data.costLedgerIdentity === null) {\n throw new TypeError('ExactRegistryRunOpts.costLedgerIdentity is required with costLedger')\n }\n if (costLedger === null && parsed.data.costPhase !== null) {\n throw new TypeError('ExactRegistryRunOpts.costPhase requires a non-null costLedger')\n }\n return Object.freeze({\n ...deepFreezeCanonicalJson(parsed.data),\n signal: signal as AbortSignal | null,\n costLedger: costLedger as CostLedgerHandle | null,\n priorFindings: snapshotExactPriorFindings(priorFindings),\n }) as ExactRegistryRunOpts\n}\n\nfunction snapshotExactPriorFindings(value: unknown): ExactRegistryRunOpts['priorFindings'] {\n if (value === null) return null\n if (Array.isArray(value)) {\n return snapshotAnalystFindings(value, 'ExactRegistryRunOpts.priorFindings')\n }\n if (!isPlainRecord(value)) {\n throw new TypeError(\n 'ExactRegistryRunOpts.priorFindings must be an array, a findings record, or null',\n )\n }\n const result: Record<string, ReadonlyArray<AnalystFinding>> = {}\n for (const [key, findings] of Object.entries(value)) {\n if (!Array.isArray(findings)) {\n throw new TypeError(`ExactRegistryRunOpts.priorFindings.${key} must be an array`)\n }\n result[key] = snapshotAnalystFindings(findings, `ExactRegistryRunOpts.priorFindings.${key}`)\n }\n return deepFreezeCanonicalJson(result)\n}\n\nfunction normalizeExactAnalysts(\n selections: ReadonlyArray<{ readonly registeredId: string; readonly analyst: Analyst }>,\n): ExactCapableAnalyst[] {\n return selections.map(({ registeredId, analyst }) => {\n const exactAnalyst = analyst as Analyst & {\n readonly executionConfig?: Readonly<Record<string, unknown>>\n }\n const id = analyst.id\n const description = analyst.description\n const inputKind = analyst.inputKind\n const rawCostValue = analyst.cost\n const requiresValue = analyst.requires\n const version = analyst.version\n const executionConfigValue = exactAnalyst.executionConfig\n const analyzeValue = analyst.analyze\n if (id !== registeredId) {\n throw new TypeError(\n `AnalystRegistry.runExact: registered analyst \"${registeredId}\" changed id to \"${id}\"`,\n )\n }\n if (executionConfigValue === undefined) {\n throw new TypeError(`AnalystRegistry.runExact: analyst \"${id}\" must declare executionConfig`)\n }\n const executionConfig = canonicalJsonSnapshot(\n executionConfigValue,\n `AnalystRegistry.runExact analyst \"${id}\" executionConfig`,\n )\n if (!isPlainRecord(executionConfig)) {\n throw new TypeError(\n `AnalystRegistry.runExact analyst \"${id}\" executionConfig must be an object`,\n )\n }\n const rawCost = canonicalJsonSnapshot(\n rawCostValue,\n `AnalystRegistry.runExact analyst \"${id}\" cost`,\n )\n const cost =\n rawCost.kind === 'llm'\n ? Object.freeze({\n ...rawCost,\n settlement_timeout_ms: validateUsageSettlementTimeout(rawCost.settlement_timeout_ms),\n })\n : rawCost\n const requires =\n requiresValue === undefined\n ? undefined\n : canonicalJsonSnapshot(\n requiresValue,\n `AnalystRegistry.runExact analyst \"${id}\" requirements`,\n )\n const analyze = analyzeValue.bind(analyst)\n return Object.freeze({\n id,\n description,\n inputKind,\n cost,\n ...(requires === undefined ? {} : { requires }),\n version,\n executionConfig,\n analyze,\n }) satisfies ExactCapableAnalyst\n })\n}\n\nfunction hasRegistryHooks(hooks: AnalystHooks | undefined): hooks is AnalystHooks {\n return Boolean(\n hooks && (hooks.onBeforeAnalyze || hooks.onAfterAnalyze || hooks.onError || hooks.onComplete),\n )\n}\n\nfunction snapshotHooks(hooks: AnalystHooks): AnalystHooks {\n const onBeforeAnalyze = hooks.onBeforeAnalyze\n const onAfterAnalyze = hooks.onAfterAnalyze\n const onError = hooks.onError\n const onComplete = hooks.onComplete\n return Object.freeze({\n ...(onBeforeAnalyze === undefined ? {} : { onBeforeAnalyze: onBeforeAnalyze.bind(hooks) }),\n ...(onAfterAnalyze === undefined ? {} : { onAfterAnalyze: onAfterAnalyze.bind(hooks) }),\n ...(onError === undefined ? {} : { onError: onError.bind(hooks) }),\n ...(onComplete === undefined ? {} : { onComplete: onComplete.bind(hooks) }),\n })\n}\n\nfunction snapshotChat(chat: ChatClient): ChatClient {\n const transport = chat.transport\n const defaultModel = chat.defaultModel\n const maximumAttempts = chat.maximumAttempts\n const call = chat.chat\n return Object.freeze({\n transport,\n ...(defaultModel === undefined ? {} : { defaultModel }),\n ...(maximumAttempts === undefined ? {} : { maximumAttempts }),\n chat: call.bind(chat),\n })\n}\n\nfunction requireExactComponentIdentity(\n value: ExactExecutionComponentIdentity | undefined,\n label: string,\n): ExactExecutionComponentSnapshot {\n if (value === undefined) {\n throw new TypeError(`AnalystRegistry.runExact: ${label} requires a versioned identity`)\n }\n return snapshotExactExecutionComponentIdentity(\n value,\n `AnalystRegistry.runExact ${label} identity`,\n )\n}\n\nfunction exactExecutionSnapshot(\n analysts: readonly ExactCapableAnalyst[],\n opts: ExactRegistryRunOpts,\n allocations: Readonly<Record<string, number | null>>,\n costLedger: ExactExecutionComponentSnapshot | null,\n hooks: ExactExecutionComponentSnapshot | null,\n chat: ExactExecutionComponentSnapshot | null,\n): ExactAnalystExecutionPlanSnapshot {\n const priorFindings = exactPriorFindingsSnapshot(opts.priorFindings)\n const budget =\n opts.budget === null\n ? ({ kind: 'none' } as const)\n : opts.budget.kind === 'equal'\n ? ({\n kind: 'equal',\n total_usd: opts.budget.totalUsd,\n allocations_usd: { ...allocations },\n } as const)\n : ({\n kind: 'weighted',\n total_usd: opts.budget.totalUsd,\n weights: { ...opts.budget.weights },\n allocations_usd: { ...allocations },\n } as const)\n const material = {\n schema_version: '1.0.0' as const,\n analysts: analysts.map((analyst) => ({\n id: analyst.id,\n version: analyst.version,\n input_kind: analyst.inputKind,\n cost: analyst.cost,\n requirements: analyst.requires ?? null,\n execution_config_digest: hashCanonical(analyst.executionConfig),\n })),\n policy: {\n budget,\n total_timeout_ms: opts.totalTimeoutMs,\n signal_provided: opts.signal !== null,\n cost_ledger: costLedger,\n cost_phase: opts.costPhase,\n tags: opts.tags === null ? null : { ...opts.tags },\n prior_findings: priorFindings,\n chain_findings: opts.chainFindings,\n missing_input_mode: opts.missingInputMode,\n registry_hooks: hooks,\n registry_chat: chat,\n },\n }\n return snapshotExactExecutionPlan(\n { ...material, digest: hashCanonical(material) },\n 'AnalystRegistry.runExact execution plan',\n )\n}\n\nfunction exactPriorFindingsSnapshot(\n findings: ExactRegistryRunOpts['priorFindings'],\n): ExactAnalystExecutionPlanSnapshot['policy']['prior_findings'] {\n if (findings === null) return { kind: 'none' }\n if (Array.isArray(findings)) {\n return {\n kind: 'ordered',\n count: findings.length,\n digest: hashCanonical(findings),\n }\n }\n const record = findings as Readonly<Record<string, ReadonlyArray<AnalystFinding>>>\n const keys = Object.keys(record).sort()\n return {\n kind: 'by_analyst',\n keys,\n count: keys.reduce((sum, key) => sum + (record[key]?.length ?? 0), 0),\n digest: hashCanonical(record),\n }\n}\n\nfunction canonicalJsonSnapshot<T>(value: T, label: string): T {\n let snapshot: T\n try {\n snapshot = JSON.parse(canonicalString(value)) as T\n } catch (cause) {\n throw new TypeError(`${label} must be canonical JSON`, { cause })\n }\n return deepFreezeCanonicalJson(snapshot)\n}\n\nfunction snapshotUsageReceiptOnce(\n receipt: AnalystUsageReceipt,\n context: string,\n): AnalystUsageReceipt {\n const data = readOwnFields(receipt, ['calls', 'tokens', 'cost', 'knownCostUsd'], context)\n data.tokens =\n data.tokens === null\n ? null\n : readOwnFields(\n data.tokens,\n ['input', 'output', 'reasoning', 'cached', 'cacheWrite'],\n `${context} tokens`,\n )\n data.cost = readOwnFields(data.cost, ['kind', 'usd'], `${context} cost`)\n const snapshot = canonicalJsonSnapshot(data as unknown as AnalystUsageReceipt, context)\n assertValidAnalystUsageReceipt(snapshot, context)\n return snapshot\n}\n\nfunction readOwnFields(\n value: unknown,\n fields: readonly string[],\n context: string,\n): Record<string, unknown> {\n if (!isPlainRecord(value)) throw new TypeError(`${context} must be a plain object`)\n const unexpected = Object.keys(value).filter((key) => !fields.includes(key))\n if (unexpected.length > 0) {\n throw new TypeError(`${context} contains unknown fields: ${unexpected.sort().join(', ')}`)\n }\n return Object.fromEntries(\n fields.flatMap((field) => (Object.hasOwn(value, field) ? [[field, value[field]]] : [])),\n )\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false\n const prototype = Object.getPrototypeOf(value)\n return prototype === Object.prototype || prototype === null\n}\n\nfunction exactFixedBudgets(\n exact: ExactAnalystBudgetPolicy | null,\n runnable: readonly Analyst[],\n selected: readonly Analyst[],\n): Readonly<Record<string, number | null>> {\n if (exact === null) return {}\n const allocations: Record<string, number | null> = Object.fromEntries(\n selected.map((analyst) => [analyst.id, null]),\n )\n if (runnable.length === 0) return deepFreezeCanonicalJson(allocations)\n if (exact.kind === 'equal') {\n const each = exact.totalUsd / runnable.length\n for (const analyst of runnable) allocations[analyst.id] = each\n return deepFreezeCanonicalJson(allocations)\n }\n const totalWeight = runnable.reduce((sum, analyst) => sum + exact.weights[analyst.id]!, 0)\n if (totalWeight === 0) {\n throw new Error(\n 'ExactRegistryRunOpts weighted budget must allocate positive weight to a runnable analyst',\n )\n }\n for (const analyst of runnable) {\n allocations[analyst.id] = (exact.totalUsd * exact.weights[analyst.id]!) / totalWeight\n }\n return deepFreezeCanonicalJson(allocations)\n}\n\ninterface AnalystExecution {\n readonly summary: AnalystRunSummary\n readonly findings: AnalystFinding[]\n readonly budgetDebitUsd: number\n}\n\nfunction snapshotExecutionFindings(\n findings: AnalystFinding[],\n exact: boolean,\n context: string,\n): AnalystFinding[] {\n return exact ? deepFreezeCanonicalJson(snapshotAnalystFindings(findings, context)) : findings\n}\n\nfunction snapshotAfterHookValues(\n summary: AnalystRunSummary,\n findings: AnalystFinding[],\n exact: boolean,\n): { summary: AnalystRunSummary; findings: AnalystFinding[] } {\n if (!exact) return { summary, findings }\n return {\n summary: canonicalJsonSnapshot(summary, 'AnalystRegistry.runExact onAfterAnalyze summary'),\n findings: deepFreezeCanonicalJson(\n snapshotAnalystFindings(findings, 'AnalystRegistry.runExact onAfterAnalyze findings'),\n ),\n }\n}\n\nfunction exactPlannedAllocation(\n plan: ExactAnalystExecutionPlanSnapshot,\n analystId: string,\n): number | undefined {\n const budget = plan.policy.budget\n if (budget.kind === 'none') return undefined\n const allocated = budget.allocations_usd[analystId]\n return allocated === null ? undefined : allocated\n}\n\nfunction snapshotExecutionEvent<T extends InternalAnalystRunEvent>(event: T, exact: boolean): T {\n return exact ? canonicalJsonSnapshot(event, 'AnalystRegistry.runExact event') : event\n}\n\nfunction logUncapturedBudgetWarning(args: {\n analyst: Analyst\n runId: string\n budgetUsd: number | undefined\n usage: AnalystUsageReceipt\n log: (message: string, fields?: Record<string, unknown>) => void\n}): void {\n if (args.budgetUsd === undefined || args.usage.cost.kind !== 'uncaptured') return\n args.log(`[analyst] WARN ${args.analyst.id} — USD cost uncaptured; budget not reconciled`, {\n runId: args.runId,\n budget_usd: args.budgetUsd,\n cost_captured: false,\n })\n}\n\nfunction validateTimeout(timeoutMs: number | undefined): number | undefined {\n if (timeoutMs === undefined) return undefined\n if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647) {\n throw new TypeError(\n 'RegistryRunOpts.timeoutMs must be a positive safe integer no greater than 2147483647',\n )\n }\n return timeoutMs\n}\n\nasync function waitForOperation<T>(\n operation: Promise<T>,\n signal: AbortSignal | undefined,\n abortGraceMs: number,\n): Promise<T> {\n if (!signal) return operation\n if (signal.aborted) {\n void operation.catch(() => {})\n throw abortReason(signal)\n }\n return new Promise<T>((resolve, reject) => {\n let settlementTimer: ReturnType<typeof setTimeout> | undefined\n const cleanup = (): void => {\n signal.removeEventListener('abort', onAbort)\n if (settlementTimer) clearTimeout(settlementTimer)\n }\n const onAbort = (): void => {\n if (abortGraceMs === 0) {\n cleanup()\n reject(abortReason(signal))\n return\n }\n settlementTimer = setTimeout(() => {\n cleanup()\n reject(abortReason(signal))\n }, abortGraceMs)\n }\n signal.addEventListener('abort', onAbort, { once: true })\n operation.then(\n (value) => {\n cleanup()\n if (signal.aborted) reject(abortReason(signal))\n else resolve(value)\n },\n (error) => {\n cleanup()\n reject(signal.aborted ? abortReason(signal) : error)\n },\n )\n })\n}\n\nasync function waitForHook<T>(\n operation: (() => T | Promise<T>) | undefined,\n signal: AbortSignal | undefined,\n): Promise<T | undefined> {\n if (operation === undefined || signal?.aborted) return undefined\n try {\n return await waitForOperation(\n Promise.resolve().then(() => {\n if (signal?.aborted) throw abortReason(signal)\n return operation()\n }),\n signal,\n 0,\n )\n } catch (error) {\n if (signal?.aborted) return undefined\n throw error\n }\n}\n\nfunction analystAbortGraceMs(analyst: Analyst): number {\n if (analyst.cost.kind === 'deterministic') return 0\n const settlementMs = validateUsageSettlementTimeout(analyst.cost.settlement_timeout_ms)\n if (settlementMs === 0) return 0\n return Math.min(settlementMs + 100, 2_147_483_647)\n}\n\nfunction abortedBeforeStartSummary(\n analyst: Analyst,\n signal: AbortSignal,\n latencyMs = 0,\n): AnalystRunSummary {\n const reason = abortReason(signal)\n return {\n analyst_id: analyst.id,\n status: 'skipped',\n reason: `${reason.name}: ${reason.message}`,\n findings_count: 0,\n latency_ms: latencyMs,\n usage: zeroUsage(),\n }\n}\n\nfunction abortReason(signal: AbortSignal): Error {\n return signal.reason instanceof Error\n ? signal.reason\n : new DOMException('The operation was aborted', 'AbortError')\n}\n\n/**\n * Default budget allocator: prefer the custom `allocate` callback if\n * provided; else weighted split when weights are set; else equal split\n * across `runningCount`. Returns undefined when no totalUsd is known.\n */\nfunction allocateBudget(\n policy: BudgetPolicy | undefined,\n args: {\n analyst: Analyst\n remainingUsd: number | undefined\n runningCount: number\n totalWeight: number | undefined\n },\n): number | undefined {\n if (!policy) return undefined\n if (policy.allocate) {\n const allocated = policy.allocate({\n analyst: args.analyst,\n totalUsd: policy.totalUsd,\n remainingUsd: args.remainingUsd,\n runningCount: args.runningCount,\n })\n if (allocated === undefined) {\n if (policy.totalUsd !== undefined) {\n throw new Error(\n `BudgetPolicy.allocate('${args.analyst.id}') cannot return undefined when totalUsd is set`,\n )\n }\n return undefined\n }\n assertBudgetAmount(allocated, `BudgetPolicy.allocate('${args.analyst.id}')`)\n return args.remainingUsd === undefined ? allocated : Math.min(allocated, args.remainingUsd)\n }\n if (policy.totalUsd == null) return undefined\n const allocated = policy.weights\n ? (policy.totalUsd * analystWeight(policy.weights, args.analyst.id)) / args.totalWeight!\n : policy.totalUsd / Math.max(1, args.runningCount)\n return args.remainingUsd === undefined ? allocated : Math.min(allocated, args.remainingUsd)\n}\n\nfunction validateBudgetPolicy(policy: BudgetPolicy | undefined): void {\n if (!policy) return\n if (policy.totalUsd !== undefined) assertBudgetAmount(policy.totalUsd, 'BudgetPolicy.totalUsd')\n for (const [analystId, weight] of Object.entries(policy.weights ?? {})) {\n assertBudgetAmount(weight, `BudgetPolicy.weights['${analystId}']`)\n }\n}\n\nfunction assertBudgetAmount(value: number, field: string): void {\n if (!Number.isFinite(value) || value < 0) {\n throw new Error(`${field} must be a non-negative finite number`)\n }\n}\n\nfunction validateEffectiveBudget(\n budgetUsd: number | undefined,\n remainingUsd: number | undefined,\n analystId: string,\n): number | undefined {\n if (budgetUsd !== undefined) {\n assertBudgetAmount(budgetUsd, `AnalystContext.budgetUsd for '${analystId}'`)\n }\n if (remainingUsd === undefined) return budgetUsd\n if (budgetUsd === undefined) {\n throw new Error(\n `AnalystContext.budgetUsd for '${analystId}' cannot be removed while an overall budget remains`,\n )\n }\n if (budgetUsd > remainingUsd) {\n throw new Error(\n `AnalystContext.budgetUsd for '${analystId}' (${budgetUsd}) exceeds the remaining overall budget (${remainingUsd})`,\n )\n }\n return budgetUsd\n}\n\nfunction analystWeight(weights: Record<string, number>, analystId: string): number {\n const weight = weights[analystId] ?? 1\n assertBudgetAmount(weight, `BudgetPolicy.weights['${analystId}']`)\n return weight\n}\n\nfunction zeroUsage(): AnalystUsageReceipt {\n return {\n calls: 0,\n tokens: { input: 0, output: 0 },\n cost: { kind: 'observed', usd: 0 },\n }\n}\n\nfunction resolveUsage(\n analyst: Analyst,\n receipts: ReadonlyArray<AnalystUsageReceipt>,\n exact = false,\n): AnalystUsageReceipt {\n if (receipts.length > 0) return mergeUsageReceipts(receipts, exact)\n if (analyst.cost.kind === 'deterministic') return zeroUsage()\n return { calls: null, tokens: null, cost: { kind: 'uncaptured', usd: null } }\n}\n\nfunction mergeUsageReceipts(\n receipts: ReadonlyArray<AnalystUsageReceipt>,\n exact = false,\n): AnalystUsageReceipt {\n const calls = receipts.every((receipt) => receipt.calls !== null)\n ? usageSum(\n receipts.map((receipt) => receipt.calls ?? 0),\n exact,\n 'calls',\n true,\n )\n : null\n const tokens = receipts.every((receipt) => receipt.tokens !== null)\n ? (Object.fromEntries(\n (['input', 'output', 'reasoning', 'cached', 'cacheWrite'] as const).flatMap((field) =>\n field === 'input' ||\n field === 'output' ||\n receipts.some((receipt) => receipt.tokens?.[field] !== undefined)\n ? [\n [\n field,\n usageSum(\n receipts.map((receipt) => receipt.tokens?.[field] ?? 0),\n exact,\n `tokens.${field}`,\n true,\n ),\n ],\n ]\n : [],\n ),\n ) as unknown as RunTokenUsage)\n : null\n const cost = aggregateCostProvenance(\n receipts.map((receipt) => receipt.cost),\n exact,\n )\n return {\n calls,\n tokens,\n cost,\n ...(cost.kind === 'uncaptured'\n ? {\n knownCostUsd: usageSum(receipts.map(knownCostUsd), exact, 'known cost'),\n }\n : {}),\n }\n}\n\nfunction knownCostUsd(receipt: AnalystUsageReceipt): number {\n return receipt.cost.kind === 'uncaptured' ? (receipt.knownCostUsd ?? 0) : receipt.cost.usd\n}\n\nfunction budgetDebit(receipt: AnalystUsageReceipt, allocatedUsd: number | undefined): number {\n const known = knownCostUsd(receipt)\n return receipt.cost.kind === 'uncaptured' && allocatedUsd !== undefined\n ? Math.max(known, allocatedUsd)\n : known\n}\n\nfunction aggregateCostProvenance(\n costs: ReadonlyArray<RunCostProvenance>,\n exact = false,\n): RunCostProvenance {\n if (costs.some((cost) => cost.kind === 'uncaptured')) {\n return { kind: 'uncaptured', usd: null }\n }\n const usd = usageSum(\n costs.map((cost) => cost.usd ?? 0),\n exact,\n 'captured cost',\n )\n return costs.some((cost) => cost.kind === 'estimated')\n ? { kind: 'estimated', usd }\n : { kind: 'observed', usd }\n}\n\nfunction executionCost(\n executions: ReadonlyArray<AnalystExecution>,\n exact: boolean,\n): { known: number; provenance: RunCostProvenance } {\n const usages = executions.map((execution) => execution.summary.usage)\n return {\n known: usageSum(usages.map(knownCostUsd), exact, 'run known cost'),\n provenance: aggregateCostProvenance(\n usages.map((usage) => usage.cost),\n exact,\n ),\n }\n}\n\nfunction usageSum(\n values: readonly number[],\n exact: boolean,\n field: string,\n integer = false,\n): number {\n const sum = values.reduce((total, value) => total + value, 0)\n if (exact && (integer ? !Number.isSafeInteger(sum) : !Number.isFinite(sum))) {\n throw new RangeError(\n `exact analyst usage ${field} aggregate ${integer ? 'exceeds a safe integer' : 'is not finite'}`,\n )\n }\n return sum\n}\n\n/**\n * Resolve the `priorFindings` slice an analyst sees.\n *\n * - Array form → the analyst sees only findings whose `analyst_id`\n * matches its own id, so a kind never reads\n * another kind's history by accident.\n * - Record form → the analyst gets the entry keyed by its id, with\n * the `'*'` wildcard appended (in that order). Use\n * the wildcard when several kinds should see the same\n * historical findings.\n */\nfunction selectPriorFindings(\n source: RegistryRunOpts['priorFindings'],\n analystId: string,\n): ReadonlyArray<AnalystFinding> | undefined {\n if (!source) return undefined\n if (Array.isArray(source)) {\n const own = source.filter((f) => f.analyst_id === analystId)\n return own.length > 0 ? own : undefined\n }\n const record = source as Record<string, ReadonlyArray<AnalystFinding>>\n const own = record[analystId] ?? []\n const wildcard = record['*'] ?? []\n const merged = [...own, ...wildcard]\n return merged.length > 0 ? merged : undefined\n}\n","import { type BehavioralAnalystOptions, behavioralAnalyst } from './behavioral-analyst'\nimport type { TraceAnalysisEngine } from './engine'\nimport { createTraceAnalyst, type TraceAnalystDefinition } from './kind-factory'\nimport { DEFAULT_TRACE_ANALYST_KINDS } from './kinds'\nimport { AnalystRegistry, type AnalystRegistryOptions } from './registry'\n\nexport interface DefaultAnalystRegistryOptions {\n /**\n * Recursive engine for model-backed trace analysts. When omitted, the\n * registry contains only deterministic analysts. The engine's id, version,\n * and model become the exact-run identity of every analyst it executes.\n */\n engine?: TraceAnalysisEngine\n definitions?: readonly TraceAnalystDefinition[]\n /** Set false to omit the deterministic behavioral analyst (default: include). */\n includeBehavioral?: boolean\n behavioral?: BehavioralAnalystOptions\n registry?: AnalystRegistryOptions\n}\n\nexport function buildDefaultAnalystRegistry(\n options: DefaultAnalystRegistryOptions = {},\n): AnalystRegistry {\n if (options.definitions && !options.engine) {\n throw new TypeError(\n 'buildDefaultAnalystRegistry: definitions require an engine — a definition cannot run without one',\n )\n }\n const registry = new AnalystRegistry(options.registry)\n if (options.includeBehavioral !== false) {\n registry.register(behavioralAnalyst(options.behavioral))\n }\n if (options.engine) {\n for (const definition of options.definitions ?? DEFAULT_TRACE_ANALYST_KINDS) {\n registry.register(createTraceAnalyst(definition, { engine: options.engine }))\n }\n }\n return registry\n}\n","/**\n * Provider-neutral chat contract for every model call made by agent-eval.\n *\n * The caller owns model execution. agent-eval issues no provider request and\n * holds no provider credential: `createChatClient` binds a transport the\n * caller supplies, and evaluation code receives canonical requests and results\n * without importing a provider SDK.\n */\n\nimport type { LlmCallRequest, LlmCallResult } from '../llm-client'\n\n/**\n * Unified chat interface using the package's canonical LLM request and result.\n */\nexport interface ChatClient {\n /** Display name of the bound transport, included in telemetry. */\n readonly transport: ChatTransport\n /** Default model when the caller omits one. */\n readonly defaultModel?: string\n /** Total provider attempts this transport can make for one chat call. */\n readonly maximumAttempts?: number\n\n /** Implementations must enforce `req.maxTokens` when it is present. */\n chat(req: ChatRequest, opts?: ChatCallOpts): Promise<ChatResponse>\n}\n\nexport type ChatTransport =\n | 'sandbox-sdk' // box.streamPrompt() — chat completion via sandbox SDK\n | 'custom' // caller-adapted SDK or transport\n | 'mock' // test-time injection\n\nexport interface ChatRequest extends Omit<LlmCallRequest, 'model'> {\n /** Optional — falls back to ChatClient.defaultModel. */\n model?: string\n}\n\nexport type ChatResponse = LlmCallResult\n\nexport interface ChatCallOpts {\n /** Cancel the in-flight request. */\n signal?: AbortSignal\n /** Hard USD ceiling for this single call (informational; the underlying transport may not enforce). */\n maxCostUsd?: number\n /** Correlation tag carried into request headers when the transport allows. */\n correlationId?: string\n /** Stable provider idempotency key for retries/redrives of one paid call. */\n idempotencyKey?: string\n}\n\n// ── Factory ─────────────────────────────────────────────────────────\n\nexport type CreateChatClientOpts = SandboxSdkTransportOpts | CustomTransportOpts | MockTransportOpts\n\ninterface BaseTransportOpts {\n defaultModel?: string\n /** Total provider attempts. Required for opaque transports used in capped runs. */\n maximumAttempts?: number\n}\n\n/**\n * Sandbox-SDK transport. The caller supplies a canonical chat function for an\n * already-configured Sandbox handle, so agent-eval does not import the SDK.\n */\nexport interface SandboxSdkTransportOpts extends BaseTransportOpts {\n transport: 'sandbox-sdk'\n chat: (req: ChatRequest, opts?: ChatCallOpts) => Promise<ChatResponse>\n}\n\n/** Caller-adapted SDK or transport returning the canonical ChatResponse shape. */\nexport interface CustomTransportOpts extends BaseTransportOpts {\n transport: 'custom'\n chat: (req: ChatRequest, opts?: ChatCallOpts) => Promise<ChatResponse>\n}\n\n/**\n * Mock transport for tests. The handler receives the request and returns\n * whatever the test wants. No retries, no JSON-schema degrade.\n */\nexport interface MockTransportOpts extends BaseTransportOpts {\n transport: 'mock'\n handler: (req: ChatRequest, opts?: ChatCallOpts) => Promise<ChatResponse>\n}\n\n/**\n * Build a ChatClient bound to a specific transport. The returned client\n * is safe to share across analysts in a single registry run.\n */\nexport function createChatClient(opts: CreateChatClientOpts): ChatClient {\n switch (opts.transport) {\n case 'sandbox-sdk':\n return {\n transport: 'sandbox-sdk',\n defaultModel: opts.defaultModel,\n maximumAttempts: opts.maximumAttempts,\n chat: async (req, callOpts) => opts.chat(resolveModel(req, opts.defaultModel), callOpts),\n }\n case 'custom':\n return {\n transport: 'custom',\n defaultModel: opts.defaultModel,\n maximumAttempts: opts.maximumAttempts,\n chat: async (req, callOpts) => opts.chat(resolveModel(req, opts.defaultModel), callOpts),\n }\n case 'mock':\n return {\n transport: 'mock',\n defaultModel: opts.defaultModel,\n maximumAttempts: 1,\n chat: async (req, callOpts) => opts.handler(resolveModel(req, opts.defaultModel), callOpts),\n }\n }\n}\n\nfunction resolveModel(req: ChatRequest, defaultModel: string | undefined): ChatRequest {\n if (req.model) return req\n if (!defaultModel) {\n throw new Error(\n 'ChatClient.chat: no model on request and no defaultModel on the client. ' +\n 'Either pass req.model or bind defaultModel at createChatClient().',\n )\n }\n return { ...req, model: defaultModel }\n}\n"],"mappings":";;;;;;;;;;;AAqEA,SAAgB,qBAAqB,SAA+C;CAClF,OAAO,cAAc,uBAAuB,SAAS,iBAAiB,CAAC;AACzE;;AAGA,SAAgB,iBAAiB,KAAyC;CACxE,OAAO,cAAc,mBAAmB,KAAK,aAAa,CAAC;AAC7D;AAEA,SAAgB,mBAAmB,OAAgB,UAAU,eAAiC;CAC5F,MAAM,WAAW,yBAAyB,OAAO,OAAO;CACxD,IAAI,SAAS,mBAAmB,KAAA,GAC9B,OAAO,2BAA2B,UAAU,OAAO;CAErD,IAAI,SAAS,eAAe,KAAA,GAC1B,MAAM,IAAI,UAAU,GAAG,QAAQ,2CAA2C;CAE5E,OAAO;AACT;;AAGA,SAAgB,+BACd,OACA,UAAU,6BACa;CACvB,OAAO,2BAA2B,yBAAyB,OAAO,OAAO,GAAG,OAAO;AACrF;AAEA,SAAS,yBAAyB,OAAgB,SAA0C;CAC1F,IAAI;CACJ,IAAI;EACF,WAAW,KAAK,MAAM,gBAAgB,KAAK,CAAC;CAC9C,SAAS,OAAO;EACd,MAA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MAAM,IAAI,UACR,kGACF;CAEF,MAAM,WAAW,IAAI,gBAAgB,QAAQ,QAAQ;CACrD,IAAI,QAAQ,sBAAsB,OAChC,SAAS,SAAS,kBAAkB,QAAQ,UAAU,CAAC;CAEzD,IAAI,QAAQ,QACV,KAAK,MAAM,cAAc,QAAQ,eAAe,6BAC9C,SAAS,SAAS,mBAAmB,YAAY,EAAE,QAAQ,QAAQ,OAAO,CAAC,CAAC;CAGhF,OAAO;AACT;;;;;;;ACiDA,SAAgB,iBAAiB,MAAwC;CACvE,QAAQ,KAAK,WAAb;EACE,KAAK,eACH,OAAO;GACL,WAAW;GACX,cAAc,KAAK;GACnB,iBAAiB,KAAK;GACtB,MAAM,OAAO,KAAK,aAAa,KAAK,KAAK,aAAa,KAAK,KAAK,YAAY,GAAG,QAAQ;EACzF;EACF,KAAK,UACH,OAAO;GACL,WAAW;GACX,cAAc,KAAK;GACnB,iBAAiB,KAAK;GACtB,MAAM,OAAO,KAAK,aAAa,KAAK,KAAK,aAAa,KAAK,KAAK,YAAY,GAAG,QAAQ;EACzF;EACF,KAAK,QACH,OAAO;GACL,WAAW;GACX,cAAc,KAAK;GACnB,iBAAiB;GACjB,MAAM,OAAO,KAAK,aAAa,KAAK,QAAQ,aAAa,KAAK,KAAK,YAAY,GAAG,QAAQ;EAC5F;CACJ;AACF;AAEA,SAAS,aAAa,KAAkB,cAA+C;CACrF,IAAI,IAAI,OAAO,OAAO;CACtB,IAAI,CAAC,cACH,MAAM,IAAI,MACR,2IAEF;CAEF,OAAO;EAAE,GAAG;EAAK,OAAO;CAAa;AACvC"}
1
+ {"version":3,"file":"chat-client-DEtybj5i.js","names":["ANALYST_ID","ACTOR_PROMPT","ACTOR_PROMPT","ACTOR_PROMPT","ACTOR_PROMPT"],"sources":["../src/feedback-trajectory-review.ts","../src/trace-analyst/behavioral-metrics.ts","../src/analyst/behavioral-analyst.ts","../src/analyst/kinds/control-integrity.ts","../src/analyst/kinds/failure-mode.ts","../src/analyst/kinds/improvement.ts","../src/analyst/kinds/intent-divergence.ts","../src/analyst/kinds/knowledge-gap.ts","../src/analyst/kinds/knowledge-poisoning.ts","../src/analyst/kinds/index.ts","../src/analyst/registry.ts","../src/analyst/default-registry.ts","../src/analyst/chat-client.ts"],"sourcesContent":["import { type ExactAnalystRunResult, snapshotExactExecutionPlan } from './analyst/exact-types'\nimport type {\n AnalystFinding,\n AnalystRunResult,\n AnalystUsageReceipt,\n EvidenceRef,\n} from './analyst/types'\nimport { assertValidAnalystUsageReceipt } from './analyst/usage-receipt'\nimport type { FeedbackLabelSource, FeedbackTrajectory } from './feedback-trajectory'\nimport { canonicalString, hashCanonical } from './ledger-core/canonical'\nimport { deepFreezeCanonicalJson } from './ledger-core/deep-freeze'\n\nexport type AnalystReviewSource = Exclude<FeedbackLabelSource, 'system'>\nexport type AnalystFindingDigest = `sha256:${string}`\nexport type AnalystRunDigest = `sha256:${string}`\n\nexport interface AnalystMissedIssue {\n id: string\n reason: string\n evidence?: EvidenceRef[]\n}\n\ninterface AnalystReviewDecisionBase {\n runDigest: AnalystRunDigest\n source: AnalystReviewSource\n reviewerId: string\n reviewId: string\n reason: string\n decidedAt: string\n}\n\nexport type AnalystReviewDecision =\n | (AnalystReviewDecisionBase & {\n findingId: string\n findingDigest: AnalystFindingDigest\n verdict: 'confirmed' | 'rejected'\n missedIssues?: never\n })\n | (AnalystReviewDecisionBase & {\n verdict: 'completeness_assessed'\n missedIssues: AnalystMissedIssue[]\n findingId?: never\n findingDigest?: never\n })\n\nexport interface AnalystReviewCounts {\n emitted: number\n confirmed: number\n rejected: number\n missed: number\n}\n\nexport interface AnalystReviewQuality {\n precision: number\n recall: number\n f1: number\n counts: AnalystReviewCounts\n}\n\nexport interface StoredAnalystReview {\n runId: string\n runDigest: AnalystRunDigest\n findings: AnalystFinding[]\n findingIds: string[]\n analystIds: string[]\n reviewDecisions: AnalystReviewDecision[]\n}\n\n/** Bind an analyst finding's complete canonical JSON content to a stable digest. */\nexport function analystFindingDigest(finding: AnalystFinding): AnalystFindingDigest {\n return hashCanonical(snapshotAnalystFinding(finding, 'analyst finding'))\n}\n\n/** Bind the complete analyst result to one immutable review target. */\nexport function analystRunDigest(run: AnalystRunResult): AnalystRunDigest {\n return hashCanonical(snapshotAnalystRun(run, 'analyst run'))\n}\n\nexport function snapshotAnalystRun(value: unknown, context = 'analyst run'): AnalystRunResult {\n const snapshot = snapshotAnalystRunRecord(value, context)\n if (snapshot.execution_plan !== undefined) {\n return sealExactAnalystRunReceipt(snapshot, context)\n }\n if (snapshot.completion !== undefined) {\n throw new TypeError(`${context} completion is valid only for an exact run`)\n }\n return snapshot as unknown as AnalystRunResult\n}\n\n/** Canonicalize, validate, and deeply freeze one complete or failed exact-run receipt. */\nexport function snapshotExactAnalystRunReceipt(\n value: unknown,\n context = 'exact analyst run receipt',\n): ExactAnalystRunResult {\n return sealExactAnalystRunReceipt(snapshotAnalystRunRecord(value, context), context)\n}\n\nfunction snapshotAnalystRunRecord(value: unknown, context: string): Record<string, unknown> {\n let snapshot: unknown\n try {\n snapshot = JSON.parse(canonicalString(value)) as unknown\n } catch (cause) {\n throw new TypeError(`${context} must have a canonical JSON representation`, { cause })\n }\n if (!isRecord(snapshot)) throw new TypeError(`${context} must be an object`)\n assertOnlyKeys(\n snapshot,\n [\n 'run_id',\n 'correlation_id',\n 'started_at',\n 'ended_at',\n 'findings',\n 'per_analyst',\n 'total_cost_usd',\n 'total_cost_provenance',\n 'execution_plan',\n 'completion',\n ],\n context,\n )\n requiredString(snapshot.run_id, `${context} run_id`)\n requiredString(snapshot.correlation_id, `${context} correlation_id`)\n canonicalTimestamp(snapshot.started_at, `${context} started_at`)\n canonicalTimestamp(snapshot.ended_at, `${context} ended_at`)\n snapshot.findings = snapshotAnalystFindings(snapshot.findings, `${context} findings`)\n if (!Array.isArray(snapshot.per_analyst)) {\n throw new TypeError(`${context} per_analyst must be an array`)\n }\n for (const [index, summary] of snapshot.per_analyst.entries()) {\n assertAnalystRunSummary(summary, `${context} per_analyst ${index}`)\n }\n if (\n typeof snapshot.total_cost_usd !== 'number' ||\n !Number.isFinite(snapshot.total_cost_usd) ||\n snapshot.total_cost_usd < 0\n ) {\n throw new TypeError(`${context} total_cost_usd must be a finite non-negative number`)\n }\n if (snapshot.total_cost_provenance !== undefined) {\n assertCostProvenance(snapshot.total_cost_provenance, `${context} total_cost_provenance`)\n }\n return snapshot\n}\n\nfunction assertAnalystRunSummary(value: unknown, context: string): void {\n if (!isRecord(value)) throw new TypeError(`${context} must be an object`)\n assertOnlyKeys(\n value,\n [\n 'analyst_id',\n 'status',\n 'reason',\n 'findings_count',\n 'latency_ms',\n 'usage',\n 'allocated_budget_usd',\n 'error',\n ],\n context,\n )\n requiredString(value.analyst_id, `${context} analyst_id`)\n if (value.status !== 'ok' && value.status !== 'skipped' && value.status !== 'failed') {\n throw new TypeError(`${context} status is invalid`)\n }\n if (value.reason !== undefined) requiredString(value.reason, `${context} reason`)\n if (value.status === 'skipped' && value.reason === undefined) {\n throw new TypeError(`${context} skipped summary requires reason`)\n }\n nonnegativeSafeInteger(value.findings_count, `${context} findings_count`)\n finiteNonnegative(value.latency_ms, `${context} latency_ms`)\n assertAnalystUsageReceipt(value.usage, `${context} usage`)\n if (value.allocated_budget_usd !== undefined && value.allocated_budget_usd !== null) {\n finiteNonnegative(value.allocated_budget_usd, `${context} allocated_budget_usd`)\n }\n if (value.error !== undefined) {\n if (value.status !== 'failed' || !isRecord(value.error)) {\n throw new TypeError(`${context} error is valid only for failed summaries`)\n }\n assertOnlyKeys(value.error, ['class', 'message'], `${context} error`)\n requiredString(value.error.class, `${context} error class`)\n requiredString(value.error.message, `${context} error message`)\n } else if (value.status === 'failed') {\n throw new TypeError(`${context} failed summary requires error`)\n }\n}\n\nfunction assertAnalystUsageReceipt(value: unknown, context: string): void {\n if (!isRecord(value)) throw new TypeError(`${context} must be an object`)\n assertOnlyKeys(value, ['calls', 'tokens', 'cost', 'knownCostUsd'], context)\n for (const field of ['calls', 'tokens', 'cost'] as const) {\n if (!Object.hasOwn(value, field)) {\n throw new TypeError(`${context} ${field} is required`)\n }\n }\n if (value.tokens !== null) {\n if (!isRecord(value.tokens)) throw new TypeError(`${context} tokens must be an object or null`)\n assertOnlyKeys(\n value.tokens,\n ['input', 'output', 'reasoning', 'cached', 'cacheWrite'],\n `${context} tokens`,\n )\n }\n assertCostProvenance(value.cost, `${context} cost`)\n assertValidAnalystUsageReceipt(value as unknown as AnalystUsageReceipt, context)\n}\n\nfunction assertCostProvenance(value: unknown, context: string): void {\n if (!isRecord(value)) throw new TypeError(`${context} must be an object`)\n assertOnlyKeys(value, ['kind', 'usd'], context)\n if (value.kind === 'uncaptured') {\n if (value.usd !== null) throw new TypeError(`${context} uncaptured usd must be null`)\n return\n }\n if (value.kind !== 'observed' && value.kind !== 'estimated') {\n throw new TypeError(`${context} kind is invalid`)\n }\n finiteNonnegative(value.usd, `${context} usd`)\n}\n\nfunction sealExactAnalystRunReceipt(\n run: Record<string, unknown>,\n context: string,\n): ExactAnalystRunResult {\n if (run.execution_plan === undefined) {\n throw new TypeError(`${context} exact run requires execution_plan`)\n }\n const plan = snapshotExactExecutionPlan(run.execution_plan, `${context} execution_plan`)\n const completion = snapshotExactRunCompletion(run.completion, `${context} completion`)\n run.execution_plan = plan\n run.completion = completion\n const summaries = run.per_analyst as Array<{\n analyst_id: string\n status: 'ok' | 'skipped' | 'failed'\n findings_count: number\n usage: { cost: { kind: string; usd: number | null }; knownCostUsd?: number }\n allocated_budget_usd?: number | null\n }>\n const findings = run.findings as AnalystFinding[]\n const planned = plan.analysts.map((analyst) => analyst.id)\n const completed = summaries.map((summary) => summary.analyst_id)\n const ordered = completed.every((analystId, index) => analystId === planned[index])\n if (!ordered || (completion.status === 'complete' && completed.length !== planned.length)) {\n throw new TypeError(\n completion.status === 'complete'\n ? `${context} complete receipt must contain every execution_plan analyst in exact order`\n : `${context} failed receipt per_analyst must be an execution_plan prefix`,\n )\n }\n const completedIds = new Set(completed)\n for (const finding of findings) {\n if (!completedIds.has(finding.analyst_id)) {\n throw new TypeError(`${context} finding names an analyst absent from per_analyst`)\n }\n }\n for (const summary of summaries) {\n const actual = findings.filter((finding) => finding.analyst_id === summary.analyst_id).length\n if (summary.findings_count !== actual) {\n throw new TypeError(\n `${context} findings_count does not match findings for \"${summary.analyst_id}\"`,\n )\n }\n const hasAllocation = Object.hasOwn(summary, 'allocated_budget_usd')\n if (summary.status === 'skipped') {\n if (hasAllocation) {\n throw new TypeError(\n `${context} skipped summary \"${summary.analyst_id}\" cannot report an allocated budget`,\n )\n }\n continue\n }\n const allocation = summary.allocated_budget_usd\n const validAllocation =\n hasAllocation &&\n (plan.policy.budget.kind === 'none'\n ? allocation === null\n : typeof allocation === 'number' &&\n plan.policy.budget.allocations_usd[summary.analyst_id] !== null &&\n plan.policy.budget.allocations_usd[summary.analyst_id] !== undefined &&\n allocation <= plan.policy.budget.allocations_usd[summary.analyst_id]!)\n if (!validAllocation) {\n throw new TypeError(\n `${context} summary \"${summary.analyst_id}\" allocation does not match its execution plan`,\n )\n }\n }\n let knownCost = 0\n for (const summary of summaries) {\n const amount =\n summary.usage.cost.kind === 'uncaptured'\n ? (summary.usage.knownCostUsd ?? 0)\n : (summary.usage.cost.usd ?? 0)\n knownCost = finiteNonnegative(knownCost + amount, `${context} aggregate known cost`)\n }\n if (run.total_cost_usd !== knownCost) {\n throw new TypeError(`${context} total_cost_usd does not match per_analyst usage`)\n }\n if (run.total_cost_provenance === undefined) {\n throw new TypeError(`${context} exact run requires total_cost_provenance`)\n }\n const costs = summaries.map((summary) => summary.usage.cost)\n const expectedProvenance = costs.some((cost) => cost.kind === 'uncaptured')\n ? { kind: 'uncaptured', usd: null }\n : {\n kind: costs.some((cost) => cost.kind === 'estimated') ? 'estimated' : 'observed',\n usd: costs.reduce(\n (sum, cost) =>\n finiteNonnegative(sum + (cost.usd ?? 0), `${context} aggregate captured cost`),\n 0,\n ),\n }\n if (hashCanonical(run.total_cost_provenance) !== hashCanonical(expectedProvenance)) {\n throw new TypeError(`${context} total_cost_provenance does not match per_analyst usage`)\n }\n return deepFreezeCanonicalJson(run as unknown as ExactAnalystRunResult)\n}\n\nfunction snapshotExactRunCompletion(\n value: unknown,\n context: string,\n): ExactAnalystRunResult['completion'] {\n if (!isRecord(value)) throw new TypeError(`${context} must be an object`)\n if (value.status === 'complete') {\n assertOnlyKeys(value, ['status'], context)\n return value as ExactAnalystRunResult['completion']\n }\n if (value.status !== 'failed') {\n throw new TypeError(`${context} status must be complete or failed`)\n }\n assertOnlyKeys(value, ['status', 'error'], context)\n if (!isRecord(value.error)) throw new TypeError(`${context} failed receipt requires error`)\n assertOnlyKeys(value.error, ['class', 'message'], `${context} error`)\n requiredString(value.error.class, `${context} error class`)\n requiredString(value.error.message, `${context} error message`)\n return value as unknown as ExactAnalystRunResult['completion']\n}\n\nfunction finiteNonnegative(value: unknown, context: string): number {\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {\n throw new TypeError(`${context} must be a non-negative finite number`)\n }\n return value\n}\n\nfunction nonnegativeSafeInteger(value: unknown, context: string): number {\n if (!Number.isSafeInteger(value) || (value as number) < 0) {\n throw new TypeError(`${context} must be a non-negative safe integer`)\n }\n return value as number\n}\n\nexport function snapshotAnalystFindings(\n value: unknown,\n context = 'analyst run findings',\n): AnalystFinding[] {\n if (!Array.isArray(value)) {\n throw new TypeError(`${context} must be an array`)\n }\n const findings = value.map((finding, index) =>\n snapshotAnalystFinding(finding, `${context} finding ${index}`),\n )\n assertUniqueFindingIds(findings.map((finding) => finding.finding_id))\n return findings\n}\n\nexport function readAnalystReview(trajectory: FeedbackTrajectory): StoredAnalystReview | undefined {\n const analystAttempts = trajectory.attempts.filter(\n (attempt) => isRecord(attempt.artifact) && attempt.artifact.type === 'analyst-run',\n )\n const analysis = isRecord(trajectory.metadata?.analysis)\n ? trajectory.metadata.analysis\n : undefined\n if (analystAttempts.length === 0) {\n if (analysis?.kind === 'analyst-run') {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: analyst trajectory \"${trajectory.id}\" is missing its archived run`,\n )\n }\n return undefined\n }\n if (analystAttempts.length !== 1) {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: analyst trajectory \"${trajectory.id}\" must contain exactly one archived run`,\n )\n }\n if (analysis?.kind !== 'analyst-run') {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: analyst trajectory \"${trajectory.id}\" is missing review state`,\n )\n }\n\n const artifact = analystAttempts[0]!.artifact\n if (!isRecord(artifact)) {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: analyst trajectory \"${trajectory.id}\" has an invalid archived run`,\n )\n }\n const runId = requiredString(\n artifact.analystRunId,\n `analyst trajectory \"${trajectory.id}\" run id`,\n )\n if (analysis.runId !== runId) {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: analyst trajectory \"${trajectory.id}\" run identity does not match its review state`,\n )\n }\n const artifactRunDigest = requiredDigest(\n artifact.runDigest,\n `analyst trajectory \"${trajectory.id}\" archived run digest`,\n )\n const storedRunDigest = requiredDigest(\n analysis.runDigest,\n `analyst trajectory \"${trajectory.id}\" review run digest`,\n )\n if (artifactRunDigest !== storedRunDigest) {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: analyst trajectory \"${trajectory.id}\" run digest does not match its review state`,\n )\n }\n const findings = snapshotAnalystFindings(\n artifact.findings,\n `analyst trajectory \"${trajectory.id}\"`,\n )\n const findingIds = findings.map((finding) => finding.finding_id)\n const analystIds = stringArray(\n artifact.analystIds,\n `analyst trajectory \"${trajectory.id}\" analyst ids`,\n )\n const attemptMetadata = analystAttempts[0]!.metadata\n if (!isRecord(attemptMetadata)) {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: analyst trajectory \"${trajectory.id}\" is missing archived run metadata`,\n )\n }\n const archivedRun = snapshotAnalystRun(\n {\n run_id: runId,\n correlation_id: artifact.correlationId,\n started_at: analysis.startedAt,\n ended_at: analysis.endedAt,\n findings,\n per_analyst: attemptMetadata.perAnalyst,\n total_cost_usd: analysis.knownCostUsd,\n ...(analysis.costProvenance === undefined\n ? {}\n : { total_cost_provenance: analysis.costProvenance }),\n ...(artifact.executionPlan === undefined\n ? {}\n : {\n execution_plan: artifact.executionPlan,\n completion: artifact.completion,\n }),\n },\n `analyst trajectory \"${trajectory.id}\" archived run`,\n )\n const knownAnalystIds = new Set(analystIds)\n for (const [index, finding] of findings.entries()) {\n if (!knownAnalystIds.has(finding.analyst_id)) {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: analyst trajectory \"${trajectory.id}\" omits generating analyst \"${finding.analyst_id}\" at finding ${index}`,\n )\n }\n }\n const reviewDecisions = validateAnalystReviewDecisions({\n runId,\n runDigest: storedRunDigest,\n findings,\n analystIds,\n decisions: analysis.reviewDecisions,\n requireComplete: true,\n })\n const expectedRunDigest = analystRunDigest(archivedRun)\n if (storedRunDigest !== expectedRunDigest) {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: analyst trajectory \"${trajectory.id}\" archived run digest mismatch`,\n )\n }\n return {\n runId,\n runDigest: expectedRunDigest,\n findings,\n findingIds,\n analystIds,\n reviewDecisions,\n }\n}\n\nexport function completedAnalystReviewQuality(review: StoredAnalystReview): AnalystReviewQuality {\n const findingDecisions = review.reviewDecisions.filter(\n (decision): decision is Extract<AnalystReviewDecision, { verdict: 'confirmed' | 'rejected' }> =>\n decision.verdict !== 'completeness_assessed',\n )\n const completeness = review.reviewDecisions.filter(\n (decision): decision is Extract<AnalystReviewDecision, { verdict: 'completeness_assessed' }> =>\n decision.verdict === 'completeness_assessed',\n )\n if (completeness.length !== 1) {\n throw new TypeError(\n 'feedbackTrajectoryToOptimizerRow: analyst run requires exactly one independent completeness_assessed decision',\n )\n }\n\n const confirmed = findingDecisions.filter((decision) => decision.verdict === 'confirmed').length\n const rejected = findingDecisions.length - confirmed\n const emitted = review.findingIds.length\n const missed = completeness[0]!.missedIssues.length\n const precision = emitted === 0 ? 1 : confirmed / emitted\n const recallDenominator = confirmed + missed\n const recall = recallDenominator === 0 ? 1 : confirmed / recallDenominator\n const f1 = precision + recall === 0 ? 0 : (2 * precision * recall) / (precision + recall)\n return {\n precision,\n recall,\n f1,\n counts: { emitted, confirmed, rejected, missed },\n }\n}\n\nexport function validateAnalystReviewDecisions(input: {\n runId: string\n runDigest: AnalystRunDigest\n findings: readonly AnalystFinding[]\n analystIds: readonly string[]\n decisions: unknown\n requireComplete?: boolean\n}): AnalystReviewDecision[] {\n if (!Array.isArray(input.decisions)) {\n throw new TypeError('analyst review decisions must be an array')\n }\n const findings = snapshotAnalystFindings(input.findings)\n const expectedRunDigest = requiredDigest(input.runDigest, 'analyst review run digest')\n const findingsById = new Map(findings.map((finding) => [finding.finding_id, finding]))\n const generatingAnalystIds = new Set(input.analystIds)\n const seenFindingIds = new Set<string>()\n let completenessCount = 0\n\n const decisions = input.decisions.map((value, index): AnalystReviewDecision => {\n if (!isRecord(value)) {\n throw new TypeError(`analyst review decision ${index} must be an object`)\n }\n const source = requiredString(value.source, `analyst review decision ${index} source`)\n if (!isAnalystReviewSource(source)) {\n throw new TypeError(\n `analyst review decision ${index} source must be user, judge, environment, metric, or policy`,\n )\n }\n const reviewerId = requiredString(\n value.reviewerId,\n `analyst review decision ${index} reviewerId`,\n )\n if (generatingAnalystIds.has(reviewerId)) {\n throw new TypeError(\n `analyst review decision ${index} reviewerId must differ from the generating analyst`,\n )\n }\n const reviewId = requiredString(value.reviewId, `analyst review decision ${index} reviewId`)\n if (reviewId === input.runId) {\n throw new TypeError(\n `analyst review decision ${index} reviewId must identify an independent review`,\n )\n }\n const reason = requiredString(value.reason, `analyst review decision ${index} reason`)\n const decidedAt = canonicalTimestamp(\n value.decidedAt,\n `analyst review decision ${index} decidedAt`,\n )\n const runDigest = requiredDigest(value.runDigest, `analyst review decision ${index} runDigest`)\n if (runDigest !== expectedRunDigest) {\n throw new TypeError(`analyst review decision ${index} run digest mismatch`)\n }\n\n if (value.verdict === 'completeness_assessed') {\n assertOnlyKeys(\n value,\n [\n 'runDigest',\n 'verdict',\n 'missedIssues',\n 'source',\n 'reviewerId',\n 'reviewId',\n 'reason',\n 'decidedAt',\n ],\n `analyst review decision ${index}`,\n )\n completenessCount += 1\n if (completenessCount > 1) {\n throw new TypeError('duplicate completeness_assessed analyst review decision')\n }\n return {\n runDigest,\n verdict: 'completeness_assessed',\n missedIssues: validateMissedIssues(\n value.missedIssues,\n findingsById,\n `analyst review decision ${index}`,\n ),\n source,\n reviewerId,\n reviewId,\n reason,\n decidedAt,\n }\n }\n\n if (value.verdict !== 'confirmed' && value.verdict !== 'rejected') {\n throw new TypeError(\n `analyst review decision ${index} verdict must be confirmed, rejected, or completeness_assessed`,\n )\n }\n assertOnlyKeys(\n value,\n [\n 'runDigest',\n 'findingId',\n 'findingDigest',\n 'verdict',\n 'source',\n 'reviewerId',\n 'reviewId',\n 'reason',\n 'decidedAt',\n ],\n `analyst review decision ${index}`,\n )\n const findingId = requiredString(value.findingId, `analyst review decision ${index} findingId`)\n const finding = findingsById.get(findingId)\n if (!finding) {\n throw new TypeError(`analyst review decision references unknown finding id \"${findingId}\"`)\n }\n if (seenFindingIds.has(findingId)) {\n throw new TypeError(`duplicate analyst review decision for finding id \"${findingId}\"`)\n }\n seenFindingIds.add(findingId)\n const findingDigest = requiredString(\n value.findingDigest,\n `analyst review decision ${index} findingDigest`,\n )\n const expectedDigest = analystFindingDigest(finding)\n if (findingDigest !== expectedDigest) {\n throw new TypeError(\n `analyst review decision ${index} digest mismatch for finding id \"${findingId}\"`,\n )\n }\n return {\n runDigest,\n findingId,\n findingDigest: expectedDigest,\n verdict: value.verdict,\n source,\n reviewerId,\n reviewId,\n reason,\n decidedAt,\n }\n })\n\n if (input.requireComplete) {\n const missing = findings\n .map((finding) => finding.finding_id)\n .filter((findingId) => !seenFindingIds.has(findingId))\n if (missing.length > 0) {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: missing independent decisions for finding ids: ${missing.join(', ')}`,\n )\n }\n if (completenessCount !== 1) {\n throw new TypeError(\n 'feedbackTrajectoryToOptimizerRow: analyst run requires exactly one independent completeness_assessed decision',\n )\n }\n }\n return decisions\n}\n\nexport function assertUniqueFindingIds(findingIds: readonly string[]): void {\n const seen = new Set<string>()\n for (const findingId of findingIds) {\n if (findingId.trim().length === 0) throw new TypeError('analyst finding id must not be empty')\n if (seen.has(findingId)) {\n throw new TypeError(`analyst run contains duplicate finding id \"${findingId}\"`)\n }\n seen.add(findingId)\n }\n}\n\nfunction snapshotAnalystFinding(value: unknown, context: string): AnalystFinding {\n let snapshot: unknown\n try {\n snapshot = JSON.parse(canonicalString(value)) as unknown\n } catch (cause) {\n throw new TypeError(`${context} must have a canonical JSON representation`, { cause })\n }\n assertAnalystFinding(snapshot, context)\n return snapshot\n}\n\nfunction assertAnalystFinding(value: unknown, context: string): asserts value is AnalystFinding {\n if (!isRecord(value)) throw new TypeError(`${context} must be an object`)\n assertOnlyKeys(\n value,\n [\n 'schema_version',\n 'finding_id',\n 'analyst_id',\n 'produced_at',\n 'severity',\n 'area',\n 'claim',\n 'rationale',\n 'evidence_refs',\n 'recommended_action',\n 'validation_plan',\n 'confidence',\n 'subject',\n 'derived_from_judge',\n 'metadata',\n ],\n context,\n )\n if (value.schema_version !== '1.0.0') {\n throw new TypeError(`${context} schema_version must be \"1.0.0\"`)\n }\n requiredString(value.finding_id, `${context} finding_id`)\n requiredString(value.analyst_id, `${context} analyst_id`)\n canonicalTimestamp(value.produced_at, `${context} produced_at`)\n if (\n value.severity !== 'critical' &&\n value.severity !== 'high' &&\n value.severity !== 'medium' &&\n value.severity !== 'low' &&\n value.severity !== 'info'\n ) {\n throw new TypeError(`${context} severity is invalid`)\n }\n requiredString(value.area, `${context} area`)\n requiredString(value.claim, `${context} claim`)\n optionalString(value.rationale, `${context} rationale`)\n value.evidence_refs = validateEvidenceRefs(value.evidence_refs, `${context} evidence_refs`)\n optionalString(value.recommended_action, `${context} recommended_action`)\n optionalString(value.validation_plan, `${context} validation_plan`)\n if (\n typeof value.confidence !== 'number' ||\n !Number.isFinite(value.confidence) ||\n value.confidence < 0 ||\n value.confidence > 1\n ) {\n throw new TypeError(`${context} confidence must be a finite number from 0 through 1`)\n }\n optionalString(value.subject, `${context} subject`)\n if (value.derived_from_judge !== undefined && typeof value.derived_from_judge !== 'boolean') {\n throw new TypeError(`${context} derived_from_judge must be a boolean`)\n }\n if (value.metadata !== undefined && !isRecord(value.metadata)) {\n throw new TypeError(`${context} metadata must be an object`)\n }\n}\n\nfunction validateMissedIssues(\n value: unknown,\n findingsById: ReadonlyMap<string, AnalystFinding>,\n context: string,\n): AnalystMissedIssue[] {\n if (!Array.isArray(value)) {\n throw new TypeError(`${context} missedIssues must be an array`)\n }\n const seen = new Set<string>()\n return value.map((issue, index) => {\n const issueContext = `${context} missedIssues ${index}`\n if (!isRecord(issue)) throw new TypeError(`${issueContext} must be an object`)\n assertOnlyKeys(issue, ['id', 'reason', 'evidence'], issueContext)\n const id = requiredString(issue.id, `${issueContext} id`)\n if (findingsById.has(id)) {\n throw new TypeError(`${issueContext} id \"${id}\" is already an emitted finding id`)\n }\n if (seen.has(id)) {\n throw new TypeError(`duplicate missed issue id \"${id}\"`)\n }\n seen.add(id)\n const reason = requiredString(issue.reason, `${issueContext} reason`)\n return {\n id,\n reason,\n ...(issue.evidence === undefined\n ? {}\n : { evidence: validateEvidenceRefs(issue.evidence, `${issueContext} evidence`) }),\n }\n })\n}\n\nfunction validateEvidenceRefs(value: unknown, context: string): EvidenceRef[] {\n if (!Array.isArray(value)) throw new TypeError(`${context} must be an array`)\n return value.map((evidence, index) => {\n const evidenceContext = `${context} ${index}`\n if (!isRecord(evidence)) throw new TypeError(`${evidenceContext} must be an object`)\n assertOnlyKeys(evidence, ['kind', 'uri', 'excerpt'], evidenceContext)\n if (\n evidence.kind !== 'span' &&\n evidence.kind !== 'event' &&\n evidence.kind !== 'artifact' &&\n evidence.kind !== 'finding' &&\n evidence.kind !== 'metric'\n ) {\n throw new TypeError(`${evidenceContext} kind is invalid`)\n }\n const uri = requiredString(evidence.uri, `${evidenceContext} uri`)\n const excerpt = evidence.excerpt\n optionalString(excerpt, `${evidenceContext} excerpt`)\n return {\n kind: evidence.kind,\n uri,\n ...(excerpt === undefined ? {} : { excerpt: excerpt as string }),\n }\n })\n}\n\nfunction assertOnlyKeys(\n value: Record<string, unknown>,\n allowed: readonly string[],\n name: string,\n): void {\n const allowedKeys = new Set(allowed)\n const unexpected = Object.keys(value).filter((key) => !allowedKeys.has(key))\n if (unexpected.length > 0) {\n throw new TypeError(`${name} contains unknown fields: ${unexpected.sort().join(', ')}`)\n }\n}\n\nfunction stringArray(value: unknown, name: string): string[] {\n if (!Array.isArray(value) || value.some((item) => typeof item !== 'string')) {\n throw new TypeError(`${name} must be an array of strings`)\n }\n const strings = value.map((item) => requiredString(item, name))\n if (new Set(strings).size !== strings.length) {\n throw new TypeError(`${name} must contain unique values`)\n }\n return strings\n}\n\nfunction requiredString(value: unknown, name: string): string {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new TypeError(`${name} must be a non-empty string`)\n }\n return value\n}\n\nfunction requiredDigest(value: unknown, name: string): AnalystRunDigest {\n const digest = requiredString(value, name)\n if (!/^sha256:[a-f0-9]{64}$/.test(digest)) {\n throw new TypeError(`${name} must be a sha256 digest`)\n }\n return digest as AnalystRunDigest\n}\n\nfunction optionalString(value: unknown, name: string): void {\n if (value !== undefined && typeof value !== 'string') {\n throw new TypeError(`${name} must be a string`)\n }\n}\n\nfunction canonicalTimestamp(value: unknown, name: string): string {\n const timestamp = requiredString(value, name)\n const parsed = new Date(timestamp)\n if (Number.isNaN(parsed.valueOf()) || parsed.toISOString() !== timestamp) {\n throw new TypeError(`${name} must be a canonical ISO 8601 UTC timestamp`)\n }\n return timestamp\n}\n\nfunction isAnalystReviewSource(value: string): value is AnalystReviewSource {\n return (\n value === 'user' ||\n value === 'judge' ||\n value === 'environment' ||\n value === 'metric' ||\n value === 'policy'\n )\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n","/**\n * Deterministic behavioral metrics over OTLP spans — pure arithmetic, no LLM.\n *\n * It computes token growth, output decay, tool monoculture, and missing\n * self-verification once in TypeScript with no model judgment.\n *\n * General, not trace-specific: the detectors key off token trajectories and\n * tool usage present in any agentic OTLP trace, not any one benchmark.\n */\n\nimport { LLM_CONTEXT_TOKENS } from '../trace/attribute-vocabulary'\nimport { executionTrackByLane } from '../trace/execution-tracks'\nimport {\n LLM_INPUT_TOKEN_ATTR_KEYS,\n LLM_OUTPUT_TOKEN_ATTR_KEYS,\n TOOL_NAME_ATTR_KEYS,\n} from '../trace/otlp-attributes'\nimport { spanEpochMillis } from './otlp-span'\nimport type { TraceAnalystSpan } from './types'\n\nexport type SuboptimalCode =\n | 'monotonic-input-growth'\n | 'output-length-decay'\n | 'single-tool-dependency'\n | 'no-self-verification'\n\nexport interface SuboptimalSignal {\n code: SuboptimalCode\n severity: 'high' | 'medium' | 'low'\n /** Human-readable claim, with the backing numbers inlined. */\n detail: string\n /** The exact figures the detector fired on — auditable, no model in the loop. */\n evidence: Record<string, number | string | boolean>\n}\n\nexport interface BehavioralMetrics {\n /** The only trace represented by these metrics; null when spans are empty. */\n traceId: string | null\n llmCallCount: number\n /** Causally serial LLM timelines. Parallel branches are never joined. */\n tokenSequences: BehavioralTokenSequence[]\n /** Token values from the longest serial timeline, retained for convenience. */\n inputTokenTrajectory: number[]\n outputTokenTrajectory: number[]\n toolHistogram: Record<string, number>\n totalToolCalls: number\n distinctTools: number\n /** distinct/total tool calls; 1.0 when there are no tool calls. */\n toolDiversityRatio: number\n hasSelfVerification: boolean\n signals: SuboptimalSignal[]\n}\n\nexport interface BehavioralTokenSequence {\n scopeId: string\n spanIds: string[]\n inputTokenTrajectory: Array<number | null>\n outputTokenTrajectory: Array<number | null>\n}\n\ninterface TokenSample {\n span: TraceAnalystSpan\n input: number | null\n output: number | null\n step: number | null\n}\n\n/** ≥ this input-token growth ratio across a run, with no compression, fires. */\nconst INPUT_GROWTH_FACTOR = 3\n/** Tool-usage signals need at least this many calls to be meaningful. */\nconst MIN_TOOL_CALLS = 3\n/**\n * Serial calls required before a strictly-decreasing output run counts as decay.\n *\n * A run of n independent lengths is strictly decreasing by chance with\n * probability 1/n!, so the old minimum of 3 fired on roughly one sequence in\n * six. The paired `inputIsMonotonic && inputGrew` guard does not offset that:\n * context accumulates by construction in a serial agent loop, so input growth\n * is very nearly free evidence. At 5 calls chance alone accounts for under 1%,\n * which is the bar a signal reported at full confidence has to clear.\n */\nconst OUTPUT_DECAY_MINIMUM_CALLS = 5\n/**\n * The last output must fall to at most this fraction of the first.\n *\n * Length wanders between turns for reasons that are not degradation, so\n * direction alone is not a finding — an observed 784 → 646 run (18%) was\n * reported as decay and was noise. Requiring the response to lose most of its\n * length keeps the signal on the failure it names: late steps that quietly\n * stop doing the work.\n */\nconst OUTPUT_DECAY_MAXIMUM_RETAINED_FRACTION = 0.6\n/** Tool names that read or check state count as self-verification, not mutation.\n * Covers the inspect verbs plus the read/search tools real harnesses use to\n * verify (Claude Code Read/Grep/Glob, codex read_file/ls/cat, git status/diff,\n * test/lint). A pure shell tool (Bash/exec_command) is intentionally NOT matched\n * — its name can't tell a `pytest` from an `rm`. */\nconst VERIFY_RE =\n /verif|eval|inspect|check|assert|validat|review|confirm|read|grep|glob|search|view|\\blist\\b|\\bls\\b|\\bcat\\b|\\bfind\\b|diff|status|\\btest|lint|typecheck/i\n\nfunction num(v: unknown): number | null {\n return typeof v === 'number' && Number.isFinite(v) ? v : null\n}\nfunction numAttr(attrs: Record<string, unknown>, keys: readonly string[]): number | null {\n for (const key of keys) {\n const value = num(attrs[key])\n if (value !== null) return value\n }\n return null\n}\nfunction inputTokensOf(s: TraceAnalystSpan): number | null {\n const exactContext = num(s.attributes[LLM_CONTEXT_TOKENS])\n if (exactContext !== null) return exactContext\n // Foreign producers disagree on whether prompt includes cached tokens.\n // Without an exact total, retain the reported prompt instead of guessing.\n return (\n numAttr(s.attributes, LLM_INPUT_TOKEN_ATTR_KEYS) ?? num(s.attributes['llm.usage.input_tokens'])\n )\n}\nfunction outputTokensOf(s: TraceAnalystSpan): number | null {\n return (\n numAttr(s.attributes, LLM_OUTPUT_TOKEN_ATTR_KEYS) ??\n num(s.attributes['llm.usage.output_tokens'])\n )\n}\nfunction stepOf(s: TraceAnalystSpan): number | null {\n return num(s.attributes.step)\n}\nfunction toolNameOf(s: TraceAnalystSpan): string | null {\n if (s.tool_name) return s.tool_name\n for (const key of TOOL_NAME_ATTR_KEYS) {\n const t = s.attributes[key]\n if (typeof t === 'string' && t.length > 0) return t\n }\n return null\n}\n\n/**\n * Reduce a span list to behavioral metrics + fired suboptimality signals.\n * Pure + deterministic: same spans → same output, on any machine, no model.\n */\nexport function computeTraceMetrics(spans: readonly TraceAnalystSpan[]): BehavioralMetrics {\n const traceIds = new Set(spans.map((span) => span.trace_id))\n if (traceIds.size > 1) {\n throw new Error(\n `computeTraceMetrics: expected spans from one trace, received ${traceIds.size} traces`,\n )\n }\n const traceId = traceIds.values().next().value ?? null\n\n const samples: TokenSample[] = spans.map((span) => ({\n span,\n input: inputTokensOf(span),\n output: outputTokensOf(span),\n step: stepOf(span),\n }))\n const llmSamples = samples.filter((sample) => sample.span.kind === 'LLM')\n const tokenSamples =\n llmSamples.length > 0\n ? llmSamples\n : samples.filter((sample) => sample.input !== null || sample.output !== null)\n const tokenSequences = buildTokenSequences(tokenSamples, spans)\n const primarySequence = tokenSequences[0]\n const inputTokenTrajectory =\n primarySequence?.inputTokenTrajectory.filter((value): value is number => value !== null) ?? []\n const outputTokenTrajectory =\n primarySequence?.outputTokenTrajectory.filter((value): value is number => value !== null) ?? []\n const toolHistogram: Record<string, number> = {}\n let hasSelfVerification = false\n\n for (const s of spans) {\n const tool = toolNameOf(s)\n if (tool) {\n toolHistogram[tool] = (toolHistogram[tool] ?? 0) + 1\n if (VERIFY_RE.test(tool)) hasSelfVerification = true\n }\n }\n\n const totalToolCalls = Object.values(toolHistogram).reduce((a, b) => a + b, 0)\n const distinctTools = Object.keys(toolHistogram).length\n const toolDiversityRatio = totalToolCalls === 0 ? 1 : distinctTools / totalToolCalls\n\n const signals: SuboptimalSignal[] = []\n const seenTokenSignals = new Set<SuboptimalCode>()\n for (const sequence of tokenSequences) {\n for (const signal of tokenSignals(sequence)) {\n if (seenTokenSignals.has(signal.code)) continue\n seenTokenSignals.add(signal.code)\n signals.push(signal)\n }\n }\n\n if (totalToolCalls >= MIN_TOOL_CALLS && distinctTools === 1) {\n const only = Object.keys(toolHistogram)[0]!\n signals.push({\n code: 'single-tool-dependency',\n severity: 'medium',\n detail: `All ${totalToolCalls} observed tool calls are \\`${only}\\`; no alternate tool call was observed.`,\n evidence: { tool: only, calls: totalToolCalls, distinct_tools: 1 },\n })\n }\n\n if (totalToolCalls >= MIN_TOOL_CALLS && !hasSelfVerification) {\n signals.push({\n code: 'no-self-verification',\n severity: 'medium',\n detail: `${totalToolCalls} tool calls were observed without a verification-named tool call.`,\n evidence: { tool_calls: totalToolCalls, verification_calls: 0 },\n })\n }\n\n return {\n traceId,\n llmCallCount: tokenSamples.length,\n tokenSequences,\n inputTokenTrajectory,\n outputTokenTrajectory,\n toolHistogram,\n totalToolCalls,\n distinctTools,\n toolDiversityRatio,\n hasSelfVerification,\n signals,\n }\n}\n\nfunction buildTokenSequences(\n samples: readonly TokenSample[],\n spans: readonly TraceAnalystSpan[],\n): BehavioralTokenSequence[] {\n const spansById = new Map(spans.map((span) => [span.span_id, span]))\n const executionScopeFor = createTokenExecutionScopeResolver(spansById)\n const scopedSamples = samples.map((sample) => ({\n sample,\n ...executionScopeFor(sample.span),\n }))\n const trackByLane = executionTrackByLane(scopedSamples)\n const byTrack = new Map<string, { scopeId: string; samples: TokenSample[] }>()\n for (const scoped of scopedSamples) {\n const trackId = trackByLane.get(scoped.key)!\n const track = byTrack.get(trackId) ?? { scopeId: scoped.scopeId, samples: [] }\n track.samples.push(scoped.sample)\n byTrack.set(trackId, track)\n }\n\n const sequences: BehavioralTokenSequence[] = []\n for (const { scopeId, samples: tracked } of byTrack.values()) {\n const runs = serialTokenRuns([...tracked].sort(compareTokenSamples))\n runs.forEach((run, index) => {\n sequences.push({\n scopeId: runs.length === 1 ? scopeId : `${scopeId}#${index + 1}`,\n spanIds: run.map((sample) => sample.span.span_id),\n inputTokenTrajectory: run.map((sample) => sample.input),\n outputTokenTrajectory: run.map((sample) => sample.output),\n })\n })\n }\n\n return sequences.sort(\n (a, b) =>\n b.spanIds.length - a.spanIds.length ||\n a.scopeId.localeCompare(b.scopeId) ||\n a.spanIds[0]!.localeCompare(b.spanIds[0]!),\n )\n}\n\ninterface AncestorScope {\n agentId: string | null\n rootId: string | null\n missingParentId: string | null\n laneSpanId: string | null\n}\n\nfunction createTokenExecutionScopeResolver(spansById: ReadonlyMap<string, TraceAnalystSpan>): (\n span: TraceAnalystSpan,\n) => {\n key: string\n scopeKey: string\n scopeId: string\n start: number | null\n end: number | null\n} {\n const cache = new Map<string, AncestorScope>()\n return (span) => {\n const ancestry = resolveAncestorScope(span.parent_span_id, spansById, cache)\n const rootId = ancestry.rootId\n const scopeId = ancestry.agentId\n ? `span:${ancestry.agentId}`\n : ancestry.missingParentId\n ? `parent:${ancestry.missingParentId}`\n : rootId\n ? `root:${rootId}`\n : span.agent_name\n ? `agent:${span.agent_name}`\n : `trace:${span.trace_id}`\n const scopeSpanId = ancestry.agentId ?? ancestry.missingParentId ?? rootId\n const laneSpan = ancestry.laneSpanId ? spansById.get(ancestry.laneSpanId) : undefined\n const direct = scopeSpanId === null || ancestry.laneSpanId === scopeSpanId\n const timedSpan = direct ? span : laneSpan\n return {\n key: JSON.stringify([scopeId, direct ? span.span_id : ancestry.laneSpanId]),\n scopeKey: scopeId,\n scopeId,\n start: timedSpan ? spanEpochMillis(timedSpan.start_time) : null,\n end: timedSpan ? spanEpochMillis(timedSpan.end_time) : null,\n }\n }\n}\n\nfunction resolveAncestorScope(\n startId: string | null,\n spansById: ReadonlyMap<string, TraceAnalystSpan>,\n cache: Map<string, AncestorScope>,\n): AncestorScope {\n const empty: AncestorScope = {\n agentId: null,\n rootId: null,\n missingParentId: null,\n laneSpanId: null,\n }\n if (!startId) return empty\n\n const path: string[] = []\n const pathIndex = new Map<string, number>()\n let currentId: string | null = startId\n let resolved = empty\n while (currentId) {\n const cached = cache.get(currentId)\n if (cached) {\n resolved = cached\n break\n }\n const cycleStart = pathIndex.get(currentId)\n if (cycleStart !== undefined) {\n resolved = {\n agentId: null,\n rootId: [...path.slice(cycleStart)].sort()[0]!,\n missingParentId: null,\n laneSpanId: [...path.slice(cycleStart)].sort()[0]!,\n }\n break\n }\n const current = spansById.get(currentId)\n if (!current) {\n resolved = {\n agentId: null,\n rootId: null,\n missingParentId: currentId,\n laneSpanId: currentId,\n }\n break\n }\n if (current.kind === 'AGENT') {\n resolved = {\n agentId: current.span_id,\n rootId: null,\n missingParentId: null,\n laneSpanId: current.span_id,\n }\n break\n }\n pathIndex.set(currentId, path.length)\n path.push(currentId)\n currentId = current.parent_span_id\n }\n\n for (let index = path.length - 1; index >= 0; index -= 1) {\n if (resolved.agentId === null && resolved.rootId === null) {\n resolved = { ...resolved, rootId: path[index]!, laneSpanId: path[index]! }\n } else if (\n resolved.laneSpanId === (resolved.agentId ?? resolved.missingParentId ?? resolved.rootId)\n ) {\n resolved = { ...resolved, laneSpanId: path[index]! }\n }\n cache.set(path[index]!, resolved)\n }\n return resolved\n}\n\nfunction compareTokenSamples(a: TokenSample, b: TokenSample): number {\n const aStart = spanEpochMillis(a.span.start_time)\n const bStart = spanEpochMillis(b.span.start_time)\n if (aStart === null && bStart !== null) return 1\n if (aStart !== null && bStart === null) return -1\n if (aStart !== null && bStart !== null && aStart !== bStart) return aStart - bStart\n if (a.step !== null && b.step !== null && a.step !== b.step) return a.step - b.step\n return a.span.span_id.localeCompare(b.span.span_id)\n}\n\nfunction serialTokenRuns(ordered: readonly TokenSample[]): TokenSample[][] {\n const runs: TokenSample[][] = []\n let serial: TokenSample[] = []\n let overlap: TokenSample[] = []\n let overlapEnd = Number.NEGATIVE_INFINITY\n\n const flushSerial = () => {\n if (serial.length > 0) runs.push(serial)\n serial = []\n }\n const flushOverlap = () => {\n if (overlap.length === 1) {\n serial.push(overlap[0]!)\n } else if (overlap.length > 1) {\n flushSerial()\n for (const sample of overlap) runs.push([sample])\n }\n overlap = []\n overlapEnd = Number.NEGATIVE_INFINITY\n }\n\n for (const sample of ordered) {\n const start = spanEpochMillis(sample.span.start_time)\n const end = spanEpochMillis(sample.span.end_time)\n if (start === null || end === null || sample.span.duration_ms <= 0 || end < start) {\n flushOverlap()\n flushSerial()\n runs.push([sample])\n continue\n }\n if (overlap.length > 0 && start >= overlapEnd) flushOverlap()\n overlap.push(sample)\n overlapEnd = Math.max(overlapEnd, end)\n }\n flushOverlap()\n flushSerial()\n return runs\n}\n\nfunction tokenSignals(sequence: BehavioralTokenSequence): SuboptimalSignal[] {\n const signals: SuboptimalSignal[] = []\n const inputs = sequence.inputTokenTrajectory\n const outputs = sequence.outputTokenTrajectory\n if (inputs.length >= 3 && inputs.every((value): value is number => value !== null)) {\n const first = inputs[0]!\n const last = inputs[inputs.length - 1]!\n const isMonotonic = everyAdjacent(inputs, (previous, current) => current >= previous)\n const growthFromZero = first === 0 && last > 0\n const growth = growthFromZero ? Infinity : first > 0 ? last / first : 0\n if (isMonotonic && last > first && growth >= INPUT_GROWTH_FACTOR) {\n const growthLabel = growthFromZero ? '0→nonzero (unbounded)' : `${growth.toFixed(1)}x`\n signals.push({\n code: 'monotonic-input-growth',\n severity: 'high',\n detail: `LLM input tokens grew ${growthLabel} (${first}→${last}) across ${inputs.length} serial calls without an intervening decrease.`,\n evidence: {\n first,\n last,\n growth_x: growthFromZero ? 'unbounded' : Number(growth.toFixed(2)),\n calls: inputs.length,\n scope: sequence.scopeId,\n first_span_id: sequence.spanIds[0]!,\n last_span_id: sequence.spanIds[sequence.spanIds.length - 1]!,\n },\n })\n }\n }\n\n if (\n inputs.length >= OUTPUT_DECAY_MINIMUM_CALLS &&\n inputs.length === outputs.length &&\n inputs.every((value): value is number => value !== null) &&\n outputs.every((value): value is number => value !== null)\n ) {\n const first = outputs[0]!\n const last = outputs[outputs.length - 1]!\n const inputIsMonotonic = everyAdjacent(inputs, (previous, current) => current >= previous)\n const outputIsMonotonic = everyAdjacent(outputs, (previous, current) => current <= previous)\n const inputGrew = inputs[inputs.length - 1]! > inputs[0]!\n const decayIsMaterial = last <= first * OUTPUT_DECAY_MAXIMUM_RETAINED_FRACTION\n if (inputIsMonotonic && inputGrew && outputIsMonotonic && decayIsMaterial) {\n signals.push({\n code: 'output-length-decay',\n severity: 'medium',\n detail: `LLM output tokens shrank ${first}→${last} over ${outputs.length} serial calls while input tokens increased monotonically.`,\n evidence: {\n first,\n last,\n calls: outputs.length,\n scope: sequence.scopeId,\n first_span_id: sequence.spanIds[0]!,\n last_span_id: sequence.spanIds[sequence.spanIds.length - 1]!,\n },\n })\n }\n }\n return signals\n}\n\nfunction everyAdjacent(\n values: readonly number[],\n predicate: (previous: number, current: number) => boolean,\n): boolean {\n return values.slice(1).every((current, index) => predicate(values[index]!, current))\n}\n","/**\n * Deterministic behavioral analysis over arithmetic in trace spans.\n * This pass is cheap and repeatable; semantic analysis remains the job of\n * model-backed analysts. Relative quality requires a labeled comparison.\n */\n\nimport {\n type BehavioralMetrics,\n computeTraceMetrics,\n type SuboptimalCode,\n} from '../trace-analyst/behavioral-metrics'\nimport type { TraceAnalysisStore } from '../trace-analyst/store'\nimport type { ExactCapableAnalyst } from './exact-types'\nimport { type AnalystFinding, makeFinding } from './types'\n\nconst RECOMMENDED_ACTION: Record<SuboptimalCode, string> = {\n 'monotonic-input-growth':\n 'Inspect context assembly; if prior history is repeatedly included, summarize completed work before the next model call.',\n 'output-length-decay':\n 'Check late-step completeness; if shorter responses omit required work, add explicit completion criteria to the agent instructions.',\n 'single-tool-dependency':\n 'Test whether an inspect or verification tool improves outcomes after the repeated call fails or returns no progress.',\n 'no-self-verification':\n 'After state-changing actions, require an observable check before the agent proceeds.',\n}\n\nconst ANALYST_ID = 'efficiency-behavioral'\nconst DEFAULT_MAX_TRACES = 1_000\nconst DEFAULT_MAX_EVIDENCE_REFS = 20\nconst TRACE_PAGE_SIZE = 200\n\nexport interface BehavioralAnalystOptions {\n /** Refuse larger unfiltered datasets instead of sampling them silently. Default 1,000. */\n maxTraces?: number\n /** Evidence locations retained per finding. Counts still cover every analyzed trace. Default 20. */\n maxEvidenceRefsPerFinding?: number\n}\n\nconst AGGREGATE_CLAIM: Record<SuboptimalCode, (observed: number, analyzed: number) => string> = {\n 'monotonic-input-growth': (observed, analyzed) =>\n `${observed}/${analyzed} analyzed traces showed input tokens grow from zero to nonzero or to at least 3x their initial value across at least 3 serial model calls without a decrease.`,\n 'output-length-decay': (observed, analyzed) =>\n `${observed}/${analyzed} analyzed traces showed output tokens decrease while input tokens increased monotonically across at least 3 serial model calls.`,\n 'single-tool-dependency': (observed, analyzed) =>\n `${observed}/${analyzed} analyzed traces used only one named tool across at least 3 tool calls.`,\n 'no-self-verification': (observed, analyzed) =>\n `${observed}/${analyzed} analyzed traces had at least 3 tool calls without a verification-named tool call.`,\n}\n\nasync function listTraceIds(\n store: TraceAnalysisStore,\n maxTraces: number,\n signal?: AbortSignal,\n): Promise<string[]> {\n const traceIds = new Set<string>()\n let offset = 0\n let expectedTotal: number | undefined\n\n while (true) {\n signal?.throwIfAborted()\n const page = await store.queryTraces({ limit: TRACE_PAGE_SIZE, offset })\n if (expectedTotal === undefined) expectedTotal = page.total\n if (page.total !== expectedTotal) {\n throw new Error(\n `behavioralAnalyst: trace count changed during pagination (${expectedTotal} to ${page.total})`,\n )\n }\n if (page.total > maxTraces) {\n throw new RangeError(\n `behavioralAnalyst: ${page.total} traces exceed maxTraces=${maxTraces}; filter the store or raise the explicit limit`,\n )\n }\n for (const trace of page.traces) traceIds.add(trace.trace_id)\n if (traceIds.size > maxTraces) {\n throw new RangeError(\n `behavioralAnalyst: more than maxTraces=${maxTraces} unique traces were returned`,\n )\n }\n if (!page.has_more) break\n if (page.traces.length === 0) {\n throw new Error('behavioralAnalyst: trace store returned an empty page with has_more=true')\n }\n offset += page.traces.length\n }\n\n if (traceIds.size !== expectedTotal) {\n throw new Error(\n `behavioralAnalyst: pagination returned ${traceIds.size}/${expectedTotal ?? 0} unique traces`,\n )\n }\n\n return [...traceIds].sort()\n}\n\n/**\n * Map computed signals → structured AnalystFindings. Pure: no LLM, no clock\n * dependence beyond `produced_at` (overridable for deterministic tests).\n */\nexport function deriveEfficiencyFindings(\n metrics: BehavioralMetrics,\n opts: { analystId?: string; producedAt?: string } = {},\n): AnalystFinding[] {\n const analystId = opts.analystId ?? ANALYST_ID\n const traceId = metrics.traceId\n return metrics.signals.map((sig) =>\n makeFinding({\n analyst_id: analystId,\n area: 'efficiency',\n subject: sig.code,\n claim: sig.detail,\n severity: sig.severity,\n // Deterministic arithmetic over spans, not a model judgment → certain.\n confidence: 1,\n evidence_refs: [\n {\n kind: 'metric',\n uri: traceId\n ? `metric://trace/${encodeURIComponent(traceId)}/efficiency/${sig.code}`\n : `metric://efficiency/${sig.code}`,\n excerpt: JSON.stringify(sig.evidence),\n },\n ],\n recommended_action: RECOMMENDED_ACTION[sig.code],\n metadata: {\n deterministic: true,\n evidence: sig.evidence,\n ...(traceId ? { trace_id: traceId } : {}),\n },\n id_basis: sig.code,\n ...(opts.producedAt ? { produced_at: opts.producedAt } : {}),\n }),\n )\n}\n\n/** The deterministic behavioral/efficiency analyst (no LLM, any-model). */\nexport function behavioralAnalyst(\n options: BehavioralAnalystOptions = {},\n): ExactCapableAnalyst<TraceAnalysisStore> {\n const maxTraces = positiveInteger(options.maxTraces ?? DEFAULT_MAX_TRACES, 'maxTraces')\n const maxEvidenceRefsPerFinding = positiveInteger(\n options.maxEvidenceRefsPerFinding ?? DEFAULT_MAX_EVIDENCE_REFS,\n 'maxEvidenceRefsPerFinding',\n )\n return {\n id: ANALYST_ID,\n description:\n 'Deterministic behavioral/efficiency findings over OTLP spans — token-growth, output-decay, tool-monoculture, missing self-verification. Zero LLM; model-agnostic by construction.',\n inputKind: 'trace-store',\n cost: { kind: 'deterministic' },\n version: '2.0.0',\n executionConfig: {\n kind: 'behavioral-efficiency',\n max_traces: maxTraces,\n max_evidence_refs_per_finding: maxEvidenceRefsPerFinding,\n },\n async analyze(store, context) {\n const analyzedTraceIds = await listTraceIds(store, maxTraces, context.signal)\n const findingsById = new Map<\n string,\n {\n finding: AnalystFinding\n observedTraceCount: number\n evidenceTraceIds: string[]\n evidence: AnalystFinding['evidence_refs']\n }\n >()\n for (const traceId of analyzedTraceIds) {\n context.signal?.throwIfAborted()\n const viewed = await store.viewTrace({ trace_id: traceId })\n if (viewed.trace_id !== traceId) {\n throw new Error(\n `behavioralAnalyst: requested trace '${traceId}', received '${viewed.trace_id}'`,\n )\n }\n if (!viewed.spans) {\n throw new Error(\n `behavioralAnalyst: trace '${traceId}' is oversized; complete spans are required`,\n )\n }\n const metrics = computeTraceMetrics(viewed.spans)\n if (metrics.traceId !== null && metrics.traceId !== traceId) {\n throw new Error(\n `behavioralAnalyst: requested trace '${traceId}', received '${metrics.traceId}'`,\n )\n }\n for (const finding of deriveEfficiencyFindings(metrics)) {\n const current = findingsById.get(finding.finding_id)\n if (!current) {\n findingsById.set(finding.finding_id, {\n finding,\n observedTraceCount: 1,\n evidenceTraceIds: [traceId],\n evidence: [...finding.evidence_refs],\n })\n continue\n }\n current.observedTraceCount += 1\n if (current.evidence.length < maxEvidenceRefsPerFinding) {\n current.evidenceTraceIds.push(traceId)\n current.evidence.push(...finding.evidence_refs)\n }\n }\n }\n return [...findingsById.values()].map(\n ({ finding, observedTraceCount, evidenceTraceIds, evidence }) => ({\n ...finding,\n claim: AGGREGATE_CLAIM[finding.subject as SuboptimalCode](\n observedTraceCount,\n analyzedTraceIds.length,\n ),\n rationale: `${observedTraceCount}/${analyzedTraceIds.length} analyzed traces exhibited this pattern.`,\n evidence_refs: evidence,\n metadata: {\n deterministic: true,\n evidence_trace_ids: evidenceTraceIds,\n omitted_evidence_trace_count: observedTraceCount - evidenceTraceIds.length,\n observed_trace_count: observedTraceCount,\n analyzed_trace_count: analyzedTraceIds.length,\n },\n }),\n )\n },\n }\n}\n\nfunction positiveInteger(value: number, name: string): number {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new RangeError(`behavioralAnalyst: ${name} must be a positive safe integer`)\n }\n return value\n}\n","import {\n analyzeSupervisorRunIntegrity,\n type SupervisorRunIntegrityEvidence,\n} from '../../supervisor-run/integrity'\nimport type { SupervisorRunSources, SupervisorRunTree } from '../../supervisor-run/types'\nimport type { ExactCapableAnalyst } from '../exact-types'\nimport { type AnalystContext, type AnalystFinding, type EvidenceRef, makeFinding } from '../types'\n\nconst ANALYST_ID = 'control-integrity'\n\nfunction shown(value: unknown): string {\n if (value === undefined) return '<absent>'\n const encoded = JSON.stringify(value)\n return encoded === undefined ? String(value) : encoded\n}\n\nfunction evidenceRef(namespace: string, value: SupervisorRunIntegrityEvidence): EvidenceRef {\n return {\n kind: 'metric',\n uri: `supervisor-run://${encodeURIComponent(namespace)}/${value.path}`,\n excerpt: shown(value.value),\n }\n}\n\n/** Translate typed supervisor-run integrity issues into the shared analyst envelope. */\nexport function emitControlIntegrityFindings(\n input: SupervisorRunSources | SupervisorRunTree,\n producedAt: string,\n): AnalystFinding[] {\n const report = analyzeSupervisorRunIntegrity(input, { capturedAt: producedAt })\n return report.issues.map((issue) =>\n makeFinding({\n analyst_id: ANALYST_ID,\n produced_at: producedAt,\n area: issue.area,\n severity: issue.severity,\n subject: `${report.runRef}/${issue.subject}`,\n claim: issue.claim,\n rationale: issue.detail,\n evidence_refs: issue.evidence.map((value) => evidenceRef(report.runRef, value)),\n recommended_action: issue.recommendedAction,\n validation_plan:\n 'Re-run this deterministic analyst on the retained SupervisorRunSources or SupervisorRunTree after correcting the producer.',\n confidence: 1,\n metadata: {\n integrity_code: issue.code,\n integrity_input: report.input,\n integrity_run_ref: report.runRef,\n integrity_subject: issue.subject,\n ...issue.metadata,\n },\n }),\n )\n}\n\n/** Deterministic Analyst adapter for `SupervisorRunSources | SupervisorRunTree`. */\nexport class ControlIntegrityAnalyst\n implements ExactCapableAnalyst<SupervisorRunSources | SupervisorRunTree>\n{\n readonly id = ANALYST_ID\n readonly description =\n 'Deterministic supervisor-run integrity checks with explicit unavailable evidence.'\n readonly inputKind = 'custom' as const\n readonly cost = { kind: 'deterministic' as const, est_usd_per_run: 0 }\n readonly version = '2.0.0'\n readonly executionConfig = {\n kind: 'control-integrity',\n produced_at_source: 'tags.producedAt-or-system-clock',\n } as const\n\n async analyze(\n input: SupervisorRunSources | SupervisorRunTree,\n ctx: AnalystContext,\n ): Promise<AnalystFinding[]> {\n const producedAt = ctx.tags?.producedAt ?? new Date().toISOString()\n const findings = emitControlIntegrityFindings(input, producedAt)\n ctx.log?.(`control-integrity: ${findings.length} finding(s)`, {\n input: 'nodes' in input ? 'SupervisorRunTree' : 'SupervisorRunSources',\n })\n return findings\n }\n}\n\nexport const CONTROL_INTEGRITY_ANALYST = new ControlIntegrityAnalyst()\n","/**\n * Failure-mode analyst — prices each failure by the work it burned.\n *\n * Brief: for every failure worth reporting, find the span where it\n * started, find the span where the agent resumed productive work, and\n * report the distance between them as the cost. Severity follows that\n * measured cost. Frequency does not set severity.\n *\n * Why the reframe: counting is already free. `getDatasetOverview`\n * returns `errors.trace_count`, `errors.span_count`, and an\n * `error_clusters[]` array carrying each signature's tool, trace and\n * span counts, prevalence, and exemplar ids — deterministically, before\n * a single model call. The 1.x prompt spent a recursive investigation\n * re-deriving exactly that and answered with \"Bash tool calls are the\n * dominant failure surface (54 error spans across 47 distinct\n * signatures)\" and \"79/5260 tool calls ended in errors\". Both numbers\n * were true, both were already on the overview, and neither told an\n * operator which failure to fix first.\n *\n * What is NOT free is attributing waste. An error the agent shrugged\n * off on the next span cost approximately nothing. An error that sent\n * it down a wrong path for twenty spans, or that ended with a human\n * typing the correction, cost real wall-clock and real tokens. Only a\n * reader that follows the trace forward from the error to the point of\n * resumption can measure that, and that walk is what the model is paid\n * for here.\n *\n * The bounding pair is enforced structurally rather than by prompt\n * alone: `minimumEvidenceCitations: 2` rejects any finding that cannot\n * cite both the error span and the span that closed it, so an\n * unmeasured cost claim cannot reach the registry.\n *\n * Eight bounded model subqueries let the actor adjudicate the one\n * genuine judgement call — is a given post-error span real progress or\n * more flailing? — over excerpts it has already loaded.\n */\n\nimport { findingSubjectGrammarPromptFor } from '../finding-subject'\nimport type { TraceAnalystDefinition } from '../kind-factory'\n\nconst subjectGrammar = findingSubjectGrammarPromptFor('failure-mode')\n\nconst ACTOR_PROMPT = `You are a failure-cost analyst for an OTLP trace dataset. Your job is to find the failures that **burned the most agent work** and to price each one in spans, model calls, and wall-clock. How often an error occurred is not its cost and is not your output.\n\n${subjectGrammar}\n\nUse a lowercase cluster label that names the cost shape, not the error string: \"human-corrected-file-overwrite\", \"unrecovered-auth-loop\", \"long-detour-schema-guess\".\n\nWORKLIST → RECOVERY BOUNDARY → PRICE → CITE protocol:\n\n1. \\`getDatasetOverview({})\\` first. Read \\`errors.trace_count\\`, \\`errors.span_count\\`, and \\`error_clusters[]\\` — each cluster carries \\`signature\\`, \\`tool_name\\`, \\`trace_count\\`, \\`span_count\\`, \\`prevalence\\`, \\`exemplar_trace_ids\\`, and \\`exemplar_span_ids\\`. This is the deterministic analyzer's output, already computed for free. It is your WORKLIST: the exemplar ids name the spans you go price. It is never your findings.\n2. Reach error-bearing traces the exemplars miss with \\`queryTraces(filters={\"has_errors\": true}, limit=...)\\`. Prefer long traces and traces whose errors sit early: a failure has room to be expensive only when work followed it.\n3. Take one candidate error span E and read its trace in order. \\`viewTrace\\` returns that trace's spans sorted by \\`start_time\\`, which is the ordering every distance below is counted in. When \\`viewTrace\\` returns \\`oversized\\` instead of spans, locate candidates with \\`searchTrace\\` and pull the exact ids with \\`viewSpans\\`; use \\`searchSpan\\` when one span's payload is truncated.\n4. Find the RECOVERY BOUNDARY R — the first span after E in which the agent resumed productive work. Productive means a different, task-advancing action. A retry of the same call with the same arguments, a re-read of the same file, a re-plan of the same step, and an apology are all still inside the failure. Then price it:\n - spans_burned: spans strictly between E and R\n - model_calls_burned: how many of those spans have kind \\`LLM\\`\n - wall_clock_ms: R \\`end_time\\` minus E \\`start_time\\`\n Report all three. If the agent never resumed, R is the trace's last span and the failure is UNRECOVERED.\n5. Set severity from what ENDED the failure and from the measured distance, never from how many times the signature appears:\n - HUMAN-CORRECTED — a human turn after E supplies the correction. This is the most expensive class at any span count, because the failure escaped the agent entirely and reached the user: severity critical. Detect it as a new user-role message in a later \\`LLM\\` span's input attributes, or a new root-level \\`AGENT\\` span in which the user restates or repairs the task. Search with patterns like \\`\"role\"\\\\s*:\\\\s*\"user\"\\`, \\`(that|this) is (wrong|not what)\\`, \\`I (said|asked|told you)\\`, \\`stop\\`, \\`undo\\`, \\`revert\\`, \\`you (deleted|broke|missed|ignored)\\`, \\`try again\\`. Quote the human's words exactly.\n - UNRECOVERED — the trace ends without resumption: severity critical.\n - LONG DETOUR — 10 or more spans burned, or 3 or more \\`LLM\\` spans burned: severity high.\n - SHORT DETOUR — 2 to 9 spans burned: severity medium.\n - SELF-RECOVERED ON THE NEXT SPAN — cost is approximately zero. Do not emit it. That is resilience, and reporting it dilutes the ranking.\n One error that cost 20 spans outranks 50 errors that each cost one retry. Frequency may appear in a finding only as a multiplier on a measured per-instance cost, never as the reason for its severity.\n6. **Cluster, do not enumerate.** Errors sharing a root cause AND a recovery shape are ONE finding: report the summed cost across instances, state how many instances it covers, and cite the bounding pair of the single most expensive instance. Two errors with the same signature but different recovery shapes — one shrugged off, one human-corrected — are NOT the same finding; the expensive one is the finding and the cheap one is noise.\n\nFORBIDDEN OUTPUT. Each of the following duplicates the deterministic pass, and a duplicate finding is worse than no finding because it costs a reviewer the same attention while carrying no new information:\n - a count of errors by tool (\"Bash is the dominant failure surface, 54 error spans\")\n - a count or inventory of error signatures (\"47 distinct error signatures\")\n - an error rate (\"79 of 5260 tool calls ended in errors\")\n - any restatement of \\`prevalence\\`, \\`trace_count\\`, or \\`span_count\\` from \\`error_clusters[]\\`\nEvery finding MUST state its measured cost — spans burned, model calls burned, wall-clock — in the claim, and MUST cite the two spans that bound it: the error span and the recovery span, or the escaping human turn, or the trace's last span when unrecovered. A failure you cannot bound with two spans is one you did not measure: drop it.\n\n**Adjudicate boundaries with subqueries.** The single judgement call in this protocol is whether a post-error span is genuine resumption or more flailing. Load E, the spans between, and the candidate R, then send one bounded \\`llm_query\\` per candidate carrying those exact excerpts and asking which span first advances the task. Subqueries cannot call trace tools, so a trace id tells them nothing — paste the excerpts. Accept a boundary only when the excerpts you loaded support the answer.\n\nConfidence 0.9+ when both bounding spans are quoted and the spans between them were counted directly; 0.6-0.8 when an oversized trace forced you to sample the interval and the distance is an estimate; below 0.5 does not belong in this analyst, because an unmeasurable cost is not a finding. Keep the recommended action a short imperative; the improvement analyst expands it.\n\nIf every error in this dataset was recovered on the next span, return an empty findings array. That is the correct answer for a dataset whose failures were all cheap. Do not backfill it with the counts listed above and do not pad it with speculation.`\n\nexport const FAILURE_MODE_KIND_SPEC: TraceAnalystDefinition = {\n id: 'failure-mode',\n description:\n 'Ranks failures by the work each one burned — spans, model calls, and wall-clock between the error and the span where the agent resumed — and treats a failure that reached a human as the most expensive class.',\n area: 'failure-mode',\n version: '2.0.0',\n instructions: ACTOR_PROMPT,\n toolGroup: 'all',\n // Pricing one failure costs a bounded trace read plus a span-pair read,\n // where counting cost a single overview call; the read budget is sized for\n // that walk, not for the recount it replaces.\n limits: { maxLlmCalls: 8, maxIterations: 24, maxToolCalls: 80 },\n // The error span and the span that closed it. A cost claim that cannot cite\n // both was never measured.\n minimumEvidenceCitations: 2,\n}\n","/**\n * Improvement analyst — actionable self-improvement findings.\n *\n * Brief: read findings from upstream analysts (failure-mode,\n * knowledge-gap, knowledge-poisoning) AND the trace dataset itself,\n * then propose **concrete edits** to the agent's runtime: prompt\n * additions, RAG documents to ingest, tool descriptions to rewrite,\n * scaffolding changes to make, memory entries to invalidate. Each\n * finding is one proposed edit with the locus, the diff, and the\n * expected effect.\n *\n * This is the self-improvement loop's last mile: the prior\n * kinds describe *what's wrong*; this kind describes *what to change*.\n *\n * Eight bounded model subqueries let the actor compare competing fix\n * directions over the same cited evidence before recommending one.\n */\n\nimport { findingSubjectGrammarPromptFor } from '../finding-subject'\nimport type { TraceAnalystDefinition } from '../kind-factory'\n\nconst subjectGrammar = findingSubjectGrammarPromptFor('improvement')\n\nconst ACTOR_PROMPT = `You are a self-improvement analyst. Your job is to propose **concrete, locus-named edits** the agent's runtime should adopt to fix the failure modes, knowledge gaps, and poisonings present in this dataset.\n\nUpstream analysts have already classified the problems. Your job is to convert each problem into a *change to make* and grade its expected leverage. Each finding is one proposed edit.\n\n${subjectGrammar}\n\nDISCOVERY → CANDIDATE-FIXES → COMPETE → CITE protocol:\n\n1. \\`getDatasetOverview({})\\` first. Note the agents, tools, and any system-prompt fingerprints (look for the prompt text echoed in early spans).\n2. For each high-severity failure pattern, generate 2-3 candidate fixes. Real candidate axes:\n - **System-prompt edit** — add an instruction, remove a misleading one, restructure precedence\n - **Tool description edit** — rewrite a tool's description so the agent picks it correctly / passes valid args\n - **New tool** — add a tool the agent kept emulating in code\n - **RAG ingestion** — add a document or correct a stale one\n - **Memory invalidation** — clear cached prior-run decisions that no longer apply\n - **Scaffolding** — add a precondition check, a retry policy, a turn budget, a verification step\n - **Output schema** — narrow the agent's output to forbid the failure shape\n - **Skill / MCP / hook / subagent** — change the reusable profile component responsible for the behavior\n - **Workflow / rollout policy** — change orchestration, budget, sampling, or stopping behavior\n - **Code** — change an implementation path when profile edits cannot repair the behavior\n3. **Compare candidate fixes with bounded subqueries.** Load the representative failure excerpts, then send one \\`llm_query\\` per candidate-fix axis the same evidence. Ask for likely effect, side effects, and implementation scope. Subqueries cannot call trace tools; trace ids alone are insufficient context.\n4. After the comparisons return, **pick the winning candidate per cluster** based on expected effect and risk, then emit ONE finding. Keep the alternatives and rejection reasons in the rationale so the recommendation is auditable.\n5. **Cross-reference upstream findings.** Cite prior failure-mode or knowledge-gap findings as \\`finding://<prior-finding-id>\\`. This builds the dependency graph that lets the dashboard show \"fix #X resolves failure modes A, B, C.\"\n\nFor each winning recommendation, emit ONE finding. Use one exact locus from the subject grammar and state the edit in one sentence. Match leverage to the source failure's severity; use medium for quality-of-life changes and info for cleanup with no behavioral effect. Cite the targeted \\`finding://<id>\\` when available and the most representative span when useful. Quote the problem being fixed. Use confidence 0.85+ for a mechanical fix to a well-evidenced failure, 0.6-0.8 when judgment is required, and <0.5 for speculation. Explain in at most two sentences why this candidate beat its alternatives. The recommended action must be the literal diff, quoted replacement, tool description, or setting change.\n\nIf no upstream failure findings exist in this run, derive your own from the trace dataset using the failure-mode protocol inline (\\`searchTrace\\` for STATUS_CODE_ERROR / MaxTurnsExceeded / etc.). Prefer upstream findings when present because the analysts are designed to chain.\n\nDo NOT propose a fix you cannot defend with evidence. \"Tighten the prompt\" is not a finding; \"Add 'When the user asks for X, always Y' to the system prompt section \"request-classification\"\" is.`\n\nexport const IMPROVEMENT_KIND_SPEC: TraceAnalystDefinition = {\n id: 'improvement',\n description:\n 'Converts upstream failure / gap / poisoning findings into concrete locus-named edits (prompt, tool-doc, RAG, scaffolding) with leverage grades.',\n area: 'improvement',\n version: '1.2.0',\n instructions: ACTOR_PROMPT,\n toolGroup: 'all',\n limits: {\n maxLlmCalls: 8,\n maxIterations: 30,\n maxToolCalls: 80,\n maxOutputChars: 12_000,\n },\n}\n","/**\n * Intent-divergence analyst — was the agent doing what the user asked,\n * and how early was the drift knowable?\n *\n * Brief: unlike every other kind, this one has free ground truth sitting\n * in the trace. A corrective human turn (\"no, I meant…\", \"stop doing X\",\n * \"why are you still asking\") is an *observed, labelled* divergence\n * event — the user themself marked the moment the agent was off target.\n * The analyst takes that label and works BACKWARD to the earliest\n * assistant turn where the divergence was already detectable, names the\n * signal in the user's stated intent that turn contradicted, and counts\n * the turns burned in between.\n *\n * \"The user corrected the agent\" is counting, and the deterministic\n * behavioral pass already counts it. The finding this kind owes is the\n * backward-looking one: at turn N the agent did X against stated intent\n * Y, the user corrected at turn N+K, so K turns were burned. A finding\n * with no earliest-detectable turn and no burned-turn count carries no\n * cost estimate and no place to put the fix, so it is not emitted.\n *\n * Second locus: turns where the *user's own* request was ambiguous or\n * self-contradictory, evidenced by the user later clarifying rather than\n * correcting. Nothing misbehaved there — the fix is a clarifying-question\n * policy that spends one turn up front instead of K turns of rework, so\n * those findings target `scaffolding:*` rather than the agent's\n * instructions.\n *\n * Six bounded model subqueries let the actor test competing\n * earliest-detectable anchors against the same loaded turn excerpts.\n */\n\nimport { findingSubjectGrammarPromptFor } from '../finding-subject'\nimport type { TraceAnalystDefinition } from '../kind-factory'\n\nconst subjectGrammar = findingSubjectGrammarPromptFor('intent-divergence')\n\nconst ACTOR_PROMPT = `You are an intent-divergence analyst for an OTLP trace dataset. Your job is to find where the agent stopped doing what the user asked, and to establish **how early that was knowable**.\n\nThis dataset carries ground truth the other analysts do not have. When a human turn corrects the agent — \"no, I meant…\", \"stop doing X\", \"why are you still asking\" — the user has labelled a divergence for you. That label marks the END of the divergence, not its start. Your finding is the start: the earliest assistant turn already off-intent, the signal in the user's stated intent it contradicted, and the number of turns burned before the correction landed.\n\n${subjectGrammar}\n\nDISCOVERY → BACKTRACK → QUANTIFY → CITE protocol:\n\n1. \\`getDatasetOverview({})\\` first. Note the agent names and \\`sample_trace_ids\\`; conversational datasets carry several human turns per trace and those are the ones worth pulling.\n2. **DISCOVERY — find the corrective human turns.** Use \\`searchTrace\\` for user-authored corrections:\n Every pattern MUST begin with \\`(?i)\\`. The trace store compiles a search pattern case-sensitively unless it opens with that flag, and corrections are overwhelmingly sentence-initial and capitalised (\"Stop\", \"No,\", \"I said\"), so a lowercase pattern silently returns zero hits.\n - Imperative stops: \\`(?i)\\\\bstop\\\\b\\`, \\`(?i)\\\\b(don'?t|do not)\\\\b\\`, \\`(?i)^\\\\s*no[,.!]\\`, \\`(?i)\\\\bnot what I (wanted|asked|meant)\\\\b\\`, \\`(?i)\\\\bthat'?s not what\\\\b\\`, \\`(?i)\\\\brevert\\\\b\\`, \\`(?i)\\\\bstart over\\\\b\\`\n - Repetition and frustration: \\`(?i)\\\\bI (said|asked|told you)\\\\b\\`, \\`(?i)\\\\balready told you\\\\b\\`, \\`(?i)\\\\bwhy are you (still )?\\\\w+ing\\\\b\\`, \\`(?i)\\\\bjust (do|use|write|make)\\\\b\\`, \\`(?i)\\\\bagain\\\\b\\`\n - Clarification markers (second-order, see step 6): \\`(?i)\\\\bI mean(t)?\\\\b\\`, \\`(?i)\\\\bto be clear\\\\b\\`, \\`(?i)\\\\bactually,? I (want|need)\\\\b\\`, \\`(?i)\\\\bwhat I meant\\\\b\\`, \\`(?i)\\\\blet me rephrase\\\\b\\`\n Attribute every match to a role before using it. The same phrases inside an assistant turn are hedging, not correction.\n3. **BACKTRACK — walk the trace backward from the correction.** Read the ordered turns preceding it with \\`viewTrace\\` / \\`viewSpans\\`. Locate the user's ORIGINAL statement of intent (usually the first human turn, sometimes a constraint added mid-run), then locate the FIRST assistant turn that contradicts it. That turn, not the correction, anchors the finding. Name the concrete signal already available at that turn: an explicit constraint the agent violated, a scope it exceeded, a different question it answered, a file or target the user never named, a decision the user had already made.\n4. **QUANTIFY — count the burned turns.** K = (index of the corrective human turn) − (index of the earliest detectable assistant turn). Report both indices and K. If you cannot locate an earliest-detectable turn, you have a correction and not a divergence: drop it.\n5. **CLUSTER.** Repeated corrections about the same misread intent are ONE finding citing all of them, not one finding per corrective turn. Corrections about genuinely different intents in the same trace are separate findings.\n6. **Second-order — the request itself was ambiguous.** When the user CLARIFIES rather than corrects (\"I mean the staging config, not prod\"), the agent's reading was defensible and the request was underspecified or self-contradictory. Emit those against a \\`scaffolding:*\\` locus — a clarifying-question policy or a plan checkpoint — because the fix is one sharp question before acting, priced against the K turns the ambiguity cost. Do not charge the agent's instructions for a request that could not be resolved from its own text.\n\n**Test competing anchors with subqueries.** After the backward walk, load the excerpts for the original intent turn, your candidate earliest-detectable turn, and the turn before it. Send one bounded \\`llm_query\\` per candidate anchor asking whether the divergence is already present in that turn's text alone. Subqueries cannot call trace tools, and a turn index alone is insufficient context. Take the EARLIEST candidate the loaded excerpts support.\n\nFor each cluster, emit ONE finding. Use an exact locus from the subject grammar — the surface whose edit prevents the divergence, not the surface where it surfaced. State the claim in the shape \"turn N did X against stated intent Y; user corrected at turn N+K, burning K turns.\" Rate it critical when the divergence produced a user-visible or irreversible action, high when K is 3 or more or the run ended without the intent satisfied, medium for one or two burned turns, and low for a cosmetic correction. Cite BOTH spans with exact quotes: the earliest-detectable assistant turn and the corrective human turn. Use confidence 0.85+ when the stated intent and the diverging turn are both quotable and the contradiction is explicit, and 0.6-0.8 when the earliest-detectable turn is inferred from surrounding context. The recommended action must be the literal instruction, question, or checkpoint to add.\n\nDo NOT report a divergence the agent noticed and reversed inside the same turn — that is self-correction and it cost the user nothing. Do NOT report a human turn that adds NEW scope; a changed mind is not a divergence. If the dataset holds no corrective or clarifying human turns, return an empty findings array instead of grading tone.`\n\nexport const INTENT_DIVERGENCE_KIND_SPEC: TraceAnalystDefinition = {\n id: 'intent-divergence',\n description:\n 'Anchors each corrective human turn to the earliest assistant turn where the divergence from stated intent was already detectable, and prices it in burned turns.',\n area: 'intent-divergence',\n version: '1.0.0',\n instructions: ACTOR_PROMPT,\n // Backtracking reads the ordered turns BEFORE the correction, so the\n // search-only group cannot serve this kind: discovery finds the label,\n // viewTrace / viewSpans find the anchor.\n toolGroup: 'all',\n limits: { maxLlmCalls: 6, maxIterations: 22, maxToolCalls: 64 },\n // Both ends of the divergence must be quoted — the anchor turn alone is an\n // unlabelled guess, the corrective turn alone is the counting the\n // deterministic pass already does.\n minimumEvidenceCitations: 2,\n}\n","/**\n * Knowledge-gap analyst — what did the agent NOT know that it needed?\n *\n * Brief: find moments in the trace where the agent had to guess, ask\n * the user to fill in context, recover from a wrong assumption, or\n * loop on a retrieval. Each finding names a *missing or outdated piece\n * of knowledge* the agent's curated knowledge base should have held —\n * or a downstream lookup (web, docs, tool description) that surfaced\n * stale or outdated information.\n *\n * The primary expected store is `@tangle-network/agent-knowledge`: a\n * Karpathy-style wiki the agent maintains with raw ↔ curated pages,\n * source anchors, and claim/relation triples. A gap is anything the\n * agent had to discover at run-time that should already have lived\n * there. Secondary loci: web-search results that returned outdated\n * pages, tool descriptions that omitted critical behavior, system-\n * prompt sections that didn't cover the case.\n *\n * Distinct from failure-mode: failure-mode classifies *how* it broke;\n * knowledge-gap names the *information* whose absence (or staleness)\n * caused the break. One failure-mode often maps to several gaps.\n *\n * Five bounded model subqueries let the actor compare candidate gaps\n * across source layers after it has loaded the relevant excerpts.\n */\n\nimport { findingSubjectGrammarPromptFor } from '../finding-subject'\nimport type { TraceAnalystDefinition } from '../kind-factory'\n\nconst subjectGrammar = findingSubjectGrammarPromptFor('knowledge-gap')\n\nconst ACTOR_PROMPT = `You are a knowledge-gap analyst for an OTLP trace dataset. Your job is to identify the **specific pieces of information the agent lacked, or that were stale**, that caused poor decisions.\n\nThe agent under analysis maintains a curated knowledge base via \\`@tangle-network/agent-knowledge\\` — a wiki of \\`KnowledgePage\\`s with raw source anchors, claims, and relations. The primary expected store of agent-knowable facts IS that wiki. A \"knowledge gap\" is anything the agent had to discover or guess at run-time that the wiki should have held — or an outdated/contradictory fact the agent picked up from a non-wiki source.\n\n${subjectGrammar}\n\nDISCOVERY → ATTRIBUTE-TO-LAYER → CITE protocol:\n\n1. \\`getDatasetOverview({})\\` first. Note which agents, tools, and models appear.\n2. Pull traces where the agent shows gap signals. The strongest signals are:\n - Self-correction turns (\"I assumed X but…\", \"let me re-check\", \"actually,\")\n - Clarifying-question turns where the agent asked the user something the runtime should have surfaced\n - Repeated retrieval / lookup calls for the same artifact with slightly varied queries\n - Tool errors that name a missing argument or unknown resource\n - Web-search calls returning pages dated before a known cutoff for content that changes (versioned APIs, schemas, policies)\n - Agent quoting a tool's docs / system prompt incorrectly because the actual text was insufficient\n - Fabricated identifiers that don't appear in dataset \\`sample_trace_ids\\`\n Use \\`searchTrace\\` with patterns like \\`I (don.?t|do not) know\\`, \\`assumed\\`, \\`unclear\\`, \\`could you (clarify|tell me|provide)\\`, \\`not found\\`, \\`undefined\\`, \\`unknown\\`, \\`null\\`, dates older than the analysis window, or the agent's specific clarification phrases.\n3. For each gap, identify the **layer of the runtime that should have prevented it** and use its exact locus from the subject grammar above.\n4. For each defensible gap, emit ONE finding. Use an exact locus from the subject grammar and name the missing or stale knowledge (for example, \"wiki has no page on invoice line-item shape; agent re-derived it from raw spans\"). Rate it high when it caused failure or a clarifying question, medium for unnecessary turns, and low for minor inefficiency. Cite the span where the question, correction, retrieval miss, or stale result surfaced and quote it exactly. Use confidence 0.85+ when the agent articulated the gap and 0.6-0.8 when inferred. Recommend a concrete wiki edit for an agent-knowledge locus or a prompt/tool-description edit otherwise.\n\n**Compare layers over loaded evidence.** After the first scan, load the exact excerpts behind candidates across \\`agent-knowledge:*\\`, \\`websearch:outdated\\`, \\`tool-doc:*\\`, \\`system-prompt:*\\`, and \\`memory:*\\`. Use one bounded \\`llm_query\\` per layer to classify those excerpts. Subqueries cannot call trace tools. Merge their classifications into the final finding set only when the source excerpts support them.\n\nDo NOT report a gap that the agent later recovered from cleanly within the same turn. That is resilience, not a gap. Cite the non-recovery version when both exist.`\n\nexport const KNOWLEDGE_GAP_KIND_SPEC: TraceAnalystDefinition = {\n id: 'knowledge-gap',\n description:\n 'Identifies missing or stale pieces of knowledge — primarily against the agent-knowledge wiki — and attributes each to the runtime layer (wiki page, claim, raw source, websearch, tool-doc, system-prompt, memory) that should have held it.',\n area: 'knowledge-gap',\n version: '1.2.0',\n instructions: ACTOR_PROMPT,\n toolGroup: 'discoveryAndSearch',\n limits: { maxLlmCalls: 5, maxIterations: 18, maxToolCalls: 48 },\n}\n","/**\n * Knowledge-poisoning analyst — what FALSE information misled the agent?\n *\n * Brief: find moments where the agent acted on information that was\n * *wrong* — stale memory, RAG documents that contradicted ground truth,\n * tool descriptions that lied about return shapes, system-prompt\n * instructions that no longer matched reality, prior-run summaries that\n * cached a wrong decision.\n *\n * Distinct from knowledge-gap: a gap is \"the agent didn't know X\"; a\n * poisoning is \"the agent confidently used X, but X was wrong.\" Gaps\n * surface as questions / self-correction; poisonings surface as\n * confident-but-wrong actions that downstream evidence contradicts.\n *\n * Eight bounded model subqueries let the actor independently assess\n * the action and contradiction excerpts for candidate poisonings.\n */\n\nimport { findingSubjectGrammarPromptFor } from '../finding-subject'\nimport type { TraceAnalystDefinition } from '../kind-factory'\n\nconst subjectGrammar = findingSubjectGrammarPromptFor('knowledge-poisoning')\n\nconst ACTOR_PROMPT = `You are a knowledge-poisoning analyst for an OTLP trace dataset. Your job is to identify cases where the agent **confidently used wrong information** — not where it lacked information (that's the knowledge-gap analyst).\n\n${subjectGrammar}\n\nDISCOVERY → DUAL-VERIFY → CITE protocol:\n\n1. \\`getDatasetOverview({})\\` first. Identify the agents, models, and tools.\n2. Pull traces where the agent's confident action was later contradicted. Strongest signals:\n - Agent stated a fact in one span; a later span surfaced contradictory evidence; the agent then proceeded anyway or fabricated reconciliation.\n - Tool call with stale arguments (an id that no longer exists, an API shape that changed).\n - Agent cited an \\`agent-knowledge\\` wiki page or claim whose content contradicts the trace's own evidence — the wiki itself drifted.\n - Web-search result the agent cited that returned an outdated page; agent treated it as canonical.\n - System-prompt instruction the agent followed that ground-truth evidence in the trace contradicts (e.g. prompt says \"use endpoint A\"; tool reply says \"endpoint A deprecated, use B\").\n - Repeated wrong-shape parsing despite the tool's actual output proving the shape.\n3. Use \\`searchTrace\\` with regex on phrases like \\`actually\\`, \\`turns out\\`, \\`previously assumed\\`, \\`old version\\`, \\`deprecated\\`, \\`updated to\\`, \\`now uses\\`, or specific entity names you suspect have changed.\n4. For each candidate poisoning, **DUAL-VERIFY**:\n - Confirm the agent actually acted on the false belief (cite the span where it did)\n - Confirm the belief is actually false in this trace's own evidence (cite the span that contradicts it)\n Only emit a finding when both halves are supported. If you can only support one, drop it because single-evidence poisoning findings are too speculative to be useful.\n\n**Independently assess both halves.** Load the action excerpt and contradicting excerpt yourself, then send bounded \\`llm_query\\` calls the exact evidence for \"did the agent act?\" and \"does the trace contradict the belief?\" Subqueries cannot call trace tools. Accept a poisoning only when both assessments and the source excerpts support it.\n\nFor each confirmed poisoning, emit ONE finding. Use the source of the false belief as the exact subject. State \"agent believed X (from source S); trace evidence shows X is false.\" Rate it critical for a wrong user-visible action, high when caught internally after significant waste, and medium for inefficiency. Cite BOTH the action span and the contradicting span with exact quotes. Use confidence 0.85+ when both halves have exact quotes and 0.6-0.8 when one half is inferred. Recommend the literal source correction: update the wiki claim, invalidate and re-curate the raw source, or replace the stale prompt/tool instruction.\n\nDo NOT report a finding if the agent caught and corrected the false belief in the same turn. Reserve poisoning for cases where the false belief shaped downstream action.`\n\nexport const KNOWLEDGE_POISONING_KIND_SPEC: TraceAnalystDefinition = {\n id: 'knowledge-poisoning',\n description:\n 'Identifies confident-but-wrong actions caused by stale memory, contradicting RAG, deprecated tool docs, or outdated system-prompt instructions.',\n area: 'knowledge-poisoning',\n version: '1.2.0',\n instructions: ACTOR_PROMPT,\n toolGroup: 'all',\n limits: { maxLlmCalls: 8, maxIterations: 20, maxToolCalls: 64 },\n minimumEvidenceCitations: 2,\n}\n","/**\n * Default analyst kinds focused on agent failure + recursive\n * self-improvement.\n *\n * The five kinds chain. Two independent classifiers partition the\n * outcome surface: failure-mode names how a run broke, intent-divergence\n * names where it drifted from what the user asked and how many turns\n * that cost. Knowledge-gap and knowledge-poisoning then explain *why* in\n * two orthogonal ways — missing information versus false information.\n * Improvement proposes the concrete edits. Register all five against the\n * same trace store in this order and run the registry with\n * `chainFindings: true` to pass each completed kind's findings to the\n * kinds that follow it.\n */\n\nexport {\n CONTROL_INTEGRITY_ANALYST,\n ControlIntegrityAnalyst,\n emitControlIntegrityFindings,\n} from './control-integrity'\nexport { FAILURE_MODE_KIND_SPEC } from './failure-mode'\nexport { IMPROVEMENT_KIND_SPEC } from './improvement'\nexport { INTENT_DIVERGENCE_KIND_SPEC } from './intent-divergence'\nexport { KNOWLEDGE_GAP_KIND_SPEC } from './knowledge-gap'\nexport { KNOWLEDGE_POISONING_KIND_SPEC } from './knowledge-poisoning'\n\nimport type { TraceAnalystDefinition } from '../kind-factory'\nimport { FAILURE_MODE_KIND_SPEC } from './failure-mode'\nimport { IMPROVEMENT_KIND_SPEC } from './improvement'\nimport { INTENT_DIVERGENCE_KIND_SPEC } from './intent-divergence'\nimport { KNOWLEDGE_GAP_KIND_SPEC } from './knowledge-gap'\nimport { KNOWLEDGE_POISONING_KIND_SPEC } from './knowledge-poisoning'\n\n/**\n * The default kind suite. Order is the run order operators should use:\n * failure-mode and intent-divergence first (neither reads upstream\n * findings), gap + poisoning next (both explain the problems those two\n * found), improvement last (chains all four). Intent-divergence sits\n * ahead of improvement deliberately — a proposed edit should be able to\n * act on a priced divergence, and it is the only kind whose findings\n * carry a burned-turn cost to rank against.\n */\nexport const DEFAULT_TRACE_ANALYST_KINDS: readonly TraceAnalystDefinition[] = [\n FAILURE_MODE_KIND_SPEC,\n INTENT_DIVERGENCE_KIND_SPEC,\n KNOWLEDGE_GAP_KIND_SPEC,\n KNOWLEDGE_POISONING_KIND_SPEC,\n IMPROVEMENT_KIND_SPEC,\n] as const\n","/**\n * AnalystRegistry — orchestrate N analysts against one run.\n *\n * Owns three responsibilities and only three:\n * 1. Registration — ids must be unique; bad registrations fail loudly\n * at register-time, not run-time.\n * 2. Routing — each analyst declares its `inputKind`; the registry\n * picks the matching field from AnalystRunInputs and skips the\n * analyst with a logged reason if it's missing.\n * 3. Isolation — one analyst's exception MUST NOT stop other analysts.\n * Failed analysts produce zero findings + a 'failed' summary row.\n *\n * Cross-cutting concerns (telemetry, error → finding conversion, cost\n * ingestion, storage rotation) live in `AnalystHooks`. Budget shaping\n * (equal split vs weighted vs custom) lives in `BudgetPolicy`. Both\n * have sensible defaults; consumers override only what they need.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { z } from 'zod'\nimport { combineAbortSignals } from '../abort-signal'\nimport type { CostLedgerHandle } from '../cost-ledger'\nimport {\n snapshotAnalystFindings,\n snapshotExactAnalystRunReceipt,\n} from '../feedback-trajectory-review'\nimport { canonicalString, hashCanonical } from '../ledger-core/canonical'\nimport { deepFreezeCanonicalJson } from '../ledger-core/deep-freeze'\nimport type { RunCostProvenance, RunTokenUsage } from '../run-record'\nimport type { ChatClient } from './chat-client'\nimport type {\n ExactAnalystExecutionPlanSnapshot,\n ExactAnalystRunEvent,\n ExactAnalystRunResult,\n ExactCapableAnalyst,\n ExactExecutionComponentIdentity,\n ExactExecutionComponentSnapshot,\n} from './exact-types'\nimport { snapshotExactExecutionComponentIdentity, snapshotExactExecutionPlan } from './exact-types'\nimport type {\n Analyst,\n AnalystContext,\n AnalystFinding,\n AnalystRunEvent,\n AnalystRunInputs,\n AnalystRunResult,\n AnalystRunSummary,\n AnalystUsageReceipt,\n} from './types'\nimport { assertValidAnalystUsageReceipt, validateUsageSettlementTimeout } from './usage-receipt'\n\n// ── Hook + policy surfaces ─────────────────────────────────────────\n\nexport interface AnalystHooks {\n /** Legacy runs may mutate ctx; exact runs provide a frozen observational context. */\n onBeforeAnalyze?(args: {\n analyst: Analyst\n ctx: AnalystContext\n runId: string\n }): void | Promise<void>\n /** After every analyst (ok | failed | skipped). Use for telemetry, ingestion, rotation. */\n onAfterAnalyze?(args: {\n analyst: Analyst\n summary: AnalystRunSummary\n findings: AnalystFinding[]\n runId: string\n }): void | Promise<void>\n /**\n * On analyst exception. Hook MAY return findings to convert the\n * error into structured findings; the summary still reports 'failed'.\n * Return void to keep the default empty-findings behavior.\n */\n onError?(args: {\n analyst: Analyst\n error: Error\n runId: string\n }): AnalystFinding[] | undefined | Promise<AnalystFinding[] | undefined>\n /** Once after registry.run() completes. Use for final aggregation, persistence. */\n onComplete?(args: { result: AnalystRunResult }): void | Promise<void>\n}\n\nexport interface BudgetPolicy {\n /** Overall USD cap across the registry.run(). */\n totalUsd?: number\n /** Per-analyst weight for the default allocator. Missing ids get weight 1. */\n weights?: Record<string, number>\n /**\n * Custom allocator — receives the analyst, remaining/total budget, and\n * the count of analysts that will run. Returns the per-analyst budget\n * (or undefined only when the run has no overall cap). Overrides weights\n * when set.\n */\n allocate?: (args: {\n analyst: Analyst\n totalUsd: number | undefined\n remainingUsd: number | undefined\n runningCount: number\n }) => number | undefined\n}\n\nexport interface AnalystRegistryOptions {\n /** Shared chat client passed to every LLM analyst via AnalystContext. */\n chat?: ChatClient\n /** Logger callback. Defaults to a no-op. */\n log?: (msg: string, fields?: Record<string, unknown>) => void\n /** Hooks invoked around analyze() — observability + customization seam. */\n hooks?: AnalystHooks\n /** Required identity/config when `runExact` applies `hooks`. */\n hooksIdentity?: ExactExecutionComponentIdentity\n /** Default budget when run() doesn't override. */\n defaultBudget?: BudgetPolicy\n /** Required identity/config when `runExact` provides `chat`. */\n chatIdentity?: ExactExecutionComponentIdentity\n}\n\nexport interface RegistryRunOpts {\n /** Restrict to a subset of registered analysts by id. */\n only?: string[]\n /** Skip these analysts even if registered. Useful for cheap iteration. */\n skip?: string[]\n /** Budget policy — totalUsd + optional weights/allocator. Falls back to options.defaultBudget. */\n budget?: BudgetPolicy\n /** Active-work cap for the complete registry run. Model receipt settlement may follow. */\n timeoutMs?: number\n /** Abort signal — forwarded into every analyst's context. */\n signal?: AbortSignal\n /** Shared paid-call account forwarded to every analyst. */\n costLedger?: CostLedgerHandle\n /** Attribution phase for calls written to `costLedger`. */\n costPhase?: string\n /** Tags echoed into AnalystContext.tags — useful for tracking environment/version in findings. */\n tags?: Record<string, string>\n /**\n * Prior-run findings made available as retrieval context to every\n * analyst via `ctx.priorFindings`. The registry forwards the slice\n * whose `analyst_id` matches each registered analyst so a kind sees\n * only its own history. Pass `{ '*': findings }` to broadcast to\n * every analyst (useful when several kinds share the same historical\n * context). For findings from this run, use `chainFindings` instead.\n */\n priorFindings?: ReadonlyArray<AnalystFinding> | Record<string, ReadonlyArray<AnalystFinding>>\n /**\n * Pass findings produced earlier in this registry run to each later analyst\n * via `ctx.upstreamFindings`. Registration order is dependency order.\n * Disabled by default because independent analyst suites must opt in.\n */\n chainFindings?: boolean\n}\n\n/** A caller-selected allocation rule for an exact analyst run. */\nexport type ExactAnalystBudgetPolicy =\n | {\n readonly kind: 'equal'\n readonly totalUsd: number\n }\n | {\n readonly kind: 'weighted'\n readonly totalUsd: number\n /** One explicit weight for every selected analyst id. */\n readonly weights: Readonly<Record<string, number>>\n }\n\n/**\n * Complete per-run analyst policy.\n *\n * Every field is required. `null` explicitly disables an optional resource or context channel.\n * `analystIds` is execution order; it is not filtered through registry insertion order.\n * Missing-input behavior is explicit so callers cannot accidentally inherit it by omission.\n * Exact runs are serial; more elaborate scheduling belongs in the caller's runtime.\n */\nexport interface ExactRegistryRunOpts {\n readonly analystIds: readonly string[]\n readonly budget: ExactAnalystBudgetPolicy | null\n readonly totalTimeoutMs: number | null\n readonly signal: AbortSignal | null\n readonly costLedger: CostLedgerHandle | null\n readonly costLedgerIdentity: ExactExecutionComponentIdentity | null\n readonly costPhase: string | null\n readonly tags: Readonly<Record<string, string>> | null\n readonly priorFindings:\n | ReadonlyArray<AnalystFinding>\n | Readonly<Record<string, ReadonlyArray<AnalystFinding>>>\n | null\n readonly chainFindings: boolean\n readonly missingInputMode: 'skip' | 'abort'\n readonly applyRegistryHooks: boolean\n readonly useRegistryChat: boolean\n}\n\ntype NormalizedBudgetPlan =\n | { readonly kind: 'none' }\n | { readonly kind: 'dynamic'; readonly policy: BudgetPolicy }\n\ninterface PreparedAnalyst {\n readonly analyst: Analyst\n readonly input:\n | { readonly kind: 'present'; readonly value: unknown }\n | { readonly kind: 'missing' }\n}\n\ninterface AnalystExecutionPlan {\n readonly runId: string\n readonly prepared: readonly PreparedAnalyst[]\n readonly budget: NormalizedBudgetPlan\n readonly totalTimeoutMs: number | null\n readonly signal: AbortSignal | null\n readonly costLedger: CostLedgerHandle | null\n readonly costPhase: string | null\n readonly tags: Readonly<Record<string, string>> | null\n readonly priorFindings:\n | ReadonlyArray<AnalystFinding>\n | Readonly<Record<string, ReadonlyArray<AnalystFinding>>>\n | null\n readonly chainFindings: boolean\n readonly hooks: AnalystHooks\n readonly chat: ChatClient | undefined\n readonly log: (msg: string, fields?: Record<string, unknown>) => void\n readonly executionSnapshot: ExactAnalystExecutionPlanSnapshot | undefined\n}\n\ntype InternalAnalystRunEvent = AnalystRunEvent\n\n/** A post-start exact-run failure; completed work remains attached for accounting and review. */\nexport class ExactAnalystRunExecutionError extends Error {\n readonly name: string = 'ExactAnalystRunExecutionError'\n readonly result: ExactAnalystRunResult\n\n constructor(message: string, result: ExactAnalystRunResult, options?: ErrorOptions) {\n super(message, options)\n const snapshot = snapshotExactAnalystRunReceipt(result, 'ExactAnalystRunExecutionError result')\n if (snapshot.completion.status !== 'failed') {\n throw new TypeError('ExactAnalystRunExecutionError result must be a failed receipt')\n }\n this.result = snapshot\n }\n}\n\nexport class AnalystRegistry {\n private readonly analysts = new Map<string, Analyst>()\n private readonly options: AnalystRegistryOptions\n\n constructor(options: AnalystRegistryOptions = {}) {\n this.options = options\n }\n\n register(analyst: Analyst): void {\n const id = analyst.id\n const version = analyst.version\n const cost = analyst.cost\n if (!id) throw new Error('AnalystRegistry.register: analyst.id is required')\n if (this.analysts.has(id)) {\n throw new Error(`AnalystRegistry.register: duplicate analyst id \"${id}\"`)\n }\n if (!version) {\n throw new Error(`AnalystRegistry.register: analyst \"${id}\" must declare a version`)\n }\n if (cost.kind === 'deterministic' && cost.settlement_timeout_ms !== undefined) {\n throw new TypeError(\n `AnalystRegistry.register: deterministic analyst \"${id}\" cannot declare settlement_timeout_ms`,\n )\n }\n if (cost.settlement_timeout_ms !== undefined) {\n validateUsageSettlementTimeout(cost.settlement_timeout_ms)\n }\n this.analysts.set(id, analyst)\n }\n\n list(): ReadonlyArray<{\n id: string\n description: string\n version: string\n cost: Analyst['cost']\n }> {\n return Array.from(this.analysts.values()).map((a) => ({\n id: a.id,\n description: a.description,\n version: a.version,\n cost: a.cost,\n }))\n }\n\n async run(\n runId: string,\n inputs: AnalystRunInputs,\n runOpts: RegistryRunOpts = {},\n ): Promise<AnalystRunResult> {\n // Thin collector over `runStream`. Both surfaces share the same\n // loop body so they cannot drift on isolation / hook order / cost.\n for await (const ev of this.runStream(runId, inputs, runOpts)) {\n if (ev.type === 'run-completed') return ev.result\n }\n throw new Error('AnalystRegistry.run: stream completed without run-completed event')\n }\n\n /** Run exactly the ordered analysts and complete policy supplied by the caller. */\n async runExact(\n runId: string,\n inputs: AnalystRunInputs,\n runOpts: ExactRegistryRunOpts,\n ): Promise<ExactAnalystRunResult> {\n for await (const ev of this.runExactStream(runId, inputs, runOpts)) {\n if (ev.type === 'run-completed') return ev.result\n }\n throw new Error('AnalystRegistry.runExact: stream completed without run-completed event')\n }\n\n /** Streaming counterpart to {@link runExact}. */\n async *runExactStream(\n runId: string,\n inputs: AnalystRunInputs,\n runOpts: ExactRegistryRunOpts,\n ): AsyncGenerator<ExactAnalystRunEvent, void, void> {\n for await (const event of this.executePlanStream(\n this.normalizeExactPlan(runId, inputs, runOpts),\n )) {\n yield event as ExactAnalystRunEvent\n }\n }\n\n /**\n * Streaming counterpart to `run()`. Emits `AnalystRunEvent` values\n * in real time — `run-started`, then per-analyst `skipped` /\n * `started` / `completed`, then a terminal `run-completed` whose\n * payload is the full `AnalystRunResult`. UIs use this to render\n * progress; persistence consumers use `run()` and read the result.\n *\n * Hooks (`onBeforeAnalyze` / `onAfterAnalyze` / `onError` /\n * `onComplete`) fire as before — streaming is additive, not a hook\n * replacement.\n */\n async *runStream(\n runId: string,\n inputs: AnalystRunInputs,\n runOpts: RegistryRunOpts = {},\n ): AsyncGenerator<AnalystRunEvent, void, void> {\n yield* this.executePlanStream(this.normalizeLegacyPlan(runId, inputs, runOpts))\n }\n\n private normalizeLegacyPlan(\n runId: string,\n inputs: AnalystRunInputs,\n runOpts: RegistryRunOpts,\n ): AnalystExecutionPlan {\n const timeoutMs = validateTimeout(runOpts.timeoutMs) ?? null\n const budget = runOpts.budget ?? this.options.defaultBudget\n validateBudgetPolicy(budget)\n const selected = this.selectAnalysts(runOpts)\n return {\n runId,\n prepared: selected.map((analyst) => ({\n analyst,\n input: this.routeInput(analyst, inputs),\n })),\n budget: budget ? { kind: 'dynamic', policy: budget } : { kind: 'none' },\n totalTimeoutMs: timeoutMs,\n signal: runOpts.signal ?? null,\n costLedger: runOpts.costLedger ?? null,\n costPhase: runOpts.costPhase ?? null,\n tags: runOpts.tags ?? null,\n priorFindings: runOpts.priorFindings ?? null,\n chainFindings: runOpts.chainFindings ?? false,\n hooks: this.options.hooks ?? {},\n chat: this.options.chat,\n log: this.options.log ?? (() => {}),\n executionSnapshot: undefined,\n }\n }\n\n private normalizeExactPlan(\n runId: string,\n inputs: AnalystRunInputs,\n runOpts: ExactRegistryRunOpts,\n ): AnalystExecutionPlan {\n const exactRunId = snapshotExactRunId(runId)\n const exact = snapshotExactRegistryRunOpts(runOpts)\n const selected = normalizeExactAnalysts(this.selectExactAnalysts(exact.analystIds))\n const registryChat = this.options.chat\n const registryChatIdentity = this.options.chatIdentity\n const registryHooks = this.options.hooks\n const registryHooksIdentity = this.options.hooksIdentity\n if (exact.useRegistryChat && registryChat === undefined) {\n throw new TypeError(\n 'ExactRegistryRunOpts.useRegistryChat is true but the registry has no chat client',\n )\n }\n if (exact.applyRegistryHooks && !hasRegistryHooks(registryHooks)) {\n throw new TypeError(\n 'ExactRegistryRunOpts.applyRegistryHooks is true but the registry has no lifecycle hooks',\n )\n }\n const inputSnapshot = snapshotAnalystRunInputChannels(inputs)\n const prepared = selected.map((analyst) => ({\n analyst,\n input: this.routeInput(analyst, inputSnapshot),\n }))\n if (exact.missingInputMode === 'abort') {\n const missing = prepared.find((candidate) => candidate.input.kind === 'missing')?.analyst\n if (missing) {\n throw new TypeError(\n `ExactRegistryRunOpts.missingInputMode abort preflight found no \"${missing.inputKind}\" input for \"${missing.id}\"`,\n )\n }\n }\n const hooksIdentity =\n exact.applyRegistryHooks && registryHooks\n ? requireExactComponentIdentity(registryHooksIdentity, 'registry hooks')\n : null\n const chatIdentity = exact.useRegistryChat\n ? requireExactComponentIdentity(registryChatIdentity, 'registry chat')\n : null\n const costLedgerIdentity =\n exact.costLedger === null\n ? null\n : requireExactComponentIdentity(exact.costLedgerIdentity ?? undefined, 'cost ledger')\n const allocations = exactFixedBudgets(\n exact.budget,\n prepared\n .filter(\n (\n candidate,\n ): candidate is {\n analyst: ExactCapableAnalyst\n input: { kind: 'present'; value: unknown }\n } => candidate.input.kind === 'present',\n )\n .map((candidate) => candidate.analyst),\n selected,\n )\n const executionSnapshot = exactExecutionSnapshot(\n selected,\n exact,\n allocations,\n costLedgerIdentity,\n hooksIdentity,\n chatIdentity,\n )\n return {\n runId: exactRunId,\n prepared,\n budget: { kind: 'none' },\n totalTimeoutMs: exact.totalTimeoutMs,\n signal: exact.signal,\n costLedger: exact.costLedger,\n costPhase: exact.costPhase,\n tags: exact.tags,\n priorFindings: exact.priorFindings,\n chainFindings: exact.chainFindings,\n hooks: exact.applyRegistryHooks && registryHooks ? snapshotHooks(registryHooks) : {},\n chat: exact.useRegistryChat && registryChat ? snapshotChat(registryChat) : undefined,\n // Exact runs expose live events and versioned hooks. An inherited logger is intentionally\n // excluded because an anonymous callback can throw, block, or mutate shared state.\n log: () => {},\n executionSnapshot,\n }\n }\n\n private async *executePlanStream(\n plan: AnalystExecutionPlan,\n ): AsyncGenerator<InternalAnalystRunEvent, void, void> {\n const exact = plan.executionSnapshot !== undefined\n if (exact && plan.signal?.aborted) throw abortReason(plan.signal)\n\n const correlationId = `ar_${randomUUID().slice(0, 12)}`\n const log = plan.log\n const startedAt = new Date().toISOString()\n const started = Date.now()\n const timeoutSignal =\n plan.totalTimeoutMs === null ? undefined : AbortSignal.timeout(plan.totalTimeoutMs)\n const runSignal = combineAbortSignals(plan.signal ?? undefined, timeoutSignal)\n const deadlineMs = plan.totalTimeoutMs === null ? undefined : started + plan.totalTimeoutMs\n const runnable = plan.prepared\n .filter(\n (\n candidate,\n ): candidate is {\n analyst: Analyst\n input: { kind: 'present'; value: unknown }\n } => candidate.input.kind === 'present',\n )\n .map((candidate) => candidate.analyst)\n let remainingUsd = plan.budget.kind === 'dynamic' ? plan.budget.policy.totalUsd : undefined\n const weights = plan.budget.kind === 'dynamic' ? plan.budget.policy.weights : undefined\n const totalWeight =\n weights &&\n plan.budget.kind === 'dynamic' &&\n plan.budget.policy.totalUsd != null &&\n !plan.budget.policy.allocate &&\n runnable.length > 0\n ? runnable.reduce((sum, analyst) => sum + analystWeight(weights, analyst.id), 0)\n : undefined\n if (totalWeight === 0) {\n throw new Error('BudgetPolicy.weights must allocate positive weight to a runnable analyst')\n }\n const upstreamFindings: AnalystFinding[] = []\n\n yield snapshotExecutionEvent(\n {\n type: 'run-started',\n run_id: plan.runId,\n correlation_id: correlationId,\n started_at: startedAt,\n analyst_ids: plan.prepared.map(({ analyst }) => analyst.id),\n ...(plan.executionSnapshot === undefined ? {} : { execution_plan: plan.executionSnapshot }),\n },\n exact,\n )\n\n const executions: AnalystExecution[] = []\n let executionFailure: unknown\n\n for (const { analyst, input } of plan.prepared) {\n const t0 = Date.now()\n if (runSignal?.aborted) {\n const summary = abortedBeforeStartSummary(analyst, runSignal)\n executions.push({ summary, findings: [], budgetDebitUsd: 0 })\n log(`[analyst] skip ${analyst.id} — run aborted`, {\n runId: plan.runId,\n reason: summary.reason,\n })\n yield snapshotExecutionEvent({ type: 'analyst-skipped', summary }, exact)\n if (exact) {\n executionFailure = abortReason(runSignal)\n break\n }\n continue\n }\n\n if (input.kind === 'missing') {\n const summary: AnalystRunSummary = {\n analyst_id: analyst.id,\n status: 'skipped',\n reason: `missing input of kind '${analyst.inputKind}'`,\n findings_count: 0,\n latency_ms: 0,\n usage: zeroUsage(),\n }\n const execution = { summary, findings: [], budgetDebitUsd: 0 } satisfies AnalystExecution\n executions.push(execution)\n log(`[analyst] skip ${analyst.id} — missing input`, {\n runId: plan.runId,\n kind: analyst.inputKind,\n })\n const hookValues = snapshotAfterHookValues(summary, [], exact)\n try {\n await waitForHook(\n plan.hooks.onAfterAnalyze\n ? () =>\n plan.hooks.onAfterAnalyze?.({\n analyst,\n summary: hookValues.summary,\n findings: hookValues.findings,\n runId: plan.runId,\n })\n : undefined,\n runSignal,\n )\n } catch (error) {\n if (!exact) throw error\n executionFailure = error\n }\n yield snapshotExecutionEvent({ type: 'analyst-skipped', summary }, exact)\n if (executionFailure !== undefined) break\n continue\n }\n\n const allocatedUsd =\n plan.executionSnapshot === undefined\n ? allocateBudget(plan.budget.kind === 'dynamic' ? plan.budget.policy : undefined, {\n analyst,\n remainingUsd,\n runningCount: runnable.length,\n totalWeight,\n })\n : exactPlannedAllocation(plan.executionSnapshot, analyst.id)\n const budgetCeilingUsd = plan.executionSnapshot === undefined ? remainingUsd : allocatedUsd\n const usageReceipts: AnalystUsageReceipt[] = []\n const contextTags = plan.tags === null ? undefined : { ...plan.tags }\n const priorFindings = selectPriorFindings(plan.priorFindings ?? undefined, analyst.id)\n const chainedFindings =\n plan.chainFindings && upstreamFindings.length > 0 ? [...upstreamFindings] : undefined\n const ctx: AnalystContext = {\n runId: plan.runId,\n correlationId,\n deadlineMs,\n budgetUsd: allocatedUsd,\n costLedger: plan.costLedger ?? undefined,\n costPhase: plan.costPhase ?? undefined,\n chat: plan.chat,\n tags: contextTags,\n log: (message, fields) =>\n log(`[${analyst.id}] ${message}`, {\n runId: plan.runId,\n correlationId,\n ...fields,\n }),\n signal: runSignal,\n priorFindings,\n upstreamFindings: chainedFindings,\n recordUsage: (receipt) => {\n if (!exact) {\n assertValidAnalystUsageReceipt(receipt)\n usageReceipts.push(receipt)\n return\n }\n usageReceipts.push(\n snapshotUsageReceiptOnce(\n receipt,\n `AnalystRegistry.runExact analyst \"${analyst.id}\" usage`,\n ),\n )\n },\n }\n if (exact) {\n if (contextTags) deepFreezeCanonicalJson(contextTags)\n if (priorFindings) deepFreezeCanonicalJson(priorFindings)\n if (chainedFindings) deepFreezeCanonicalJson(chainedFindings)\n Object.freeze(ctx)\n }\n\n try {\n await waitForHook(\n plan.hooks.onBeforeAnalyze\n ? () => plan.hooks.onBeforeAnalyze?.({ analyst, ctx, runId: plan.runId })\n : undefined,\n runSignal,\n )\n } catch (error) {\n if (!exact) throw error\n executionFailure = error\n break\n }\n if (runSignal?.aborted) {\n const summary = abortedBeforeStartSummary(analyst, runSignal, Date.now() - t0)\n executions.push({ summary, findings: [], budgetDebitUsd: 0 })\n yield snapshotExecutionEvent({ type: 'analyst-skipped', summary }, exact)\n if (exact) {\n executionFailure = abortReason(runSignal)\n break\n }\n continue\n }\n let effectiveBudget: number | undefined\n try {\n effectiveBudget = validateEffectiveBudget(ctx.budgetUsd, budgetCeilingUsd, analyst.id)\n } catch (error) {\n if (!exact) throw error\n executionFailure = error\n break\n }\n const analystContext: AnalystContext = exact ? ctx : { ...ctx }\n const executionSignal = exact ? ctx.signal : runSignal\n yield snapshotExecutionEvent(\n {\n type: 'analyst-started',\n analyst_id: analyst.id,\n started_at: new Date(t0).toISOString(),\n },\n exact,\n )\n\n let findings: AnalystFinding[]\n let summary: AnalystRunSummary\n let lifecycleFailure: unknown\n let analysisFailure: Error | undefined\n try {\n if (runSignal?.aborted) throw abortReason(runSignal)\n const analyzed = await waitForOperation(\n (analyst as Analyst<unknown>).analyze(input.value, analystContext),\n executionSignal,\n analystAbortGraceMs(analyst),\n )\n findings = snapshotExecutionFindings(\n analyzed,\n exact,\n `AnalystRegistry.runExact analyst \"${analyst.id}\" findings`,\n )\n } catch (error) {\n const cause = error instanceof Error ? error : new Error(String(error))\n analysisFailure = cause\n let hookFindings: AnalystFinding[] = []\n if (!executionSignal?.aborted) {\n try {\n const rawHookFindings =\n (await waitForHook(\n plan.hooks.onError\n ? () =>\n plan.hooks.onError?.({\n analyst,\n error: cause,\n runId: plan.runId,\n })\n : undefined,\n executionSignal,\n )) ?? []\n hookFindings = snapshotExecutionFindings(\n rawHookFindings,\n exact,\n `AnalystRegistry.runExact analyst \"${analyst.id}\" onError findings`,\n )\n } catch (error) {\n lifecycleFailure = error\n }\n }\n findings = hookFindings\n }\n\n let usage: AnalystUsageReceipt\n try {\n usage = resolveUsage(analyst, usageReceipts, exact)\n } catch (error) {\n if (!exact) throw error\n executionFailure = error\n break\n }\n if (analysisFailure === undefined) {\n summary = {\n analyst_id: analyst.id,\n status: 'ok',\n findings_count: findings.length,\n latency_ms: Date.now() - t0,\n usage,\n ...(exact ? { allocated_budget_usd: effectiveBudget ?? null } : {}),\n }\n log(`[analyst] ok ${analyst.id}`, {\n runId: plan.runId,\n findings: findings.length,\n latency_ms: summary.latency_ms,\n cost_usd: knownCostUsd(usage),\n cost_kind: usage.cost.kind,\n input_tokens: usage.tokens?.input ?? null,\n output_tokens: usage.tokens?.output ?? null,\n })\n } else {\n const errorClass = analysisFailure.constructor.name || 'Error'\n const errorMessage =\n exact && analysisFailure.message.length === 0\n ? 'Analyst failed without an error message'\n : analysisFailure.message\n summary = {\n analyst_id: analyst.id,\n status: 'failed',\n findings_count: findings.length,\n latency_ms: Date.now() - t0,\n usage,\n ...(exact ? { allocated_budget_usd: effectiveBudget ?? null } : {}),\n error: { class: errorClass, message: errorMessage },\n }\n log(`[analyst] FAIL ${analyst.id}`, {\n runId: plan.runId,\n error_class: errorClass,\n error: errorMessage,\n cost_usd: knownCostUsd(usage),\n cost_kind: usage.cost.kind,\n })\n }\n logUncapturedBudgetWarning({\n analyst,\n runId: plan.runId,\n budgetUsd: effectiveBudget,\n usage,\n log,\n })\n\n const execution = {\n summary,\n findings,\n budgetDebitUsd: budgetDebit(summary.usage, effectiveBudget),\n } satisfies AnalystExecution\n if (exact) {\n try {\n executionCost([...executions, execution], true)\n } catch (error) {\n executionFailure = error\n break\n }\n }\n executions.push(execution)\n if (plan.budget.kind === 'dynamic' && remainingUsd !== undefined) {\n remainingUsd = Math.max(0, remainingUsd - execution.budgetDebitUsd)\n }\n if (plan.chainFindings) upstreamFindings.push(...findings)\n if (lifecycleFailure !== undefined) {\n if (!exact) throw lifecycleFailure\n executionFailure = lifecycleFailure\n break\n }\n\n const hookValues = snapshotAfterHookValues(summary, findings, exact)\n try {\n await waitForHook(\n plan.hooks.onAfterAnalyze\n ? () =>\n plan.hooks.onAfterAnalyze?.({\n analyst,\n summary: hookValues.summary,\n findings: hookValues.findings,\n runId: plan.runId,\n })\n : undefined,\n executionSignal,\n )\n } catch (error) {\n if (!exact) throw error\n executionFailure = error\n break\n }\n yield snapshotExecutionEvent({ type: 'analyst-completed', summary, findings }, exact)\n if (exact && runSignal?.aborted) {\n executionFailure = abortReason(runSignal)\n break\n }\n }\n\n const summaries = executions.map(({ summary }) => summary)\n const findings = executions.flatMap((execution) => execution.findings)\n const cost = executionCost(executions, exact)\n const baseResult: AnalystRunResult = {\n run_id: plan.runId,\n correlation_id: correlationId,\n started_at: startedAt,\n ended_at: new Date().toISOString(),\n findings,\n per_analyst: summaries,\n total_cost_usd: cost.known,\n total_cost_provenance: cost.provenance,\n }\n if (plan.executionSnapshot === undefined) {\n await waitForHook(\n plan.hooks.onComplete ? () => plan.hooks.onComplete?.({ result: baseResult }) : undefined,\n runSignal,\n )\n yield { type: 'run-completed', result: baseResult }\n return\n }\n\n let completeResult: ExactAnalystRunResult | undefined\n if (executionFailure === undefined) {\n try {\n completeResult = snapshotExactAnalystRunReceipt(\n {\n ...baseResult,\n execution_plan: plan.executionSnapshot,\n completion: { status: 'complete' },\n },\n 'AnalystRegistry.runExact result',\n )\n await waitForHook(\n plan.hooks.onComplete\n ? () => plan.hooks.onComplete?.({ result: completeResult! })\n : undefined,\n runSignal,\n )\n } catch (error) {\n executionFailure = error\n }\n }\n if (runSignal?.aborted) executionFailure ??= abortReason(runSignal)\n if (executionFailure === undefined && completeResult) {\n yield snapshotExecutionEvent({ type: 'run-completed', result: completeResult }, true)\n return\n }\n\n const cause =\n executionFailure instanceof Error ? executionFailure : new Error(String(executionFailure))\n const errorClass = cause.constructor.name || 'Error'\n const errorMessage =\n cause.message.trim().length === 0\n ? 'Exact analyst run failed without a message'\n : cause.message\n throw new ExactAnalystRunExecutionError(\n `exact analyst run failed after starting: ${errorMessage}; partial result is attached`,\n {\n ...baseResult,\n execution_plan: plan.executionSnapshot,\n completion: {\n status: 'failed',\n error: { class: errorClass, message: errorMessage },\n },\n },\n { cause },\n )\n }\n\n private selectAnalysts(opts: RegistryRunOpts): Analyst[] {\n let candidates = Array.from(this.analysts.values())\n if (opts.only?.length) {\n const only = new Set(opts.only)\n candidates = candidates.filter((a) => only.has(a.id))\n }\n if (opts.skip?.length) {\n const skip = new Set(opts.skip)\n candidates = candidates.filter((a) => !skip.has(a.id))\n }\n return candidates\n }\n\n private selectExactAnalysts(\n ids: readonly string[],\n ): ReadonlyArray<{ readonly registeredId: string; readonly analyst: Analyst }> {\n return ids.map((id) => {\n const analyst = this.analysts.get(id)\n if (!analyst) throw new Error(`ExactRegistryRunOpts.analystIds names unknown analyst \"${id}\"`)\n return { registeredId: id, analyst }\n })\n }\n\n private routeInput(\n analyst: Analyst,\n inputs: AnalystRunInputs,\n ): { kind: 'present'; value: unknown } | { kind: 'missing' } {\n switch (analyst.inputKind) {\n case 'trace-store': {\n const value = inputs.traceStore\n return value ? { kind: 'present', value } : { kind: 'missing' }\n }\n case 'artifact-dir': {\n const value = inputs.artifactDir\n return value ? { kind: 'present', value } : { kind: 'missing' }\n }\n case 'run-record': {\n const value = inputs.runRecord\n return value ? { kind: 'present', value } : { kind: 'missing' }\n }\n case 'judge-input': {\n const value = inputs.judgeInput\n return value ? { kind: 'present', value } : { kind: 'missing' }\n }\n case 'custom': {\n const custom = inputs.custom\n const value = custom?.[analyst.id]\n return value !== undefined ? { kind: 'present', value } : { kind: 'missing' }\n }\n }\n }\n}\n\nconst exactRunFields = [\n 'analystIds',\n 'budget',\n 'totalTimeoutMs',\n 'signal',\n 'costLedger',\n 'costLedgerIdentity',\n 'costPhase',\n 'tags',\n 'priorFindings',\n 'chainFindings',\n 'missingInputMode',\n 'applyRegistryHooks',\n 'useRegistryChat',\n] as const\n\nconst exactNonEmptyString = z.string().min(1)\nconst exactFiniteNonnegative = z.number().finite().nonnegative()\nconst exactBudgetSchema = z.discriminatedUnion('kind', [\n z.strictObject({\n kind: z.literal('equal'),\n totalUsd: exactFiniteNonnegative,\n }),\n z.strictObject({\n kind: z.literal('weighted'),\n totalUsd: exactFiniteNonnegative,\n weights: z.record(exactNonEmptyString, exactFiniteNonnegative),\n }),\n])\nconst exactRunDataSchema = z\n .strictObject({\n analystIds: z.array(exactNonEmptyString).min(1),\n budget: exactBudgetSchema.nullable(),\n totalTimeoutMs: z.number().int().positive().max(2_147_483_647).nullable(),\n costLedgerIdentity: z.unknown().nullable(),\n costPhase: exactNonEmptyString.nullable(),\n tags: z.record(z.string(), z.string()).nullable(),\n chainFindings: z.boolean(),\n missingInputMode: z.enum(['skip', 'abort']),\n applyRegistryHooks: z.boolean(),\n useRegistryChat: z.boolean(),\n })\n .superRefine((policy, context) => {\n const issue = (path: PropertyKey[], message: string): void =>\n context.addIssue({ code: 'custom', path, message })\n if (new Set(policy.analystIds).size !== policy.analystIds.length) {\n issue(['analystIds'], 'must not contain duplicates')\n }\n if (\n policy.budget?.kind === 'weighted' &&\n Object.values(policy.budget.weights).every((weight) => weight === 0)\n ) {\n issue(['budget', 'weights'], 'must allocate positive weight to at least one analyst')\n }\n if (policy.budget?.kind === 'weighted') {\n const selected = [...policy.analystIds].sort()\n const weighted = Object.keys(policy.budget.weights).sort()\n if (\n selected.length !== weighted.length ||\n selected.some((id, index) => id !== weighted[index])\n ) {\n issue(['budget', 'weights'], 'must name every selected analyst and no others')\n }\n }\n })\n\nfunction snapshotExactRunId(value: unknown): string {\n if (typeof value !== 'string' || value.length === 0) {\n throw new TypeError('AnalystRegistry.runExact: runId must be a non-empty string')\n }\n return canonicalJsonSnapshot(value, 'AnalystRegistry.runExact runId')\n}\n\nfunction snapshotAnalystRunInputChannels(inputs: AnalystRunInputs): AnalystRunInputs {\n if (!inputs || typeof inputs !== 'object' || Array.isArray(inputs)) {\n throw new TypeError('AnalystRegistry.runExact: inputs must be an object')\n }\n const traceStore = inputs.traceStore\n const artifactDir = inputs.artifactDir\n const runRecord = inputs.runRecord\n const judgeInput = inputs.judgeInput\n const custom = inputs.custom\n return Object.freeze({\n traceStore,\n artifactDir,\n runRecord,\n judgeInput,\n custom,\n })\n}\n\n/**\n * Read the untrusted caller object once, then validate and execute only this frozen snapshot.\n * Functions and resource handles retain identity; all data fields are copied canonically.\n */\nfunction snapshotExactRegistryRunOpts(value: unknown): ExactRegistryRunOpts {\n const captured = readOwnFields(value, exactRunFields, 'ExactRegistryRunOpts')\n const missing = exactRunFields.find((field) => !Object.hasOwn(captured, field))\n if (missing) {\n throw new TypeError(`ExactRegistryRunOpts.${missing} must be supplied explicitly`)\n }\n const { signal, costLedger, priorFindings, ...rawData } = captured\n const data = canonicalJsonSnapshot(rawData, 'ExactRegistryRunOpts')\n const parsed = exactRunDataSchema.safeParse(data)\n if (!parsed.success) {\n const issue = parsed.error.issues[0]\n if (issue?.code === 'unrecognized_keys' && issue.path.join('.') === 'budget') {\n const required =\n isPlainRecord(data.budget) && data.budget.kind === 'weighted'\n ? 'kind, totalUsd, weights'\n : 'kind, totalUsd'\n throw new TypeError(`ExactRegistryRunOpts.budget must contain exactly ${required}`)\n }\n const path = issue?.path.length ? `.${issue.path.join('.')}` : ''\n throw new TypeError(`ExactRegistryRunOpts${path}: ${issue?.message ?? 'is invalid'}`)\n }\n if (\n signal !== null &&\n (!signal ||\n typeof signal !== 'object' ||\n typeof (signal as AbortSignal).addEventListener !== 'function')\n ) {\n throw new TypeError('ExactRegistryRunOpts.signal must be an AbortSignal or null')\n }\n if (costLedger !== null && (!costLedger || typeof costLedger !== 'object')) {\n throw new TypeError('ExactRegistryRunOpts.costLedger must be a CostLedgerHandle or null')\n }\n if (costLedger === null && parsed.data.costLedgerIdentity !== null) {\n throw new TypeError('ExactRegistryRunOpts.costLedgerIdentity must be null without costLedger')\n }\n if (costLedger !== null && parsed.data.costLedgerIdentity === null) {\n throw new TypeError('ExactRegistryRunOpts.costLedgerIdentity is required with costLedger')\n }\n if (costLedger === null && parsed.data.costPhase !== null) {\n throw new TypeError('ExactRegistryRunOpts.costPhase requires a non-null costLedger')\n }\n return Object.freeze({\n ...deepFreezeCanonicalJson(parsed.data),\n signal: signal as AbortSignal | null,\n costLedger: costLedger as CostLedgerHandle | null,\n priorFindings: snapshotExactPriorFindings(priorFindings),\n }) as ExactRegistryRunOpts\n}\n\nfunction snapshotExactPriorFindings(value: unknown): ExactRegistryRunOpts['priorFindings'] {\n if (value === null) return null\n if (Array.isArray(value)) {\n return snapshotAnalystFindings(value, 'ExactRegistryRunOpts.priorFindings')\n }\n if (!isPlainRecord(value)) {\n throw new TypeError(\n 'ExactRegistryRunOpts.priorFindings must be an array, a findings record, or null',\n )\n }\n const result: Record<string, ReadonlyArray<AnalystFinding>> = {}\n for (const [key, findings] of Object.entries(value)) {\n if (!Array.isArray(findings)) {\n throw new TypeError(`ExactRegistryRunOpts.priorFindings.${key} must be an array`)\n }\n result[key] = snapshotAnalystFindings(findings, `ExactRegistryRunOpts.priorFindings.${key}`)\n }\n return deepFreezeCanonicalJson(result)\n}\n\nfunction normalizeExactAnalysts(\n selections: ReadonlyArray<{ readonly registeredId: string; readonly analyst: Analyst }>,\n): ExactCapableAnalyst[] {\n return selections.map(({ registeredId, analyst }) => {\n const exactAnalyst = analyst as Analyst & {\n readonly executionConfig?: Readonly<Record<string, unknown>>\n }\n const id = analyst.id\n const description = analyst.description\n const inputKind = analyst.inputKind\n const rawCostValue = analyst.cost\n const requiresValue = analyst.requires\n const version = analyst.version\n const executionConfigValue = exactAnalyst.executionConfig\n const analyzeValue = analyst.analyze\n if (id !== registeredId) {\n throw new TypeError(\n `AnalystRegistry.runExact: registered analyst \"${registeredId}\" changed id to \"${id}\"`,\n )\n }\n if (executionConfigValue === undefined) {\n throw new TypeError(`AnalystRegistry.runExact: analyst \"${id}\" must declare executionConfig`)\n }\n const executionConfig = canonicalJsonSnapshot(\n executionConfigValue,\n `AnalystRegistry.runExact analyst \"${id}\" executionConfig`,\n )\n if (!isPlainRecord(executionConfig)) {\n throw new TypeError(\n `AnalystRegistry.runExact analyst \"${id}\" executionConfig must be an object`,\n )\n }\n const rawCost = canonicalJsonSnapshot(\n rawCostValue,\n `AnalystRegistry.runExact analyst \"${id}\" cost`,\n )\n const cost =\n rawCost.kind === 'llm'\n ? Object.freeze({\n ...rawCost,\n settlement_timeout_ms: validateUsageSettlementTimeout(rawCost.settlement_timeout_ms),\n })\n : rawCost\n const requires =\n requiresValue === undefined\n ? undefined\n : canonicalJsonSnapshot(\n requiresValue,\n `AnalystRegistry.runExact analyst \"${id}\" requirements`,\n )\n const analyze = analyzeValue.bind(analyst)\n return Object.freeze({\n id,\n description,\n inputKind,\n cost,\n ...(requires === undefined ? {} : { requires }),\n version,\n executionConfig,\n analyze,\n }) satisfies ExactCapableAnalyst\n })\n}\n\nfunction hasRegistryHooks(hooks: AnalystHooks | undefined): hooks is AnalystHooks {\n return Boolean(\n hooks && (hooks.onBeforeAnalyze || hooks.onAfterAnalyze || hooks.onError || hooks.onComplete),\n )\n}\n\nfunction snapshotHooks(hooks: AnalystHooks): AnalystHooks {\n const onBeforeAnalyze = hooks.onBeforeAnalyze\n const onAfterAnalyze = hooks.onAfterAnalyze\n const onError = hooks.onError\n const onComplete = hooks.onComplete\n return Object.freeze({\n ...(onBeforeAnalyze === undefined ? {} : { onBeforeAnalyze: onBeforeAnalyze.bind(hooks) }),\n ...(onAfterAnalyze === undefined ? {} : { onAfterAnalyze: onAfterAnalyze.bind(hooks) }),\n ...(onError === undefined ? {} : { onError: onError.bind(hooks) }),\n ...(onComplete === undefined ? {} : { onComplete: onComplete.bind(hooks) }),\n })\n}\n\nfunction snapshotChat(chat: ChatClient): ChatClient {\n const transport = chat.transport\n const defaultModel = chat.defaultModel\n const maximumAttempts = chat.maximumAttempts\n const call = chat.chat\n return Object.freeze({\n transport,\n ...(defaultModel === undefined ? {} : { defaultModel }),\n ...(maximumAttempts === undefined ? {} : { maximumAttempts }),\n chat: call.bind(chat),\n })\n}\n\nfunction requireExactComponentIdentity(\n value: ExactExecutionComponentIdentity | undefined,\n label: string,\n): ExactExecutionComponentSnapshot {\n if (value === undefined) {\n throw new TypeError(`AnalystRegistry.runExact: ${label} requires a versioned identity`)\n }\n return snapshotExactExecutionComponentIdentity(\n value,\n `AnalystRegistry.runExact ${label} identity`,\n )\n}\n\nfunction exactExecutionSnapshot(\n analysts: readonly ExactCapableAnalyst[],\n opts: ExactRegistryRunOpts,\n allocations: Readonly<Record<string, number | null>>,\n costLedger: ExactExecutionComponentSnapshot | null,\n hooks: ExactExecutionComponentSnapshot | null,\n chat: ExactExecutionComponentSnapshot | null,\n): ExactAnalystExecutionPlanSnapshot {\n const priorFindings = exactPriorFindingsSnapshot(opts.priorFindings)\n const budget =\n opts.budget === null\n ? ({ kind: 'none' } as const)\n : opts.budget.kind === 'equal'\n ? ({\n kind: 'equal',\n total_usd: opts.budget.totalUsd,\n allocations_usd: { ...allocations },\n } as const)\n : ({\n kind: 'weighted',\n total_usd: opts.budget.totalUsd,\n weights: { ...opts.budget.weights },\n allocations_usd: { ...allocations },\n } as const)\n const material = {\n schema_version: '1.0.0' as const,\n analysts: analysts.map((analyst) => ({\n id: analyst.id,\n version: analyst.version,\n input_kind: analyst.inputKind,\n cost: analyst.cost,\n requirements: analyst.requires ?? null,\n execution_config_digest: hashCanonical(analyst.executionConfig),\n })),\n policy: {\n budget,\n total_timeout_ms: opts.totalTimeoutMs,\n signal_provided: opts.signal !== null,\n cost_ledger: costLedger,\n cost_phase: opts.costPhase,\n tags: opts.tags === null ? null : { ...opts.tags },\n prior_findings: priorFindings,\n chain_findings: opts.chainFindings,\n missing_input_mode: opts.missingInputMode,\n registry_hooks: hooks,\n registry_chat: chat,\n },\n }\n return snapshotExactExecutionPlan(\n { ...material, digest: hashCanonical(material) },\n 'AnalystRegistry.runExact execution plan',\n )\n}\n\nfunction exactPriorFindingsSnapshot(\n findings: ExactRegistryRunOpts['priorFindings'],\n): ExactAnalystExecutionPlanSnapshot['policy']['prior_findings'] {\n if (findings === null) return { kind: 'none' }\n if (Array.isArray(findings)) {\n return {\n kind: 'ordered',\n count: findings.length,\n digest: hashCanonical(findings),\n }\n }\n const record = findings as Readonly<Record<string, ReadonlyArray<AnalystFinding>>>\n const keys = Object.keys(record).sort()\n return {\n kind: 'by_analyst',\n keys,\n count: keys.reduce((sum, key) => sum + (record[key]?.length ?? 0), 0),\n digest: hashCanonical(record),\n }\n}\n\nfunction canonicalJsonSnapshot<T>(value: T, label: string): T {\n let snapshot: T\n try {\n snapshot = JSON.parse(canonicalString(value)) as T\n } catch (cause) {\n throw new TypeError(`${label} must be canonical JSON`, { cause })\n }\n return deepFreezeCanonicalJson(snapshot)\n}\n\nfunction snapshotUsageReceiptOnce(\n receipt: AnalystUsageReceipt,\n context: string,\n): AnalystUsageReceipt {\n const data = readOwnFields(receipt, ['calls', 'tokens', 'cost', 'knownCostUsd'], context)\n data.tokens =\n data.tokens === null\n ? null\n : readOwnFields(\n data.tokens,\n ['input', 'output', 'reasoning', 'cached', 'cacheWrite'],\n `${context} tokens`,\n )\n data.cost = readOwnFields(data.cost, ['kind', 'usd'], `${context} cost`)\n const snapshot = canonicalJsonSnapshot(data as unknown as AnalystUsageReceipt, context)\n assertValidAnalystUsageReceipt(snapshot, context)\n return snapshot\n}\n\nfunction readOwnFields(\n value: unknown,\n fields: readonly string[],\n context: string,\n): Record<string, unknown> {\n if (!isPlainRecord(value)) throw new TypeError(`${context} must be a plain object`)\n const unexpected = Object.keys(value).filter((key) => !fields.includes(key))\n if (unexpected.length > 0) {\n throw new TypeError(`${context} contains unknown fields: ${unexpected.sort().join(', ')}`)\n }\n return Object.fromEntries(\n fields.flatMap((field) => (Object.hasOwn(value, field) ? [[field, value[field]]] : [])),\n )\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false\n const prototype = Object.getPrototypeOf(value)\n return prototype === Object.prototype || prototype === null\n}\n\nfunction exactFixedBudgets(\n exact: ExactAnalystBudgetPolicy | null,\n runnable: readonly Analyst[],\n selected: readonly Analyst[],\n): Readonly<Record<string, number | null>> {\n if (exact === null) return {}\n const allocations: Record<string, number | null> = Object.fromEntries(\n selected.map((analyst) => [analyst.id, null]),\n )\n if (runnable.length === 0) return deepFreezeCanonicalJson(allocations)\n if (exact.kind === 'equal') {\n const each = exact.totalUsd / runnable.length\n for (const analyst of runnable) allocations[analyst.id] = each\n return deepFreezeCanonicalJson(allocations)\n }\n const totalWeight = runnable.reduce((sum, analyst) => sum + exact.weights[analyst.id]!, 0)\n if (totalWeight === 0) {\n throw new Error(\n 'ExactRegistryRunOpts weighted budget must allocate positive weight to a runnable analyst',\n )\n }\n for (const analyst of runnable) {\n allocations[analyst.id] = (exact.totalUsd * exact.weights[analyst.id]!) / totalWeight\n }\n return deepFreezeCanonicalJson(allocations)\n}\n\ninterface AnalystExecution {\n readonly summary: AnalystRunSummary\n readonly findings: AnalystFinding[]\n readonly budgetDebitUsd: number\n}\n\nfunction snapshotExecutionFindings(\n findings: AnalystFinding[],\n exact: boolean,\n context: string,\n): AnalystFinding[] {\n return exact ? deepFreezeCanonicalJson(snapshotAnalystFindings(findings, context)) : findings\n}\n\nfunction snapshotAfterHookValues(\n summary: AnalystRunSummary,\n findings: AnalystFinding[],\n exact: boolean,\n): { summary: AnalystRunSummary; findings: AnalystFinding[] } {\n if (!exact) return { summary, findings }\n return {\n summary: canonicalJsonSnapshot(summary, 'AnalystRegistry.runExact onAfterAnalyze summary'),\n findings: deepFreezeCanonicalJson(\n snapshotAnalystFindings(findings, 'AnalystRegistry.runExact onAfterAnalyze findings'),\n ),\n }\n}\n\nfunction exactPlannedAllocation(\n plan: ExactAnalystExecutionPlanSnapshot,\n analystId: string,\n): number | undefined {\n const budget = plan.policy.budget\n if (budget.kind === 'none') return undefined\n const allocated = budget.allocations_usd[analystId]\n return allocated === null ? undefined : allocated\n}\n\nfunction snapshotExecutionEvent<T extends InternalAnalystRunEvent>(event: T, exact: boolean): T {\n return exact ? canonicalJsonSnapshot(event, 'AnalystRegistry.runExact event') : event\n}\n\nfunction logUncapturedBudgetWarning(args: {\n analyst: Analyst\n runId: string\n budgetUsd: number | undefined\n usage: AnalystUsageReceipt\n log: (message: string, fields?: Record<string, unknown>) => void\n}): void {\n if (args.budgetUsd === undefined || args.usage.cost.kind !== 'uncaptured') return\n args.log(`[analyst] WARN ${args.analyst.id} — USD cost uncaptured; budget not reconciled`, {\n runId: args.runId,\n budget_usd: args.budgetUsd,\n cost_captured: false,\n })\n}\n\nfunction validateTimeout(timeoutMs: number | undefined): number | undefined {\n if (timeoutMs === undefined) return undefined\n if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647) {\n throw new TypeError(\n 'RegistryRunOpts.timeoutMs must be a positive safe integer no greater than 2147483647',\n )\n }\n return timeoutMs\n}\n\nasync function waitForOperation<T>(\n operation: Promise<T>,\n signal: AbortSignal | undefined,\n abortGraceMs: number,\n): Promise<T> {\n if (!signal) return operation\n if (signal.aborted) {\n void operation.catch(() => {})\n throw abortReason(signal)\n }\n return new Promise<T>((resolve, reject) => {\n let settlementTimer: ReturnType<typeof setTimeout> | undefined\n const cleanup = (): void => {\n signal.removeEventListener('abort', onAbort)\n if (settlementTimer) clearTimeout(settlementTimer)\n }\n const onAbort = (): void => {\n if (abortGraceMs === 0) {\n cleanup()\n reject(abortReason(signal))\n return\n }\n settlementTimer = setTimeout(() => {\n cleanup()\n reject(abortReason(signal))\n }, abortGraceMs)\n }\n signal.addEventListener('abort', onAbort, { once: true })\n operation.then(\n (value) => {\n cleanup()\n if (signal.aborted) reject(abortReason(signal))\n else resolve(value)\n },\n (error) => {\n cleanup()\n reject(signal.aborted ? abortReason(signal) : error)\n },\n )\n })\n}\n\nasync function waitForHook<T>(\n operation: (() => T | Promise<T>) | undefined,\n signal: AbortSignal | undefined,\n): Promise<T | undefined> {\n if (operation === undefined || signal?.aborted) return undefined\n try {\n return await waitForOperation(\n Promise.resolve().then(() => {\n if (signal?.aborted) throw abortReason(signal)\n return operation()\n }),\n signal,\n 0,\n )\n } catch (error) {\n if (signal?.aborted) return undefined\n throw error\n }\n}\n\nfunction analystAbortGraceMs(analyst: Analyst): number {\n if (analyst.cost.kind === 'deterministic') return 0\n const settlementMs = validateUsageSettlementTimeout(analyst.cost.settlement_timeout_ms)\n if (settlementMs === 0) return 0\n return Math.min(settlementMs + 100, 2_147_483_647)\n}\n\nfunction abortedBeforeStartSummary(\n analyst: Analyst,\n signal: AbortSignal,\n latencyMs = 0,\n): AnalystRunSummary {\n const reason = abortReason(signal)\n return {\n analyst_id: analyst.id,\n status: 'skipped',\n reason: `${reason.name}: ${reason.message}`,\n findings_count: 0,\n latency_ms: latencyMs,\n usage: zeroUsage(),\n }\n}\n\nfunction abortReason(signal: AbortSignal): Error {\n return signal.reason instanceof Error\n ? signal.reason\n : new DOMException('The operation was aborted', 'AbortError')\n}\n\n/**\n * Default budget allocator: prefer the custom `allocate` callback if\n * provided; else weighted split when weights are set; else equal split\n * across `runningCount`. Returns undefined when no totalUsd is known.\n */\nfunction allocateBudget(\n policy: BudgetPolicy | undefined,\n args: {\n analyst: Analyst\n remainingUsd: number | undefined\n runningCount: number\n totalWeight: number | undefined\n },\n): number | undefined {\n if (!policy) return undefined\n if (policy.allocate) {\n const allocated = policy.allocate({\n analyst: args.analyst,\n totalUsd: policy.totalUsd,\n remainingUsd: args.remainingUsd,\n runningCount: args.runningCount,\n })\n if (allocated === undefined) {\n if (policy.totalUsd !== undefined) {\n throw new Error(\n `BudgetPolicy.allocate('${args.analyst.id}') cannot return undefined when totalUsd is set`,\n )\n }\n return undefined\n }\n assertBudgetAmount(allocated, `BudgetPolicy.allocate('${args.analyst.id}')`)\n return args.remainingUsd === undefined ? allocated : Math.min(allocated, args.remainingUsd)\n }\n if (policy.totalUsd == null) return undefined\n const allocated = policy.weights\n ? (policy.totalUsd * analystWeight(policy.weights, args.analyst.id)) / args.totalWeight!\n : policy.totalUsd / Math.max(1, args.runningCount)\n return args.remainingUsd === undefined ? allocated : Math.min(allocated, args.remainingUsd)\n}\n\nfunction validateBudgetPolicy(policy: BudgetPolicy | undefined): void {\n if (!policy) return\n if (policy.totalUsd !== undefined) assertBudgetAmount(policy.totalUsd, 'BudgetPolicy.totalUsd')\n for (const [analystId, weight] of Object.entries(policy.weights ?? {})) {\n assertBudgetAmount(weight, `BudgetPolicy.weights['${analystId}']`)\n }\n}\n\nfunction assertBudgetAmount(value: number, field: string): void {\n if (!Number.isFinite(value) || value < 0) {\n throw new Error(`${field} must be a non-negative finite number`)\n }\n}\n\nfunction validateEffectiveBudget(\n budgetUsd: number | undefined,\n remainingUsd: number | undefined,\n analystId: string,\n): number | undefined {\n if (budgetUsd !== undefined) {\n assertBudgetAmount(budgetUsd, `AnalystContext.budgetUsd for '${analystId}'`)\n }\n if (remainingUsd === undefined) return budgetUsd\n if (budgetUsd === undefined) {\n throw new Error(\n `AnalystContext.budgetUsd for '${analystId}' cannot be removed while an overall budget remains`,\n )\n }\n if (budgetUsd > remainingUsd) {\n throw new Error(\n `AnalystContext.budgetUsd for '${analystId}' (${budgetUsd}) exceeds the remaining overall budget (${remainingUsd})`,\n )\n }\n return budgetUsd\n}\n\nfunction analystWeight(weights: Record<string, number>, analystId: string): number {\n const weight = weights[analystId] ?? 1\n assertBudgetAmount(weight, `BudgetPolicy.weights['${analystId}']`)\n return weight\n}\n\nfunction zeroUsage(): AnalystUsageReceipt {\n return {\n calls: 0,\n tokens: { input: 0, output: 0 },\n cost: { kind: 'observed', usd: 0 },\n }\n}\n\nfunction resolveUsage(\n analyst: Analyst,\n receipts: ReadonlyArray<AnalystUsageReceipt>,\n exact = false,\n): AnalystUsageReceipt {\n if (receipts.length > 0) return mergeUsageReceipts(receipts, exact)\n if (analyst.cost.kind === 'deterministic') return zeroUsage()\n return { calls: null, tokens: null, cost: { kind: 'uncaptured', usd: null } }\n}\n\nfunction mergeUsageReceipts(\n receipts: ReadonlyArray<AnalystUsageReceipt>,\n exact = false,\n): AnalystUsageReceipt {\n const calls = receipts.every((receipt) => receipt.calls !== null)\n ? usageSum(\n receipts.map((receipt) => receipt.calls ?? 0),\n exact,\n 'calls',\n true,\n )\n : null\n const tokens = receipts.every((receipt) => receipt.tokens !== null)\n ? (Object.fromEntries(\n (['input', 'output', 'reasoning', 'cached', 'cacheWrite'] as const).flatMap((field) =>\n field === 'input' ||\n field === 'output' ||\n receipts.some((receipt) => receipt.tokens?.[field] !== undefined)\n ? [\n [\n field,\n usageSum(\n receipts.map((receipt) => receipt.tokens?.[field] ?? 0),\n exact,\n `tokens.${field}`,\n true,\n ),\n ],\n ]\n : [],\n ),\n ) as unknown as RunTokenUsage)\n : null\n const cost = aggregateCostProvenance(\n receipts.map((receipt) => receipt.cost),\n exact,\n )\n return {\n calls,\n tokens,\n cost,\n ...(cost.kind === 'uncaptured'\n ? {\n knownCostUsd: usageSum(receipts.map(knownCostUsd), exact, 'known cost'),\n }\n : {}),\n }\n}\n\nfunction knownCostUsd(receipt: AnalystUsageReceipt): number {\n return receipt.cost.kind === 'uncaptured' ? (receipt.knownCostUsd ?? 0) : receipt.cost.usd\n}\n\nfunction budgetDebit(receipt: AnalystUsageReceipt, allocatedUsd: number | undefined): number {\n const known = knownCostUsd(receipt)\n return receipt.cost.kind === 'uncaptured' && allocatedUsd !== undefined\n ? Math.max(known, allocatedUsd)\n : known\n}\n\nfunction aggregateCostProvenance(\n costs: ReadonlyArray<RunCostProvenance>,\n exact = false,\n): RunCostProvenance {\n if (costs.some((cost) => cost.kind === 'uncaptured')) {\n return { kind: 'uncaptured', usd: null }\n }\n const usd = usageSum(\n costs.map((cost) => cost.usd ?? 0),\n exact,\n 'captured cost',\n )\n return costs.some((cost) => cost.kind === 'estimated')\n ? { kind: 'estimated', usd }\n : { kind: 'observed', usd }\n}\n\nfunction executionCost(\n executions: ReadonlyArray<AnalystExecution>,\n exact: boolean,\n): { known: number; provenance: RunCostProvenance } {\n const usages = executions.map((execution) => execution.summary.usage)\n return {\n known: usageSum(usages.map(knownCostUsd), exact, 'run known cost'),\n provenance: aggregateCostProvenance(\n usages.map((usage) => usage.cost),\n exact,\n ),\n }\n}\n\nfunction usageSum(\n values: readonly number[],\n exact: boolean,\n field: string,\n integer = false,\n): number {\n const sum = values.reduce((total, value) => total + value, 0)\n if (exact && (integer ? !Number.isSafeInteger(sum) : !Number.isFinite(sum))) {\n throw new RangeError(\n `exact analyst usage ${field} aggregate ${integer ? 'exceeds a safe integer' : 'is not finite'}`,\n )\n }\n return sum\n}\n\n/**\n * Resolve the `priorFindings` slice an analyst sees.\n *\n * - Array form → the analyst sees only findings whose `analyst_id`\n * matches its own id, so a kind never reads\n * another kind's history by accident.\n * - Record form → the analyst gets the entry keyed by its id, with\n * the `'*'` wildcard appended (in that order). Use\n * the wildcard when several kinds should see the same\n * historical findings.\n */\nfunction selectPriorFindings(\n source: RegistryRunOpts['priorFindings'],\n analystId: string,\n): ReadonlyArray<AnalystFinding> | undefined {\n if (!source) return undefined\n if (Array.isArray(source)) {\n const own = source.filter((f) => f.analyst_id === analystId)\n return own.length > 0 ? own : undefined\n }\n const record = source as Record<string, ReadonlyArray<AnalystFinding>>\n const own = record[analystId] ?? []\n const wildcard = record['*'] ?? []\n const merged = [...own, ...wildcard]\n return merged.length > 0 ? merged : undefined\n}\n","import { type BehavioralAnalystOptions, behavioralAnalyst } from './behavioral-analyst'\nimport type { TraceAnalysisEngine } from './engine'\nimport { createTraceAnalyst, type TraceAnalystDefinition } from './kind-factory'\nimport { DEFAULT_TRACE_ANALYST_KINDS } from './kinds'\nimport { AnalystRegistry, type AnalystRegistryOptions } from './registry'\n\nexport interface DefaultAnalystRegistryOptions {\n /**\n * Recursive engine for model-backed trace analysts. When omitted, the\n * registry contains only deterministic analysts. The engine's id, version,\n * and model become the exact-run identity of every analyst it executes.\n */\n engine?: TraceAnalysisEngine\n definitions?: readonly TraceAnalystDefinition[]\n /** Set false to omit the deterministic behavioral analyst (default: include). */\n includeBehavioral?: boolean\n behavioral?: BehavioralAnalystOptions\n registry?: AnalystRegistryOptions\n}\n\nexport function buildDefaultAnalystRegistry(\n options: DefaultAnalystRegistryOptions = {},\n): AnalystRegistry {\n if (options.definitions && !options.engine) {\n throw new TypeError(\n 'buildDefaultAnalystRegistry: definitions require an engine — a definition cannot run without one',\n )\n }\n const registry = new AnalystRegistry(options.registry)\n if (options.includeBehavioral !== false) {\n registry.register(behavioralAnalyst(options.behavioral))\n }\n if (options.engine) {\n for (const definition of options.definitions ?? DEFAULT_TRACE_ANALYST_KINDS) {\n registry.register(createTraceAnalyst(definition, { engine: options.engine }))\n }\n }\n return registry\n}\n","/**\n * Provider-neutral chat contract for every model call made by agent-eval.\n *\n * The caller owns model execution. agent-eval issues no provider request and\n * holds no provider credential: `createChatClient` binds a transport the\n * caller supplies, and evaluation code receives canonical requests and results\n * without importing a provider SDK.\n */\n\nimport type { LlmCallRequest, LlmCallResult } from '../llm-client'\n\n/**\n * Unified chat interface using the package's canonical LLM request and result.\n */\nexport interface ChatClient {\n /** Display name of the bound transport, included in telemetry. */\n readonly transport: ChatTransport\n /** Default model when the caller omits one. */\n readonly defaultModel?: string\n /** Total provider attempts this transport can make for one chat call. */\n readonly maximumAttempts?: number\n\n /** Implementations must enforce `req.maxTokens` when it is present. */\n chat(req: ChatRequest, opts?: ChatCallOpts): Promise<ChatResponse>\n}\n\nexport type ChatTransport =\n | 'sandbox-sdk' // box.streamPrompt() — chat completion via sandbox SDK\n | 'custom' // caller-adapted SDK or transport\n | 'mock' // test-time injection\n\nexport interface ChatRequest extends Omit<LlmCallRequest, 'model'> {\n /** Optional — falls back to ChatClient.defaultModel. */\n model?: string\n}\n\nexport type ChatResponse = LlmCallResult\n\nexport interface ChatCallOpts {\n /** Cancel the in-flight request. */\n signal?: AbortSignal\n /** Hard USD ceiling for this single call (informational; the underlying transport may not enforce). */\n maxCostUsd?: number\n /** Correlation tag carried into request headers when the transport allows. */\n correlationId?: string\n /** Stable provider idempotency key for retries/redrives of one paid call. */\n idempotencyKey?: string\n}\n\n// ── Factory ─────────────────────────────────────────────────────────\n\nexport type CreateChatClientOpts = SandboxSdkTransportOpts | CustomTransportOpts | MockTransportOpts\n\ninterface BaseTransportOpts {\n defaultModel?: string\n /** Total provider attempts. Required for opaque transports used in capped runs. */\n maximumAttempts?: number\n}\n\n/**\n * Sandbox-SDK transport. The caller supplies a canonical chat function for an\n * already-configured Sandbox handle, so agent-eval does not import the SDK.\n */\nexport interface SandboxSdkTransportOpts extends BaseTransportOpts {\n transport: 'sandbox-sdk'\n chat: (req: ChatRequest, opts?: ChatCallOpts) => Promise<ChatResponse>\n}\n\n/** Caller-adapted SDK or transport returning the canonical ChatResponse shape. */\nexport interface CustomTransportOpts extends BaseTransportOpts {\n transport: 'custom'\n chat: (req: ChatRequest, opts?: ChatCallOpts) => Promise<ChatResponse>\n}\n\n/**\n * Mock transport for tests. The handler receives the request and returns\n * whatever the test wants. No retries, no JSON-schema degrade.\n */\nexport interface MockTransportOpts extends BaseTransportOpts {\n transport: 'mock'\n handler: (req: ChatRequest, opts?: ChatCallOpts) => Promise<ChatResponse>\n}\n\n/**\n * Build a ChatClient bound to a specific transport. The returned client\n * is safe to share across analysts in a single registry run.\n */\nexport function createChatClient(opts: CreateChatClientOpts): ChatClient {\n switch (opts.transport) {\n case 'sandbox-sdk':\n return {\n transport: 'sandbox-sdk',\n defaultModel: opts.defaultModel,\n maximumAttempts: opts.maximumAttempts,\n chat: async (req, callOpts) => opts.chat(resolveModel(req, opts.defaultModel), callOpts),\n }\n case 'custom':\n return {\n transport: 'custom',\n defaultModel: opts.defaultModel,\n maximumAttempts: opts.maximumAttempts,\n chat: async (req, callOpts) => opts.chat(resolveModel(req, opts.defaultModel), callOpts),\n }\n case 'mock':\n return {\n transport: 'mock',\n defaultModel: opts.defaultModel,\n maximumAttempts: 1,\n chat: async (req, callOpts) => opts.handler(resolveModel(req, opts.defaultModel), callOpts),\n }\n }\n}\n\nfunction resolveModel(req: ChatRequest, defaultModel: string | undefined): ChatRequest {\n if (req.model) return req\n if (!defaultModel) {\n throw new Error(\n 'ChatClient.chat: no model on request and no defaultModel on the client. ' +\n 'Either pass req.model or bind defaultModel at createChatClient().',\n )\n }\n return { ...req, model: defaultModel }\n}\n"],"mappings":";;;;;;;;;;;AAqEA,SAAgB,qBAAqB,SAA+C;CAClF,OAAO,cAAc,uBAAuB,SAAS,iBAAiB,CAAC;AACzE;;AAGA,SAAgB,iBAAiB,KAAyC;CACxE,OAAO,cAAc,mBAAmB,KAAK,aAAa,CAAC;AAC7D;AAEA,SAAgB,mBAAmB,OAAgB,UAAU,eAAiC;CAC5F,MAAM,WAAW,yBAAyB,OAAO,OAAO;CACxD,IAAI,SAAS,mBAAmB,KAAA,GAC9B,OAAO,2BAA2B,UAAU,OAAO;CAErD,IAAI,SAAS,eAAe,KAAA,GAC1B,MAAM,IAAI,UAAU,GAAG,QAAQ,2CAA2C;CAE5E,OAAO;AACT;;AAGA,SAAgB,+BACd,OACA,UAAU,6BACa;CACvB,OAAO,2BAA2B,yBAAyB,OAAO,OAAO,GAAG,OAAO;AACrF;AAEA,SAAS,yBAAyB,OAAgB,SAA0C;CAC1F,IAAI;CACJ,IAAI;EACF,WAAW,KAAK,MAAM,gBAAgB,KAAK,CAAC;CAC9C,SAAS,OAAO;EACd,MAAM,IAAI,UAAU,GAAG,QAAQ,6CAA6C,EAAE,MAAM,CAAC;CACvF;CACA,IAAI,CAAC,SAAS,QAAQ,GAAG,MAAM,IAAI,UAAU,GAAG,QAAQ,mBAAmB;CAC3E,eACE,UACA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,GACA,OACF;CACA,eAAe,SAAS,QAAQ,GAAG,QAAQ,QAAQ;CACnD,eAAe,SA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