@tangle-network/agent-eval 0.216.1 → 0.218.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (532) hide show
  1. package/CHANGELOG.md +137 -57
  2. package/README.md +2 -2
  3. package/dist/adapters/http.d.ts +2 -2
  4. package/dist/{agent-profile-VFcQncbW.d.ts → agent-profile-DTt8uGP9.d.ts} +4 -17
  5. package/dist/agent-profile-DTt8uGP9.d.ts.map +1 -0
  6. package/dist/{agent-profile-cell-BK8mlqlq.js → agent-profile-cell-B1V1gUZs.js} +4 -53
  7. package/dist/agent-profile-cell-B1V1gUZs.js.map +1 -0
  8. package/dist/{agent-profile-cell-BNp-Js9F.d.ts → agent-profile-cell-BcpFbNd5.d.ts} +2 -22
  9. package/dist/agent-profile-cell-BcpFbNd5.d.ts.map +1 -0
  10. package/dist/{agreement-irr-BEWLIF3_.js → agreement-irr-BhAqjluA.js} +5 -5
  11. package/dist/agreement-irr-BhAqjluA.js.map +1 -0
  12. package/dist/analyst/index.d.ts +36 -169
  13. package/dist/analyst/index.d.ts.map +1 -1
  14. package/dist/analyst/index.js +17 -192
  15. package/dist/analyst/index.js.map +1 -1
  16. package/dist/{analyze-runs-D68fd-su.d.ts → analyze-runs-DjlZOVXx.d.ts} +5 -5
  17. package/dist/{analyze-runs-D68fd-su.d.ts.map → analyze-runs-DjlZOVXx.d.ts.map} +1 -1
  18. package/dist/{analyze-runs-C84irm4i.js → analyze-runs-DqPJaJ4X.js} +225 -21
  19. package/dist/analyze-runs-DqPJaJ4X.js.map +1 -0
  20. package/dist/authenticity/index.d.ts +0 -23
  21. package/dist/authenticity/index.d.ts.map +1 -1
  22. package/dist/authenticity/index.js +1 -34
  23. package/dist/authenticity/index.js.map +1 -1
  24. package/dist/{benchmark-command-By0vh8q7.js → benchmark-command-BupdHRyf.js} +1225 -661
  25. package/dist/benchmark-command-BupdHRyf.js.map +1 -0
  26. package/dist/benchmarks/index.d.ts +5 -6
  27. package/dist/benchmarks/index.d.ts.map +1 -1
  28. package/dist/benchmarks/index.js +4 -4
  29. package/dist/benchmarks/index.js.map +1 -1
  30. package/dist/builder-eval/index.d.ts +3 -3
  31. package/dist/builder-eval/index.js +2 -2
  32. package/dist/builder-eval/index.js.map +1 -1
  33. package/dist/campaign/index.d.ts +7 -7
  34. package/dist/campaign/index.js +15 -15
  35. package/dist/{campaign-BudZ70zo.js → campaign-CGvUTnmc.js} +324 -800
  36. package/dist/campaign-CGvUTnmc.js.map +1 -0
  37. package/dist/{campaign-evidence-Clrn4hBV.js → campaign-evidence-DunzcJGv.js} +10 -18
  38. package/dist/{campaign-evidence-Clrn4hBV.js.map → campaign-evidence-DunzcJGv.js.map} +1 -1
  39. package/dist/{canonical-B2RqLofv.js → canonical-Dq2hOQ8L.js} +2 -2
  40. package/dist/{canonical-B2RqLofv.js.map → canonical-Dq2hOQ8L.js.map} +1 -1
  41. package/dist/cell-spend-DEWR3nj-.js +90 -0
  42. package/dist/cell-spend-DEWR3nj-.js.map +1 -0
  43. package/dist/{chat-client-l-MVDlDk.js → chat-client-B2pXlPdx.js} +2 -2
  44. package/dist/{chat-client-l-MVDlDk.js.map → chat-client-B2pXlPdx.js.map} +1 -1
  45. package/dist/{chat-json-call-puMArmtW.js → chat-json-call-Dm9c-b41.js} +3 -2
  46. package/dist/chat-json-call-Dm9c-b41.js.map +1 -0
  47. package/dist/{claim-q4HQhK1G.js → claim-BPVuyHuy.js} +3 -3
  48. package/dist/{claim-q4HQhK1G.js.map → claim-BPVuyHuy.js.map} +1 -1
  49. package/dist/cli.js +113 -12
  50. package/dist/cli.js.map +1 -1
  51. package/dist/{client-BzL9niqi.d.ts → client-hwo3cJjR.d.ts} +3 -16
  52. package/dist/client-hwo3cJjR.d.ts.map +1 -0
  53. package/dist/{cluster-bootstrap-qcUWYFl-.js → cluster-bootstrap-DEwwhl0C.js} +3 -3
  54. package/dist/{cluster-bootstrap-qcUWYFl-.js.map → cluster-bootstrap-DEwwhl0C.js.map} +1 -1
  55. package/dist/{produced-state-BsDmnwxc.js → completion-verifier-DbLVf3i8.js} +9 -64
  56. package/dist/completion-verifier-DbLVf3i8.js.map +1 -0
  57. package/dist/contract/index.d.ts +12 -12
  58. package/dist/contract/index.js +107 -403
  59. package/dist/contract/index.js.map +1 -1
  60. package/dist/{cost-ledger-BP8V4kUQ.js → cost-ledger-D0352Z4d.js} +4 -8
  61. package/dist/cost-ledger-D0352Z4d.js.map +1 -0
  62. package/dist/dataset-DQqhOCPt.d.ts.map +1 -1
  63. package/dist/{default-registry-COhk9g36.js → default-registry-BJ-Pq6yL.js} +314 -285
  64. package/dist/default-registry-BJ-Pq6yL.js.map +1 -0
  65. package/dist/{default-registry-DzHiGruW.d.ts → default-registry-DXgLmoDI.d.ts} +7 -50
  66. package/dist/default-registry-DXgLmoDI.d.ts.map +1 -0
  67. package/dist/{define-agent-eval-CNTPzIkp.js → define-agent-eval-BGdFKlrc.js} +170 -110
  68. package/dist/define-agent-eval-BGdFKlrc.js.map +1 -0
  69. package/dist/{define-agent-eval-WSck0CZJ.d.ts → define-agent-eval-BlH10zEw.d.ts} +8 -8
  70. package/dist/define-agent-eval-BlH10zEw.d.ts.map +1 -0
  71. package/dist/{descriptive-DboxPZrG.js → descriptive-CVNy48rR.js} +2 -2
  72. package/dist/{descriptive-DboxPZrG.js.map → descriptive-CVNy48rR.js.map} +1 -1
  73. package/dist/diagnosis/index.d.ts +4 -14
  74. package/dist/diagnosis/index.d.ts.map +1 -1
  75. package/dist/diagnosis/index.js +67 -28
  76. package/dist/diagnosis/index.js.map +1 -1
  77. package/dist/{dspy-rlm-engine-LRCu61m5.js → dspy-rlm-engine-CSMwudLO.js} +5 -10
  78. package/dist/dspy-rlm-engine-CSMwudLO.js.map +1 -0
  79. package/dist/{emitter-HcCmFQl_.d.ts → emitter-DABYYTcH.d.ts} +5 -5
  80. package/dist/emitter-DABYYTcH.d.ts.map +1 -0
  81. package/dist/emitter-DbMXUIVP.js.map +1 -1
  82. package/dist/{engine-3A_4jOlI.d.ts → engine-BvZ0R-36.d.ts} +17 -21
  83. package/dist/engine-BvZ0R-36.d.ts.map +1 -0
  84. package/dist/{equal-terms-BtdXayCJ.js → equal-terms-DbPGcVtI.js} +2 -2
  85. package/dist/equal-terms-DbPGcVtI.js.map +1 -0
  86. package/dist/{errors-DVZiqS7K.js → errors-BcOs5MKW.js} +2 -8
  87. package/dist/{errors-DVZiqS7K.js.map → errors-BcOs5MKW.js.map} +1 -1
  88. package/dist/eval-campaign-BUMIxKTE.js +393 -0
  89. package/dist/eval-campaign-BUMIxKTE.js.map +1 -0
  90. package/dist/{evaluation-6Yoi74gM.d.ts → evaluation-BOZ38vOH.d.ts} +7 -7
  91. package/dist/evaluation-BOZ38vOH.d.ts.map +1 -0
  92. package/dist/evaluation.d.ts +2 -2
  93. package/dist/evaluation.js +1 -1
  94. package/dist/evaluation.js.map +1 -1
  95. package/dist/{exact-types-ClugMJfI.d.ts → exact-types-CflbJ9f3.d.ts} +2 -2
  96. package/dist/{exact-types-ClugMJfI.d.ts.map → exact-types-CflbJ9f3.d.ts.map} +1 -1
  97. package/dist/{exec-ChJ6d5if.js → exec-CpbtOXVt.js} +2 -24
  98. package/dist/{exec-ChJ6d5if.js.map → exec-CpbtOXVt.js.map} +1 -1
  99. package/dist/execution-tracks-CpgFPpS5.js.map +1 -1
  100. package/dist/experiment/index.d.ts +9 -112
  101. package/dist/experiment/index.d.ts.map +1 -1
  102. package/dist/experiment/index.js +258 -311
  103. package/dist/experiment/index.js.map +1 -1
  104. package/dist/{exporters-X4xwla8A.js → exporters-DWvM16LE.js} +3 -3
  105. package/dist/exporters-DWvM16LE.js.map +1 -0
  106. package/dist/{exporters-ChTnR90l.d.ts → exporters-Dk3oEbK_.d.ts} +2 -4
  107. package/dist/{exporters-ChTnR90l.d.ts.map → exporters-Dk3oEbK_.d.ts.map} +1 -1
  108. package/dist/{external-optimizer-process-BjMGUuds.js → external-optimizer-process-C3Wm7Vhn.js} +4 -3
  109. package/dist/external-optimizer-process-C3Wm7Vhn.js.map +1 -0
  110. package/dist/{external-optimizer-subprocess-BqW0hHcI.js → external-optimizer-subprocess-B5gdLRZv.js} +9 -11
  111. package/dist/external-optimizer-subprocess-B5gdLRZv.js.map +1 -0
  112. package/dist/{extract-usage-BrnzRJ6H.js → extract-usage-BZLU01kR.js} +2 -23
  113. package/dist/{extract-usage-BrnzRJ6H.js.map → extract-usage-BZLU01kR.js.map} +1 -1
  114. package/dist/{failure-cluster-CbgEDcFJ.d.ts → failure-cluster-DN0t63Z0.d.ts} +4 -43
  115. package/dist/failure-cluster-DN0t63Z0.d.ts.map +1 -0
  116. package/dist/{failure-taxonomy-CjabTATj.js → failure-taxonomy-Bx5oWqaW.js} +2 -19
  117. package/dist/{failure-taxonomy-CjabTATj.js.map → failure-taxonomy-Bx5oWqaW.js.map} +1 -1
  118. package/dist/{feedback-trajectory-C4EG0nNH.d.ts → feedback-trajectory-BWmhRBGu.d.ts} +7 -9
  119. package/dist/feedback-trajectory-BWmhRBGu.d.ts.map +1 -0
  120. package/dist/{semantic-concept-judge-BQF8te0T.js → findings-store-BtTzPL0d.js} +9 -249
  121. package/dist/findings-store-BtTzPL0d.js.map +1 -0
  122. package/dist/fuzz.d.ts +19 -62
  123. package/dist/fuzz.d.ts.map +1 -1
  124. package/dist/fuzz.js +62 -108
  125. package/dist/fuzz.js.map +1 -1
  126. package/dist/{hf-dataset-BR2yhuNn.js → hf-dataset-CKxIJQba.js} +4 -24
  127. package/dist/hf-dataset-CKxIJQba.js.map +1 -0
  128. package/dist/hosted/index.d.ts +2 -2
  129. package/dist/hosted/index.js +2 -2
  130. package/dist/{index-CyszSg4O.d.ts → index-B16FNdW5.d.ts} +145 -360
  131. package/dist/index-B16FNdW5.d.ts.map +1 -0
  132. package/dist/{index-DV-jSzxF.d.ts → index-BLGqZ81N.d.ts} +10 -15
  133. package/dist/{index-DV-jSzxF.d.ts.map → index-BLGqZ81N.d.ts.map} +1 -1
  134. package/dist/{index-BO41eGj5.d.ts → index-CX-GAUpw.d.ts} +3 -7
  135. package/dist/index-CX-GAUpw.d.ts.map +1 -0
  136. package/dist/{index-DHKEAv3s.d.ts → index-CalAsXMR.d.ts} +8 -68
  137. package/dist/index-CalAsXMR.d.ts.map +1 -0
  138. package/dist/{index-BFRO6chs.d.ts → index-CiRwLv2R.d.ts} +5 -69
  139. package/dist/index-CiRwLv2R.d.ts.map +1 -0
  140. package/dist/{index-DPcngtwt.d.ts → index-DbMOXYnP.d.ts} +11 -36
  141. package/dist/index-DbMOXYnP.d.ts.map +1 -0
  142. package/dist/index.d.ts +211 -218
  143. package/dist/index.d.ts.map +1 -1
  144. package/dist/index.js +999 -1714
  145. package/dist/index.js.map +1 -1
  146. package/dist/{integrity-dLiDe2kD.js → integrity-C8oUeB0g.js} +326 -203
  147. package/dist/integrity-C8oUeB0g.js.map +1 -0
  148. package/dist/{integrity-BXOsAb3i.js → integrity-W4CADcFc.js} +3 -7
  149. package/dist/{integrity-BXOsAb3i.js.map → integrity-W4CADcFc.js.map} +1 -1
  150. package/dist/{integrity-DAMEDFaC.d.ts → integrity-_qgZLA5p.d.ts} +4 -6
  151. package/dist/{integrity-DAMEDFaC.d.ts.map → integrity-_qgZLA5p.d.ts.map} +1 -1
  152. package/dist/{internal-Epl-YBZW.js → internal-BTK91Bqt.js} +3 -3
  153. package/dist/{internal-Epl-YBZW.js.map → internal-BTK91Bqt.js.map} +1 -1
  154. package/dist/{interval-CELpye1n.js → interval-Dq9gt7jx.js} +3 -3
  155. package/dist/{interval-CELpye1n.js.map → interval-Dq9gt7jx.js.map} +1 -1
  156. package/dist/{journal-DfRz9kps.js → journal-C7om8Gum.js} +157 -147
  157. package/dist/journal-C7om8Gum.js.map +1 -0
  158. package/dist/json-BhdsJaOQ.js +111 -0
  159. package/dist/json-BhdsJaOQ.js.map +1 -0
  160. package/dist/{judge-calibration-BpCy5XQl.js → judge-calibration-BkXMIWA4.js} +3 -3
  161. package/dist/{judge-calibration-BpCy5XQl.js.map → judge-calibration-BkXMIWA4.js.map} +1 -1
  162. package/dist/{judge-gate-iY9s4L44.js → judge-gate-Co5tuh57.js} +4 -27
  163. package/dist/{judge-gate-iY9s4L44.js.map → judge-gate-Co5tuh57.js.map} +1 -1
  164. package/dist/{judge-gate-CE7CQAgt.d.ts → judge-gate-DsL0yFcb.d.ts} +8 -9
  165. package/dist/judge-gate-DsL0yFcb.d.ts.map +1 -0
  166. package/dist/{kind-factory-BobI5Jy3.js → kind-factory-Gy4fXixd.js} +88 -17
  167. package/dist/kind-factory-Gy4fXixd.js.map +1 -0
  168. package/dist/ledger-core/index.d.ts +2 -2
  169. package/dist/ledger-core/index.js +4 -4
  170. package/dist/ledger-core/lock-holder.d.ts +2 -0
  171. package/dist/ledger-core/lock-holder.js +181 -0
  172. package/dist/ledger-core/lock-holder.js.map +1 -0
  173. package/dist/{ledger-core-Gq7yp8lP.js → ledger-core-CAxUdDk0.js} +5 -84
  174. package/dist/ledger-core-CAxUdDk0.js.map +1 -0
  175. package/dist/{llm-client-CyBAoYiX.js → llm-client-_Y6ic-tf.js} +243 -355
  176. package/dist/llm-client-_Y6ic-tf.js.map +1 -0
  177. package/dist/{llm-judge-CG12SQJq.js → llm-judge-Djxh-Uhs.js} +662 -482
  178. package/dist/llm-judge-Djxh-Uhs.js.map +1 -0
  179. package/dist/lock-holder-DaJbfpci.d.ts +86 -0
  180. package/dist/lock-holder-DaJbfpci.d.ts.map +1 -0
  181. package/dist/matrix/index.d.ts +3 -3
  182. package/dist/matrix/index.js +3 -2
  183. package/dist/{matrix-Dm0BQW7U.js → matrix-B8l-Nsxd.js} +3 -88
  184. package/dist/matrix-B8l-Nsxd.js.map +1 -0
  185. package/dist/{matrix-DSrSxjjy.d.ts → matrix-CCSBna4q.d.ts} +9 -18
  186. package/dist/matrix-CCSBna4q.d.ts.map +1 -0
  187. package/dist/{mean-DHoMiudD.js → mean-BbA_JCzW.js} +39 -5
  188. package/dist/mean-BbA_JCzW.js.map +1 -0
  189. package/dist/meta-eval/index.d.ts +5 -5
  190. package/dist/meta-eval/index.js +10 -10
  191. package/dist/metrics-BKaPBtIG.js.map +1 -1
  192. package/dist/{mint-DNU8QPG4.d.ts → mint-BRZXuwRi.d.ts} +4 -4
  193. package/dist/{mint-DNU8QPG4.d.ts.map → mint-BRZXuwRi.d.ts.map} +1 -1
  194. package/dist/{mint-QaD5cA0u.js → mint-CbdwjTPW.js} +4 -4
  195. package/dist/{mint-QaD5cA0u.js.map → mint-CbdwjTPW.js.map} +1 -1
  196. package/dist/{multi-layer-verifier-BUaQ4C17.d.ts → multi-layer-verifier-DEgMUk6v.d.ts} +2 -2
  197. package/dist/{multi-layer-verifier-BUaQ4C17.d.ts.map → multi-layer-verifier-DEgMUk6v.d.ts.map} +1 -1
  198. package/dist/{multiplicity-DQUFcbW4.js → multiplicity-Sg0U7h8j.js} +2 -2
  199. package/dist/{multiplicity-DQUFcbW4.js.map → multiplicity-Sg0U7h8j.js.map} +1 -1
  200. package/dist/multishot/golden/index.d.ts +1 -23
  201. package/dist/multishot/golden/index.d.ts.map +1 -1
  202. package/dist/multishot/golden/index.js +3 -3
  203. package/dist/multishot/golden/index.js.map +1 -1
  204. package/dist/multishot/index.d.ts +3 -12
  205. package/dist/multishot/index.d.ts.map +1 -1
  206. package/dist/multishot/index.js +4 -3
  207. package/dist/multishot/index.js.map +1 -1
  208. package/dist/openapi.json +114 -10
  209. package/dist/{otel-spans-B9tUXRHF.js → otel-spans-CdN909k1.js} +3 -3
  210. package/dist/{otel-spans-B9tUXRHF.js.map → otel-spans-CdN909k1.js.map} +1 -1
  211. package/dist/{paired-arms-CwMGJsrS.js → paired-arms-Ct4LTKc1.js} +32 -9
  212. package/dist/paired-arms-Ct4LTKc1.js.map +1 -0
  213. package/dist/{paired-binary-CvpFHfKZ.js → paired-binary-B_nejA44.js} +3 -36
  214. package/dist/paired-binary-B_nejA44.js.map +1 -0
  215. package/dist/{paired-promotion-decision-DPKz8ZnF.d.ts → paired-promotion-decision-CQMJ5xGN.d.ts} +2 -34
  216. package/dist/paired-promotion-decision-CQMJ5xGN.d.ts.map +1 -0
  217. package/dist/{paired-promotion-decision-DsAPYGCm.js → paired-promotion-decision-D0SHb-ZL.js} +3 -3
  218. package/dist/{paired-promotion-decision-DsAPYGCm.js.map → paired-promotion-decision-D0SHb-ZL.js.map} +1 -1
  219. package/dist/{pareto-Cm6ndrWN.js → pareto-CTv8vozZ.js} +11 -11
  220. package/dist/pareto-CTv8vozZ.js.map +1 -0
  221. package/dist/pipelines/index.d.ts +16 -19
  222. package/dist/pipelines/index.d.ts.map +1 -1
  223. package/dist/pipelines/index.js +4 -68
  224. package/dist/pipelines/index.js.map +1 -1
  225. package/dist/{power-and-mde-Hj2ubb4B.js → power-and-mde-N5nU4_Ly.js} +3 -3
  226. package/dist/{power-and-mde-Hj2ubb4B.js.map → power-and-mde-N5nU4_Ly.js.map} +1 -1
  227. package/dist/{prime-protocol-CHKgA3a6.js → prime-protocol-BFgGrEMP.js} +3 -3
  228. package/dist/prime-protocol-BFgGrEMP.js.map +1 -0
  229. package/dist/{prime-protocol-HiB9HX7E.d.ts → prime-protocol-BWG2DQIk.d.ts} +3 -21
  230. package/dist/prime-protocol-BWG2DQIk.d.ts.map +1 -0
  231. package/dist/profile-cell.d.ts +2 -2
  232. package/dist/profile-cell.js +2 -2
  233. package/dist/{promotion-gate-BawrdPYr.d.ts → promotion-gate-CxEHRsZW.d.ts} +7 -8
  234. package/dist/{promotion-gate-BawrdPYr.d.ts.map → promotion-gate-CxEHRsZW.d.ts.map} +1 -1
  235. package/dist/{promotion-policy-KO57gbyV.js → promotion-policy-6A8osGr_.js} +4 -4
  236. package/dist/{promotion-policy-KO57gbyV.js.map → promotion-policy-6A8osGr_.js.map} +1 -1
  237. package/dist/{proposal-findings-CY1xKn_a.js → proposal-findings-n-5WBbEx.js} +3 -3
  238. package/dist/proposal-findings-n-5WBbEx.js.map +1 -0
  239. package/dist/{query-BUCZCK7F.js → query-B_RZ36an.js} +5 -5
  240. package/dist/query-B_RZ36an.js.map +1 -0
  241. package/dist/{query-DK1nWcmp.d.ts → query-Cmv_U8vf.d.ts} +4 -24
  242. package/dist/{query-DK1nWcmp.d.ts.map → query-Cmv_U8vf.d.ts.map} +1 -1
  243. package/dist/{random-ByUSnV9w.js → random-DDDcC7YU.js} +2 -2
  244. package/dist/{random-ByUSnV9w.js.map → random-DDDcC7YU.js.map} +1 -1
  245. package/dist/{raw-provider-sink-DoHz4JNG.js → raw-provider-sink-75w4FWBj.js} +2 -2
  246. package/dist/{raw-provider-sink-DoHz4JNG.js.map → raw-provider-sink-75w4FWBj.js.map} +1 -1
  247. package/dist/{redact-mtCCcT8z.d.ts → redact-DXdlFb_U.d.ts} +2 -3
  248. package/dist/redact-DXdlFb_U.d.ts.map +1 -0
  249. package/dist/{redact-B5xXKqQ3.js → redact-mtkTiJVk.js} +2 -7
  250. package/dist/{redact-B5xXKqQ3.js.map → redact-mtkTiJVk.js.map} +1 -1
  251. package/dist/{registry-D7_hm2fK.d.ts → registry-ssNoHzwD.d.ts} +4 -4
  252. package/dist/{registry-D7_hm2fK.d.ts.map → registry-ssNoHzwD.d.ts.map} +1 -1
  253. package/dist/{release-confidence-CpuP65S5.js → release-confidence-CYIFH-fp.js} +6 -11
  254. package/dist/release-confidence-CYIFH-fp.js.map +1 -0
  255. package/dist/{report-command-SC9nqb4M.js → render-Cs34y0iX.js} +625 -587
  256. package/dist/render-Cs34y0iX.js.map +1 -0
  257. package/dist/reporting.d.ts +6 -6
  258. package/dist/reporting.js +8 -8
  259. package/dist/{researcher-CEcfku-T.d.ts → researcher-GU1tV4dn.d.ts} +9 -9
  260. package/dist/{researcher-CEcfku-T.d.ts.map → researcher-GU1tV4dn.d.ts.map} +1 -1
  261. package/dist/{reward-CpCmAM8L.d.ts → reward-DrZ71vnf.d.ts} +3 -26
  262. package/dist/reward-DrZ71vnf.d.ts.map +1 -0
  263. package/dist/{reward-hacking-E0d-WVcP.js → reward-hacking-ByuETaIb.js} +3 -3
  264. package/dist/{reward-hacking-E0d-WVcP.js.map → reward-hacking-ByuETaIb.js.map} +1 -1
  265. package/dist/{reward-hacking-RVdZ6Kkt.d.ts → reward-hacking-E52wq86n.d.ts} +5 -18
  266. package/dist/reward-hacking-E52wq86n.d.ts.map +1 -0
  267. package/dist/reward-nw2xZGZG.js.map +1 -1
  268. package/dist/rl.d.ts +117 -295
  269. package/dist/rl.d.ts.map +1 -1
  270. package/dist/rl.js +27 -747
  271. package/dist/rl.js.map +1 -1
  272. package/dist/rollout/index.d.ts +5 -5
  273. package/dist/rollout/index.js +7 -8
  274. package/dist/{rollout-DZV1t2Wg.js → rollout-Dd1ucT_M.js} +88 -13
  275. package/dist/rollout-Dd1ucT_M.js.map +1 -0
  276. package/dist/{rubric-predictive-validity-DaFW70y9.js → rubric-predictive-validity-D3_oI72N.js} +3 -3
  277. package/dist/{rubric-predictive-validity-DaFW70y9.js.map → rubric-predictive-validity-D3_oI72N.js.map} +1 -1
  278. package/dist/{rubric-predictive-validity-C03EC7ZE.d.ts → rubric-predictive-validity-DiwT8PbL.d.ts} +2 -2
  279. package/dist/{rubric-predictive-validity-C03EC7ZE.d.ts.map → rubric-predictive-validity-DiwT8PbL.d.ts.map} +1 -1
  280. package/dist/{run-record-C1E24G2A.d.ts → run-record-CaxbLq6Y.d.ts} +4 -10
  281. package/dist/run-record-CaxbLq6Y.d.ts.map +1 -0
  282. package/dist/{run-record-C5e7FjhJ.js → run-record-CysKLB93.js} +3 -3
  283. package/dist/run-record-CysKLB93.js.map +1 -0
  284. package/dist/{run-record-Boc5IUTp.js → run-record-DhEJgoPz.js} +4 -4
  285. package/dist/{run-record-Boc5IUTp.js.map → run-record-DhEJgoPz.js.map} +1 -1
  286. package/dist/sandbox-harness-BlSOu4LX.d.ts.map +1 -1
  287. package/dist/{schema-CSf6qWgZ.js → schema-Bt2vLFm3.js} +2 -14
  288. package/dist/schema-Bt2vLFm3.js.map +1 -0
  289. package/dist/schema-C-ziyJD7.d.ts.map +1 -1
  290. package/dist/{schema-BuiujZ-g.js → schema-CvhfLjtZ.js} +78 -48
  291. package/dist/schema-CvhfLjtZ.js.map +1 -0
  292. package/dist/{schema-2g7trUwH.d.ts → schema-D6EVKzTB.d.ts} +4 -5
  293. package/dist/schema-D6EVKzTB.d.ts.map +1 -0
  294. package/dist/search/index.d.ts +3 -31
  295. package/dist/search/index.d.ts.map +1 -1
  296. package/dist/search/index.js +4 -4
  297. package/dist/{search-kernel-DyNEa6IU.d.ts → search-kernel-p9JB3SmL.d.ts} +10 -27
  298. package/dist/search-kernel-p9JB3SmL.d.ts.map +1 -0
  299. package/dist/{search-ledger-CVUGLDZp.js → search-ledger-ClpN4I3e.js} +7 -7
  300. package/dist/{search-ledger-CVUGLDZp.js.map → search-ledger-ClpN4I3e.js.map} +1 -1
  301. package/dist/{search-ledger-file-DDQUgvCg.js → search-ledger-file-Bd5Tioq6.js} +4 -4
  302. package/dist/search-ledger-file-Bd5Tioq6.js.map +1 -0
  303. package/dist/{search-shipper-BOSD46qv.js → search-shipper-Bg2HW3Uv.js} +4 -4
  304. package/dist/search-shipper-Bg2HW3Uv.js.map +1 -0
  305. package/dist/{search-summary-BQCSWf1g.js → search-summary-CrBuvVnf.js} +5 -5
  306. package/dist/{search-summary-BQCSWf1g.js.map → search-summary-CrBuvVnf.js.map} +1 -1
  307. package/dist/{sequential-CzK5DarL.js → sequential-BVv1sjsw.js} +2 -32
  308. package/dist/{sequential-CzK5DarL.js.map → sequential-BVv1sjsw.js.map} +1 -1
  309. package/dist/{sequential-Bf_pbE50.js → sequential-CimQrbjv.js} +5 -5
  310. package/dist/sequential-CimQrbjv.js.map +1 -0
  311. package/dist/{sequential-BhsrMupG.d.ts → sequential-KwGspfeR.d.ts} +2 -9
  312. package/dist/{sequential-BhsrMupG.d.ts.map → sequential-KwGspfeR.d.ts.map} +1 -1
  313. package/dist/{sequential-eprocess-DM_qENCl.js → sequential-eprocess-DodI6RoF.js} +2 -2
  314. package/dist/{sequential-eprocess-DM_qENCl.js.map → sequential-eprocess-DodI6RoF.js.map} +1 -1
  315. package/dist/{server-e9oWO_bN.js → server-C6M0qR8h.js} +101 -101
  316. package/dist/server-C6M0qR8h.js.map +1 -0
  317. package/dist/{single-run-lock-CV9Eyd_q.js → single-run-lock-Dekd8_Wv.js} +7 -7
  318. package/dist/single-run-lock-Dekd8_Wv.js.map +1 -0
  319. package/dist/{skillopt-optimization-method-BiwA8nfX.js → skillopt-optimization-method-5dlex7MJ.js} +1386 -1184
  320. package/dist/skillopt-optimization-method-5dlex7MJ.js.map +1 -0
  321. package/dist/{spans-BHAUXMGN.d.ts → spans-CVngGij3.d.ts} +2 -2
  322. package/dist/{spans-BHAUXMGN.d.ts.map → spans-CVngGij3.d.ts.map} +1 -1
  323. package/dist/{statistical-heldout-CYpGaoDH.d.ts → statistical-heldout-BHfLZHrm.d.ts} +8 -67
  324. package/dist/statistical-heldout-BHfLZHrm.d.ts.map +1 -0
  325. package/dist/{statistical-heldout-42NlCNDe.js → statistical-heldout-Bksv92Th.js} +3 -3
  326. package/dist/statistical-heldout-Bksv92Th.js.map +1 -0
  327. package/dist/{steps-Bg5-KVx1.d.ts → steps-DlepJPwD.d.ts} +2 -56
  328. package/dist/steps-DlepJPwD.d.ts.map +1 -0
  329. package/dist/{store-C4avFjIi.d.ts → store-B3nWRy3B.d.ts} +2 -2
  330. package/dist/{store-C4avFjIi.d.ts.map → store-B3nWRy3B.d.ts.map} +1 -1
  331. package/dist/{store-otlp-DJ9dtA5x.js → store-otlp-BteDAbHK.js} +3 -3
  332. package/dist/{store-otlp-DJ9dtA5x.js.map → store-otlp-BteDAbHK.js.map} +1 -1
  333. package/dist/{store-tool-spans-CIX5arAG.js → store-tool-spans-D5l_OfTJ.js} +8 -8
  334. package/dist/store-tool-spans-D5l_OfTJ.js.map +1 -0
  335. package/dist/{store-tool-spans-DdCSPa7C.d.ts → store-tool-spans-DZS0HWVf.d.ts} +9 -18
  336. package/dist/store-tool-spans-DZS0HWVf.d.ts.map +1 -0
  337. package/dist/storyboard/index.d.ts +4 -11
  338. package/dist/storyboard/index.d.ts.map +1 -1
  339. package/dist/storyboard/index.js +1 -16
  340. package/dist/storyboard/index.js.map +1 -1
  341. package/dist/{summary-report-V_JACR4Y.js → summary-report-BsXJoYX5.js} +88 -10
  342. package/dist/summary-report-BsXJoYX5.js.map +1 -0
  343. package/dist/{summary-report-bdFDXq0b.d.ts → summary-report-CkbRcSuu.d.ts} +25 -19
  344. package/dist/summary-report-CkbRcSuu.d.ts.map +1 -0
  345. package/dist/supervisor-run/index.d.ts +60 -28
  346. package/dist/supervisor-run/index.d.ts.map +1 -1
  347. package/dist/supervisor-run/index.js +4 -458
  348. package/dist/supervisor-run/index.js.map +1 -1
  349. package/dist/{systemone-BomhHr2c.d.ts → systemone-BMzDJb1i.d.ts} +5 -5
  350. package/dist/{systemone-BomhHr2c.d.ts.map → systemone-BMzDJb1i.d.ts.map} +1 -1
  351. package/dist/systemone-protocol.js +1 -1
  352. package/dist/{systemone-review-CUVcQJu6.d.ts → systemone-review-CwE6JGIp.d.ts} +2 -2
  353. package/dist/{systemone-review-CUVcQJu6.d.ts.map → systemone-review-CwE6JGIp.d.ts.map} +1 -1
  354. package/dist/{systemone-review-D7sXwsqq.js → systemone-review-DzdOJ8I6.js} +3 -3
  355. package/dist/{systemone-review-D7sXwsqq.js.map → systemone-review-DzdOJ8I6.js.map} +1 -1
  356. package/dist/systemone.d.ts +5 -5
  357. package/dist/systemone.js +5 -5
  358. package/dist/systemone.js.map +1 -1
  359. package/dist/{task-failure-attributes-hEmASjix.js → task-failure-attributes-BMsblaDh.js} +3 -3
  360. package/dist/task-failure-attributes-BMsblaDh.js.map +1 -0
  361. package/dist/{terminal-record-DZyQZ3pz.js → terminal-record-D4Rv-j1W.js} +244 -196
  362. package/dist/terminal-record-D4Rv-j1W.js.map +1 -0
  363. package/dist/{tool-groups-C3NEcdCM.d.ts → tool-groups-DyNz2JZ_.d.ts} +3 -3
  364. package/dist/tool-groups-DyNz2JZ_.d.ts.map +1 -0
  365. package/dist/{tool-waste-BKgvd-TP.d.ts → tool-waste-CkjzWmeY.d.ts} +25 -28
  366. package/dist/tool-waste-CkjzWmeY.d.ts.map +1 -0
  367. package/dist/{tool-waste-BlesqTqW.js → tool-waste-DLsjS_p-.js} +5 -5
  368. package/dist/{tool-waste-BlesqTqW.js.map → tool-waste-DLsjS_p-.js.map} +1 -1
  369. package/dist/{trace-questions-CM2CAocU.d.ts → trace-questions-xxwgsuMi.d.ts} +4 -9
  370. package/dist/{trace-questions-CM2CAocU.d.ts.map → trace-questions-xxwgsuMi.d.ts.map} +1 -1
  371. package/dist/trace-repair/index.d.ts +14 -211
  372. package/dist/trace-repair/index.d.ts.map +1 -1
  373. package/dist/trace-repair/index.js +865 -981
  374. package/dist/trace-repair/index.js.map +1 -1
  375. package/dist/traces.d.ts +18 -46
  376. package/dist/traces.d.ts.map +1 -1
  377. package/dist/traces.js +13 -13
  378. package/dist/traces.js.map +1 -1
  379. package/dist/trajectory-replay/index.d.ts +7 -118
  380. package/dist/trajectory-replay/index.d.ts.map +1 -1
  381. package/dist/trajectory-replay/index.js +921 -869
  382. package/dist/trajectory-replay/index.js.map +1 -1
  383. package/dist/{tree-C1XYeXvy.js → tree-B5e1uAeL.js} +132 -21
  384. package/dist/tree-B5e1uAeL.js.map +1 -0
  385. package/dist/{types-Cbe2fWBa.d.ts → types-BKCzzmit.d.ts} +3 -3
  386. package/dist/{types-Cbe2fWBa.d.ts.map → types-BKCzzmit.d.ts.map} +1 -1
  387. package/dist/{types-B3jzCp0p.js → types-BXgASBCL.js} +2 -2
  388. package/dist/{types-B3jzCp0p.js.map → types-BXgASBCL.js.map} +1 -1
  389. package/dist/{types-C1tnkEgM.d.ts → types-CW8ewATZ.d.ts} +4 -113
  390. package/dist/types-CW8ewATZ.d.ts.map +1 -0
  391. package/dist/{types-BqkVmHfv.d.ts → types-CmXY0PQf.d.ts} +2 -4
  392. package/dist/types-CmXY0PQf.d.ts.map +1 -0
  393. package/dist/{types-C02qtnG8.d.ts → types-D-mgRzlh.d.ts} +7 -28
  394. package/dist/types-D-mgRzlh.d.ts.map +1 -0
  395. package/dist/{types-IXD2HJzu.js → types-DqFMNTgK.js} +2 -4
  396. package/dist/types-DqFMNTgK.js.map +1 -0
  397. package/dist/{types-Cq8mSbq8.d.ts → types-DtkO1G9L.d.ts} +7 -9
  398. package/dist/{types-Cq8mSbq8.d.ts.map → types-DtkO1G9L.d.ts.map} +1 -1
  399. package/dist/{verdict-Dl0tiT1X.js → verdict-BGQmxQ8A.js} +3 -3
  400. package/dist/verdict-BGQmxQ8A.js.map +1 -0
  401. package/dist/{verdict-E4eRNf7-.d.ts → verdict-C24NELtN.d.ts} +2 -15
  402. package/dist/{verdict-E4eRNf7-.d.ts.map → verdict-C24NELtN.d.ts.map} +1 -1
  403. package/dist/{verdict-cache-Bm8EKL2s.js → verdict-cache-CL_7tePD.js} +2 -2
  404. package/dist/verdict-cache-CL_7tePD.js.map +1 -0
  405. package/dist/wire/index.d.ts +31 -410
  406. package/dist/wire/index.d.ts.map +1 -1
  407. package/dist/wire/index.js +2 -2
  408. package/docs/changes/jev-evidence-review.md +1 -1
  409. package/docs/changes/jev-product-adoption.md +1 -1
  410. package/docs/changes/jev-recorded-evidence.md +1 -1
  411. package/docs/design/statistics-decisions.md +18 -18
  412. package/docs/design.md +1 -1
  413. package/docs/eval-surface-map.md +1 -0
  414. package/docs/evaluation-integrity.md +1 -1
  415. package/docs/profile-json-identity.md +1 -2
  416. package/docs/proofs/campaign-attempt-retention-20261001/README.md +2 -2
  417. package/docs/public-api.md +158 -538
  418. package/docs/rollout.md +1 -1
  419. package/docs/trace-repair-admission.md +1 -1
  420. package/docs/wire-protocol.md +1 -1
  421. package/package.json +7 -2
  422. package/dist/active-curriculum-B_Lc9kfO.js +0 -61
  423. package/dist/active-curriculum-B_Lc9kfO.js.map +0 -1
  424. package/dist/agent-profile-VFcQncbW.d.ts.map +0 -1
  425. package/dist/agent-profile-cell-BK8mlqlq.js.map +0 -1
  426. package/dist/agent-profile-cell-BNp-Js9F.d.ts.map +0 -1
  427. package/dist/agreement-irr-BEWLIF3_.js.map +0 -1
  428. package/dist/analyze-runs-C84irm4i.js.map +0 -1
  429. package/dist/baseline-Udi_PLuT.js +0 -259
  430. package/dist/baseline-Udi_PLuT.js.map +0 -1
  431. package/dist/benchmark-CXmVVHH2.js +0 -562
  432. package/dist/benchmark-CXmVVHH2.js.map +0 -1
  433. package/dist/benchmark-command-By0vh8q7.js.map +0 -1
  434. package/dist/campaign-BudZ70zo.js.map +0 -1
  435. package/dist/chat-json-call-puMArmtW.js.map +0 -1
  436. package/dist/claude-jsonl-dZir12m6.js +0 -86
  437. package/dist/claude-jsonl-dZir12m6.js.map +0 -1
  438. package/dist/client-BzL9niqi.d.ts.map +0 -1
  439. package/dist/cost-ledger-BP8V4kUQ.js.map +0 -1
  440. package/dist/counterfactual-CPaWN99-.d.ts +0 -60
  441. package/dist/counterfactual-CPaWN99-.d.ts.map +0 -1
  442. package/dist/counterfactual-Dn3veueY.js +0 -98
  443. package/dist/counterfactual-Dn3veueY.js.map +0 -1
  444. package/dist/default-registry-COhk9g36.js.map +0 -1
  445. package/dist/default-registry-DzHiGruW.d.ts.map +0 -1
  446. package/dist/define-agent-eval-CNTPzIkp.js.map +0 -1
  447. package/dist/define-agent-eval-WSck0CZJ.d.ts.map +0 -1
  448. package/dist/dspy-rlm-engine-LRCu61m5.js.map +0 -1
  449. package/dist/effect-sizes-BhzEpXMc.js +0 -82
  450. package/dist/effect-sizes-BhzEpXMc.js.map +0 -1
  451. package/dist/emitter-HcCmFQl_.d.ts.map +0 -1
  452. package/dist/engine-3A_4jOlI.d.ts.map +0 -1
  453. package/dist/equal-terms-BtdXayCJ.js.map +0 -1
  454. package/dist/eval-campaign-90jeaCAI.js +0 -343
  455. package/dist/eval-campaign-90jeaCAI.js.map +0 -1
  456. package/dist/evaluation-6Yoi74gM.d.ts.map +0 -1
  457. package/dist/exporters-X4xwla8A.js.map +0 -1
  458. package/dist/external-optimizer-process-BjMGUuds.js.map +0 -1
  459. package/dist/external-optimizer-subprocess-BqW0hHcI.js.map +0 -1
  460. package/dist/failure-cluster-CbgEDcFJ.d.ts.map +0 -1
  461. package/dist/feedback-trajectory-C4EG0nNH.d.ts.map +0 -1
  462. package/dist/hf-dataset-BR2yhuNn.js.map +0 -1
  463. package/dist/index-BFRO6chs.d.ts.map +0 -1
  464. package/dist/index-BO41eGj5.d.ts.map +0 -1
  465. package/dist/index-CyszSg4O.d.ts.map +0 -1
  466. package/dist/index-DHKEAv3s.d.ts.map +0 -1
  467. package/dist/index-DPcngtwt.d.ts.map +0 -1
  468. package/dist/integrity-dLiDe2kD.js.map +0 -1
  469. package/dist/journal-DfRz9kps.js.map +0 -1
  470. package/dist/judge-gate-CE7CQAgt.d.ts.map +0 -1
  471. package/dist/kind-factory-BobI5Jy3.js.map +0 -1
  472. package/dist/ledger-core-Gq7yp8lP.js.map +0 -1
  473. package/dist/llm-client-CyBAoYiX.js.map +0 -1
  474. package/dist/llm-judge-CG12SQJq.js.map +0 -1
  475. package/dist/matrix-DSrSxjjy.d.ts.map +0 -1
  476. package/dist/matrix-Dm0BQW7U.js.map +0 -1
  477. package/dist/mean-DHoMiudD.js.map +0 -1
  478. package/dist/normal-DsJZtrJc.js +0 -25
  479. package/dist/normal-DsJZtrJc.js.map +0 -1
  480. package/dist/paired-arms-CwMGJsrS.js.map +0 -1
  481. package/dist/paired-binary-CvpFHfKZ.js.map +0 -1
  482. package/dist/paired-promotion-decision-DPKz8ZnF.d.ts.map +0 -1
  483. package/dist/pareto-Cm6ndrWN.js.map +0 -1
  484. package/dist/prime-protocol-CHKgA3a6.js.map +0 -1
  485. package/dist/prime-protocol-HiB9HX7E.d.ts.map +0 -1
  486. package/dist/produced-state-BsDmnwxc.js.map +0 -1
  487. package/dist/proposal-findings-CY1xKn_a.js.map +0 -1
  488. package/dist/query-BUCZCK7F.js.map +0 -1
  489. package/dist/redact-mtCCcT8z.d.ts.map +0 -1
  490. package/dist/release-confidence-CpuP65S5.js.map +0 -1
  491. package/dist/report-command-SC9nqb4M.js.map +0 -1
  492. package/dist/reward-CpCmAM8L.d.ts.map +0 -1
  493. package/dist/reward-hacking-RVdZ6Kkt.d.ts.map +0 -1
  494. package/dist/rollout-DZV1t2Wg.js.map +0 -1
  495. package/dist/run-record-C1E24G2A.d.ts.map +0 -1
  496. package/dist/run-record-C5e7FjhJ.js.map +0 -1
  497. package/dist/schema-2g7trUwH.d.ts.map +0 -1
  498. package/dist/schema-BuiujZ-g.js.map +0 -1
  499. package/dist/schema-CSf6qWgZ.js.map +0 -1
  500. package/dist/search-kernel-DyNEa6IU.d.ts.map +0 -1
  501. package/dist/search-ledger-file-DDQUgvCg.js.map +0 -1
  502. package/dist/search-shipper-BOSD46qv.js.map +0 -1
  503. package/dist/semantic-concept-judge-BQF8te0T.js.map +0 -1
  504. package/dist/sequential-Bf_pbE50.js.map +0 -1
  505. package/dist/server-e9oWO_bN.js.map +0 -1
  506. package/dist/single-run-lock-CV9Eyd_q.js.map +0 -1
  507. package/dist/skillopt-optimization-method-BiwA8nfX.js.map +0 -1
  508. package/dist/statistical-heldout-42NlCNDe.js.map +0 -1
  509. package/dist/statistical-heldout-CYpGaoDH.d.ts.map +0 -1
  510. package/dist/steps-Bg5-KVx1.d.ts.map +0 -1
  511. package/dist/store-tool-spans-CIX5arAG.js.map +0 -1
  512. package/dist/store-tool-spans-DdCSPa7C.d.ts.map +0 -1
  513. package/dist/student-t-DVPW7CdL.js +0 -39
  514. package/dist/student-t-DVPW7CdL.js.map +0 -1
  515. package/dist/summary-report-V_JACR4Y.js.map +0 -1
  516. package/dist/summary-report-bdFDXq0b.d.ts.map +0 -1
  517. package/dist/task-failure-attributes-hEmASjix.js.map +0 -1
  518. package/dist/terminal-record-DZyQZ3pz.js.map +0 -1
  519. package/dist/tool-groups-C3NEcdCM.d.ts.map +0 -1
  520. package/dist/tool-waste-BKgvd-TP.d.ts.map +0 -1
  521. package/dist/trajectory-Y1fmdlw7.d.ts +0 -24
  522. package/dist/trajectory-Y1fmdlw7.d.ts.map +0 -1
  523. package/dist/tree-C1XYeXvy.js.map +0 -1
  524. package/dist/types-BqkVmHfv.d.ts.map +0 -1
  525. package/dist/types-C02qtnG8.d.ts.map +0 -1
  526. package/dist/types-C1tnkEgM.d.ts.map +0 -1
  527. package/dist/types-IXD2HJzu.js.map +0 -1
  528. package/dist/usage-receipt-Cx3xNeyB.js +0 -76
  529. package/dist/usage-receipt-Cx3xNeyB.js.map +0 -1
  530. package/dist/verdict-Dl0tiT1X.js.map +0 -1
  531. package/dist/verdict-cache-Bm8EKL2s.js.map +0 -1
  532. package/docs/design/self-improvement-evidence-audit.md +0 -263
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/analyst/adapters.ts","../../src/analyst/bind.ts","../../src/analyst/define.ts","../../src/analyst/domain-taxonomy.ts","../../src/analyst/failure-modes.ts","../../src/analyst/findings-ledger.ts","../../src/analyst/kinds/skill-usage.ts","../../src/analyst/promote.ts","../../src/analyst/rollup.ts","../../src/analyst/team-shape.ts","../../src/analyst/trace-questions.ts"],"sourcesContent":["/**\n * Adapter factory — lifts the semantic-concept judge into the Analyst\n * contract without re-implementing it.\n *\n * It builds an Analyst with a stable id (caller chooses; a default is given),\n * a version derived from the judge's version plus an adapter revision, and an\n * `analyze()` that calls the judge and lifts its output to `AnalystFinding[]`\n * through `makeFinding()`. The judge's `Severity` ('critical' | 'major' |\n * 'minor' | 'info') projects onto `AnalystSeverity`: 'major' becomes 'high'\n * and 'minor' becomes 'medium'.\n *\n * The adapter owns no state. Calling the factory twice is safe.\n */\n\nimport { CostLedger } from '../cost-ledger'\nimport type { Severity as LayerSeverity } from '../multi-layer-verifier'\nimport {\n runSemanticConceptJudge,\n SEMANTIC_CONCEPT_JUDGE_VERSION,\n type SemanticConceptJudgeInput,\n type SemanticConceptJudgeOptions,\n type SemanticConceptJudgeResult,\n} from '../semantic-concept-judge'\nimport type { Analyst, AnalystFinding, AnalystSeverity } from './types'\nimport { makeFinding } from './types'\nimport { settleUsageReceiptFromCostLedger, validateUsageSettlementTimeout } from './usage-receipt'\n\nconst ADAPTER_REV = '1'\n\n// ── Severity bridges ───────────────────────────────────────────────\n\nfunction liftSeverity(s: LayerSeverity): AnalystSeverity {\n switch (s) {\n case 'critical':\n return 'critical'\n case 'major':\n return 'high'\n case 'minor':\n return 'medium'\n case 'info':\n return 'info'\n }\n}\n\n// ── SemanticConceptJudge → Analyst ─────────────────────────────────\n\nexport interface SemanticConceptJudgeAdapterOpts {\n id?: string\n area?: string\n /** Registry context owns cancellation and the per-analyst cost ledger. */\n options: Omit<SemanticConceptJudgeOptions, 'costLedger' | 'signal'>\n /** Maximum post-cancellation wait for a provider receipt. Default 5 seconds. */\n settlementTimeoutMs?: number\n}\n\nexport function createSemanticConceptJudgeAdapter(\n opts: SemanticConceptJudgeAdapterOpts,\n): Analyst<SemanticConceptJudgeInput> {\n const id = opts.id ?? 'semantic-concept-judge'\n const area = opts.area ?? 'concept-coverage'\n const settlementTimeoutMs = validateUsageSettlementTimeout(opts.settlementTimeoutMs)\n return {\n id,\n description:\n 'Runs the semantic-concept judge and surfaces missing / weak concepts as findings.',\n inputKind: 'custom',\n cost: {\n kind: 'llm',\n models: opts.options.model ? [opts.options.model] : undefined,\n settlement_timeout_ms: settlementTimeoutMs,\n },\n version: `${SEMANTIC_CONCEPT_JUDGE_VERSION}-adapter-${ADAPTER_REV}`,\n async analyze(input, ctx) {\n const costLedger = new CostLedger(ctx.budgetUsd)\n let result: SemanticConceptJudgeResult\n try {\n result = await runSemanticConceptJudge(input, {\n ...opts.options,\n costLedger,\n signal: ctx.signal,\n })\n } finally {\n const usage = await settleUsageReceiptFromCostLedger(costLedger, {\n channel: 'judge',\n timeoutMs: settlementTimeoutMs,\n })\n if (!usage.settled) {\n ctx.log?.('semantic-concept judge provider settlement timed out', {\n pending_calls: usage.pendingCalls,\n timeout_ms: settlementTimeoutMs,\n })\n }\n ctx.recordUsage?.(usage.receipt)\n }\n if (!result.available) {\n return [\n makeFinding({\n analyst_id: id,\n area,\n claim: 'semantic-concept judge unavailable',\n rationale: result.error,\n severity: 'info',\n confidence: 1,\n evidence_refs: [],\n metadata: { reason: result.error },\n }),\n ]\n }\n const out: AnalystFinding[] = []\n for (const f of result.findings) {\n // Only surface gaps: missing concepts or low scores. Concepts at\n // 7+/10 with present=true are not findings — they're successes.\n if (f.present && f.score >= 7) continue\n out.push(\n makeFinding({\n analyst_id: id,\n area,\n subject: f.concept,\n claim: f.present\n ? `concept \"${f.concept}\" is weak (${f.score}/10)`\n : `concept \"${f.concept}\" is missing`,\n rationale: f.evidence,\n severity: liftSeverity(f.severity),\n confidence: 0.85,\n evidence_refs: [{ kind: 'artifact', uri: 'inline:evidence', excerpt: f.evidence }],\n metadata: {\n concept: f.concept,\n present: f.present,\n score_10: f.score,\n },\n }),\n )\n }\n return out\n },\n }\n}\n","/**\n * bindAnalyst — compile an `AnalystDefinition` into a runnable arm.\n *\n * The definition declares protocol (question, task text, reply grammar,\n * evidence projection, budget, repair turns); the transport binding supplies\n * execution (a bridge endpoint, or the caller-owned model path). Each\n * projection mode dispatches to the same strategy its arm's entry point runs,\n * so a compiled definition and the historical creator send byte-identical\n * requests — the definition parity suite asserts this per arm.\n *\n * A projection × transport pair with no strategy fails loud with\n * `AnalystExpressivenessError` naming the pair: an arm shape this layer cannot\n * express must be reported, never approximated.\n */\n\nimport type { CustomTokenPricing } from '../cost-ledger'\nimport type { AnalystBenchmarkRunner } from './benchmark'\nimport { runChunkedAnalystDefinition } from './benchmark-public-model'\nimport { runReplVariableAnalystDefinition } from './benchmark-public-rlm'\nimport type { PublicAnalystBenchmarkModelConfig } from './benchmark-public-types'\nimport { runInlineAnalystDefinition } from './benchmark-runner-prime'\nimport { type AnalystDefinition, AnalystExpressivenessError } from './definition'\nimport type { PrimeBridgeTransport } from './prime-bridge-transport'\nimport type { AnalystRunInputs } from './types'\n\n/** Execution half of a binding: who actually reaches the model. */\nexport type AnalystTransportBinding =\n | {\n /** An OpenAI-compatible cli-bridge endpoint (inline projections). */\n readonly kind: 'prime-bridge'\n readonly baseUrl: string\n readonly model: string\n readonly transport?: PrimeBridgeTransport\n readonly pricing?: CustomTokenPricing\n }\n | {\n /** The caller-owned model path (chunked and repl-variable projections). */\n readonly kind: 'model-owner'\n readonly config: PublicAnalystBenchmarkModelConfig\n }\n\n/**\n * Compile a definition plus a transport binding into a runnable arm. Dispatch\n * is total over the expressible pairs; everything else is a loud refusal.\n */\nexport function bindAnalyst<TRow, TAssignment, TBlock>(\n definition: AnalystDefinition<TRow, TAssignment, TBlock>,\n transports: AnalystTransportBinding,\n): AnalystBenchmarkRunner<AnalystRunInputs> {\n const mode = definition.projection.mode\n if (mode === 'inline' && transports.kind === 'prime-bridge') {\n return runInlineAnalystDefinition(definition, {\n baseUrl: transports.baseUrl,\n model: transports.model,\n ...(transports.transport ? { transport: transports.transport } : {}),\n ...(transports.pricing ? { pricing: transports.pricing } : {}),\n })\n }\n if (mode === 'chunked' && transports.kind === 'model-owner') {\n return runChunkedAnalystDefinition(definition, transports.config)\n }\n if (mode === 'repl-variable' && transports.kind === 'model-owner') {\n return runReplVariableAnalystDefinition(\n // The repl-variable strategy is written against the engine's raw-finding\n // row type; the definition's own row declaration carries it.\n definition as Parameters<typeof runReplVariableAnalystDefinition>[0],\n transports.config,\n )\n }\n throw new AnalystExpressivenessError(\n `no strategy compiles a '${mode}' projection over a '${transports.kind}' transport; ` +\n `definition '${definition.id}' cannot be expressed by this layer yet`,\n )\n}\n","import type { TraceAnalysisStore } from '../trace-analyst/store'\nimport type { ExactCapableAnalyst } from './exact-types'\nimport type { TraceAnalystDefinition } from './kind-factory'\nimport type { Analyst, AnalystCost } from './types'\n\n/**\n * Define a reusable trace-research question.\n *\n * The returned value contains no model, credentials, or execution state. Bind\n * it to any TraceAnalysisEngine with `runTraceAnalyst` or\n * `createTraceAnalyst`.\n */\nexport function defineTraceAnalyst(definition: TraceAnalystDefinition): TraceAnalystDefinition {\n for (const [name, value] of [\n ['id', definition.id],\n ['description', definition.description],\n ['area', definition.area],\n ['version', definition.version],\n ['instructions', definition.instructions],\n ] as const) {\n if (typeof value !== 'string' || !value.trim()) {\n throw new TypeError(`defineTraceAnalyst: ${name} must be a non-empty string`)\n }\n }\n return {\n ...definition,\n limits: definition.limits ? { ...definition.limits } : undefined,\n }\n}\n\nexport interface DefineCustomAnalystOptions {\n id: string\n description: string\n version?: string\n cost: AnalystCost\n analyze: Analyst<TraceAnalysisStore>['analyze']\n}\n\nexport interface DefineExactCustomAnalystOptions extends DefineCustomAnalystOptions {\n /** Canonical JSON for behavior knobs not already bound by `version`. */\n executionConfig: Readonly<Record<string, unknown>>\n}\n\n/** Construct a registrable analyst from a hand-written analyze function. */\nexport function defineCustomAnalyst(\n options: DefineExactCustomAnalystOptions,\n): ExactCapableAnalyst<TraceAnalysisStore>\nexport function defineCustomAnalyst(\n options: DefineCustomAnalystOptions,\n): Analyst<TraceAnalysisStore>\nexport function defineCustomAnalyst(\n options: DefineCustomAnalystOptions | DefineExactCustomAnalystOptions,\n): Analyst<TraceAnalysisStore> | ExactCapableAnalyst<TraceAnalysisStore> {\n if (!options.id.trim()) throw new TypeError('defineCustomAnalyst: id must not be empty')\n if (!options.description.trim()) {\n throw new TypeError('defineCustomAnalyst: description must not be empty')\n }\n if (options.cost === undefined) {\n throw new TypeError('defineCustomAnalyst: cost must be declared')\n }\n if (\n 'executionConfig' in options &&\n (!options.executionConfig ||\n typeof options.executionConfig !== 'object' ||\n Array.isArray(options.executionConfig))\n ) {\n throw new TypeError('defineCustomAnalyst: executionConfig must be an object')\n }\n return {\n id: options.id,\n description: options.description,\n version: options.version ?? '1.0.0',\n inputKind: 'trace-store',\n cost: options.cost,\n analyze: options.analyze,\n ...('executionConfig' in options ? { executionConfig: options.executionConfig } : {}),\n }\n}\n","/**\n * Domain taxonomy — one versioned tree that both the layer ladder and the\n * domain hierarchy live in.\n *\n * Domain nodes nest to any depth (\"building systems\" → \"cryptographic\" →\n * \"zk proving\" → \"binary fields\"). Problems attach to one primary domain path\n * plus free tags, plays attach to a problem, and runs attach to a play. Every\n * node hangs under the implicit `lab` root, so one parent map answers both\n * \"which play holds this run\" and \"which domain holds this problem\", and\n * `promote` walks a single ladder: run → play → problem → domain path → lab.\n *\n * Plain data in, plain data out: every function returns a new value or a\n * typed failure, and nothing here reads a file or the network.\n */\n\nexport const DOMAIN_TAXONOMY_SCHEMA = 'agent-eval.domain-taxonomy.v1'\n\n/** Id of the implicit root every top-level domain hangs under. */\nexport const LAB_NODE_ID = 'lab'\n\n/** Layers a taxonomy node can sit at, lowest first. */\nexport const TAXONOMY_NODE_LAYERS = ['run', 'play', 'problem', 'domain'] as const\n\nexport type TaxonomyNodeLayer = (typeof TAXONOMY_NODE_LAYERS)[number]\n\nexport interface TaxonomyNode {\n id: string\n label: string\n layer: TaxonomyNodeLayer\n /** Null only for a top-level domain, whose parent is the implicit lab root. */\n parent: string | null\n /** Secondary classifications; they never change the node's place in the tree. */\n tags?: string[]\n}\n\nexport interface DomainTaxonomy {\n schema: typeof DOMAIN_TAXONOMY_SCHEMA\n /** Caller-chosen version; promoted findings record the version they were lifted under. */\n version: string\n nodes: TaxonomyNode[]\n}\n\nexport type TaxonomyOutcome<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; error: { message: string } }\n\n/** The layer a node of each kind must hang under. */\nconst PARENT_LAYER: Record<TaxonomyNodeLayer, TaxonomyNodeLayer | null> = {\n run: 'play',\n play: 'problem',\n problem: 'domain',\n domain: 'domain',\n}\n\nfunction fail<T>(message: string): TaxonomyOutcome<T> {\n return { succeeded: false, error: { message } }\n}\n\n/**\n * Validate a taxonomy: unique ids, known parents, each node under a parent of\n * the right layer, no cycles. `lab` is reserved for the implicit root.\n */\nexport function defineDomainTaxonomy(input: {\n version: string\n nodes: ReadonlyArray<TaxonomyNode>\n}): TaxonomyOutcome<DomainTaxonomy> {\n if (typeof input.version !== 'string' || !input.version.trim()) {\n return fail('taxonomy version must be a non-empty string')\n }\n const nodes = input.nodes.map((node) => ({\n id: node.id,\n label: node.label,\n layer: node.layer,\n parent: node.parent,\n ...(node.tags === undefined ? {} : { tags: [...node.tags] }),\n }))\n const byId = new Map<string, TaxonomyNode>()\n for (const node of nodes) {\n if (typeof node.id !== 'string' || !node.id.trim()) return fail('node ids must be non-empty')\n if (node.id === LAB_NODE_ID) return fail(`'${LAB_NODE_ID}' is the implicit root id`)\n if (byId.has(node.id)) return fail(`node '${node.id}' appears twice`)\n if (!(TAXONOMY_NODE_LAYERS as readonly string[]).includes(node.layer)) {\n return fail(`node '${node.id}' has unknown layer '${String(node.layer)}'`)\n }\n if (typeof node.label !== 'string' || !node.label.trim()) {\n return fail(`node '${node.id}' needs a label`)\n }\n byId.set(node.id, node)\n }\n for (const node of nodes) {\n if (node.parent === null) {\n if (node.layer !== 'domain') return fail(`${node.layer} '${node.id}' needs a parent`)\n continue\n }\n const parent = byId.get(node.parent)\n if (!parent) return fail(`node '${node.id}' names unknown parent '${node.parent}'`)\n if (parent.layer !== PARENT_LAYER[node.layer]) {\n return fail(\n `${node.layer} '${node.id}' must hang under a ${PARENT_LAYER[node.layer]}, not ${parent.layer} '${parent.id}'`,\n )\n }\n }\n for (const node of nodes) {\n const seen = new Set<string>()\n let current: TaxonomyNode | undefined = node\n while (current) {\n if (seen.has(current.id)) return fail(`node '${node.id}' sits on a parent cycle`)\n seen.add(current.id)\n current = current.parent === null ? undefined : byId.get(current.parent)\n }\n }\n return {\n succeeded: true,\n value: { schema: DOMAIN_TAXONOMY_SCHEMA, version: input.version, nodes },\n }\n}\n\nexport interface TaxonomyAttachment {\n id: string\n label: string\n layer: Exclude<TaxonomyNodeLayer, 'domain'>\n /**\n * For a problem: its primary domain path, broadest first. It must be a\n * chain of domain nodes from the top level down. Ignored for plays and runs.\n */\n path?: readonly string[]\n /** For a play or run: the problem or play it belongs to. */\n parent?: string\n tags?: readonly string[]\n}\n\n/** Attach a problem to one primary domain path, a play to a problem, or a run to a play. */\nexport function attachToTaxonomy(\n taxonomy: DomainTaxonomy,\n attachment: TaxonomyAttachment,\n): TaxonomyOutcome<DomainTaxonomy> {\n let parent: string\n if (attachment.layer === 'problem') {\n if (!attachment.path || attachment.path.length === 0) {\n return fail(`problem '${attachment.id}' needs a primary domain path`)\n }\n const resolved = resolveDomainPath(taxonomy, attachment.path)\n if (!resolved.succeeded) return resolved\n parent = attachment.path[attachment.path.length - 1]!\n } else {\n if (!attachment.parent) return fail(`${attachment.layer} '${attachment.id}' needs a parent`)\n parent = attachment.parent\n }\n return defineDomainTaxonomy({\n version: taxonomy.version,\n nodes: [\n ...taxonomy.nodes,\n {\n id: attachment.id,\n label: attachment.label,\n layer: attachment.layer,\n parent,\n ...(attachment.tags === undefined ? {} : { tags: [...attachment.tags] }),\n },\n ],\n })\n}\n\n/** Check that a path is a top-down chain of domain nodes. */\nexport function resolveDomainPath(\n taxonomy: DomainTaxonomy,\n path: readonly string[],\n): TaxonomyOutcome<readonly TaxonomyNode[]> {\n const byId = nodeIndex(taxonomy)\n const chain: TaxonomyNode[] = []\n let expectedParent: string | null = null\n for (const id of path) {\n const node = byId.get(id)\n if (node?.layer !== 'domain') return fail(`'${id}' is not a domain node`)\n if (node.parent !== expectedParent) {\n return fail(`domain path breaks at '${id}': its parent is '${node.parent ?? LAB_NODE_ID}'`)\n }\n chain.push(node)\n expectedParent = id\n }\n return { succeeded: true, value: chain }\n}\n\n/** Layer of a node id, with `lab` for the implicit root; undefined when unknown. */\nexport function taxonomyLayerOf(\n taxonomy: DomainTaxonomy,\n id: string,\n): TaxonomyNodeLayer | 'lab' | undefined {\n if (id === LAB_NODE_ID) return 'lab'\n return nodeIndex(taxonomy).get(id)?.layer\n}\n\n/** Parent id, with `lab` above every top-level domain and null above `lab`. */\nexport function taxonomyParentOf(taxonomy: DomainTaxonomy, id: string): string | null | undefined {\n if (id === LAB_NODE_ID) return null\n const node = nodeIndex(taxonomy).get(id)\n if (!node) return undefined\n return node.parent ?? LAB_NODE_ID\n}\n\n/** The node and its ancestors, nearest first, ending at `lab`. Empty for an unknown id. */\nexport function taxonomyAncestry(taxonomy: DomainTaxonomy, id: string): string[] {\n const byId = nodeIndex(taxonomy)\n const chain: string[] = []\n let current: string | null = id\n while (current !== null) {\n if (current === LAB_NODE_ID) {\n chain.push(current)\n break\n }\n const node = byId.get(current)\n if (!node) return []\n chain.push(current)\n current = node.parent ?? LAB_NODE_ID\n }\n return chain\n}\n\n/** Domain path of a node, broadest first: the domain ids above it, and itself when a domain. */\nexport function domainPathOf(taxonomy: DomainTaxonomy, id: string): string[] {\n const byId = nodeIndex(taxonomy)\n return taxonomyAncestry(taxonomy, id)\n .filter((ancestor) => byId.get(ancestor)?.layer === 'domain')\n .reverse()\n}\n\n/**\n * Deepest node that is an ancestor of (or equal to) every id, or undefined\n * when an id is unknown. `lab` is the answer when they share nothing else.\n */\nexport function lowestCommonAncestor(\n taxonomy: DomainTaxonomy,\n ids: readonly string[],\n): string | undefined {\n if (ids.length === 0) return undefined\n const chains = ids.map((id) => taxonomyAncestry(taxonomy, id))\n if (chains.some((chain) => chain.length === 0)) return undefined\n const others = chains.slice(1).map((chain) => new Set(chain))\n return chains[0]!.find((id) => others.every((chain) => chain.has(id)))\n}\n\nfunction nodeIndex(taxonomy: DomainTaxonomy): Map<string, TaxonomyNode> {\n return new Map(taxonomy.nodes.map((node) => [node.id, node]))\n}\n","/**\n * failure-modes — a judged analyst with fixed-choice labels, gated on its own\n * calibration.\n *\n * Labels are adapted from the MAST multi-agent failure taxonomy (Cemri et al.,\n * \"Why Do Multi-Agent LLM Systems Fail?\", 2025): its fourteen modes in three\n * groups, plus four single-agent modes so the public AgentRx set maps onto the\n * same labels, plus `none`. Two more fixed questions cover delegation-brief\n * completeness and steer handling.\n *\n * The judge runs through the System One decision path (`systemOneAnalyst`).\n * Construction requires a calibration — gold labels compared with the judge's\n * labels on the same items — and refuses to build an analyst whose Cohen's κ\n * is below `FAILURE_MODES_MIN_KAPPA`. A rubric that does not agree with its\n * gold set has nothing to report, so it reports nothing.\n */\n\nimport { readFile } from 'node:fs/promises'\nimport { nominalAgreement } from '../statistics/agreement-irr'\nimport { type SystemOneEvaluatorOptions, systemOneAnalyst } from '../systemone'\nimport type { SystemOneQuestions, SystemOneState } from '../systemone-protocol'\nimport { normalizeAgentRxCategory } from './benchmark-dataset-agentrx'\nimport type { AgentRxRow } from './benchmark-dataset-types'\nimport { loadPublicBenchmarkRows } from './benchmark-public-data'\nimport type { FindingCalibration, FindingScope } from './finding-scope'\nimport { type Analyst, type AnalystContext, type AnalystFinding, makeFinding } from './types'\n\nexport const FAILURE_MODES_ANALYST_ID = 'failure-modes'\nexport const FAILURE_MODES_VERSION = '1'\n\n/** κ below this refuses the rubric. */\nexport const FAILURE_MODES_MIN_KAPPA = 0.6\n\nexport const FAILURE_MODE_LABELS = {\n // MAST 1 — specification and system design\n 'disobey-task-specification': 'Ignored or violated the stated task requirements or constraints.',\n 'disobey-role-specification': 'Acted outside its assigned role or took over another role.',\n 'step-repetition': 'Repeated a step already completed without new reason.',\n 'loss-of-conversation-history': 'Lost earlier context and acted as if it was never given.',\n 'unaware-of-termination-conditions': 'Did not recognize when the task was done or must stop.',\n // MAST 2 — inter-agent misalignment\n 'conversation-reset': 'Restarted the exchange and discarded progress.',\n 'fail-to-ask-for-clarification': 'Proceeded on an ambiguous instruction without asking.',\n 'task-derailment': 'Drifted from the task toward a different goal.',\n 'information-withholding': 'Kept back information another agent needed.',\n 'ignored-other-agent-input': \"Disregarded another agent's input or recommendation.\",\n 'reasoning-action-mismatch': 'Acted against its own stated reasoning or plan.',\n // MAST 3 — task verification and termination\n 'premature-termination': 'Stopped before the goal of the task was met.',\n 'no-or-incomplete-verification': 'Delivered without verifying, or verified only part.',\n 'incorrect-verification': 'Verified, but the check was wrong or passed bad output.',\n // Single-agent modes, so AgentRx labels map onto this set.\n 'invented-information': 'Stated facts, results or tool output that do not exist.',\n 'invalid-tool-invocation': 'Called a tool with an invalid name, argument or format.',\n 'misread-tool-output': 'Misinterpreted what a tool or handoff returned.',\n 'system-failure': 'Failed because of infrastructure, not the agent.',\n none: 'No failure mode applies.',\n} as const\n\nexport type FailureModeLabel = keyof typeof FAILURE_MODE_LABELS\n\n/**\n * AgentRx root-cause category → failure-mode label. `null` categories have no\n * counterpart here and are left out of the gold set, counted as unmapped.\n */\nexport const AGENT_RX_FAILURE_MODE_MAP: Readonly<Record<string, FailureModeLabel | null>> = {\n 'instruction-plan-adherence-failure': 'disobey-task-specification',\n 'invention-of-new-information': 'invented-information',\n 'invalid-invocation': 'invalid-tool-invocation',\n 'misinterpretation-of-tool-output-handoff-failure': 'misread-tool-output',\n 'intent-plan-misalignment': 'task-derailment',\n 'underspecified-user-intent': 'fail-to-ask-for-clarification',\n 'intent-not-supported': null,\n 'guardrails-triggered': null,\n 'system-failure': 'system-failure',\n inconclusive: null,\n}\n\nexport const FAILURE_MODES_QUESTIONS = {\n failure_mode: {\n type: 'choice',\n instructions:\n 'Which single failure mode best explains why this agent or team fell short? Choose none when it did not fail.',\n criteria: FAILURE_MODE_LABELS,\n },\n delegation_brief: {\n type: 'choice',\n instructions:\n 'When this agent delegated work, did the brief state the goal, the constraints, the expected output, and how the result would be checked?',\n criteria: {\n complete: 'Every delegated brief stated goal, constraints, output and check.',\n partial: 'Some brief left out one or more of goal, constraints, output or check.',\n missing: 'Work was delegated with no usable brief.',\n 'no-delegation': 'Nothing was delegated.',\n },\n },\n steer_handling: {\n type: 'choice',\n instructions: 'When a steer or correction arrived mid-task, what did the agent do with it?',\n criteria: {\n applied: 'Changed course as the steer asked.',\n ignored: 'Continued as before, or acknowledged without acting.',\n 'no-steer': 'No steer arrived.',\n },\n },\n} as const satisfies SystemOneQuestions\n\nexport interface FailureModeLabelItem {\n id: string\n label: FailureModeLabel\n}\n\nexport interface FailureModesCalibration extends FindingCalibration {\n /** Gold items with no judge label; each counts as a disagreement. */\n missingPredictions: number\n}\n\nexport type FailureModesOutcome<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; error: { kind: 'invalid' | 'uncalibrated'; message: string } }\n\nfunction isLabel(value: unknown): value is FailureModeLabel {\n return typeof value === 'string' && Object.hasOwn(FAILURE_MODE_LABELS, value)\n}\n\n/** Gold labels from AgentRx rows: each trajectory's root-cause category, mapped onto this set. */\nfunction failureModeGoldFromAgentRx(rows: readonly AgentRxRow[]): {\n gold: FailureModeLabelItem[]\n unmapped: Array<{ id: string; category: string }>\n} {\n const gold: FailureModeLabelItem[] = []\n const unmapped: Array<{ id: string; category: string }> = []\n for (const row of rows) {\n const id = `agentrx:${String(row.trajectory_id)}`\n const rootId = row.root_cause_failure_id ?? row.root_cause?.failure_id\n const root = row.failures.find((failure) => String(failure.failure_id) === String(rootId))\n if (!root)\n throw new TypeError(`AgentRx trajectory '${row.trajectory_id}' has no root-cause failure`)\n const category = normalizeAgentRxCategory(root.failure_category)\n if (!Object.hasOwn(AGENT_RX_FAILURE_MODE_MAP, category)) {\n throw new RangeError(\n `AgentRx category '${root.failure_category}' is outside the AgentRx taxonomy`,\n )\n }\n const label = AGENT_RX_FAILURE_MODE_MAP[category]\n if (label === null || label === undefined) unmapped.push({ id, category })\n else gold.push({ id, label })\n }\n return { gold, unmapped }\n}\n\n/** Validate a caller's gold file: a JSON array of `{ id, label }` with unique ids and known labels. */\nexport function parseFailureModeGold(raw: unknown): FailureModesOutcome<FailureModeLabelItem[]> {\n if (!Array.isArray(raw)) {\n return { succeeded: false, error: { kind: 'invalid', message: 'gold must be a JSON array' } }\n }\n const seen = new Set<string>()\n const items: FailureModeLabelItem[] = []\n for (const [index, row] of raw.entries()) {\n const id = (row as { id?: unknown } | null)?.id\n const label = (row as { label?: unknown } | null)?.label\n if (typeof id !== 'string' || !id.trim() || !isLabel(label)) {\n return {\n succeeded: false,\n error: {\n kind: 'invalid',\n message: `gold row ${index} needs a string id and a known label`,\n },\n }\n }\n if (seen.has(id)) {\n return { succeeded: false, error: { kind: 'invalid', message: `gold id '${id}' repeats` } }\n }\n seen.add(id)\n items.push({ id, label })\n }\n return { succeeded: true, value: items }\n}\n\nexport interface FailureModeGoldSources {\n /** The public AgentRx label file, the same file `analyst-benchmark --dataset agentrx --labels` reads. */\n agentRxLabelsPath?: string\n /** The caller's gold file: a JSON array of `{ id, label }`. */\n goldPath?: string\n}\n\nexport interface FailureModeGold {\n gold: FailureModeLabelItem[]\n /** AgentRx rows read from `agentRxLabelsPath`; every one is either in `gold` or in `unmapped`. */\n agentRxRows: number\n unmapped: Array<{ id: string; category: string }>\n}\n\n/**\n * Load the calibration gold set from the public AgentRx labels and the\n * caller's gold file, through the analyst module's public-dataset loader.\n * Ids must be unique across both sources. No source, or no gold item, is a\n * failure: an empty gold set would calibrate to an undefined κ.\n */\nexport async function loadFailureModeGold(\n sources: FailureModeGoldSources,\n): Promise<FailureModesOutcome<FailureModeGold>> {\n const invalid = (message: string) =>\n ({ succeeded: false, error: { kind: 'invalid', message } }) as const\n const gold: FailureModeLabelItem[] = []\n let agentRxRows = 0\n let unmapped: FailureModeGold['unmapped'] = []\n try {\n if (sources.agentRxLabelsPath !== undefined) {\n const rows = await loadPublicBenchmarkRows(sources.agentRxLabelsPath)\n agentRxRows = rows.length\n const mapped = failureModeGoldFromAgentRx(rows as unknown as AgentRxRow[])\n gold.push(...mapped.gold)\n unmapped = mapped.unmapped\n }\n if (sources.goldPath !== undefined) {\n const parsed = parseFailureModeGold(JSON.parse(await readFile(sources.goldPath, 'utf8')))\n if (!parsed.succeeded) return parsed\n gold.push(...parsed.value)\n }\n } catch (error) {\n return invalid(error instanceof Error ? error.message : String(error))\n }\n if (gold.length === 0) return invalid('failure-modes calibration needs at least one gold item')\n const ids = new Set<string>()\n for (const item of gold) {\n if (ids.has(item.id)) return invalid(`gold id '${item.id}' repeats across sources`)\n ids.add(item.id)\n }\n return { succeeded: true, value: { gold, agentRxRows, unmapped } }\n}\n\n/**\n * Score the judge's labels against gold labels for the same items, usually\n * the set `loadFailureModeGold` returns.\n */\nexport function calibrateFailureModes(\n gold: readonly FailureModeLabelItem[],\n predictions: readonly FailureModeLabelItem[],\n): FailureModesCalibration {\n const predicted = new Map<string, FailureModeLabel>()\n for (const prediction of predictions) {\n if (predicted.has(prediction.id))\n throw new TypeError(`prediction id '${prediction.id}' repeats`)\n predicted.set(prediction.id, prediction.label)\n }\n const ids = new Set<string>()\n let missingPredictions = 0\n const pairs: Array<readonly [string, string]> = []\n for (const item of gold) {\n if (ids.has(item.id)) throw new TypeError(`gold id '${item.id}' repeats`)\n ids.add(item.id)\n const label = predicted.get(item.id)\n if (label === undefined) missingPredictions += 1\n // A missing prediction is its own label: it can never match gold.\n pairs.push([item.label, label ?? '(no prediction)'])\n }\n const agreement = nominalAgreement(pairs)\n return {\n gold_n: agreement.n,\n agreement: agreement.agreement,\n kappa: agreement.kappa,\n missingPredictions,\n }\n}\n\nexport interface FailureModesAnalystOptions<I> extends SystemOneEvaluatorOptions {\n model: string\n /** The layer the judged subject sits at. */\n layer: 'agent' | 'team' | 'run'\n calibration: FindingCalibration\n renderState: (input: I, context: AnalystContext) => SystemOneState | Promise<SystemOneState>\n /** The judged population: the agent, team or run the state describes. */\n scope: (input: I, context: AnalystContext) => FindingScope\n subject?: (input: I, context: AnalystContext) => string\n}\n\n/**\n * Build the failure-modes analyst, or refuse when its calibration does not\n * clear `FAILURE_MODES_MIN_KAPPA`. An undefined κ (no gold, or one label\n * everywhere) is refused the same way.\n */\nexport function createFailureModesAnalyst<I>(\n options: FailureModesAnalystOptions<I>,\n): FailureModesOutcome<Analyst<I>> {\n const { calibration, layer, model, renderState, scope, subject, ...transport } = options\n if (!(calibration.gold_n > 0) || !(calibration.kappa >= FAILURE_MODES_MIN_KAPPA)) {\n return {\n succeeded: false,\n error: {\n kind: 'uncalibrated',\n message: `failure-modes rubric has kappa ${Number.isNaN(calibration.kappa) ? 'undefined' : calibration.kappa.toFixed(3)} over ${calibration.gold_n} gold items; reporting requires kappa >= ${FAILURE_MODES_MIN_KAPPA}`,\n },\n }\n }\n const method = {\n kind: 'judged' as const,\n name: FAILURE_MODES_ANALYST_ID,\n version: FAILURE_MODES_VERSION,\n calibration: {\n gold_n: calibration.gold_n,\n agreement: calibration.agreement,\n kappa: calibration.kappa,\n },\n }\n const analyst = systemOneAnalyst({\n ...transport,\n model,\n renderState,\n id: FAILURE_MODES_ANALYST_ID,\n description: 'Labels agent, team and run failures with a calibrated fixed-choice rubric.',\n inputKind: 'custom',\n version: FAILURE_MODES_VERSION,\n questions: FAILURE_MODES_QUESTIONS,\n findings: (value, input, context) => {\n const judgedSubject = subject?.(input, context)\n const base = {\n analyst_id: FAILURE_MODES_ANALYST_ID,\n derived_from_judge: true,\n layer,\n scope: scope(input, context),\n method,\n evidence_refs: [{ kind: 'artifact' as const, uri: `run://${context.runId}` }],\n ...(judgedSubject === undefined ? {} : { subject: judgedSubject }),\n }\n const out: AnalystFinding[] = []\n const mode = value.answers.failure_mode\n if (mode.choice !== 'none') {\n out.push(\n makeFinding({\n ...base,\n area: 'failure-mode',\n severity: 'medium',\n confidence: mode.confidence,\n claim: `Failure mode: ${mode.choice}`,\n claim_id: `failure-mode:${mode.choice}`,\n rationale: FAILURE_MODE_LABELS[mode.choice],\n }),\n )\n }\n const brief = value.answers.delegation_brief\n if (brief.choice === 'partial' || brief.choice === 'missing') {\n out.push(\n makeFinding({\n ...base,\n area: 'delegation-brief',\n severity: brief.choice === 'missing' ? 'high' : 'medium',\n confidence: brief.confidence,\n claim: `Delegation brief ${brief.choice}`,\n claim_id: `delegation-brief:${brief.choice}`,\n }),\n )\n }\n const steer = value.answers.steer_handling\n if (steer.choice === 'ignored') {\n out.push(\n makeFinding({\n ...base,\n area: 'steer-handling',\n severity: 'high',\n confidence: steer.confidence,\n claim: 'Steer ignored',\n claim_id: 'steer-handling:ignored',\n }),\n )\n }\n return out\n },\n })\n return { succeeded: true, value: analyst }\n}\n","/**\n * Findings ledger — analyst findings in the shared ledger-core journal.\n *\n * Each appended finding is one hash-chained, canonical JSON entry, fsynced and\n * pinned to a trusted head, so a later reader can prove nothing was rewritten\n * or cut from the end. A row is validated by `AnalystFindingSchema` before it\n * is written and again when it is read, so a 1.1.0 finding whose declared\n * population disagrees with its evidence never enters the record.\n *\n * Appends are idempotent per (run, finding): replaying a run's findings is a\n * no-op, and the same finding id with different content is a conflict.\n * `FindingsStore` remains the unchained JSONL store for existing consumers.\n */\n\nimport { z } from 'zod'\nimport type { LedgerHash } from '../ledger-core/canonical'\nimport { FileLedgerJournal, type LedgerJournalCodec } from '../ledger-core/journal'\nimport { merkleRoot } from '../ledger-core/merkle'\nimport { AnalystFindingSchema, type FindingLayer } from './finding-scope'\nimport {\n type DiffPolicy,\n diffFindings,\n type FindingsDiff,\n type PersistedFinding,\n} from './findings-store'\nimport type { AnalystFinding } from './types'\n\nconst schema = 'agent-eval.findings-ledger.v1' as const\nconst digest = z.string().regex(/^sha256:[a-f0-9]{64}$/)\nconst identity = z\n .string()\n .min(1)\n .refine((value) => value.trim() === value, { message: 'must not carry surrounding space' })\n\nconst eventSchema = z\n .object({\n kind: z.literal('finding'),\n eventId: identity,\n run_id: identity,\n finding: AnalystFindingSchema,\n })\n .strict()\n\ntype Event = z.infer<typeof eventSchema>\n\nconst entrySchema = z\n .object({\n schema: z.literal(schema),\n sequence: z.number().int().nonnegative(),\n previousHash: digest.nullable(),\n event: eventSchema,\n entryHash: digest,\n })\n .strict()\n\n/** One finding as the ledger holds it. */\nexport interface LedgerFinding extends PersistedFinding {\n /** Position in the journal; later entries were appended later. */\n sequence: number\n entryHash: LedgerHash\n}\n\nexport interface FindingsLedgerRead {\n findings: LedgerFinding[]\n /** RFC 9162 Merkle root over every entry hash, in journal order. */\n merkleRoot: LedgerHash\n}\n\nexport type FindingsLedgerOutcome<T> =\n | { succeeded: true; value: T }\n | {\n succeeded: false\n error: { kind: 'invalid' | 'conflict' | 'unavailable'; message: string }\n }\n\nexport interface FindingsLedger {\n readonly path: string\n append(\n runId: string,\n findings: readonly AnalystFinding[],\n ): Promise<FindingsLedgerOutcome<{ appended: number; replayed: number }>>\n read(): Promise<FindingsLedgerOutcome<FindingsLedgerRead>>\n}\n\nclass FindingsLedgerConflictError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'FindingsLedgerConflictError'\n }\n}\n\nclass FindingsLedgerInvalidError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'FindingsLedgerInvalidError'\n }\n}\n\nfunction codec(): LedgerJournalCodec<{ schema: typeof schema }, Event, LedgerFinding[]> {\n return {\n subject: 'findings ledger',\n header: { schema },\n integrityError: (message, options) => new Error(message, options),\n conflictError: (message) => new FindingsLedgerConflictError(message),\n parseEntry: (raw, context) => {\n const decoded = entrySchema.safeParse(raw)\n if (!decoded.success) {\n const issue = decoded.error.issues[0]\n throw new FindingsLedgerInvalidError(\n `findings ledger ${context.path}:${context.line} is invalid at ${(issue?.path ?? []).join('.')}: ${issue?.message}`,\n )\n }\n return {\n ...decoded.data,\n event: decoded.data.event as Event,\n previousHash: decoded.data.previousHash as LedgerHash | null,\n entryHash: decoded.data.entryHash as LedgerHash,\n }\n },\n checkEntryHeader: (entry) => {\n if (entry.schema !== schema) throw new FindingsLedgerInvalidError('unsupported ledger schema')\n },\n createProjector: () => {\n const rows: LedgerFinding[] = []\n return {\n apply: (entry) => {\n const { event } = entry\n if (event.eventId !== eventIdFor(event.run_id, event.finding.finding_id)) {\n throw new FindingsLedgerInvalidError(\n `event id ${event.eventId} does not name its finding`,\n )\n }\n rows.push({\n ...(event.finding as AnalystFinding),\n run_id: event.run_id,\n sequence: entry.sequence,\n entryHash: entry.entryHash,\n })\n },\n snapshot: () => [...rows],\n }\n },\n }\n}\n\nfunction eventIdFor(runId: string, findingId: string): string {\n return `finding:${runId}:${findingId}`\n}\n\nasync function outcome<T>(operation: () => Promise<T>): Promise<FindingsLedgerOutcome<T>> {\n try {\n return { succeeded: true, value: await operation() }\n } catch (error) {\n return {\n succeeded: false,\n error: {\n kind:\n error instanceof FindingsLedgerConflictError\n ? 'conflict'\n : error instanceof FindingsLedgerInvalidError || error instanceof z.ZodError\n ? 'invalid'\n : 'unavailable',\n message: error instanceof Error ? error.message : String(error),\n },\n }\n }\n}\n\n/** Open (or create on first append) the findings journal at `path`; every reopen requires its pin. */\nexport function openFindingsLedger(options: { path: string }): FindingsLedger {\n if (!options.path.trim()) throw new TypeError('findings ledger: path is empty')\n const journal = new FileLedgerJournal(options.path, codec(), { requireTrustedHead: true })\n return {\n path: journal.path,\n append: (runId, findings) =>\n outcome(async () => {\n identity.parse(runId)\n let appended = 0\n let replayed = 0\n for (const finding of findings) {\n const parsed = AnalystFindingSchema.safeParse(finding)\n if (!parsed.success) {\n const issue = parsed.error.issues[0]\n throw new FindingsLedgerInvalidError(\n `finding ${finding.finding_id} is invalid at ${(issue?.path ?? []).join('.')}: ${issue?.message}`,\n )\n }\n const result = await journal.append(\n {\n kind: 'finding',\n eventId: eventIdFor(runId, finding.finding_id),\n run_id: runId,\n finding: parsed.data,\n },\n { pinHead: true },\n )\n if (result.appended) appended += 1\n else replayed += 1\n }\n return { appended, replayed }\n }),\n read: () =>\n outcome(async () => {\n const findings = await journal.replay()\n return { findings, merkleRoot: merkleRoot(findings.map((row) => row.entryHash)) }\n }),\n }\n}\n\n// ── Queries ──────────────────────────────────────────────────────────\n\nexport interface FindingsQuery {\n layer?: FindingLayer | readonly FindingLayer[]\n subject?: string\n analystId?: string\n runId?: string\n claimId?: string\n /**\n * Findings whose `scope.domain_path` starts with this path. A finding with no\n * domain path never matches, so a path query cannot return unscoped findings.\n */\n domainPath?: readonly string[]\n}\n\n/** Filter ledger rows. Every set criterion must hold; 1.0.0 rows have no layer and never match one. */\nexport function queryFindings<T extends AnalystFinding & { run_id?: string }>(\n rows: readonly T[],\n query: FindingsQuery,\n): T[] {\n const layers =\n query.layer === undefined\n ? null\n : new Set(typeof query.layer === 'string' ? [query.layer] : query.layer)\n return rows.filter((row) => {\n if (layers && (row.layer === undefined || !layers.has(row.layer))) return false\n if (query.subject !== undefined && row.subject !== query.subject) return false\n if (query.analystId !== undefined && row.analyst_id !== query.analystId) return false\n if (query.runId !== undefined && row.run_id !== query.runId) return false\n if (query.claimId !== undefined && row.claim_id !== query.claimId) return false\n if (query.domainPath !== undefined) {\n const path = row.scope?.domain_path\n if (!path || path.length < query.domainPath.length) return false\n if (query.domainPath.some((id, index) => path[index] !== id)) return false\n }\n return true\n })\n}\n\nexport interface FindingsTimeStep {\n previous_run_id: string\n run_id: string\n diff: FindingsDiff\n}\n\n/**\n * Diff each run against the run before it, in the order runs first entered\n * the ledger. Uses `diffFindings`, so `appeared`, `disappeared`, `persisted`\n * and `changed` mean exactly what they mean for two runs.\n */\nexport function diffFindingsOverTime(\n rows: readonly LedgerFinding[],\n policy: DiffPolicy = {},\n): FindingsTimeStep[] {\n const runs: string[] = []\n const byRun = new Map<string, PersistedFinding[]>()\n for (const row of [...rows].sort((a, b) => a.sequence - b.sequence)) {\n const list = byRun.get(row.run_id)\n if (list) list.push(row)\n else {\n runs.push(row.run_id)\n byRun.set(row.run_id, [row])\n }\n }\n return runs.slice(1).map((runId, index) => ({\n previous_run_id: runs[index]!,\n run_id: runId,\n diff: diffFindings(byRun.get(runs[index]!)!, byRun.get(runId)!, policy),\n }))\n}\n","/**\n * Skill-usage analyst — a DETERMINISTIC `Analyst` over a Claude/Codex skill\n * library + its trace corpus. Unlike the trace-store kinds (failure-mode,\n * improvement, ...) this kind calls no LLM: it mines real usage and skill\n * structure and emits findings by rule.\n *\n * It exists because the naive \"Skill-tool invocation count\" lies low — it\n * misses orchestrated sub-dispatch (a leaf skill run BY /pursue or /governor\n * logs under the parent), slash-command entry, local-script bypass, and\n * on-disk artifacts. The 2026-05-30 skill audit found 39/53 skills at zero\n * direct invocations, yet only one was a genuine cut: the rest were\n * measurement-invisible or discovery-limited. This analyst encodes that\n * lesson as a multi-signal usage model so a cheap repeatable pass can keep\n * the library honest, and so the expensive audit workflow's verdicts can\n * GEPA-distill it toward agreement (see `gold/skill-verdicts.gold.jsonl`).\n *\n * Report-building (`buildSkillUsageReport`, an fs scan) is separated from\n * finding emission (`SkillUsageAnalyst.analyze`, pure) so the slow scan runs\n * once at the registry boundary and the rule logic stays unit-testable.\n */\n\nimport { type Dirent, existsSync, readdirSync, readFileSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { ExactCapableAnalyst } from '../exact-types'\nimport type { AnalystContext, AnalystFinding, AnalystSeverity } from '../types'\nimport { computeFindingId } from '../types'\n\n// ── Input model ──────────────────────────────────────────────────────\n\nexport type SkillKind = 'public' | 'private'\n\n/** One skill's multi-signal usage + structure. All counts are deterministic. */\nexport interface SkillUsageRecord {\n name: string\n kind: SkillKind\n /** Absolute path to the skill's SKILL.md. */\n path: string\n lines: number\n /** `\"skill\":\"<name>\"` Skill-tool invocations across the trace corpus. */\n directInvocations: number\n /** `<command-name>/<name>` slash invocations across the trace corpus. */\n slashInvocations: number\n /** Sibling skills whose SKILL.md dispatches to this one (`/<name>`). Proxy\n * for orchestrated sub-dispatch the per-skill counter cannot see. */\n inboundRefs: number\n /** On-disk artifacts attributable to the skill (e.g. `.evolve/<name>/**`). */\n artifactCount: number\n /** Tangle-private reference count in the body (leak signal for public skills). */\n tanglePrivateRefs: number\n hasReferencesDir: boolean\n hasEvalsDir: boolean\n /** Body mentions `skill-runs.jsonl` (visible to /reflect + /governor). */\n logsRuns: boolean\n /** Description carries an explicit `Triggers:` clause / trigger phrases. */\n hasTriggerPhrases: boolean\n}\n\nexport interface SkillUsageReport {\n generatedFromTraces: number\n records: SkillUsageRecord[]\n}\n\nexport interface SkillUsageScanConfig {\n /** Dirs holding `*.jsonl` transcripts (Claude `~/.claude/projects`, Codex sessions). */\n transcriptDirs: string[]\n /** Skill roots to scan; each dir directly under `root` with a `SKILL.md` is a skill. */\n skillRoots: { root: string; kind: SkillKind }[]\n /** Roots scanned for `<root>/.evolve/<skill>` artifact dirs. */\n artifactRoots?: string[]\n /** Token-prefixed mappings: skill name → extra artifact subpaths under an artifactRoot\n * (e.g. reflect → `.evolve/reflections`). Catches non-eponymous artifact dirs. */\n artifactAliases?: Record<string, string[]>\n /** Cap files read per transcript dir (bounds a huge corpus); 0 = unbounded. */\n maxTranscriptsPerDir?: number\n}\n\n// ── Deterministic thresholds ─────────────────────────────────────────\n\n/** Anthropic's authoring guidance keeps SKILL.md short; past this with no\n * `references/` split the body burns context budget every session. */\nconst BLOAT_LINE_THRESHOLD = 300\n\nconst TANGLE_PRIVATE_RE =\n /\\b(cli-bridge|tangletools|ops-board|drew-gtr-pro|@tangle-network\\/|~\\/company|tangle\\.tools|gtm-agent)\\b|\\bkimi\\b|\\btcloud\\b/gi\nconst TRIGGER_RE = /triggers?\\s*[:-]/i\n\n// ── Report builder (fs scan — slow, runs once at the registry boundary) ──\n\nfunction listSkillDirs(root: string): { name: string; path: string }[] {\n if (!existsSync(root)) return []\n const out: { name: string; path: string }[] = []\n for (const entry of readdirSync(root, { withFileTypes: true })) {\n if (!entry.isDirectory() && !entry.isSymbolicLink()) continue\n const skillMd = join(root, entry.name, 'SKILL.md')\n if (existsSync(skillMd)) out.push({ name: entry.name, path: skillMd })\n }\n return out\n}\n\nfunction walkJsonl(dir: string, cap: number): string[] {\n if (!existsSync(dir)) return []\n const files: string[] = []\n const stack = [dir]\n while (stack.length) {\n const cur = stack.pop()!\n let entries: Dirent[]\n try {\n entries = readdirSync(cur, { withFileTypes: true })\n } catch {\n continue\n }\n for (const e of entries) {\n const full = join(cur, e.name)\n if (e.isDirectory()) stack.push(full)\n else if (e.name.endsWith('.jsonl')) {\n files.push(full)\n if (cap > 0 && files.length >= cap) return files\n }\n }\n }\n return files\n}\n\nfunction frontmatterDescription(body: string): string {\n const fm = /^---\\n([\\s\\S]*?)\\n---/.exec(body)\n const block = fm?.[1] ?? ''\n const m = /description:\\s*(.+)/i.exec(block)\n return m?.[1] ?? ''\n}\n\nfunction countArtifacts(roots: string[], name: string, aliases: string[]): number {\n let n = 0\n for (const root of roots) {\n const candidates = [join(root, '.evolve', name), ...aliases.map((a) => join(root, a))]\n for (const dir of candidates) {\n if (!existsSync(dir)) continue\n try {\n if (statSync(dir).isDirectory()) n += readdirSync(dir).length\n else n += 1\n } catch {\n /* unreadable — skip */\n }\n }\n }\n return n\n}\n\n/** Scan the corpus + skill roots into a {@link SkillUsageReport}. Deterministic. */\nexport function buildSkillUsageReport(config: SkillUsageScanConfig): SkillUsageReport {\n const skills = config.skillRoots.flatMap(({ root, kind }) =>\n listSkillDirs(root).map((s) => ({ ...s, kind })),\n )\n const names = skills.map((s) => s.name)\n\n // One pass over the corpus accumulating direct + slash counts per skill.\n const direct = new Map<string, number>(names.map((n) => [n, 0]))\n const slash = new Map<string, number>(names.map((n) => [n, 0]))\n const skillRe = /\"skill\"\\s*:\\s*\"([a-z0-9_:-]+)\"/g\n const cmdRe = /<command-name>\\/?([a-z0-9_:-]+)<\\/command-name>/g\n let transcripts = 0\n for (const dir of config.transcriptDirs) {\n for (const file of walkJsonl(dir, config.maxTranscriptsPerDir ?? 0)) {\n transcripts += 1\n let data: string\n try {\n data = readFileSync(file, 'utf8')\n } catch {\n continue\n }\n for (const m of data.matchAll(skillRe)) {\n const g = m[1]\n if (!g) continue\n const n = g.split(':').pop() ?? g\n const prev = direct.get(n)\n if (prev !== undefined) direct.set(n, prev + 1)\n }\n for (const m of data.matchAll(cmdRe)) {\n const g = m[1]\n if (g === undefined) continue\n const prev = slash.get(g)\n if (prev !== undefined) slash.set(g, prev + 1)\n }\n }\n }\n\n // Read each skill body once; compute structure + inbound refs across siblings.\n const bodies = new Map<string, string>()\n for (const s of skills) {\n try {\n bodies.set(s.name, readFileSync(s.path, 'utf8'))\n } catch {\n bodies.set(s.name, '')\n }\n }\n const inbound = new Map<string, number>(names.map((n) => [n, 0]))\n for (const target of names) {\n const ref = new RegExp(`/${target}\\\\b|\\\\[\\\\[${target}\\\\]\\\\]`)\n for (const s of skills) {\n if (s.name === target) continue\n if (ref.test(bodies.get(s.name) ?? '')) inbound.set(target, inbound.get(target)! + 1)\n }\n }\n\n const records: SkillUsageRecord[] = skills.map((s) => {\n const body = bodies.get(s.name) ?? ''\n const dir = s.path.replace(/\\/SKILL\\.md$/, '')\n return {\n name: s.name,\n kind: s.kind,\n path: s.path,\n lines: body ? body.split('\\n').length : 0,\n directInvocations: direct.get(s.name) ?? 0,\n slashInvocations: slash.get(s.name) ?? 0,\n inboundRefs: inbound.get(s.name) ?? 0,\n artifactCount: countArtifacts(\n config.artifactRoots ?? [],\n s.name,\n config.artifactAliases?.[s.name] ?? [],\n ),\n tanglePrivateRefs: (body.match(TANGLE_PRIVATE_RE) ?? []).length,\n hasReferencesDir: existsSync(join(dir, 'references')),\n hasEvalsDir: existsSync(join(dir, 'evals')),\n logsRuns: body.includes('skill-runs.jsonl'),\n hasTriggerPhrases: TRIGGER_RE.test(frontmatterDescription(body) || body.slice(0, 600)),\n }\n })\n return { generatedFromTraces: transcripts, records }\n}\n\n// ── Finding emission (pure — unit-testable, no LLM, no fs) ────────────\n\nconst ANALYST_ID = 'skill-usage'\n\nfunction finding(\n area: string,\n subject: string,\n claim: string,\n severity: AnalystSeverity,\n confidence: number,\n producedAt: string,\n recommended: string,\n evidenceUri: string,\n rationale?: string,\n): AnalystFinding {\n return {\n schema_version: '1.0.0',\n finding_id: computeFindingId({ analyst_id: ANALYST_ID, area, subject, claim }),\n analyst_id: ANALYST_ID,\n produced_at: producedAt,\n severity,\n area,\n claim,\n rationale,\n evidence_refs: [{ kind: 'artifact', uri: evidenceUri }],\n recommended_action: recommended,\n confidence,\n subject,\n }\n}\n\n/** Pure rule pass over a report → findings. Exported for direct/unit use. */\nexport function emitSkillUsageFindings(\n report: SkillUsageReport,\n producedAt: string,\n): AnalystFinding[] {\n const out: AnalystFinding[] = []\n for (const r of report.records) {\n const directTotal = r.directInvocations + r.slashInvocations\n const trueUsage = directTotal + r.inboundRefs + r.artifactCount\n\n // 1. Dead: no usage signal of ANY kind. The only real deprecation candidate.\n if (trueUsage === 0) {\n out.push(\n finding(\n 'skill-usage',\n r.name,\n `Skill '${r.name}' has zero usage across all signals (direct, slash, inbound-refs, artifacts)`,\n 'high',\n 0.6,\n producedAt,\n 'Confirm the skill covers a real recurring job; if not, deprecate. Zero true usage is the only deterministic deprecation candidate.',\n r.path,\n 'No Skill-tool call, no slash invocation, no sibling dispatches to it, and no on-disk artifacts.',\n ),\n )\n } else if (directTotal === 0 && r.inboundRefs + r.artifactCount > 0) {\n // 2. Measurement-invisible: real use via orchestration/artifacts, never invoked directly.\n out.push(\n finding(\n 'skill-usage',\n r.name,\n `Skill '${r.name}' shows 0 direct invocations but is used via orchestration/artifacts (inbound=${r.inboundRefs}, artifacts=${r.artifactCount})`,\n 'info',\n 0.8,\n producedAt,\n 'Do NOT treat as unused — usage is real but logged under parent skills or on disk. Strengthen direct-invocation discovery only if direct use is desired.',\n r.path,\n 'The Skill-tool counter undercounts orchestrated/chained leaf skills.',\n ),\n )\n }\n\n // 3. Discovery gap: low direct use AND weak trigger surface.\n if (directTotal <= 2 && !r.hasTriggerPhrases) {\n out.push(\n finding(\n 'discoverability',\n r.name,\n `Skill '${r.name}' is rarely invoked directly and its description has no explicit trigger phrases`,\n 'medium',\n 0.7,\n producedAt,\n 'Add a `Triggers:` clause with verbatim user phrases to the frontmatter description so the model auto-invokes it.',\n r.path,\n ),\n )\n }\n\n // 4. Public-repo leak.\n if (r.kind === 'public' && r.tanglePrivateRefs > 0) {\n out.push(\n finding(\n 'safety',\n r.name,\n `Public skill '${r.name}' carries ${r.tanglePrivateRefs} Tangle-private reference(s)`,\n 'high',\n 0.75,\n producedAt,\n 'Sanitize incidental internal refs (cli-bridge/kimi/tcloud/~company/private repos) or relocate to a private repo. Verify @tangle-network/* refs are to PUBLISHED packages before treating as a leak.',\n r.path,\n ),\n )\n }\n\n // 5. Bloat / no progressive disclosure.\n if (r.lines > BLOAT_LINE_THRESHOLD && !r.hasReferencesDir) {\n out.push(\n finding(\n 'maintainability',\n r.name,\n `Skill '${r.name}' is ${r.lines} lines with no references/ split (progressive disclosure)`,\n 'medium',\n 0.8,\n producedAt,\n `Split detail into references/ loaded on demand; keep SKILL.md a short overview. ${r.lines} lines load into every session's context budget.`,\n r.path,\n ),\n )\n }\n\n // 6. No evals (Anthropic's \">=3 evals before docs\" rule).\n if (!r.hasEvalsDir) {\n out.push(\n finding(\n 'data-quality',\n r.name,\n `Skill '${r.name}' ships no evals/`,\n 'low',\n 0.6,\n producedAt,\n 'Add evals/evals.json with >=3 scenarios proving the skill beats baseline; gives regression coverage.',\n r.path,\n ),\n )\n }\n\n // 7. No run logging → invisible to /reflect and /governor.\n if (!r.logsRuns) {\n out.push(\n finding(\n 'observability',\n r.name,\n `Skill '${r.name}' never appends to .evolve/skill-runs.jsonl`,\n 'low',\n 0.55,\n producedAt,\n 'Append one run line to .evolve/skill-runs.jsonl on completion, or declare it a non-logging leaf, so the self-improvement loop can see it ran.',\n r.path,\n ),\n )\n }\n }\n return out\n}\n\n// ── The Analyst ──────────────────────────────────────────────────────\n\nclass SkillUsageAnalyst implements ExactCapableAnalyst<SkillUsageReport> {\n readonly id = ANALYST_ID\n readonly description =\n 'Deterministic multi-signal skill-usage analysis: flags dead skills, measurement-invisible (orchestrated) usage, discovery gaps, public-repo leaks, bloat, missing evals, and missing run-logging.'\n readonly inputKind = 'custom' as const\n readonly cost = { kind: 'deterministic' as const, est_usd_per_run: 0 }\n readonly version = '1.0.0'\n readonly executionConfig = {\n kind: 'skill-usage',\n bloat_line_threshold: BLOAT_LINE_THRESHOLD,\n produced_at_source: 'tags.producedAt-or-system-clock',\n } as const\n\n async analyze(input: SkillUsageReport, ctx: AnalystContext): Promise<AnalystFinding[]> {\n const producedAt = ctx.tags?.producedAt ?? new Date().toISOString()\n ctx.log?.(\n `skill-usage: ${input.records.length} skills over ${input.generatedFromTraces} transcripts`,\n )\n return emitSkillUsageFindings(input, producedAt)\n }\n}\n\nexport const SKILL_USAGE_ANALYST = new SkillUsageAnalyst()\n","/**\n * Promotion — the only way a claim moves above the layer it was measured at.\n *\n * A claim is restated at a parent node only when at least `k` independent\n * children carry the same `claim_id` with intervals that agree. Otherwise it\n * stays where it is, reported as untested above. The rule is the same on every\n * rung of the ladder: run → play → problem → each domain node up the path →\n * lab.\n *\n * The rule, exactly:\n * - A finding sits at the node that is the lowest common ancestor of its\n * `scope.population` in the taxonomy, and that node's layer must equal the\n * finding's `layer`. Four runs of one play place a claim at that play; the\n * same claim stored at `domain` or `lab` is refused as exceeding its\n * evidence.\n * - Only children with `measure.interval` vote. Voters must name the same\n * measure and unit, and their intervals must share a common point.\n * - Children are counted by lineage, not by node: two children whose evidence\n * units share a lineage root (run 2 built on run 1's code) count once, and\n * a child with no recorded lineage shares one root with every other such\n * child.\n * - Promoted findings cite every voting child by `finding://<finding_id>`.\n *\n * Event, turn, agent, team and meta findings sit outside the ladder and never\n * promote.\n */\n\nimport {\n type DomainTaxonomy,\n domainPathOf,\n LAB_NODE_ID,\n lowestCommonAncestor,\n taxonomyAncestry,\n taxonomyLayerOf,\n taxonomyParentOf,\n} from './domain-taxonomy'\nimport {\n type FindingLayer,\n type FindingMeasure,\n lineageRoots,\n mergeEvidenceUnits,\n mostSevere,\n spanningWindow,\n UNKNOWN_LINEAGE,\n} from './finding-scope'\nimport { type AnalystFinding, makeFinding } from './types'\n\n/** Bump when the promotion rule changes, so promoted findings name the rule that lifted them. */\nexport const PROMOTE_VERSION = '1'\n\n/** The analyst id a promoted finding carries when its children came from different analysts. */\nexport const PROMOTE_ANALYST_ID = 'promote'\n\nexport interface PromoteOptions {\n /** Independent agreeing children required to lift a claim. Default 2, minimum 2. */\n k?: number\n /** Timestamp stamped on promoted findings; defaults to now. */\n produced_at?: string\n}\n\n/** A finding promote did not lift, with the reason in words. */\nexport interface PromotionHold {\n finding_id: string\n claim_id: string | null\n /** The node the finding sits at, or null when it could not be placed. */\n node: string | null\n reason: string\n}\n\nexport interface PromotionResult {\n /** The input findings followed by every promoted finding. */\n findings: AnalystFinding[]\n promoted: AnalystFinding[]\n /** Placed findings whose claim was not lifted; they stay true at their own node. */\n untestedAbove: PromotionHold[]\n /** Findings promote cannot place on the ladder, and why. */\n unplaced: PromotionHold[]\n}\n\ninterface Placement {\n finding: AnalystFinding\n claimId: string\n node: string\n}\n\nconst LADDER: readonly FindingLayer[] = ['run', 'play', 'problem', 'domain', 'lab']\n\nexport function promote(\n findings: readonly AnalystFinding[],\n taxonomy: DomainTaxonomy,\n options: PromoteOptions = {},\n): PromotionResult {\n const k = options.k ?? 2\n if (!Number.isInteger(k) || k < 2) {\n throw new RangeError(`promote: k must be an integer of at least 2, got ${k}`)\n }\n const unplaced: PromotionHold[] = []\n const buckets = new Map<number, Placement[]>()\n const addPlacement = (placement: Placement): void => {\n const depth = taxonomyAncestry(taxonomy, placement.node).length\n const bucket = buckets.get(depth) ?? []\n bucket.push(placement)\n buckets.set(depth, bucket)\n }\n for (const finding of findings) {\n const placed = place(finding, taxonomy)\n if ('reason' in placed) unplaced.push(placed)\n else addPlacement(placed)\n }\n\n const roots = lineageRoots(\n mergeEvidenceUnits(findings.flatMap((finding) => finding.evidence_units ?? [])),\n )\n const promoted: AnalystFinding[] = []\n const untestedAbove: PromotionHold[] = []\n const hold = (placement: Placement, reason: string): void => {\n untestedAbove.push({\n finding_id: placement.finding.finding_id,\n claim_id: placement.claimId,\n node: placement.node,\n reason,\n })\n }\n\n // Deepest nodes first: a parent's bucket is complete, native findings and\n // lifted ones alike, before it is itself grouped for the next rung.\n for (let depth = Math.max(0, ...buckets.keys()); depth > 1; depth -= 1) {\n const groups = new Map<string, { parent: string; members: Placement[] }>()\n for (const placement of buckets.get(depth) ?? []) {\n const parent = taxonomyParentOf(taxonomy, placement.node)\n if (parent === null || parent === undefined) continue\n const key = JSON.stringify([placement.claimId, parent])\n const group = groups.get(key) ?? { parent, members: [] }\n group.members.push(placement)\n groups.set(key, group)\n }\n for (const { parent, members } of groups.values()) {\n const verdict = judgeGroup(members, k, roots)\n if (!verdict.lift) {\n for (const member of members) hold(member, verdict.reason)\n continue\n }\n const lifted = liftedFinding(verdict.voters, parent, taxonomy, options.produced_at)\n promoted.push(lifted)\n addPlacement({ finding: lifted, claimId: members[0]!.claimId, node: parent })\n for (const member of members) {\n if (!verdict.voters.includes(member)) {\n hold(member, 'no interval, so it could not vote; the claim was lifted by its siblings')\n }\n }\n }\n }\n return { findings: [...findings, ...promoted], promoted, untestedAbove, unplaced }\n}\n\nfunction place(finding: AnalystFinding, taxonomy: DomainTaxonomy): Placement | PromotionHold {\n const unplaced = (reason: string, node: string | null = null): PromotionHold => ({\n finding_id: finding.finding_id,\n claim_id: finding.claim_id ?? null,\n node,\n reason,\n })\n if (finding.schema_version !== '1.1.0' || !finding.layer || !finding.scope) {\n return unplaced('no layer or scope (schema 1.0.0)')\n }\n if (finding.layer === 'meta')\n return unplaced('meta findings describe the instrument and never promote')\n if (!LADDER.includes(finding.layer)) {\n return unplaced(`${finding.layer} findings sit below the run → lab ladder`)\n }\n if (!finding.claim_id) return unplaced('no claim_id to match siblings by')\n const population = finding.scope.population\n if (population.length === 0) return unplaced('population names no units')\n const node = lowestCommonAncestor(taxonomy, population)\n if (node === undefined) return unplaced('population names ids outside the taxonomy')\n const nodeLayer = taxonomyLayerOf(taxonomy, node)\n if (nodeLayer !== finding.layer) {\n return unplaced(\n LADDER.indexOf(finding.layer) > LADDER.indexOf(nodeLayer as FindingLayer)\n ? `stated at ${finding.layer} but its population sits within ${nodeLayer} '${node}'`\n : `stated at ${finding.layer} but its population spans ${nodeLayer} '${node}'`,\n node,\n )\n }\n const path = finding.scope.domain_path\n if (path) {\n const expected = domainPathOf(taxonomy, node)\n if (path.length !== expected.length || path.some((id, index) => id !== expected[index])) {\n return unplaced(`domain_path ${JSON.stringify(path)} disagrees with the taxonomy`, node)\n }\n }\n return { finding, claimId: finding.claim_id, node }\n}\n\ntype GroupVerdict = { lift: true; voters: Placement[] } | { lift: false; reason: string }\n\nfunction judgeGroup(\n members: readonly Placement[],\n k: number,\n roots: ReadonlyMap<string, string>,\n): GroupVerdict {\n const voters = members.filter((member) => member.finding.measure?.interval !== undefined)\n if (voters.length === 0) return { lift: false, reason: 'no child carries an interval' }\n const first = voters[0]!.finding.measure!\n if (\n voters.some(\n ({ finding }) => finding.measure!.name !== first.name || finding.measure!.unit !== first.unit,\n )\n ) {\n return { lift: false, reason: 'children measure different quantities' }\n }\n const lo = Math.max(...voters.map(({ finding }) => finding.measure!.interval![0]))\n const hi = Math.min(...voters.map(({ finding }) => finding.measure!.interval![1]))\n if (lo > hi) return { lift: false, reason: 'child intervals do not agree' }\n\n const independent = independentChildren(voters, roots)\n if (independent < k) {\n const children = new Set(voters.map((voter) => voter.node)).size\n return {\n lift: false,\n reason:\n children > independent\n ? `${children} children agree but share lineage, leaving ${independent} independent of ${k} required`\n : `${independent} independent agreeing child${independent === 1 ? '' : 'ren'} of ${k} required`,\n }\n }\n return { lift: true, voters }\n}\n\n/**\n * Children joined when they share a lineage root, counted as components. A\n * child's roots are those of all its voters' evidence units; a voter with no\n * units has unknown lineage.\n */\nfunction independentChildren(\n voters: readonly Placement[],\n roots: ReadonlyMap<string, string>,\n): number {\n const rootsByNode = new Map<string, Set<string>>()\n for (const voter of voters) {\n const set = rootsByNode.get(voter.node) ?? new Set<string>()\n const units = voter.finding.evidence_units\n if (!units) set.add(UNKNOWN_LINEAGE)\n else for (const unit of units) set.add(roots.get(unit.id) ?? UNKNOWN_LINEAGE)\n rootsByNode.set(voter.node, set)\n }\n const parent = new Map<string, string>()\n const find = (id: string): string => {\n let current = id\n while (parent.get(current) !== current) current = parent.get(current)!\n return current\n }\n const owner = new Map<string, string>()\n for (const [node, nodeRoots] of rootsByNode) {\n parent.set(node, node)\n for (const root of nodeRoots) {\n const other = owner.get(root)\n if (other === undefined) owner.set(root, node)\n else parent.set(find(node), find(other))\n }\n }\n return new Set([...rootsByNode.keys()].map(find)).size\n}\n\nfunction liftedFinding(\n voters: readonly Placement[],\n parent: string,\n taxonomy: DomainTaxonomy,\n producedAt: string | undefined,\n): AnalystFinding {\n const findings = voters.map((voter) => voter.finding)\n const first = findings[0]!\n const measures = findings.map((finding) => finding.measure!) as FindingMeasure[]\n const levels = new Set(measures.map((measure) => measure.level))\n const level = levels.size === 1 ? measures[0]!.level : undefined\n const population = [...new Set(findings.flatMap((finding) => finding.scope!.population))].sort()\n const allUnits = findings.every((finding) => finding.evidence_units !== undefined)\n ? mergeEvidenceUnits(findings.flatMap((finding) => finding.evidence_units!))\n : undefined\n const confounders = [...new Set(findings.flatMap((finding) => finding.confounders ?? []))].sort()\n const analysts = new Set(findings.map((finding) => finding.analyst_id))\n const domainPath = domainPathOf(taxonomy, parent)\n const parentLayer = taxonomyLayerOf(taxonomy, parent) as FindingLayer\n return makeFinding({\n analyst_id: analysts.size === 1 ? first.analyst_id : PROMOTE_ANALYST_ID,\n area: first.area,\n claim: first.claim,\n claim_id: first.claim_id!,\n id_basis: `${first.claim_id}@${parent}`,\n subject: parent,\n severity: mostSevere(findings),\n confidence: Math.min(...findings.map((finding) => finding.confidence)),\n evidence_refs: findings.map((finding) => ({\n kind: 'finding' as const,\n uri: `finding://${finding.finding_id}`,\n })),\n layer: parentLayer,\n scope: {\n population,\n n: population.length,\n window: spanningWindow(findings),\n ...(domainPath.length > 0 && parent !== LAB_NODE_ID ? { domain_path: domainPath } : {}),\n },\n method: { kind: 'computed', name: 'promote', version: PROMOTE_VERSION },\n measure: {\n name: measures[0]!.name,\n unit: measures[0]!.unit,\n value: measures.reduce((sum, measure) => sum + measure.value, 0) / measures.length,\n interval: [\n Math.max(...measures.map((measure) => measure.interval![0])),\n Math.min(...measures.map((measure) => measure.interval![1])),\n ],\n ...(level === undefined ? {} : { level }),\n },\n ...(confounders.length > 0 ? { confounders } : {}),\n ...(allUnits ? { evidence_units: allUnits } : {}),\n rationale: `Lifted to ${parentLayer} '${parent}': ${new Set(voters.map((voter) => voter.node)).size} children carry claim '${first.claim_id}' with intervals that share [${Math.max(...measures.map((m) => m.interval![0]))}, ${Math.min(...measures.map((m) => m.interval![1]))}].`,\n metadata: {\n taxonomy_version: taxonomy.version,\n promoted_from: [...new Set(voters.map((voter) => voter.node))].sort(),\n },\n ...(producedAt === undefined ? {} : { produced_at: producedAt }),\n })\n}\n","/**\n * rollup — run findings aggregated up the ladder, with bootstrap intervals and\n * denominators, lifted only where `promote` allows.\n *\n * Run-layer findings that share a `claim_id` and a measure are pooled per play\n * into one play-layer finding. Its interval is a cluster bootstrap where each\n * cluster is a lineage root, so runs that built on each other move together\n * and four runs of one lineage yield one cluster and no interval. Those play\n * findings then go through `promote`; each finding it lifts to a problem,\n * domain node or the lab gets the pooled bootstrap over every run underneath\n * it, with its observation and cluster counts.\n */\n\nimport { clusterBootstrapMean } from '../meta-eval/cluster-bootstrap'\nimport {\n type DomainTaxonomy,\n domainPathOf,\n lowestCommonAncestor,\n taxonomyLayerOf,\n taxonomyParentOf,\n} from './domain-taxonomy'\nimport {\n lineageRoots,\n mergeEvidenceUnits,\n mostSevere,\n spanningWindow,\n UNKNOWN_LINEAGE,\n} from './finding-scope'\nimport { type PromotionHold, promote } from './promote'\nimport { type Analyst, type AnalystFinding, makeFinding } from './types'\n\nexport const ROLLUP_ANALYST_ID = 'rollup'\nexport const ROLLUP_VERSION = '1'\n\nexport interface RollupOptions {\n /** Independent agreeing children `promote` requires. Default 2. */\n k?: number\n /** Bootstrap seed; absent, the seed derives from the values, so reruns match. */\n seed?: number\n resamples?: number\n /** Interval confidence. Default 0.95. */\n confidence?: number\n produced_at?: string\n}\n\nexport interface RollupResult {\n /** Play aggregates followed by every finding promote lifted from them. */\n findings: AnalystFinding[]\n untestedAbove: PromotionHold[]\n /** Input findings rollup could not use, and why. */\n skipped: PromotionHold[]\n}\n\ninterface Observation {\n finding: AnalystFinding\n claimId: string\n run: string\n value: number\n cluster: string\n}\n\nexport function rollupFindings(\n findings: readonly AnalystFinding[],\n taxonomy: DomainTaxonomy,\n options: RollupOptions = {},\n): RollupResult {\n const confidence = options.confidence ?? 0.95\n const skipped: PromotionHold[] = []\n const skip = (finding: AnalystFinding, reason: string): void => {\n skipped.push({\n finding_id: finding.finding_id,\n claim_id: finding.claim_id ?? null,\n node: null,\n reason,\n })\n }\n const roots = lineageRoots(findings.flatMap((finding) => finding.evidence_units ?? []))\n const observations: Observation[] = []\n for (const finding of findings) {\n if (finding.layer !== 'run' || !finding.scope) continue\n if (!finding.claim_id) {\n skip(finding, 'no claim_id')\n continue\n }\n if (!finding.measure) {\n skip(finding, 'no measure to aggregate')\n continue\n }\n const run = lowestCommonAncestor(taxonomy, finding.scope.population)\n if (run === undefined || taxonomyLayerOf(taxonomy, run) !== 'run') {\n skip(finding, 'population is not one run in the taxonomy')\n continue\n }\n const units = finding.evidence_units\n const runRoots = new Set(\n units ? units.map((unit) => roots.get(unit.id) ?? UNKNOWN_LINEAGE) : [UNKNOWN_LINEAGE],\n )\n observations.push({\n finding,\n claimId: finding.claim_id,\n run,\n value: finding.measure.value,\n // A run whose units reach several roots is clustered on the first; one\n // run is one observation either way.\n cluster: [...runRoots].sort()[0]!,\n })\n }\n\n const groups = new Map<string, { play: string; members: Observation[] }>()\n for (const observation of observations) {\n const play = taxonomyParentOf(taxonomy, observation.run)!\n const key = JSON.stringify([observation.claimId, play])\n const group = groups.get(key) ?? { play, members: [] }\n group.members.push(observation)\n groups.set(key, group)\n }\n const aggregates: AnalystFinding[] = []\n for (const { play, members } of groups.values()) {\n const measure = members[0]!.finding.measure!\n if (\n members.some(\n ({ finding }) =>\n finding.measure!.name !== measure.name || finding.measure!.unit !== measure.unit,\n )\n ) {\n for (const member of members)\n skip(member.finding, `runs of play '${play}' measure different quantities`)\n continue\n }\n const pooled = pool(members, options, confidence)\n const findingsInGroup = members.map((member) => member.finding)\n const population = [...new Set(members.map((member) => member.run))].sort()\n const units = findingsInGroup.every((finding) => finding.evidence_units !== undefined)\n ? mergeEvidenceUnits(findingsInGroup.flatMap((finding) => finding.evidence_units!))\n : undefined\n const domainPath = domainPathOf(taxonomy, play)\n const first = findingsInGroup[0]!\n aggregates.push(\n makeFinding({\n analyst_id: ROLLUP_ANALYST_ID,\n area: first.area,\n claim: first.claim,\n claim_id: first.claim_id!,\n id_basis: `${first.claim_id}@${play}`,\n subject: play,\n severity: mostSevere(findingsInGroup),\n confidence: Math.min(...findingsInGroup.map((finding) => finding.confidence)),\n evidence_refs: findingsInGroup.map((finding) => ({\n kind: 'finding' as const,\n uri: `finding://${finding.finding_id}`,\n })),\n layer: 'play',\n scope: {\n population,\n n: population.length,\n window: spanningWindow(findingsInGroup),\n ...(domainPath.length > 0 ? { domain_path: domainPath } : {}),\n },\n method: { kind: 'computed', name: ROLLUP_ANALYST_ID, version: ROLLUP_VERSION },\n measure: { name: measure.name, unit: measure.unit, ...pooled.measure },\n ...(units ? { evidence_units: units } : {}),\n metadata: { denominators: pooled.denominators },\n ...(options.produced_at === undefined ? {} : { produced_at: options.produced_at }),\n }),\n )\n }\n\n const promotion = promote(aggregates, taxonomy, {\n ...(options.k === undefined ? {} : { k: options.k }),\n ...(options.produced_at === undefined ? {} : { produced_at: options.produced_at }),\n })\n const promoted = promotion.promoted.map((finding) => {\n const covered = new Set(finding.scope!.population)\n const members = observations.filter(\n (observation) => observation.claimId === finding.claim_id && covered.has(observation.run),\n )\n const pooled = pool(members, options, confidence)\n return {\n ...finding,\n measure: { name: finding.measure!.name, unit: finding.measure!.unit, ...pooled.measure },\n metadata: { ...finding.metadata, denominators: pooled.denominators },\n }\n })\n return {\n findings: [...aggregates, ...promoted],\n untestedAbove: promotion.untestedAbove,\n skipped: [...skipped, ...promotion.unplaced],\n }\n}\n\n/**\n * Cluster bootstrap of the run values. With one cluster there is no spread\n * between independent sources, so the measure carries no interval and cannot\n * vote in `promote`.\n */\nfunction pool(members: readonly Observation[], options: RollupOptions, confidence: number) {\n const result = clusterBootstrapMean(\n members.map((member) => ({ cluster: member.cluster, value: member.value })),\n {\n confidence,\n ...(options.seed === undefined ? {} : { seed: options.seed }),\n ...(options.resamples === undefined ? {} : { resamples: options.resamples }),\n },\n )\n return {\n measure:\n result.clusters >= 2\n ? {\n value: result.mean,\n interval: [result.low, result.high] as [number, number],\n level: confidence,\n }\n : { value: result.mean },\n denominators: { observations: result.n, independent_clusters: result.clusters },\n }\n}\n\nexport interface RollupInput {\n findings: readonly AnalystFinding[]\n taxonomy: DomainTaxonomy\n options?: RollupOptions\n}\n\n/** The rollup analyst: emits the play aggregates and every finding promote lifted from them. */\nexport function rollupAnalyst(): Analyst<RollupInput> {\n return {\n id: ROLLUP_ANALYST_ID,\n description:\n 'Aggregates run findings up run → play → problem → domain → lab with bootstrap intervals.',\n inputKind: 'custom',\n cost: { kind: 'deterministic' },\n version: ROLLUP_VERSION,\n async analyze(input) {\n return rollupFindings(input.findings, input.taxonomy, input.options).findings\n },\n }\n}\n","/**\n * team-shape — classify how a supervision tree was organized, from a Runtime\n * spawn journal and its coordination log.\n *\n * Input rows come in either of two shapes, read by the same parser:\n * - Runtime envelopes, as `readRuntimeSupervisorRun` returns them in\n * `SupervisorRunSources.journal` and `.coordinationLog`\n * (`teamShapeInputFromSources`);\n * - the structure-only reduction under `tests/fixtures/team-shape`\n * (`extract.py`): spawn rows `{ kind, journal, id, at }`, coordination\n * rows `{ at, type, owner, toWorker?, from?, by?, delivered? }`.\n *\n * Three edge sets over the agents:\n * - E, command, parent → child. The parent is the child id minus its last\n * `:sN` segment (`R:s1:s0` is child `s0` of `R:s1`); the spawn journal has\n * no parent field. An id outside that path is an unplaced agent: its E\n * edge is not observable, and it is never read as depth 1.\n * - G, governance, receiver → child: the agent whose journal holds the\n * child's `settled` row, plus the sender of each `steer`.\n * - C, communication, sender → receiver: coordination rows that name a\n * receiver (`toWorker`). The sender is `from`/`by` when the row names an\n * agent, else the log owner's digest, which no record joins to an agent.\n * `instruction` and `delivery-attempt` rows are the queue and transport\n * stages of the steer row that follows them, so they are not counted.\n *\n * Classes, version 1, checked in order; the first the record shows wins:\n * 1. single — one agent.\n * 2. governed-swarm — E runs between peers, or a team's governor\n * changes over the run.\n * 3. fleet — one dispatcher, and governance from a non-parent\n * agent inside the team or lateral C ≥ 20%.\n * 4. partition — two or more lead subtrees with no C or G between\n * them, and no lead settles to the root.\n * 5. hive — depth ≥ 2 and at least half the root's children\n * delegate (`hive depth N`).\n * 6. star-with-sub-leads — depth ≥ 2, fewer than half delegate.\n * 7. flat-star — depth 1; qualified by root integration share.\n * The thresholds are provisional and travel in `method.version`. A check the\n * record cannot decide (an owner digest is not an agent id, so lateral C and\n * steer governance often are not) reads `not observable from this record`,\n * never `no`, and the classification moves on to the next class.\n */\n\nimport type { SupervisorRunSources } from '../supervisor-run/types'\nimport type { Analyst } from './types'\nimport { makeFinding } from './types'\n\nexport const TEAM_SHAPE_ANALYST_ID = 'team-shape'\n\nexport const TEAM_SHAPE_THRESHOLDS = {\n /** Share of the root's children that delegate at or above which depth ≥ 2 is a hive. */\n hiveDelegatingShare: 0.5,\n /** Lateral share of C edges at or above which a one-dispatcher team is a fleet. */\n fleetLateralCShare: 0.2,\n /** Root share of integrating commits at or above which a flat star reads `root integrates`. */\n rootIntegrationShare: 0.5,\n} as const\n\n/** Version 1, provisional, with the thresholds it was decided at. */\nexport const TEAM_SHAPE_VERSION = `1-provisional;hive-delegating=${TEAM_SHAPE_THRESHOLDS.hiveDelegatingShare};fleet-lateral-c=${TEAM_SHAPE_THRESHOLDS.fleetLateralCShare};root-integration=${TEAM_SHAPE_THRESHOLDS.rootIntegrationShare}`\n\nexport const TEAM_SHAPE_CLASSES = [\n 'single',\n 'governed-swarm',\n 'fleet',\n 'partition',\n 'hive',\n 'star-with-sub-leads',\n 'flat-star',\n] as const\n\nexport type TeamShapeClass = (typeof TEAM_SHAPE_CLASSES)[number]\n\nexport const NOT_OBSERVABLE = 'not observable from this record'\nexport type NotObservable = typeof NOT_OBSERVABLE\nexport type TeamShapeObserved<T> = T | NotObservable\n\nexport interface TeamIntegration {\n commit: string\n /** Agent id, in the record's id space, that authored the integrating commit. */\n by: string\n}\n\nexport interface TeamShapeInput {\n /** The run the record came from, cited as the finding's evidence. */\n runRef: string\n /** Spawn journal JSONL. */\n spawnJournal: string\n /** Coordination log JSONL; null or absent when the run kept none. */\n coordinationLog?: string | null\n /** The release's integrating commits; disco derives them from commit trailers. */\n integrations?: readonly TeamIntegration[]\n}\n\nexport interface TeamShapeEdge {\n from: string\n to: string\n count: number\n}\n\nexport interface TeamShapeFeatures {\n agents: number\n /** Agents other than the root. */\n tasks: number\n /** Agents whose id is outside the root's `:sN` path; their E edge is not observable. */\n unplacedAgents: number\n depth: number\n fanOut: { root: number; max: number }\n /** Root's children that delegate ÷ root's children; null when the root has none. */\n delegatingShare: number | null\n /** Spawns after the first settlement. */\n reHires: number\n settlementsByReceiver: Record<string, number>\n steers: { sent: number; delivered: number }\n /** Coordination messages per task; null with no tasks or no coordination log. */\n messagesPerTask: number | null\n /** Lateral C edges ÷ C edges. */\n lateralCShare: TeamShapeObserved<number>\n /** G edges from a non-parent agent ÷ G edges. */\n nonParentGShare: TeamShapeObserved<number>\n /** Root-authored integrating commits ÷ integrating commits. */\n rootIntegrationShare: TeamShapeObserved<number>\n}\n\nexport interface TeamShapeCheck {\n result: 'yes' | 'no' | NotObservable\n reason: string\n}\n\nexport interface TeamShape {\n class: TeamShapeClass\n depth: number\n /** Only a flat star carries one: `root integrates`, `root does not integrate` or `integration unknown`. */\n qualifier: string | null\n /** Class in words: `hive depth 2`, `flat-star (integration unknown)`. */\n label: string\n rootId: string\n features: TeamShapeFeatures\n /** Every class's rule against this record, in check order. */\n checks: Record<TeamShapeClass, TeamShapeCheck>\n graph: { command: TeamShapeEdge[]; governance: TeamShapeEdge[]; communication: TeamShapeEdge[] }\n invalidRows: { spawn: number; coordination: number }\n window: { from: string; to: string } | null\n}\n\nexport type TeamShapeOutcome =\n | { succeeded: true; value: TeamShape }\n | { succeeded: false; error: { message: string } }\n\ninterface SpawnRow {\n kind: 'spawned' | 'settled'\n /** Agent whose journal holds the row: the last segment of the journal key. */\n owner: string\n /** The whole journal key, to find the root marker. */\n journal: string\n id: string\n at: number\n}\n\ninterface CoordinationRow {\n at: number | null\n type: string\n owner: string | null\n toWorker?: string\n from?: string\n by?: string\n delivered?: boolean\n}\n\n/** Team-shape input for a run read through a supervisor-run reader. */\nexport function teamShapeInputFromSources(\n sources: SupervisorRunSources,\n integrations?: readonly TeamIntegration[],\n): { succeeded: true; value: TeamShapeInput } | { succeeded: false; error: { message: string } } {\n if (sources.journal === null) {\n return {\n succeeded: false,\n error: { message: sources.journalMissingReason ?? `no spawn journal for ${sources.runRef}` },\n }\n }\n return {\n succeeded: true,\n value: {\n runRef: sources.runRef,\n spawnJournal: sources.journal,\n coordinationLog: sources.coordinationLog ?? null,\n ...(integrations === undefined ? {} : { integrations }),\n },\n }\n}\n\nexport function classifyTeamShape(input: TeamShapeInput): TeamShapeOutcome {\n const spawnLog = parseSpawnRows(input.spawnJournal)\n const coordination =\n typeof input.coordinationLog === 'string' ? parseCoordinationRows(input.coordinationLog) : null\n const spawnedAt = new Map<string, number>()\n for (const row of spawnLog.rows) {\n if (row.kind !== 'spawned') continue\n spawnedAt.set(row.id, Math.min(row.at, spawnedAt.get(row.id) ?? Number.POSITIVE_INFINITY))\n }\n const rootIds = [\n ...new Set(\n spawnLog.rows\n .filter((row) => row.kind === 'spawned' && row.journal === row.id)\n .map((r) => r.id),\n ),\n ]\n if (rootIds.length !== 1) {\n return {\n succeeded: false,\n error: {\n message: `spawn journal for ${input.runRef} has ${rootIds.length} root markers; team-shape needs exactly one`,\n },\n }\n }\n const rootId = rootIds[0]!\n const agents = new Set(spawnedAt.keys())\n\n // E: the id path. A parent outside the record leaves the agent unplaced.\n const parentOf = new Map<string, string>()\n let unplacedAgents = 0\n for (const id of agents) {\n if (id === rootId) continue\n const parent = pathParent(id)\n if (parent !== null && agents.has(parent) && id.startsWith(`${rootId}:`)) {\n parentOf.set(id, parent)\n } else unplacedAgents += 1\n }\n const children = new Map<string, string[]>()\n const command = new Map<string, TeamShapeEdge>()\n for (const [child, parent] of parentOf) {\n children.set(parent, [...(children.get(parent) ?? []), child])\n addEdge(command, parent, child)\n }\n const depthOf = (id: string): number => {\n let hops = 0\n for (let at = parentOf.get(id); at !== undefined; at = parentOf.get(at)) hops += 1\n return hops\n }\n const depth = Math.max(0, ...[...parentOf.keys()].map(depthOf))\n const rootChildren = children.get(rootId) ?? []\n const leads = rootChildren.filter((child) => (children.get(child)?.length ?? 0) > 0)\n const delegatingShare = rootChildren.length === 0 ? null : leads.length / rootChildren.length\n const subtreeOf = (id: string): string | null => {\n let at: string | undefined = id\n while (at !== undefined && parentOf.get(at) !== rootId) at = parentOf.get(at)\n return at ?? null\n }\n\n // A spawn row in a journal that belongs to neither the parent nor the child itself.\n let peerSpawns = 0\n for (const row of spawnLog.rows) {\n if (row.kind !== 'spawned' || row.id === rootId) continue\n if (row.owner !== row.id && row.owner !== parentOf.get(row.id)) peerSpawns += 1\n }\n\n // G: settlements, receiver → child.\n const governance = new Map<string, TeamShapeEdge>()\n const settlementsByReceiver: Record<string, number> = {}\n const governorsByParent = new Map<string, { agents: Set<string>; digests: Set<string> }>()\n const governorsOf = (child: string) => {\n const parent = parentOf.get(child) ?? `unplaced:${child}`\n const entry = governorsByParent.get(parent) ?? { agents: new Set(), digests: new Set() }\n governorsByParent.set(parent, entry)\n return entry\n }\n let gResolved = 0\n let gUnresolved = 0\n let gNonParent = 0\n let firstSettlement = Number.POSITIVE_INFINITY\n for (const row of spawnLog.rows) {\n if (row.kind !== 'settled' || row.owner === row.id) continue\n firstSettlement = Math.min(firstSettlement, row.at)\n settlementsByReceiver[row.owner] = (settlementsByReceiver[row.owner] ?? 0) + 1\n addEdge(governance, row.owner, row.id)\n governorsOf(row.id).agents.add(row.owner)\n gResolved += 1\n if (parentOf.get(row.id) !== row.owner) gNonParent += 1\n }\n const reHires = [...spawnedAt.entries()].filter(\n ([id, at]) => id !== rootId && at > firstSettlement,\n ).length\n\n // C, and G from steers.\n const communication = new Map<string, TeamShapeEdge>()\n let messages = 0\n let cResolved = 0\n let cUnresolved = 0\n let cLateral = 0\n let cCrossSubtree = 0\n let gCrossSubtree = 0\n const steers = { sent: 0, delivered: 0 }\n const isAgent = (value: string | undefined): value is string =>\n value !== undefined && agents.has(value)\n for (const row of coordination?.rows ?? []) {\n if (row.type === 'instruction' || row.type === 'delivery-attempt') continue\n if (row.toWorker === undefined && row.from === undefined && row.by === undefined) continue\n messages += 1\n if (row.type === 'steer') {\n steers.sent += 1\n if (row.delivered === true) steers.delivered += 1\n }\n // A refused steer reached nobody: it is counted as sent, not as an edge.\n if (!isAgent(row.toWorker) || row.delivered === false) continue\n const receiver = row.toWorker\n const agentSender = [row.from, row.by].find(isAgent)\n const sender = agentSender ?? (row.owner === null ? null : `owner:${row.owner}`)\n if (sender === null) continue\n addEdge(communication, sender, receiver)\n if (agentSender === undefined) cUnresolved += 1\n else {\n cResolved += 1\n const parent = parentOf.get(receiver)\n if (parent !== undefined && parent === parentOf.get(agentSender)) cLateral += 1\n if (crosses(subtreeOf(agentSender), subtreeOf(receiver))) cCrossSubtree += 1\n }\n if (row.type === 'steer') {\n addEdge(governance, sender, receiver)\n if (agentSender === undefined) {\n gUnresolved += 1\n governorsOf(receiver).digests.add(sender)\n } else {\n gResolved += 1\n governorsOf(receiver).agents.add(agentSender)\n if (parentOf.get(receiver) !== agentSender) gNonParent += 1\n if (crosses(subtreeOf(agentSender), subtreeOf(receiver))) gCrossSubtree += 1\n }\n }\n }\n for (const [child, receiver] of spawnLog.rows\n .filter((row) => row.kind === 'settled' && row.owner !== row.id)\n .map((row) => [row.id, row.owner] as const)) {\n if (crosses(subtreeOf(receiver), subtreeOf(child))) gCrossSubtree += 1\n }\n\n const cTotal = cResolved + cUnresolved\n const gTotal = gResolved + gUnresolved\n const lateralCShare: TeamShapeObserved<number> =\n coordination === null || cTotal === 0 || cUnresolved > 0 ? NOT_OBSERVABLE : cLateral / cTotal\n const nonParentGShare: TeamShapeObserved<number> =\n gTotal === 0 || gUnresolved > 0 ? NOT_OBSERVABLE : gNonParent / gTotal\n const integrations = input.integrations ?? []\n const rootIntegrationShare: TeamShapeObserved<number> =\n integrations.length === 0\n ? NOT_OBSERVABLE\n : integrations.filter((row) => row.by === rootId).length / integrations.length\n\n const features: TeamShapeFeatures = {\n agents: agents.size,\n tasks: agents.size - 1,\n unplacedAgents,\n depth,\n fanOut: {\n root: rootChildren.length,\n max: Math.max(0, ...[...children.values()].map((c) => c.length)),\n },\n delegatingShare,\n reHires,\n settlementsByReceiver,\n steers,\n messagesPerTask: coordination === null || agents.size < 2 ? null : messages / (agents.size - 1),\n lateralCShare,\n nonParentGShare,\n rootIntegrationShare,\n }\n\n const checks = {} as Record<TeamShapeClass, TeamShapeCheck>\n checks.single = verdict(agents.size === 1, `${agents.size} agents`)\n\n const rotating = [...governorsByParent.entries()].find(([, g]) => g.agents.size > 1)\n const digestTeams = [...governorsByParent.values()].filter((g) => g.digests.size > 1).length\n checks['governed-swarm'] =\n peerSpawns > 0\n ? { result: 'yes', reason: `${peerSpawns} spawns recorded by a peer, not the parent` }\n : rotating !== undefined\n ? {\n result: 'yes',\n reason: `children of ${rotating[0]} are governed by ${[...rotating[1].agents].join(', ')}`,\n }\n : digestTeams > 0\n ? {\n result: NOT_OBSERVABLE,\n reason: `${digestTeams} teams were steered by more than one owner digest; a digest is not an agent id, so a rotating governor cannot be told from the operator`,\n }\n : {\n result: 'no',\n reason: 'every E edge runs parent to child and no team changed governor',\n }\n\n const dispatchers = [...children.keys()]\n if (dispatchers.length !== 1 || unplacedAgents > 0) {\n checks.fleet = {\n result: unplacedAgents > 0 && dispatchers.length <= 1 ? NOT_OBSERVABLE : 'no',\n reason:\n unplacedAgents > 0 && dispatchers.length <= 1\n ? `${unplacedAgents} unplaced agents hide who dispatched their work`\n : `${dispatchers.length} agents dispatch work`,\n }\n } else if (gNonParent > 0) {\n checks.fleet = { result: 'yes', reason: `${gNonParent} G edges come from a non-parent agent` }\n } else if (cLateral / Math.max(cTotal, 1) >= TEAM_SHAPE_THRESHOLDS.fleetLateralCShare) {\n checks.fleet = { result: 'yes', reason: `lateral C ${cLateral} of ${cTotal}` }\n } else if (gUnresolved > 0 || lateralCShare === NOT_OBSERVABLE) {\n checks.fleet = {\n result: NOT_OBSERVABLE,\n reason: `one dispatcher; ${gUnresolved} steer G and ${cUnresolved} C edges are sent from owner digests that no record joins to an agent${coordination === null ? ', and the run has no coordination log' : ''}`,\n }\n } else {\n checks.fleet = verdict(\n false,\n `one dispatcher, no non-parent G, lateral C ${cLateral} of ${cTotal}`,\n )\n }\n\n const rootSettledByLeads = spawnLog.rows.filter(\n (row) => row.kind === 'settled' && row.owner === rootId && leads.includes(row.id),\n ).length\n if (leads.length < 2 || rootSettledByLeads > 0 || gCrossSubtree > 0 || cCrossSubtree > 0) {\n checks.partition = verdict(\n false,\n `${leads.length} lead subtrees, ${rootSettledByLeads} lead settlements to the root, ${gCrossSubtree + cCrossSubtree} edges between subtrees`,\n )\n } else if (gUnresolved > 0 || cUnresolved > 0 || coordination === null) {\n checks.partition = {\n result: NOT_OBSERVABLE,\n reason: `${leads.length} lead subtrees and no lead settles to the root, but edges sent from owner digests cannot be placed in a subtree`,\n }\n } else {\n checks.partition = verdict(true, `${leads.length} lead subtrees with no C or G between them`)\n }\n\n const delegating = `${leads.length} of ${rootChildren.length} root children delegate`\n const hive = depth >= 2 && (delegatingShare ?? 0) >= TEAM_SHAPE_THRESHOLDS.hiveDelegatingShare\n checks.hive = verdict(hive, `depth ${depth}; ${delegating}`)\n checks['star-with-sub-leads'] = verdict(depth >= 2 && !hive, `depth ${depth}; ${delegating}`)\n checks['flat-star'] = verdict(depth === 1, `depth ${depth}`)\n\n const shapeClass = TEAM_SHAPE_CLASSES.find((name) => checks[name].result === 'yes')\n if (shapeClass === undefined) {\n return {\n succeeded: false,\n error: { message: `no team-shape class matches ${input.runRef} (depth ${depth})` },\n }\n }\n const qualifier =\n shapeClass !== 'flat-star'\n ? null\n : rootIntegrationShare === NOT_OBSERVABLE\n ? 'integration unknown'\n : rootIntegrationShare >= TEAM_SHAPE_THRESHOLDS.rootIntegrationShare\n ? 'root integrates'\n : 'root does not integrate'\n const label =\n shapeClass === 'hive'\n ? `hive depth ${depth}`\n : qualifier === null\n ? shapeClass\n : `${shapeClass} (${qualifier})`\n\n const times = [\n ...spawnLog.rows.map((row) => row.at),\n ...(coordination?.rows ?? []).flatMap((row) => (row.at === null ? [] : [row.at])),\n ]\n return {\n succeeded: true,\n value: {\n class: shapeClass,\n depth,\n qualifier,\n label,\n rootId,\n features,\n checks,\n graph: {\n command: [...command.values()],\n governance: [...governance.values()],\n communication: [...communication.values()],\n },\n invalidRows: { spawn: spawnLog.invalid, coordination: coordination?.invalid ?? 0 },\n window:\n times.length === 0\n ? null\n : {\n from: new Date(Math.min(...times)).toISOString(),\n to: new Date(Math.max(...times)).toISOString(),\n },\n },\n }\n}\n\nfunction verdict(holds: boolean, reason: string): TeamShapeCheck {\n return { result: holds ? 'yes' : 'no', reason }\n}\n\nfunction crosses(a: string | null, b: string | null): boolean {\n return a !== null && b !== null && a !== b\n}\n\nfunction pathParent(id: string): string | null {\n const match = /^(.+):s\\d+$/.exec(id)\n return match ? match[1]! : null\n}\n\nfunction addEdge(edges: Map<string, TeamShapeEdge>, from: string, to: string): void {\n const key = JSON.stringify([from, to])\n const edge = edges.get(key)\n if (edge) edge.count += 1\n else edges.set(key, { from, to, count: 1 })\n}\n\nfunction jsonLines(text: string): Array<Record<string, unknown> | null> {\n return text\n .split('\\n')\n .filter((line) => line.trim())\n .map((line) => {\n try {\n const value: unknown = JSON.parse(line)\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null\n } catch {\n return null\n }\n })\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null\n}\n\nfunction epochMs(value: unknown): number | null {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string') {\n const ms = Date.parse(value)\n return Number.isNaN(ms) ? null : ms\n }\n return null\n}\n\n/**\n * Spawned and settled rows from a Runtime envelope (`{ root, event }`) or a\n * reduced row (`{ kind, journal, id, at }`). Other Runtime event kinds are\n * read and skipped; a spawned or settled row without an id, journal or time\n * is invalid.\n */\nfunction parseSpawnRows(text: string): { rows: SpawnRow[]; invalid: number } {\n const rows: SpawnRow[] = []\n let invalid = 0\n for (const line of jsonLines(text)) {\n if (line === null) {\n invalid += 1\n continue\n }\n const event = asRecord(line.event) ?? line\n const journal = event === line ? line.journal : line.root\n const { kind, id } = event\n if (kind !== 'spawned' && kind !== 'settled') continue\n const at = epochMs(event.at)\n if (typeof id !== 'string' || typeof journal !== 'string' || at === null) {\n invalid += 1\n continue\n }\n rows.push({ kind, journal, owner: journal.slice(journal.lastIndexOf('/') + 1), id, at })\n }\n return { rows, invalid }\n}\n\n/**\n * Coordination rows from a Runtime record (`{ at, ownerId, event: { type,\n * <body> } }`, endpoints inside the event's one object-valued field) or a\n * reduced row (`{ at, type, owner, ... }`).\n */\nfunction parseCoordinationRows(text: string): { rows: CoordinationRow[]; invalid: number } {\n const rows: CoordinationRow[] = []\n let invalid = 0\n for (const line of jsonLines(text)) {\n const event = line === null ? null : (asRecord(line.event) ?? line)\n if (line === null || event === null || typeof event.type !== 'string') {\n invalid += 1\n continue\n }\n const body =\n event === line\n ? line\n : (Object.entries(event)\n .filter(([key]) => key !== 'type')\n .map(([, value]) => asRecord(value))\n .find((value) => value !== null) ?? {})\n const owner = typeof line.owner === 'string' ? line.owner : line.ownerId\n const row: CoordinationRow = {\n at: epochMs(line.at),\n type: event.type,\n owner: typeof owner === 'string' && owner ? owner : null,\n }\n for (const key of ['toWorker', 'from', 'by'] as const) {\n const value = body[key]\n if (typeof value === 'string') row[key] = value\n }\n const delivered = body.delivered ?? line.delivered\n if (typeof delivered === 'boolean') row.delivered = delivered\n rows.push(row)\n }\n return { rows, invalid }\n}\n\n/**\n * The team-shape analyst: one `team`-layer finding per run naming its class,\n * with the features and every class check in metadata. A record with no\n * timestamps fails the analyst instead of emitting a shape it did not measure.\n */\nexport function teamShapeAnalyst(): Analyst<TeamShapeInput> {\n return {\n id: TEAM_SHAPE_ANALYST_ID,\n description:\n 'Classifies a supervision tree as single, governed swarm, fleet, partition, hive, star with sub-leads or flat star.',\n inputKind: 'custom',\n cost: { kind: 'deterministic' },\n version: TEAM_SHAPE_VERSION,\n async analyze(input) {\n const outcome = classifyTeamShape(input)\n if (!outcome.succeeded) throw new Error(`team-shape: ${outcome.error.message}`)\n const shape = outcome.value\n if (shape.window === null) {\n throw new Error(`team-shape: record for ${input.runRef} carries no event timestamps`)\n }\n return [\n makeFinding({\n analyst_id: TEAM_SHAPE_ANALYST_ID,\n area: 'team-shape',\n severity: 'info',\n confidence: 1,\n subject: shape.rootId,\n claim: `Team shape is ${shape.label}`,\n claim_id: `team-shape:${shape.class}`,\n evidence_refs: [{ kind: 'artifact', uri: input.runRef }],\n layer: 'team',\n scope: { population: [input.runRef], n: 1, window: shape.window },\n method: { kind: 'computed', name: TEAM_SHAPE_ANALYST_ID, version: TEAM_SHAPE_VERSION },\n metadata: {\n class: shape.class,\n depth: shape.depth,\n qualifier: shape.qualifier,\n features: shape.features,\n checks: shape.checks,\n edges: {\n command: shape.graph.command.length,\n governance: shape.graph.governance.length,\n communication: shape.graph.communication.length,\n },\n invalid_rows: shape.invalidRows,\n },\n }),\n ]\n },\n }\n}\n","/**\n * Many questions over one trace store, concurrently, under one cost ledger, with an independent\n * verifier for every finding.\n *\n * `traces ask` answered questions this way for people. A continuation panel (agent-runtime,\n * discovery `docs/38-one-loop-and-continuation.md`, section 5) asks dozens to hundreds of atomic\n * questions of a director's own trace every time the outside check fails, so the runner lives here,\n * beside `runTraceAnalyst`, where both callers reach one implementation.\n *\n * Each question is one `runTraceAnalyst` call, which already refuses a finding with fewer distinct\n * citations than required or with a citation the store cannot resolve. What this module adds:\n *\n * - a worker pool: at most `concurrency` investigations at once, and one failed question never\n * stops the others; its failure is its answer;\n * - one shared `CostLedger`, so a single ceiling bounds every question and every verifier;\n * - an independent verifier per admitted finding, shown only the spans the finding cites. Analysts\n * misattribute often: the best method in Who&When found the failing step 14.2% of the time. A\n * finding a verifier reading only its own evidence does not support never reaches a caller as\n * verified.\n */\n\nimport type { CostLedgerHandle } from '../cost-ledger'\nimport type { TraceAnalysisStore } from '../trace-analyst/store'\nimport { defineTraceAnalyst } from './define'\nimport type { TraceAnalysisEngine, TraceAnalystLimits } from './engine'\nimport { parseTraceSpanEvidenceUri, type RawAnalystFinding } from './finding-signature'\nimport { runTraceAnalyst } from './kind-factory'\n\n/** One question to ask of the store. */\nexport interface TraceQuestionSpec {\n /** Stable id: letters, digits, dot, underscore, hyphen. */\n readonly id: string\n readonly question: string\n /** Guidance for this question only, after the shared rules. */\n readonly instructions?: string\n}\n\nexport interface AskTraceQuestionsOptions {\n readonly questions: readonly TraceQuestionSpec[]\n readonly store: TraceAnalysisStore\n readonly engine: TraceAnalysisEngine\n /** Every question and verifier charges this ledger; its ceiling bounds the whole call. */\n readonly costLedger: CostLedgerHandle\n /** Stable id for cost attribution and logs. */\n readonly runId: string\n /** Material every question receives before its first model call, such as the check's verdict. */\n readonly context?: string\n /** Investigations running at once. Default 4. */\n readonly concurrency?: number\n /** Distinct citations a finding needs. Default 2. */\n readonly minimumEvidenceCitations?: number\n /** Run the independent verifier on every admitted finding. Default true. */\n readonly verify?: boolean\n readonly limits?: Partial<TraceAnalystLimits>\n readonly signal?: AbortSignal\n readonly log?: (message: string, fields?: Record<string, unknown>) => void\n}\n\n/** A finding and what the verifier, shown only its cited spans, concluded. */\nexport interface VerifiedTraceFinding {\n readonly finding: RawAnalystFinding\n /** The finding's trace citations, as `trace://` URIs. */\n readonly citations: readonly string[]\n /** `true` supported, `false` not supported, `null` when verification was off or failed. */\n readonly verified: boolean | null\n /** The verifier's own words, when it answered. */\n readonly verifierAnswer?: string\n}\n\nexport interface TraceQuestionOutcome {\n readonly id: string\n readonly question: string\n readonly status: 'answered' | 'failed'\n readonly failure?: string\n /** The engine's prose answer, verbatim; `null` when it returned none. */\n readonly answer: string | null\n readonly findings: readonly VerifiedTraceFinding[]\n /** `null` when the engine failed before reporting. */\n readonly modelCalls: number | null\n readonly toolCalls: number | null\n}\n\nconst QUESTION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u\nconst DEFINITION_VERSION = '1.0.0'\n\nconst QUESTION_RULES = [\n 'Answer QUESTION only from trace tool results retrieved in this run.',\n 'Cite each fact as trace://<trace_id>/span/<span_id>, and quote the span in the excerpt.',\n 'If the trace does not record a fact, say \"not in trace\". Never infer a trace fact from the question.',\n].join('\\n')\n\nconst VERIFIER_RULES = [\n 'You check one CLAIM against the spans it cites, and nothing else.',\n 'Read each cited span with viewSpans. No other trace is readable.',\n 'First line: SUPPORTED if the spans themselves establish the claim, otherwise NOT SUPPORTED.',\n 'Second line: one sentence naming the span that decides it.',\n 'Return no findings.',\n].join('\\n')\n\n/**\n * Ask every question, then verify every admitted finding. Never throws for a failed question or\n * verifier: each failure is recorded on its outcome. Throws before any model call for a malformed\n * question list or options.\n */\nexport async function askTraceQuestions(\n opts: AskTraceQuestionsOptions,\n): Promise<TraceQuestionOutcome[]> {\n const concurrency = opts.concurrency ?? 4\n if (!Number.isSafeInteger(concurrency) || concurrency < 1) {\n throw new RangeError('askTraceQuestions: concurrency must be an integer >= 1')\n }\n const minimum = opts.minimumEvidenceCitations ?? 2\n if (!Number.isSafeInteger(minimum) || minimum < 1) {\n throw new RangeError('askTraceQuestions: minimumEvidenceCitations must be an integer >= 1')\n }\n const seen = new Set<string>()\n for (const question of opts.questions) {\n if (!QUESTION_ID.test(question.id)) {\n throw new TypeError(\n `askTraceQuestions: question id ${JSON.stringify(question.id)} is malformed`,\n )\n }\n if (seen.has(question.id)) {\n throw new TypeError(`askTraceQuestions: duplicate question id ${JSON.stringify(question.id)}`)\n }\n seen.add(question.id)\n if (question.question.trim() === '') {\n throw new TypeError(`askTraceQuestions: question ${question.id} is empty`)\n }\n }\n\n const askOne = async (question: TraceQuestionSpec): Promise<TraceQuestionOutcome> => {\n if (opts.signal?.aborted) {\n return failed(question, 'the run was aborted before the question started')\n }\n let completed: Awaited<ReturnType<typeof runTraceAnalyst>>\n try {\n completed = await runTraceAnalyst({\n definition: defineTraceAnalyst({\n id: `question.${question.id}`,\n description: `trace question ${question.id}`,\n area: 'question',\n version: DEFINITION_VERSION,\n question: question.question.trim(),\n instructions: [QUESTION_RULES, question.instructions?.trim() ?? '']\n .filter(Boolean)\n .join('\\n\\n'),\n toolGroup: 'all',\n minimumEvidenceCitations: minimum,\n ...(opts.context ? { prepareContext: () => opts.context } : {}),\n ...(opts.limits ? { limits: opts.limits } : {}),\n }),\n engine: opts.engine,\n store: opts.store,\n context: {\n runId: opts.runId,\n correlationId: `${opts.runId}:${question.id}`,\n costLedger: opts.costLedger,\n costPhase: 'trace-question',\n ...(opts.signal ? { signal: opts.signal } : {}),\n ...(opts.log ? { log: opts.log } : {}),\n },\n })\n } catch (error) {\n return failed(question, errorText(error))\n }\n const findings: VerifiedTraceFinding[] = []\n for (const [index, finding] of completed.findings.entries()) {\n const citations = finding.evidence\n .map((citation) => citation.uri.trim())\n .filter((uri) => parseTraceSpanEvidenceUri(uri) !== null)\n findings.push(\n opts.verify === false\n ? { finding, citations, verified: null }\n : await verifyFinding(opts, `${question.id}.v${index + 1}`, finding, citations),\n )\n }\n const answer = completed.answer.trim() === '' ? null : completed.answer\n return {\n id: question.id,\n question: question.question,\n status: 'answered',\n answer,\n findings,\n modelCalls: completed.modelCalls,\n toolCalls: completed.toolCalls,\n }\n }\n\n // A pool, not Promise.all: at most `concurrency` engines exist at once.\n const outcomes = new Array<TraceQuestionOutcome>(opts.questions.length)\n let next = 0\n await Promise.all(\n Array.from({ length: Math.min(concurrency, opts.questions.length) }, async () => {\n while (next < opts.questions.length) {\n const index = next\n next += 1\n const question = opts.questions[index] as TraceQuestionSpec\n outcomes[index] = await askOne(question)\n }\n }),\n )\n return outcomes\n}\n\n/** The verifier reads only the spans the finding cites, through a store that holds nothing else. */\nasync function verifyFinding(\n opts: AskTraceQuestionsOptions,\n id: string,\n finding: RawAnalystFinding,\n citations: readonly string[],\n): Promise<VerifiedTraceFinding> {\n const allowed = new Map<string, Set<string>>()\n for (const uri of citations) {\n const location = parseTraceSpanEvidenceUri(uri)\n if (location === null) continue\n const spans = allowed.get(location.traceId) ?? new Set<string>()\n spans.add(location.spanId)\n allowed.set(location.traceId, spans)\n }\n if (allowed.size === 0) return { finding, citations, verified: false }\n try {\n const verdict = await runTraceAnalyst({\n definition: defineTraceAnalyst({\n id: `verify.${id}`,\n description: `independent check of finding ${id}`,\n area: 'question',\n version: DEFINITION_VERSION,\n question: `CLAIM: ${finding.claim}\\nCITED SPANS: ${citations.join(', ')}`,\n instructions: VERIFIER_RULES,\n toolGroup: 'targeted',\n ...(opts.limits ? { limits: opts.limits } : {}),\n }),\n engine: opts.engine,\n store: citedSpansOnly(opts.store, allowed),\n context: {\n runId: opts.runId,\n correlationId: `${opts.runId}:verify:${id}`,\n costLedger: opts.costLedger,\n costPhase: 'trace-question-verifier',\n ...(opts.signal ? { signal: opts.signal } : {}),\n ...(opts.log ? { log: opts.log } : {}),\n },\n })\n const first = verdict.answer.trim().split('\\n')[0]?.trim().toUpperCase() ?? ''\n return {\n finding,\n citations,\n verified: first.startsWith('SUPPORTED'),\n verifierAnswer: verdict.answer.trim(),\n }\n } catch (error) {\n opts.log?.('verifier failed', { finding: id, error: errorText(error) })\n return { finding, citations, verified: null }\n }\n}\n\n/**\n * A store that exposes exactly the cited spans. Discovery and whole-trace reads refuse, so the\n * verifier cannot go looking for other support; the underlying store's bounds still apply.\n */\nexport function citedSpansOnly(\n store: TraceAnalysisStore,\n allowed: ReadonlyMap<string, ReadonlySet<string>>,\n): TraceAnalysisStore {\n const refuse = (what: string) => async (): Promise<never> => {\n throw new Error(`${what} is not available to a verifier: read the cited spans with viewSpans`)\n }\n return {\n hasTrace: async (traceId) => allowed.has(traceId),\n hasSpans: async (input, context) => {\n const spans = allowed.get(input.trace_id)\n if (spans === undefined) return []\n return store.hasSpans(\n { trace_id: input.trace_id, span_ids: input.span_ids.filter((span) => spans.has(span)) },\n context,\n )\n },\n getOverview: refuse('getOverview'),\n queryTraces: refuse('queryTraces'),\n countTraces: refuse('countTraces'),\n viewTrace: refuse('viewTrace'),\n viewSpans: async (input, context) => {\n const spans = allowed.get(input.trace_id)\n const wanted = input.span_ids.filter((span) => spans?.has(span) === true)\n if (wanted.length === 0) {\n throw new Error('viewSpans: only the cited spans are readable')\n }\n return store.viewSpans({ ...input, span_ids: wanted }, context)\n },\n searchTrace: refuse('searchTrace'),\n searchSpan: async (input, context) => {\n if (allowed.get(input.trace_id)?.has(input.span_id) !== true) {\n throw new Error('searchSpan: only the cited spans are readable')\n }\n return store.searchSpan(input, context)\n },\n }\n}\n\nfunction failed(question: TraceQuestionSpec, failure: string): TraceQuestionOutcome {\n return {\n id: question.id,\n question: question.question,\n status: 'failed',\n failure,\n answer: null,\n findings: [],\n modelCalls: null,\n toolCalls: null,\n }\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? `${error.name}: ${error.message}` : String(error)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,MAAM,cAAc;AAIpB,SAAS,aAAa,GAAmC;CACvD,QAAQ,GAAR;EACE,KAAK,YACH,OAAO;EACT,KAAK,SACH,OAAO;EACT,KAAK,SACH,OAAO;EACT,KAAK,QACH,OAAO;CACX;AACF;AAaA,SAAgB,kCACd,MACoC;CACpC,MAAM,KAAK,KAAK,MAAM;CACtB,MAAM,OAAO,KAAK,QAAQ;CAC1B,MAAM,sBAAsB,+BAA+B,KAAK,mBAAmB;CACnF,OAAO;EACL;EACA,aACE;EACF,WAAW;EACX,MAAM;GACJ,MAAM;GACN,QAAQ,KAAK,QAAQ,QAAQ,CAAC,KAAK,QAAQ,KAAK,IAAI,KAA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AAE,GAAG;IAAO,UAAU;GAAO,GAAG,OAAO;EAChE;EACA,aAAa,OAAO,aAAa;EACjC,YAAY,OAAO,OAAO,YAAY;GACpC,IAAI,QAAQ,IAAI,MAAM,QAAQ,CAAC,EAAE,IAAI,MAAM,OAAO,MAAM,MACtD,MAAM,IAAI,MAAM,+CAA+C;GAEjE,OAAO,MAAM,WAAW,OAAO,OAAO;EACxC;CACF;AACF;AAEA,SAAS,OAAO,UAA6B,SAAuC;CAClF,OAAO;EACL,IAAI,SAAS;EACb,UAAU,SAAS;EACnB,QAAQ;EACR;EACA,QAAQ;EACR,UAAU,CAAC;EACX,YAAY;EACZ,WAAW;CACb;AACF;AAEA,SAAS,UAAU,OAAwB;CACzC,OAAO,iBAAiB,QAAQ,GAAG,MAAM,KAAK,IAAI,MAAM,YAAY,OAAO,KAAK;AAClF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/analyst/bind.ts","../../src/analyst/define.ts","../../src/analyst/domain-taxonomy.ts","../../src/analyst/failure-modes.ts","../../src/analyst/findings-ledger.ts","../../src/analyst/kinds/skill-usage.ts","../../src/analyst/promote.ts","../../src/analyst/rollup.ts","../../src/analyst/team-shape.ts","../../src/analyst/trace-questions.ts"],"sourcesContent":["/**\n * bindAnalyst — compile an `AnalystDefinition` into a runnable arm.\n *\n * The definition declares protocol (question, task text, reply grammar,\n * evidence projection, budget, repair turns); the transport binding supplies\n * execution (a bridge endpoint, or the caller-owned model path). Each\n * projection mode dispatches to the same strategy its arm's entry point runs,\n * so a compiled definition and the historical creator send byte-identical\n * requests — the definition parity suite asserts this per arm.\n *\n * A projection × transport pair with no strategy fails loud with\n * `AnalystExpressivenessError` naming the pair: an arm shape this layer cannot\n * express must be reported, never approximated.\n */\n\nimport type { CustomTokenPricing } from '../cost-ledger'\nimport type { AnalystBenchmarkRunner } from './benchmark'\nimport { runChunkedAnalystDefinition } from './benchmark-public-chunked'\nimport { runReplVariableAnalystDefinition } from './benchmark-public-rlm'\nimport type { PublicAnalystBenchmarkModelConfig } from './benchmark-public-types'\nimport { runInlineAnalystDefinition } from './benchmark-runner-prime'\nimport { type AnalystDefinition, AnalystExpressivenessError } from './definition'\nimport type { PrimeBridgeTransport } from './prime-bridge-transport'\nimport type { AnalystRunInputs } from './types'\n\n/** Execution half of a binding: who actually reaches the model. */\nexport type AnalystTransportBinding =\n | {\n /** An OpenAI-compatible cli-bridge endpoint (inline projections). */\n readonly kind: 'prime-bridge'\n readonly baseUrl: string\n readonly model: string\n readonly transport?: PrimeBridgeTransport\n readonly pricing?: CustomTokenPricing\n }\n | {\n /** The caller-owned model path (chunked and repl-variable projections). */\n readonly kind: 'model-owner'\n readonly config: PublicAnalystBenchmarkModelConfig\n }\n\n/**\n * Compile a definition plus a transport binding into a runnable arm. Dispatch\n * is total over the expressible pairs; everything else is a loud refusal.\n */\nexport function bindAnalyst<TRow, TAssignment, TBlock>(\n definition: AnalystDefinition<TRow, TAssignment, TBlock>,\n transports: AnalystTransportBinding,\n): AnalystBenchmarkRunner<AnalystRunInputs> {\n const mode = definition.projection.mode\n if (mode === 'inline' && transports.kind === 'prime-bridge') {\n return runInlineAnalystDefinition(definition, {\n baseUrl: transports.baseUrl,\n model: transports.model,\n ...(transports.transport ? { transport: transports.transport } : {}),\n ...(transports.pricing ? { pricing: transports.pricing } : {}),\n })\n }\n if (mode === 'chunked' && transports.kind === 'model-owner') {\n return runChunkedAnalystDefinition(definition, transports.config)\n }\n if (mode === 'repl-variable' && transports.kind === 'model-owner') {\n return runReplVariableAnalystDefinition(\n // The repl-variable strategy is written against the engine's raw-finding\n // row type; the definition's own row declaration carries it.\n definition as Parameters<typeof runReplVariableAnalystDefinition>[0],\n transports.config,\n )\n }\n throw new AnalystExpressivenessError(\n `no strategy compiles a '${mode}' projection over a '${transports.kind}' transport; ` +\n `definition '${definition.id}' cannot be expressed by this layer yet`,\n )\n}\n","import type { TraceAnalysisStore } from '../trace-analyst/store'\nimport type { ExactCapableAnalyst } from './exact-types'\nimport type { TraceAnalystDefinition } from './kind-factory'\nimport type { Analyst, AnalystCost } from './types'\n\n/**\n * Define a reusable trace-research question.\n *\n * The returned value contains no model, credentials, or execution state. Bind\n * it to any TraceAnalysisEngine with `runTraceAnalyst` or\n * `createTraceAnalyst`.\n */\nexport function defineTraceAnalyst(definition: TraceAnalystDefinition): TraceAnalystDefinition {\n for (const [name, value] of [\n ['id', definition.id],\n ['description', definition.description],\n ['area', definition.area],\n ['version', definition.version],\n ['instructions', definition.instructions],\n ] as const) {\n if (typeof value !== 'string' || !value.trim()) {\n throw new TypeError(`defineTraceAnalyst: ${name} must be a non-empty string`)\n }\n }\n return {\n ...definition,\n limits: definition.limits ? { ...definition.limits } : undefined,\n }\n}\n\nexport interface DefineCustomAnalystOptions {\n id: string\n description: string\n version?: string\n cost: AnalystCost\n analyze: Analyst<TraceAnalysisStore>['analyze']\n}\n\nexport interface DefineExactCustomAnalystOptions extends DefineCustomAnalystOptions {\n /** Canonical JSON for behavior knobs not already bound by `version`. */\n executionConfig: Readonly<Record<string, unknown>>\n}\n\n/** Construct a registrable analyst from a hand-written analyze function. */\nexport function defineCustomAnalyst(\n options: DefineExactCustomAnalystOptions,\n): ExactCapableAnalyst<TraceAnalysisStore>\nexport function defineCustomAnalyst(\n options: DefineCustomAnalystOptions,\n): Analyst<TraceAnalysisStore>\nexport function defineCustomAnalyst(\n options: DefineCustomAnalystOptions | DefineExactCustomAnalystOptions,\n): Analyst<TraceAnalysisStore> | ExactCapableAnalyst<TraceAnalysisStore> {\n if (!options.id.trim()) throw new TypeError('defineCustomAnalyst: id must not be empty')\n if (!options.description.trim()) {\n throw new TypeError('defineCustomAnalyst: description must not be empty')\n }\n if (options.cost === undefined) {\n throw new TypeError('defineCustomAnalyst: cost must be declared')\n }\n if (\n 'executionConfig' in options &&\n (!options.executionConfig ||\n typeof options.executionConfig !== 'object' ||\n Array.isArray(options.executionConfig))\n ) {\n throw new TypeError('defineCustomAnalyst: executionConfig must be an object')\n }\n return {\n id: options.id,\n description: options.description,\n version: options.version ?? '1.0.0',\n inputKind: 'trace-store',\n cost: options.cost,\n analyze: options.analyze,\n ...('executionConfig' in options ? { executionConfig: options.executionConfig } : {}),\n }\n}\n","/**\n * Domain taxonomy — one versioned tree that both the layer ladder and the\n * domain hierarchy live in.\n *\n * Domain nodes nest to any depth (\"building systems\" → \"cryptographic\" →\n * \"zk proving\" → \"binary fields\"). Problems attach to one primary domain path\n * plus free tags, plays attach to a problem, and runs attach to a play. Every\n * node hangs under the implicit `lab` root, so one parent map answers both\n * \"which play holds this run\" and \"which domain holds this problem\", and\n * `promote` walks a single ladder: run → play → problem → domain path → lab.\n *\n * Plain data in, plain data out: every function returns a new value or a\n * typed failure, and nothing here reads a file or the network.\n */\n\nexport const DOMAIN_TAXONOMY_SCHEMA = 'agent-eval.domain-taxonomy.v1'\n\n/** Id of the implicit root every top-level domain hangs under. */\nexport const LAB_NODE_ID = 'lab'\n\n/** Layers a taxonomy node can sit at, lowest first. */\nconst TAXONOMY_NODE_LAYERS = ['run', 'play', 'problem', 'domain'] as const\n\nexport type TaxonomyNodeLayer = (typeof TAXONOMY_NODE_LAYERS)[number]\n\nexport interface TaxonomyNode {\n id: string\n label: string\n layer: TaxonomyNodeLayer\n /** Null only for a top-level domain, whose parent is the implicit lab root. */\n parent: string | null\n /** Secondary classifications; they never change the node's place in the tree. */\n tags?: string[]\n}\n\nexport interface DomainTaxonomy {\n schema: typeof DOMAIN_TAXONOMY_SCHEMA\n /** Caller-chosen version; promoted findings record the version they were lifted under. */\n version: string\n nodes: TaxonomyNode[]\n}\n\nexport type TaxonomyOutcome<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; error: { message: string } }\n\n/** The layer a node of each kind must hang under. */\nconst PARENT_LAYER: Record<TaxonomyNodeLayer, TaxonomyNodeLayer | null> = {\n run: 'play',\n play: 'problem',\n problem: 'domain',\n domain: 'domain',\n}\n\nfunction fail<T>(message: string): TaxonomyOutcome<T> {\n return { succeeded: false, error: { message } }\n}\n\n/**\n * Validate a taxonomy: unique ids, known parents, each node under a parent of\n * the right layer, no cycles. `lab` is reserved for the implicit root.\n */\nexport function defineDomainTaxonomy(input: {\n version: string\n nodes: ReadonlyArray<TaxonomyNode>\n}): TaxonomyOutcome<DomainTaxonomy> {\n if (typeof input.version !== 'string' || !input.version.trim()) {\n return fail('taxonomy version must be a non-empty string')\n }\n const nodes = input.nodes.map((node) => ({\n id: node.id,\n label: node.label,\n layer: node.layer,\n parent: node.parent,\n ...(node.tags === undefined ? {} : { tags: [...node.tags] }),\n }))\n const byId = new Map<string, TaxonomyNode>()\n for (const node of nodes) {\n if (typeof node.id !== 'string' || !node.id.trim()) return fail('node ids must be non-empty')\n if (node.id === LAB_NODE_ID) return fail(`'${LAB_NODE_ID}' is the implicit root id`)\n if (byId.has(node.id)) return fail(`node '${node.id}' appears twice`)\n if (!(TAXONOMY_NODE_LAYERS as readonly string[]).includes(node.layer)) {\n return fail(`node '${node.id}' has unknown layer '${String(node.layer)}'`)\n }\n if (typeof node.label !== 'string' || !node.label.trim()) {\n return fail(`node '${node.id}' needs a label`)\n }\n byId.set(node.id, node)\n }\n for (const node of nodes) {\n if (node.parent === null) {\n if (node.layer !== 'domain') return fail(`${node.layer} '${node.id}' needs a parent`)\n continue\n }\n const parent = byId.get(node.parent)\n if (!parent) return fail(`node '${node.id}' names unknown parent '${node.parent}'`)\n if (parent.layer !== PARENT_LAYER[node.layer]) {\n return fail(\n `${node.layer} '${node.id}' must hang under a ${PARENT_LAYER[node.layer]}, not ${parent.layer} '${parent.id}'`,\n )\n }\n }\n for (const node of nodes) {\n const seen = new Set<string>()\n let current: TaxonomyNode | undefined = node\n while (current) {\n if (seen.has(current.id)) return fail(`node '${node.id}' sits on a parent cycle`)\n seen.add(current.id)\n current = current.parent === null ? undefined : byId.get(current.parent)\n }\n }\n return {\n succeeded: true,\n value: { schema: DOMAIN_TAXONOMY_SCHEMA, version: input.version, nodes },\n }\n}\n\nexport interface TaxonomyAttachment {\n id: string\n label: string\n layer: Exclude<TaxonomyNodeLayer, 'domain'>\n /**\n * For a problem: its primary domain path, broadest first. It must be a\n * chain of domain nodes from the top level down. Ignored for plays and runs.\n */\n path?: readonly string[]\n /** For a play or run: the problem or play it belongs to. */\n parent?: string\n tags?: readonly string[]\n}\n\n/** Attach a problem to one primary domain path, a play to a problem, or a run to a play. */\nexport function attachToTaxonomy(\n taxonomy: DomainTaxonomy,\n attachment: TaxonomyAttachment,\n): TaxonomyOutcome<DomainTaxonomy> {\n let parent: string\n if (attachment.layer === 'problem') {\n if (!attachment.path || attachment.path.length === 0) {\n return fail(`problem '${attachment.id}' needs a primary domain path`)\n }\n const resolved = resolveDomainPath(taxonomy, attachment.path)\n if (!resolved.succeeded) return resolved\n parent = attachment.path[attachment.path.length - 1]!\n } else {\n if (!attachment.parent) return fail(`${attachment.layer} '${attachment.id}' needs a parent`)\n parent = attachment.parent\n }\n return defineDomainTaxonomy({\n version: taxonomy.version,\n nodes: [\n ...taxonomy.nodes,\n {\n id: attachment.id,\n label: attachment.label,\n layer: attachment.layer,\n parent,\n ...(attachment.tags === undefined ? {} : { tags: [...attachment.tags] }),\n },\n ],\n })\n}\n\n/** Check that a path is a top-down chain of domain nodes. */\nexport function resolveDomainPath(\n taxonomy: DomainTaxonomy,\n path: readonly string[],\n): TaxonomyOutcome<readonly TaxonomyNode[]> {\n const byId = nodeIndex(taxonomy)\n const chain: TaxonomyNode[] = []\n let expectedParent: string | null = null\n for (const id of path) {\n const node = byId.get(id)\n if (node?.layer !== 'domain') return fail(`'${id}' is not a domain node`)\n if (node.parent !== expectedParent) {\n return fail(`domain path breaks at '${id}': its parent is '${node.parent ?? LAB_NODE_ID}'`)\n }\n chain.push(node)\n expectedParent = id\n }\n return { succeeded: true, value: chain }\n}\n\n/** Layer of a node id, with `lab` for the implicit root; undefined when unknown. */\nexport function taxonomyLayerOf(\n taxonomy: DomainTaxonomy,\n id: string,\n): TaxonomyNodeLayer | 'lab' | undefined {\n if (id === LAB_NODE_ID) return 'lab'\n return nodeIndex(taxonomy).get(id)?.layer\n}\n\n/** Parent id, with `lab` above every top-level domain and null above `lab`. */\nexport function taxonomyParentOf(taxonomy: DomainTaxonomy, id: string): string | null | undefined {\n if (id === LAB_NODE_ID) return null\n const node = nodeIndex(taxonomy).get(id)\n if (!node) return undefined\n return node.parent ?? LAB_NODE_ID\n}\n\n/** The node and its ancestors, nearest first, ending at `lab`. Empty for an unknown id. */\nexport function taxonomyAncestry(taxonomy: DomainTaxonomy, id: string): string[] {\n const byId = nodeIndex(taxonomy)\n const chain: string[] = []\n let current: string | null = id\n while (current !== null) {\n if (current === LAB_NODE_ID) {\n chain.push(current)\n break\n }\n const node = byId.get(current)\n if (!node) return []\n chain.push(current)\n current = node.parent ?? LAB_NODE_ID\n }\n return chain\n}\n\n/** Domain path of a node, broadest first: the domain ids above it, and itself when a domain. */\nexport function domainPathOf(taxonomy: DomainTaxonomy, id: string): string[] {\n const byId = nodeIndex(taxonomy)\n return taxonomyAncestry(taxonomy, id)\n .filter((ancestor) => byId.get(ancestor)?.layer === 'domain')\n .reverse()\n}\n\n/**\n * Deepest node that is an ancestor of (or equal to) every id, or undefined\n * when an id is unknown. `lab` is the answer when they share nothing else.\n */\nexport function lowestCommonAncestor(\n taxonomy: DomainTaxonomy,\n ids: readonly string[],\n): string | undefined {\n if (ids.length === 0) return undefined\n const chains = ids.map((id) => taxonomyAncestry(taxonomy, id))\n if (chains.some((chain) => chain.length === 0)) return undefined\n const others = chains.slice(1).map((chain) => new Set(chain))\n return chains[0]!.find((id) => others.every((chain) => chain.has(id)))\n}\n\nfunction nodeIndex(taxonomy: DomainTaxonomy): Map<string, TaxonomyNode> {\n return new Map(taxonomy.nodes.map((node) => [node.id, node]))\n}\n","/**\n * failure-modes — a judged analyst with fixed-choice labels, gated on its own\n * calibration.\n *\n * Labels are adapted from the MAST multi-agent failure taxonomy (Cemri et al.,\n * \"Why Do Multi-Agent LLM Systems Fail?\", 2025): its fourteen modes in three\n * groups, plus four single-agent modes so the public AgentRx set maps onto the\n * same labels, plus `none`. Two more fixed questions cover delegation-brief\n * completeness and steer handling.\n *\n * The judge runs through the System One decision path (`systemOneAnalyst`).\n * Construction requires a calibration — gold labels compared with the judge's\n * labels on the same items — and refuses to build an analyst whose Cohen's κ\n * is below `FAILURE_MODES_MIN_KAPPA`. A rubric that does not agree with its\n * gold set has nothing to report, so it reports nothing.\n */\n\nimport { readFile } from 'node:fs/promises'\nimport { nominalAgreement } from '../statistics/agreement-irr'\nimport { type SystemOneEvaluatorOptions, systemOneAnalyst } from '../systemone'\nimport type { SystemOneQuestions, SystemOneState } from '../systemone-protocol'\nimport { normalizeAgentRxCategory } from './benchmark-dataset-agentrx'\nimport type { AgentRxRow } from './benchmark-dataset-types'\nimport { loadPublicBenchmarkRows } from './benchmark-public-data'\nimport type { FindingCalibration, FindingScope } from './finding-scope'\nimport { type Analyst, type AnalystContext, type AnalystFinding, makeFinding } from './types'\n\nexport const FAILURE_MODES_ANALYST_ID = 'failure-modes'\nexport const FAILURE_MODES_VERSION = '1'\n\n/** κ below this refuses the rubric. */\nexport const FAILURE_MODES_MIN_KAPPA = 0.6\n\nexport const FAILURE_MODE_LABELS = {\n // MAST 1 — specification and system design\n 'disobey-task-specification': 'Ignored or violated the stated task requirements or constraints.',\n 'disobey-role-specification': 'Acted outside its assigned role or took over another role.',\n 'step-repetition': 'Repeated a step already completed without new reason.',\n 'loss-of-conversation-history': 'Lost earlier context and acted as if it was never given.',\n 'unaware-of-termination-conditions': 'Did not recognize when the task was done or must stop.',\n // MAST 2 — inter-agent misalignment\n 'conversation-reset': 'Restarted the exchange and discarded progress.',\n 'fail-to-ask-for-clarification': 'Proceeded on an ambiguous instruction without asking.',\n 'task-derailment': 'Drifted from the task toward a different goal.',\n 'information-withholding': 'Kept back information another agent needed.',\n 'ignored-other-agent-input': \"Disregarded another agent's input or recommendation.\",\n 'reasoning-action-mismatch': 'Acted against its own stated reasoning or plan.',\n // MAST 3 — task verification and termination\n 'premature-termination': 'Stopped before the goal of the task was met.',\n 'no-or-incomplete-verification': 'Delivered without verifying, or verified only part.',\n 'incorrect-verification': 'Verified, but the check was wrong or passed bad output.',\n // Single-agent modes, so AgentRx labels map onto this set.\n 'invented-information': 'Stated facts, results or tool output that do not exist.',\n 'invalid-tool-invocation': 'Called a tool with an invalid name, argument or format.',\n 'misread-tool-output': 'Misinterpreted what a tool or handoff returned.',\n 'system-failure': 'Failed because of infrastructure, not the agent.',\n none: 'No failure mode applies.',\n} as const\n\nexport type FailureModeLabel = keyof typeof FAILURE_MODE_LABELS\n\n/**\n * AgentRx root-cause category → failure-mode label. `null` categories have no\n * counterpart here and are left out of the gold set, counted as unmapped.\n */\nconst AGENT_RX_FAILURE_MODE_MAP: Readonly<Record<string, FailureModeLabel | null>> = {\n 'instruction-plan-adherence-failure': 'disobey-task-specification',\n 'invention-of-new-information': 'invented-information',\n 'invalid-invocation': 'invalid-tool-invocation',\n 'misinterpretation-of-tool-output-handoff-failure': 'misread-tool-output',\n 'intent-plan-misalignment': 'task-derailment',\n 'underspecified-user-intent': 'fail-to-ask-for-clarification',\n 'intent-not-supported': null,\n 'guardrails-triggered': null,\n 'system-failure': 'system-failure',\n inconclusive: null,\n}\n\nexport const FAILURE_MODES_QUESTIONS = {\n failure_mode: {\n type: 'choice',\n instructions:\n 'Which single failure mode best explains why this agent or team fell short? Choose none when it did not fail.',\n criteria: FAILURE_MODE_LABELS,\n },\n delegation_brief: {\n type: 'choice',\n instructions:\n 'When this agent delegated work, did the brief state the goal, the constraints, the expected output, and how the result would be checked?',\n criteria: {\n complete: 'Every delegated brief stated goal, constraints, output and check.',\n partial: 'Some brief left out one or more of goal, constraints, output or check.',\n missing: 'Work was delegated with no usable brief.',\n 'no-delegation': 'Nothing was delegated.',\n },\n },\n steer_handling: {\n type: 'choice',\n instructions: 'When a steer or correction arrived mid-task, what did the agent do with it?',\n criteria: {\n applied: 'Changed course as the steer asked.',\n ignored: 'Continued as before, or acknowledged without acting.',\n 'no-steer': 'No steer arrived.',\n },\n },\n} as const satisfies SystemOneQuestions\n\nexport interface FailureModeLabelItem {\n id: string\n label: FailureModeLabel\n}\n\nexport interface FailureModesCalibration extends FindingCalibration {\n /** Gold items with no judge label; each counts as a disagreement. */\n missingPredictions: number\n}\n\nexport type FailureModesOutcome<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; error: { kind: 'invalid' | 'uncalibrated'; message: string } }\n\nfunction isLabel(value: unknown): value is FailureModeLabel {\n return typeof value === 'string' && Object.hasOwn(FAILURE_MODE_LABELS, value)\n}\n\n/** Gold labels from AgentRx rows: each trajectory's root-cause category, mapped onto this set. */\nfunction failureModeGoldFromAgentRx(rows: readonly AgentRxRow[]): {\n gold: FailureModeLabelItem[]\n unmapped: Array<{ id: string; category: string }>\n} {\n const gold: FailureModeLabelItem[] = []\n const unmapped: Array<{ id: string; category: string }> = []\n for (const row of rows) {\n const id = `agentrx:${String(row.trajectory_id)}`\n const rootId = row.root_cause_failure_id ?? row.root_cause?.failure_id\n const root = row.failures.find((failure) => String(failure.failure_id) === String(rootId))\n if (!root)\n throw new TypeError(`AgentRx trajectory '${row.trajectory_id}' has no root-cause failure`)\n const category = normalizeAgentRxCategory(root.failure_category)\n if (!Object.hasOwn(AGENT_RX_FAILURE_MODE_MAP, category)) {\n throw new RangeError(\n `AgentRx category '${root.failure_category}' is outside the AgentRx taxonomy`,\n )\n }\n const label = AGENT_RX_FAILURE_MODE_MAP[category]\n if (label === null || label === undefined) unmapped.push({ id, category })\n else gold.push({ id, label })\n }\n return { gold, unmapped }\n}\n\n/** Validate a caller's gold file: a JSON array of `{ id, label }` with unique ids and known labels. */\nfunction parseFailureModeGold(raw: unknown): FailureModesOutcome<FailureModeLabelItem[]> {\n if (!Array.isArray(raw)) {\n return { succeeded: false, error: { kind: 'invalid', message: 'gold must be a JSON array' } }\n }\n const seen = new Set<string>()\n const items: FailureModeLabelItem[] = []\n for (const [index, row] of raw.entries()) {\n const id = (row as { id?: unknown } | null)?.id\n const label = (row as { label?: unknown } | null)?.label\n if (typeof id !== 'string' || !id.trim() || !isLabel(label)) {\n return {\n succeeded: false,\n error: {\n kind: 'invalid',\n message: `gold row ${index} needs a string id and a known label`,\n },\n }\n }\n if (seen.has(id)) {\n return { succeeded: false, error: { kind: 'invalid', message: `gold id '${id}' repeats` } }\n }\n seen.add(id)\n items.push({ id, label })\n }\n return { succeeded: true, value: items }\n}\n\nexport interface FailureModeGoldSources {\n /** The public AgentRx label file, the same file `analyst-benchmark --dataset agentrx --labels` reads. */\n agentRxLabelsPath?: string\n /** The caller's gold file: a JSON array of `{ id, label }`. */\n goldPath?: string\n}\n\nexport interface FailureModeGold {\n gold: FailureModeLabelItem[]\n /** AgentRx rows read from `agentRxLabelsPath`; every one is either in `gold` or in `unmapped`. */\n agentRxRows: number\n unmapped: Array<{ id: string; category: string }>\n}\n\n/**\n * Load the calibration gold set from the public AgentRx labels and the\n * caller's gold file, through the analyst module's public-dataset loader.\n * Ids must be unique across both sources. No source, or no gold item, is a\n * failure: an empty gold set would calibrate to an undefined κ.\n */\nexport async function loadFailureModeGold(\n sources: FailureModeGoldSources,\n): Promise<FailureModesOutcome<FailureModeGold>> {\n const invalid = (message: string) =>\n ({ succeeded: false, error: { kind: 'invalid', message } }) as const\n const gold: FailureModeLabelItem[] = []\n let agentRxRows = 0\n let unmapped: FailureModeGold['unmapped'] = []\n try {\n if (sources.agentRxLabelsPath !== undefined) {\n const rows = await loadPublicBenchmarkRows(sources.agentRxLabelsPath)\n agentRxRows = rows.length\n const mapped = failureModeGoldFromAgentRx(rows as unknown as AgentRxRow[])\n gold.push(...mapped.gold)\n unmapped = mapped.unmapped\n }\n if (sources.goldPath !== undefined) {\n const parsed = parseFailureModeGold(JSON.parse(await readFile(sources.goldPath, 'utf8')))\n if (!parsed.succeeded) return parsed\n gold.push(...parsed.value)\n }\n } catch (error) {\n return invalid(error instanceof Error ? error.message : String(error))\n }\n if (gold.length === 0) return invalid('failure-modes calibration needs at least one gold item')\n const ids = new Set<string>()\n for (const item of gold) {\n if (ids.has(item.id)) return invalid(`gold id '${item.id}' repeats across sources`)\n ids.add(item.id)\n }\n return { succeeded: true, value: { gold, agentRxRows, unmapped } }\n}\n\n/**\n * Score the judge's labels against gold labels for the same items, usually\n * the set `loadFailureModeGold` returns.\n */\nexport function calibrateFailureModes(\n gold: readonly FailureModeLabelItem[],\n predictions: readonly FailureModeLabelItem[],\n): FailureModesCalibration {\n const predicted = new Map<string, FailureModeLabel>()\n for (const prediction of predictions) {\n if (predicted.has(prediction.id))\n throw new TypeError(`prediction id '${prediction.id}' repeats`)\n predicted.set(prediction.id, prediction.label)\n }\n const ids = new Set<string>()\n let missingPredictions = 0\n const pairs: Array<readonly [string, string]> = []\n for (const item of gold) {\n if (ids.has(item.id)) throw new TypeError(`gold id '${item.id}' repeats`)\n ids.add(item.id)\n const label = predicted.get(item.id)\n if (label === undefined) missingPredictions += 1\n // A missing prediction is its own label: it can never match gold.\n pairs.push([item.label, label ?? '(no prediction)'])\n }\n const agreement = nominalAgreement(pairs)\n return {\n gold_n: agreement.n,\n agreement: agreement.agreement,\n kappa: agreement.kappa,\n missingPredictions,\n }\n}\n\nexport interface FailureModesAnalystOptions<I> extends SystemOneEvaluatorOptions {\n model: string\n /** The layer the judged subject sits at. */\n layer: 'agent' | 'team' | 'run'\n calibration: FindingCalibration\n renderState: (input: I, context: AnalystContext) => SystemOneState | Promise<SystemOneState>\n /** The judged population: the agent, team or run the state describes. */\n scope: (input: I, context: AnalystContext) => FindingScope\n subject?: (input: I, context: AnalystContext) => string\n}\n\n/**\n * Build the failure-modes analyst, or refuse when its calibration does not\n * clear `FAILURE_MODES_MIN_KAPPA`. An undefined κ (no gold, or one label\n * everywhere) is refused the same way.\n */\nexport function createFailureModesAnalyst<I>(\n options: FailureModesAnalystOptions<I>,\n): FailureModesOutcome<Analyst<I>> {\n const { calibration, layer, model, renderState, scope, subject, ...transport } = options\n if (!(calibration.gold_n > 0) || !(calibration.kappa >= FAILURE_MODES_MIN_KAPPA)) {\n return {\n succeeded: false,\n error: {\n kind: 'uncalibrated',\n message: `failure-modes rubric has kappa ${Number.isNaN(calibration.kappa) ? 'undefined' : calibration.kappa.toFixed(3)} over ${calibration.gold_n} gold items; reporting requires kappa >= ${FAILURE_MODES_MIN_KAPPA}`,\n },\n }\n }\n const method = {\n kind: 'judged' as const,\n name: FAILURE_MODES_ANALYST_ID,\n version: FAILURE_MODES_VERSION,\n calibration: {\n gold_n: calibration.gold_n,\n agreement: calibration.agreement,\n kappa: calibration.kappa,\n },\n }\n const analyst = systemOneAnalyst({\n ...transport,\n model,\n renderState,\n id: FAILURE_MODES_ANALYST_ID,\n description: 'Labels agent, team and run failures with a calibrated fixed-choice rubric.',\n inputKind: 'custom',\n version: FAILURE_MODES_VERSION,\n questions: FAILURE_MODES_QUESTIONS,\n findings: (value, input, context) => {\n const judgedSubject = subject?.(input, context)\n const base = {\n analyst_id: FAILURE_MODES_ANALYST_ID,\n derived_from_judge: true,\n layer,\n scope: scope(input, context),\n method,\n evidence_refs: [{ kind: 'artifact' as const, uri: `run://${context.runId}` }],\n ...(judgedSubject === undefined ? {} : { subject: judgedSubject }),\n }\n const out: AnalystFinding[] = []\n const mode = value.answers.failure_mode\n if (mode.choice !== 'none') {\n out.push(\n makeFinding({\n ...base,\n area: 'failure-mode',\n severity: 'medium',\n confidence: mode.confidence,\n claim: `Failure mode: ${mode.choice}`,\n claim_id: `failure-mode:${mode.choice}`,\n rationale: FAILURE_MODE_LABELS[mode.choice],\n }),\n )\n }\n const brief = value.answers.delegation_brief\n if (brief.choice === 'partial' || brief.choice === 'missing') {\n out.push(\n makeFinding({\n ...base,\n area: 'delegation-brief',\n severity: brief.choice === 'missing' ? 'high' : 'medium',\n confidence: brief.confidence,\n claim: `Delegation brief ${brief.choice}`,\n claim_id: `delegation-brief:${brief.choice}`,\n }),\n )\n }\n const steer = value.answers.steer_handling\n if (steer.choice === 'ignored') {\n out.push(\n makeFinding({\n ...base,\n area: 'steer-handling',\n severity: 'high',\n confidence: steer.confidence,\n claim: 'Steer ignored',\n claim_id: 'steer-handling:ignored',\n }),\n )\n }\n return out\n },\n })\n return { succeeded: true, value: analyst }\n}\n","/**\n * Findings ledger — analyst findings in the shared ledger-core journal.\n *\n * Each appended finding is one hash-chained, canonical JSON entry, fsynced and\n * pinned to a trusted head, so a later reader can prove nothing was rewritten\n * or cut from the end. A row is validated by `AnalystFindingSchema` before it\n * is written and again when it is read, so a 1.1.0 finding whose declared\n * population disagrees with its evidence never enters the record.\n *\n * Appends are idempotent per (run, finding): replaying a run's findings is a\n * no-op, and the same finding id with different content is a conflict.\n * `FindingsStore` remains the unchained JSONL store for existing consumers.\n */\n\nimport { z } from 'zod'\nimport type { LedgerHash } from '../ledger-core/canonical'\nimport { FileLedgerJournal, type LedgerJournalCodec } from '../ledger-core/journal'\nimport { merkleRoot } from '../ledger-core/merkle'\nimport { AnalystFindingSchema, type FindingLayer } from './finding-scope'\nimport {\n type DiffPolicy,\n diffFindings,\n type FindingsDiff,\n type PersistedFinding,\n} from './findings-store'\nimport type { AnalystFinding } from './types'\n\nconst schema = 'agent-eval.findings-ledger.v1' as const\nconst digest = z.string().regex(/^sha256:[a-f0-9]{64}$/)\nconst identity = z\n .string()\n .min(1)\n .refine((value) => value.trim() === value, { message: 'must not carry surrounding space' })\n\nconst eventSchema = z\n .object({\n kind: z.literal('finding'),\n eventId: identity,\n run_id: identity,\n finding: AnalystFindingSchema,\n })\n .strict()\n\ntype Event = z.infer<typeof eventSchema>\n\nconst entrySchema = z\n .object({\n schema: z.literal(schema),\n sequence: z.number().int().nonnegative(),\n previousHash: digest.nullable(),\n event: eventSchema,\n entryHash: digest,\n })\n .strict()\n\n/** One finding as the ledger holds it. */\nexport interface LedgerFinding extends PersistedFinding {\n /** Position in the journal; later entries were appended later. */\n sequence: number\n entryHash: LedgerHash\n}\n\nexport interface FindingsLedgerRead {\n findings: LedgerFinding[]\n /** RFC 9162 Merkle root over every entry hash, in journal order. */\n merkleRoot: LedgerHash\n}\n\nexport type FindingsLedgerOutcome<T> =\n | { succeeded: true; value: T }\n | {\n succeeded: false\n error: { kind: 'invalid' | 'conflict' | 'unavailable'; message: string }\n }\n\nexport interface FindingsLedger {\n readonly path: string\n append(\n runId: string,\n findings: readonly AnalystFinding[],\n ): Promise<FindingsLedgerOutcome<{ appended: number; replayed: number }>>\n read(): Promise<FindingsLedgerOutcome<FindingsLedgerRead>>\n}\n\nclass FindingsLedgerConflictError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'FindingsLedgerConflictError'\n }\n}\n\nclass FindingsLedgerInvalidError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'FindingsLedgerInvalidError'\n }\n}\n\nfunction codec(): LedgerJournalCodec<{ schema: typeof schema }, Event, LedgerFinding[]> {\n return {\n subject: 'findings ledger',\n header: { schema },\n integrityError: (message, options) => new Error(message, options),\n conflictError: (message) => new FindingsLedgerConflictError(message),\n parseEntry: (raw, context) => {\n const decoded = entrySchema.safeParse(raw)\n if (!decoded.success) {\n const issue = decoded.error.issues[0]\n throw new FindingsLedgerInvalidError(\n `findings ledger ${context.path}:${context.line} is invalid at ${(issue?.path ?? []).join('.')}: ${issue?.message}`,\n )\n }\n return {\n ...decoded.data,\n event: decoded.data.event as Event,\n previousHash: decoded.data.previousHash as LedgerHash | null,\n entryHash: decoded.data.entryHash as LedgerHash,\n }\n },\n checkEntryHeader: (entry) => {\n if (entry.schema !== schema) throw new FindingsLedgerInvalidError('unsupported ledger schema')\n },\n createProjector: () => {\n const rows: LedgerFinding[] = []\n return {\n apply: (entry) => {\n const { event } = entry\n if (event.eventId !== eventIdFor(event.run_id, event.finding.finding_id)) {\n throw new FindingsLedgerInvalidError(\n `event id ${event.eventId} does not name its finding`,\n )\n }\n rows.push({\n ...(event.finding as AnalystFinding),\n run_id: event.run_id,\n sequence: entry.sequence,\n entryHash: entry.entryHash,\n })\n },\n snapshot: () => [...rows],\n }\n },\n }\n}\n\nfunction eventIdFor(runId: string, findingId: string): string {\n return `finding:${runId}:${findingId}`\n}\n\nasync function outcome<T>(operation: () => Promise<T>): Promise<FindingsLedgerOutcome<T>> {\n try {\n return { succeeded: true, value: await operation() }\n } catch (error) {\n return {\n succeeded: false,\n error: {\n kind:\n error instanceof FindingsLedgerConflictError\n ? 'conflict'\n : error instanceof FindingsLedgerInvalidError || error instanceof z.ZodError\n ? 'invalid'\n : 'unavailable',\n message: error instanceof Error ? error.message : String(error),\n },\n }\n }\n}\n\n/** Open (or create on first append) the findings journal at `path`; every reopen requires its pin. */\nexport function openFindingsLedger(options: { path: string }): FindingsLedger {\n if (!options.path.trim()) throw new TypeError('findings ledger: path is empty')\n const journal = new FileLedgerJournal(options.path, codec(), { requireTrustedHead: true })\n return {\n path: journal.path,\n append: (runId, findings) =>\n outcome(async () => {\n identity.parse(runId)\n let appended = 0\n let replayed = 0\n for (const finding of findings) {\n const parsed = AnalystFindingSchema.safeParse(finding)\n if (!parsed.success) {\n const issue = parsed.error.issues[0]\n throw new FindingsLedgerInvalidError(\n `finding ${finding.finding_id} is invalid at ${(issue?.path ?? []).join('.')}: ${issue?.message}`,\n )\n }\n const result = await journal.append(\n {\n kind: 'finding',\n eventId: eventIdFor(runId, finding.finding_id),\n run_id: runId,\n finding: parsed.data,\n },\n { pinHead: true },\n )\n if (result.appended) appended += 1\n else replayed += 1\n }\n return { appended, replayed }\n }),\n read: () =>\n outcome(async () => {\n const findings = await journal.replay()\n return { findings, merkleRoot: merkleRoot(findings.map((row) => row.entryHash)) }\n }),\n }\n}\n\n// ── Queries ──────────────────────────────────────────────────────────\n\nexport interface FindingsQuery {\n layer?: FindingLayer | readonly FindingLayer[]\n subject?: string\n analystId?: string\n runId?: string\n claimId?: string\n /**\n * Findings whose `scope.domain_path` starts with this path. A finding with no\n * domain path never matches, so a path query cannot return unscoped findings.\n */\n domainPath?: readonly string[]\n}\n\n/** Filter ledger rows. Every set criterion must hold; 1.0.0 rows have no layer and never match one. */\nexport function queryFindings<T extends AnalystFinding & { run_id?: string }>(\n rows: readonly T[],\n query: FindingsQuery,\n): T[] {\n const layers =\n query.layer === undefined\n ? null\n : new Set(typeof query.layer === 'string' ? [query.layer] : query.layer)\n return rows.filter((row) => {\n if (layers && (row.layer === undefined || !layers.has(row.layer))) return false\n if (query.subject !== undefined && row.subject !== query.subject) return false\n if (query.analystId !== undefined && row.analyst_id !== query.analystId) return false\n if (query.runId !== undefined && row.run_id !== query.runId) return false\n if (query.claimId !== undefined && row.claim_id !== query.claimId) return false\n if (query.domainPath !== undefined) {\n const path = row.scope?.domain_path\n if (!path || path.length < query.domainPath.length) return false\n if (query.domainPath.some((id, index) => path[index] !== id)) return false\n }\n return true\n })\n}\n\nexport interface FindingsTimeStep {\n previous_run_id: string\n run_id: string\n diff: FindingsDiff\n}\n\n/**\n * Diff each run against the run before it, in the order runs first entered\n * the ledger. Uses `diffFindings`, so `appeared`, `disappeared`, `persisted`\n * and `changed` mean exactly what they mean for two runs.\n */\nexport function diffFindingsOverTime(\n rows: readonly LedgerFinding[],\n policy: DiffPolicy = {},\n): FindingsTimeStep[] {\n const runs: string[] = []\n const byRun = new Map<string, PersistedFinding[]>()\n for (const row of [...rows].sort((a, b) => a.sequence - b.sequence)) {\n const list = byRun.get(row.run_id)\n if (list) list.push(row)\n else {\n runs.push(row.run_id)\n byRun.set(row.run_id, [row])\n }\n }\n return runs.slice(1).map((runId, index) => ({\n previous_run_id: runs[index]!,\n run_id: runId,\n diff: diffFindings(byRun.get(runs[index]!)!, byRun.get(runId)!, policy),\n }))\n}\n","/**\n * Skill-usage analyst — a DETERMINISTIC `Analyst` over a Claude/Codex skill\n * library + its trace corpus. Unlike the trace-store kinds (failure-mode,\n * improvement, ...) this kind calls no LLM: it mines real usage and skill\n * structure and emits findings by rule.\n *\n * It exists because the naive \"Skill-tool invocation count\" lies low — it\n * misses orchestrated sub-dispatch (a leaf skill run BY /pursue or /governor\n * logs under the parent), slash-command entry, local-script bypass, and\n * on-disk artifacts. The 2026-05-30 skill audit found 39/53 skills at zero\n * direct invocations, yet only one was a genuine cut: the rest were\n * measurement-invisible or discovery-limited. This analyst encodes that\n * lesson as a multi-signal usage model so a cheap repeatable pass can keep\n * the library honest, and so the expensive audit workflow's verdicts can\n * GEPA-distill it toward agreement (see `gold/skill-verdicts.gold.jsonl`).\n *\n * Report-building (`buildSkillUsageReport`, an fs scan) is separated from\n * finding emission (`SkillUsageAnalyst.analyze`, pure) so the slow scan runs\n * once at the registry boundary and the rule logic stays unit-testable.\n */\n\nimport { type Dirent, existsSync, readdirSync, readFileSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\n\n\n\n\n// ── Input model ──────────────────────────────────────────────────────\n\ntype SkillKind = 'public' | 'private'\n\n/** One skill's multi-signal usage + structure. All counts are deterministic. */\nexport interface SkillUsageRecord {\n name: string\n kind: SkillKind\n /** Absolute path to the skill's SKILL.md. */\n path: string\n lines: number\n /** `\"skill\":\"<name>\"` Skill-tool invocations across the trace corpus. */\n directInvocations: number\n /** `<command-name>/<name>` slash invocations across the trace corpus. */\n slashInvocations: number\n /** Sibling skills whose SKILL.md dispatches to this one (`/<name>`). Proxy\n * for orchestrated sub-dispatch the per-skill counter cannot see. */\n inboundRefs: number\n /** On-disk artifacts attributable to the skill (e.g. `.evolve/<name>/**`). */\n artifactCount: number\n /** Tangle-private reference count in the body (leak signal for public skills). */\n tanglePrivateRefs: number\n hasReferencesDir: boolean\n hasEvalsDir: boolean\n /** Body mentions `skill-runs.jsonl` (visible to /reflect + /governor). */\n logsRuns: boolean\n /** Description carries an explicit `Triggers:` clause / trigger phrases. */\n hasTriggerPhrases: boolean\n}\n\nexport interface SkillUsageReport {\n generatedFromTraces: number\n records: SkillUsageRecord[]\n}\n\nexport interface SkillUsageScanConfig {\n /** Dirs holding `*.jsonl` transcripts (Claude `~/.claude/projects`, Codex sessions). */\n transcriptDirs: string[]\n /** Skill roots to scan; each dir directly under `root` with a `SKILL.md` is a skill. */\n skillRoots: { root: string; kind: SkillKind }[]\n /** Roots scanned for `<root>/.evolve/<skill>` artifact dirs. */\n artifactRoots?: string[]\n /** Token-prefixed mappings: skill name → extra artifact subpaths under an artifactRoot\n * (e.g. reflect → `.evolve/reflections`). Catches non-eponymous artifact dirs. */\n artifactAliases?: Record<string, string[]>\n /** Cap files read per transcript dir (bounds a huge corpus); 0 = unbounded. */\n maxTranscriptsPerDir?: number\n}\n\n// ── Deterministic thresholds ─────────────────────────────────────────\n\n\n\nconst TANGLE_PRIVATE_RE =\n /\\b(cli-bridge|tangletools|ops-board|drew-gtr-pro|@tangle-network\\/|~\\/company|tangle\\.tools|gtm-agent)\\b|\\bkimi\\b|\\btcloud\\b/gi\nconst TRIGGER_RE = /triggers?\\s*[:-]/i\n\n// ── Report builder (fs scan — slow, runs once at the registry boundary) ──\n\nfunction listSkillDirs(root: string): { name: string; path: string }[] {\n if (!existsSync(root)) return []\n const out: { name: string; path: string }[] = []\n for (const entry of readdirSync(root, { withFileTypes: true })) {\n if (!entry.isDirectory() && !entry.isSymbolicLink()) continue\n const skillMd = join(root, entry.name, 'SKILL.md')\n if (existsSync(skillMd)) out.push({ name: entry.name, path: skillMd })\n }\n return out\n}\n\nfunction walkJsonl(dir: string, cap: number): string[] {\n if (!existsSync(dir)) return []\n const files: string[] = []\n const stack = [dir]\n while (stack.length) {\n const cur = stack.pop()!\n let entries: Dirent[]\n try {\n entries = readdirSync(cur, { withFileTypes: true })\n } catch {\n continue\n }\n for (const e of entries) {\n const full = join(cur, e.name)\n if (e.isDirectory()) stack.push(full)\n else if (e.name.endsWith('.jsonl')) {\n files.push(full)\n if (cap > 0 && files.length >= cap) return files\n }\n }\n }\n return files\n}\n\nfunction frontmatterDescription(body: string): string {\n const fm = /^---\\n([\\s\\S]*?)\\n---/.exec(body)\n const block = fm?.[1] ?? ''\n const m = /description:\\s*(.+)/i.exec(block)\n return m?.[1] ?? ''\n}\n\nfunction countArtifacts(roots: string[], name: string, aliases: string[]): number {\n let n = 0\n for (const root of roots) {\n const candidates = [join(root, '.evolve', name), ...aliases.map((a) => join(root, a))]\n for (const dir of candidates) {\n if (!existsSync(dir)) continue\n try {\n if (statSync(dir).isDirectory()) n += readdirSync(dir).length\n else n += 1\n } catch {\n /* unreadable — skip */\n }\n }\n }\n return n\n}\n\n/** Scan the corpus + skill roots into a {@link SkillUsageReport}. Deterministic. */\nexport function buildSkillUsageReport(config: SkillUsageScanConfig): SkillUsageReport {\n const skills = config.skillRoots.flatMap(({ root, kind }) =>\n listSkillDirs(root).map((s) => ({ ...s, kind })),\n )\n const names = skills.map((s) => s.name)\n\n // One pass over the corpus accumulating direct + slash counts per skill.\n const direct = new Map<string, number>(names.map((n) => [n, 0]))\n const slash = new Map<string, number>(names.map((n) => [n, 0]))\n const skillRe = /\"skill\"\\s*:\\s*\"([a-z0-9_:-]+)\"/g\n const cmdRe = /<command-name>\\/?([a-z0-9_:-]+)<\\/command-name>/g\n let transcripts = 0\n for (const dir of config.transcriptDirs) {\n for (const file of walkJsonl(dir, config.maxTranscriptsPerDir ?? 0)) {\n transcripts += 1\n let data: string\n try {\n data = readFileSync(file, 'utf8')\n } catch {\n continue\n }\n for (const m of data.matchAll(skillRe)) {\n const g = m[1]\n if (!g) continue\n const n = g.split(':').pop() ?? g\n const prev = direct.get(n)\n if (prev !== undefined) direct.set(n, prev + 1)\n }\n for (const m of data.matchAll(cmdRe)) {\n const g = m[1]\n if (g === undefined) continue\n const prev = slash.get(g)\n if (prev !== undefined) slash.set(g, prev + 1)\n }\n }\n }\n\n // Read each skill body once; compute structure + inbound refs across siblings.\n const bodies = new Map<string, string>()\n for (const s of skills) {\n try {\n bodies.set(s.name, readFileSync(s.path, 'utf8'))\n } catch {\n bodies.set(s.name, '')\n }\n }\n const inbound = new Map<string, number>(names.map((n) => [n, 0]))\n for (const target of names) {\n const ref = new RegExp(`/${target}\\\\b|\\\\[\\\\[${target}\\\\]\\\\]`)\n for (const s of skills) {\n if (s.name === target) continue\n if (ref.test(bodies.get(s.name) ?? '')) inbound.set(target, inbound.get(target)! + 1)\n }\n }\n\n const records: SkillUsageRecord[] = skills.map((s) => {\n const body = bodies.get(s.name) ?? ''\n const dir = s.path.replace(/\\/SKILL\\.md$/, '')\n return {\n name: s.name,\n kind: s.kind,\n path: s.path,\n lines: body ? body.split('\\n').length : 0,\n directInvocations: direct.get(s.name) ?? 0,\n slashInvocations: slash.get(s.name) ?? 0,\n inboundRefs: inbound.get(s.name) ?? 0,\n artifactCount: countArtifacts(\n config.artifactRoots ?? [],\n s.name,\n config.artifactAliases?.[s.name] ?? [],\n ),\n tanglePrivateRefs: (body.match(TANGLE_PRIVATE_RE) ?? []).length,\n hasReferencesDir: existsSync(join(dir, 'references')),\n hasEvalsDir: existsSync(join(dir, 'evals')),\n logsRuns: body.includes('skill-runs.jsonl'),\n hasTriggerPhrases: TRIGGER_RE.test(frontmatterDescription(body) || body.slice(0, 600)),\n }\n })\n return { generatedFromTraces: transcripts, records }\n}\n\n// ── Finding emission (pure — unit-testable, no LLM, no fs) ────────────\n\n\n\n\n\n\n\n// ── The Analyst ──────────────────────────────────────────────────────\n\n\n\n\n","/**\n * Promotion — the only way a claim moves above the layer it was measured at.\n *\n * A claim is restated at a parent node only when at least `k` independent\n * children carry the same `claim_id` with intervals that agree. Otherwise it\n * stays where it is, reported as untested above. The rule is the same on every\n * rung of the ladder: run → play → problem → each domain node up the path →\n * lab.\n *\n * The rule, exactly:\n * - A finding sits at the node that is the lowest common ancestor of its\n * `scope.population` in the taxonomy, and that node's layer must equal the\n * finding's `layer`. Four runs of one play place a claim at that play; the\n * same claim stored at `domain` or `lab` is refused as exceeding its\n * evidence.\n * - Only children with `measure.interval` vote. Voters must name the same\n * measure and unit, and their intervals must share a common point.\n * - Children are counted by lineage, not by node: two children whose evidence\n * units share a lineage root (run 2 built on run 1's code) count once, and\n * a child with no recorded lineage shares one root with every other such\n * child.\n * - Promoted findings cite every voting child by `finding://<finding_id>`.\n *\n * Event, turn, agent, team and meta findings sit outside the ladder and never\n * promote.\n */\n\nimport {\n type DomainTaxonomy,\n domainPathOf,\n LAB_NODE_ID,\n lowestCommonAncestor,\n taxonomyAncestry,\n taxonomyLayerOf,\n taxonomyParentOf,\n} from './domain-taxonomy'\nimport {\n type FindingLayer,\n type FindingMeasure,\n lineageRoots,\n mergeEvidenceUnits,\n mostSevere,\n spanningWindow,\n UNKNOWN_LINEAGE,\n} from './finding-scope'\nimport { type AnalystFinding, makeFinding } from './types'\n\n/** Bump when the promotion rule changes, so promoted findings name the rule that lifted them. */\nconst PROMOTE_VERSION = '1'\n\n/** The analyst id a promoted finding carries when its children came from different analysts. */\nconst PROMOTE_ANALYST_ID = 'promote'\n\nexport interface PromoteOptions {\n /** Independent agreeing children required to lift a claim. Default 2, minimum 2. */\n k?: number\n /** Timestamp stamped on promoted findings; defaults to now. */\n produced_at?: string\n}\n\n/** A finding promote did not lift, with the reason in words. */\nexport interface PromotionHold {\n finding_id: string\n claim_id: string | null\n /** The node the finding sits at, or null when it could not be placed. */\n node: string | null\n reason: string\n}\n\nexport interface PromotionResult {\n /** The input findings followed by every promoted finding. */\n findings: AnalystFinding[]\n promoted: AnalystFinding[]\n /** Placed findings whose claim was not lifted; they stay true at their own node. */\n untestedAbove: PromotionHold[]\n /** Findings promote cannot place on the ladder, and why. */\n unplaced: PromotionHold[]\n}\n\ninterface Placement {\n finding: AnalystFinding\n claimId: string\n node: string\n}\n\nconst LADDER: readonly FindingLayer[] = ['run', 'play', 'problem', 'domain', 'lab']\n\nexport function promote(\n findings: readonly AnalystFinding[],\n taxonomy: DomainTaxonomy,\n options: PromoteOptions = {},\n): PromotionResult {\n const k = options.k ?? 2\n if (!Number.isInteger(k) || k < 2) {\n throw new RangeError(`promote: k must be an integer of at least 2, got ${k}`)\n }\n const unplaced: PromotionHold[] = []\n const buckets = new Map<number, Placement[]>()\n const addPlacement = (placement: Placement): void => {\n const depth = taxonomyAncestry(taxonomy, placement.node).length\n const bucket = buckets.get(depth) ?? []\n bucket.push(placement)\n buckets.set(depth, bucket)\n }\n for (const finding of findings) {\n const placed = place(finding, taxonomy)\n if ('reason' in placed) unplaced.push(placed)\n else addPlacement(placed)\n }\n\n const roots = lineageRoots(\n mergeEvidenceUnits(findings.flatMap((finding) => finding.evidence_units ?? [])),\n )\n const promoted: AnalystFinding[] = []\n const untestedAbove: PromotionHold[] = []\n const hold = (placement: Placement, reason: string): void => {\n untestedAbove.push({\n finding_id: placement.finding.finding_id,\n claim_id: placement.claimId,\n node: placement.node,\n reason,\n })\n }\n\n // Deepest nodes first: a parent's bucket is complete, native findings and\n // lifted ones alike, before it is itself grouped for the next rung.\n for (let depth = Math.max(0, ...buckets.keys()); depth > 1; depth -= 1) {\n const groups = new Map<string, { parent: string; members: Placement[] }>()\n for (const placement of buckets.get(depth) ?? []) {\n const parent = taxonomyParentOf(taxonomy, placement.node)\n if (parent === null || parent === undefined) continue\n const key = JSON.stringify([placement.claimId, parent])\n const group = groups.get(key) ?? { parent, members: [] }\n group.members.push(placement)\n groups.set(key, group)\n }\n for (const { parent, members } of groups.values()) {\n const verdict = judgeGroup(members, k, roots)\n if (!verdict.lift) {\n for (const member of members) hold(member, verdict.reason)\n continue\n }\n const lifted = liftedFinding(verdict.voters, parent, taxonomy, options.produced_at)\n promoted.push(lifted)\n addPlacement({ finding: lifted, claimId: members[0]!.claimId, node: parent })\n for (const member of members) {\n if (!verdict.voters.includes(member)) {\n hold(member, 'no interval, so it could not vote; the claim was lifted by its siblings')\n }\n }\n }\n }\n return { findings: [...findings, ...promoted], promoted, untestedAbove, unplaced }\n}\n\nfunction place(finding: AnalystFinding, taxonomy: DomainTaxonomy): Placement | PromotionHold {\n const unplaced = (reason: string, node: string | null = null): PromotionHold => ({\n finding_id: finding.finding_id,\n claim_id: finding.claim_id ?? null,\n node,\n reason,\n })\n if (finding.schema_version !== '1.1.0' || !finding.layer || !finding.scope) {\n return unplaced('no layer or scope (schema 1.0.0)')\n }\n if (finding.layer === 'meta')\n return unplaced('meta findings describe the instrument and never promote')\n if (!LADDER.includes(finding.layer)) {\n return unplaced(`${finding.layer} findings sit below the run → lab ladder`)\n }\n if (!finding.claim_id) return unplaced('no claim_id to match siblings by')\n const population = finding.scope.population\n if (population.length === 0) return unplaced('population names no units')\n const node = lowestCommonAncestor(taxonomy, population)\n if (node === undefined) return unplaced('population names ids outside the taxonomy')\n const nodeLayer = taxonomyLayerOf(taxonomy, node)\n if (nodeLayer !== finding.layer) {\n return unplaced(\n LADDER.indexOf(finding.layer) > LADDER.indexOf(nodeLayer as FindingLayer)\n ? `stated at ${finding.layer} but its population sits within ${nodeLayer} '${node}'`\n : `stated at ${finding.layer} but its population spans ${nodeLayer} '${node}'`,\n node,\n )\n }\n const path = finding.scope.domain_path\n if (path) {\n const expected = domainPathOf(taxonomy, node)\n if (path.length !== expected.length || path.some((id, index) => id !== expected[index])) {\n return unplaced(`domain_path ${JSON.stringify(path)} disagrees with the taxonomy`, node)\n }\n }\n return { finding, claimId: finding.claim_id, node }\n}\n\ntype GroupVerdict = { lift: true; voters: Placement[] } | { lift: false; reason: string }\n\nfunction judgeGroup(\n members: readonly Placement[],\n k: number,\n roots: ReadonlyMap<string, string>,\n): GroupVerdict {\n const voters = members.filter((member) => member.finding.measure?.interval !== undefined)\n if (voters.length === 0) return { lift: false, reason: 'no child carries an interval' }\n const first = voters[0]!.finding.measure!\n if (\n voters.some(\n ({ finding }) => finding.measure!.name !== first.name || finding.measure!.unit !== first.unit,\n )\n ) {\n return { lift: false, reason: 'children measure different quantities' }\n }\n const lo = Math.max(...voters.map(({ finding }) => finding.measure!.interval![0]))\n const hi = Math.min(...voters.map(({ finding }) => finding.measure!.interval![1]))\n if (lo > hi) return { lift: false, reason: 'child intervals do not agree' }\n\n const independent = independentChildren(voters, roots)\n if (independent < k) {\n const children = new Set(voters.map((voter) => voter.node)).size\n return {\n lift: false,\n reason:\n children > independent\n ? `${children} children agree but share lineage, leaving ${independent} independent of ${k} required`\n : `${independent} independent agreeing child${independent === 1 ? '' : 'ren'} of ${k} required`,\n }\n }\n return { lift: true, voters }\n}\n\n/**\n * Children joined when they share a lineage root, counted as components. A\n * child's roots are those of all its voters' evidence units; a voter with no\n * units has unknown lineage.\n */\nfunction independentChildren(\n voters: readonly Placement[],\n roots: ReadonlyMap<string, string>,\n): number {\n const rootsByNode = new Map<string, Set<string>>()\n for (const voter of voters) {\n const set = rootsByNode.get(voter.node) ?? new Set<string>()\n const units = voter.finding.evidence_units\n if (!units) set.add(UNKNOWN_LINEAGE)\n else for (const unit of units) set.add(roots.get(unit.id) ?? UNKNOWN_LINEAGE)\n rootsByNode.set(voter.node, set)\n }\n const parent = new Map<string, string>()\n const find = (id: string): string => {\n let current = id\n while (parent.get(current) !== current) current = parent.get(current)!\n return current\n }\n const owner = new Map<string, string>()\n for (const [node, nodeRoots] of rootsByNode) {\n parent.set(node, node)\n for (const root of nodeRoots) {\n const other = owner.get(root)\n if (other === undefined) owner.set(root, node)\n else parent.set(find(node), find(other))\n }\n }\n return new Set([...rootsByNode.keys()].map(find)).size\n}\n\nfunction liftedFinding(\n voters: readonly Placement[],\n parent: string,\n taxonomy: DomainTaxonomy,\n producedAt: string | undefined,\n): AnalystFinding {\n const findings = voters.map((voter) => voter.finding)\n const first = findings[0]!\n const measures = findings.map((finding) => finding.measure!) as FindingMeasure[]\n const levels = new Set(measures.map((measure) => measure.level))\n const level = levels.size === 1 ? measures[0]!.level : undefined\n const population = [...new Set(findings.flatMap((finding) => finding.scope!.population))].sort()\n const allUnits = findings.every((finding) => finding.evidence_units !== undefined)\n ? mergeEvidenceUnits(findings.flatMap((finding) => finding.evidence_units!))\n : undefined\n const confounders = [...new Set(findings.flatMap((finding) => finding.confounders ?? []))].sort()\n const analysts = new Set(findings.map((finding) => finding.analyst_id))\n const domainPath = domainPathOf(taxonomy, parent)\n const parentLayer = taxonomyLayerOf(taxonomy, parent) as FindingLayer\n return makeFinding({\n analyst_id: analysts.size === 1 ? first.analyst_id : PROMOTE_ANALYST_ID,\n area: first.area,\n claim: first.claim,\n claim_id: first.claim_id!,\n id_basis: `${first.claim_id}@${parent}`,\n subject: parent,\n severity: mostSevere(findings),\n confidence: Math.min(...findings.map((finding) => finding.confidence)),\n evidence_refs: findings.map((finding) => ({\n kind: 'finding' as const,\n uri: `finding://${finding.finding_id}`,\n })),\n layer: parentLayer,\n scope: {\n population,\n n: population.length,\n window: spanningWindow(findings),\n ...(domainPath.length > 0 && parent !== LAB_NODE_ID ? { domain_path: domainPath } : {}),\n },\n method: { kind: 'computed', name: 'promote', version: PROMOTE_VERSION },\n measure: {\n name: measures[0]!.name,\n unit: measures[0]!.unit,\n value: measures.reduce((sum, measure) => sum + measure.value, 0) / measures.length,\n interval: [\n Math.max(...measures.map((measure) => measure.interval![0])),\n Math.min(...measures.map((measure) => measure.interval![1])),\n ],\n ...(level === undefined ? {} : { level }),\n },\n ...(confounders.length > 0 ? { confounders } : {}),\n ...(allUnits ? { evidence_units: allUnits } : {}),\n rationale: `Lifted to ${parentLayer} '${parent}': ${new Set(voters.map((voter) => voter.node)).size} children carry claim '${first.claim_id}' with intervals that share [${Math.max(...measures.map((m) => m.interval![0]))}, ${Math.min(...measures.map((m) => m.interval![1]))}].`,\n metadata: {\n taxonomy_version: taxonomy.version,\n promoted_from: [...new Set(voters.map((voter) => voter.node))].sort(),\n },\n ...(producedAt === undefined ? {} : { produced_at: producedAt }),\n })\n}\n","/**\n * rollup — run findings aggregated up the ladder, with bootstrap intervals and\n * denominators, lifted only where `promote` allows.\n *\n * Run-layer findings that share a `claim_id` and a measure are pooled per play\n * into one play-layer finding. Its interval is a cluster bootstrap where each\n * cluster is a lineage root, so runs that built on each other move together\n * and four runs of one lineage yield one cluster and no interval. Those play\n * findings then go through `promote`; each finding it lifts to a problem,\n * domain node or the lab gets the pooled bootstrap over every run underneath\n * it, with its observation and cluster counts.\n */\n\nimport { clusterBootstrapMean } from '../meta-eval/cluster-bootstrap'\nimport {\n type DomainTaxonomy,\n domainPathOf,\n lowestCommonAncestor,\n taxonomyLayerOf,\n taxonomyParentOf,\n} from './domain-taxonomy'\nimport {\n lineageRoots,\n mergeEvidenceUnits,\n mostSevere,\n spanningWindow,\n UNKNOWN_LINEAGE,\n} from './finding-scope'\nimport { type PromotionHold, promote } from './promote'\nimport { type AnalystFinding, makeFinding } from './types'\n\nconst ROLLUP_ANALYST_ID = 'rollup'\nconst ROLLUP_VERSION = '1'\n\nexport interface RollupOptions {\n /** Independent agreeing children `promote` requires. Default 2. */\n k?: number\n /** Bootstrap seed; absent, the seed derives from the values, so reruns match. */\n seed?: number\n resamples?: number\n /** Interval confidence. Default 0.95. */\n confidence?: number\n produced_at?: string\n}\n\nexport interface RollupResult {\n /** Play aggregates followed by every finding promote lifted from them. */\n findings: AnalystFinding[]\n untestedAbove: PromotionHold[]\n /** Input findings rollup could not use, and why. */\n skipped: PromotionHold[]\n}\n\ninterface Observation {\n finding: AnalystFinding\n claimId: string\n run: string\n value: number\n cluster: string\n}\n\nexport function rollupFindings(\n findings: readonly AnalystFinding[],\n taxonomy: DomainTaxonomy,\n options: RollupOptions = {},\n): RollupResult {\n const confidence = options.confidence ?? 0.95\n const skipped: PromotionHold[] = []\n const skip = (finding: AnalystFinding, reason: string): void => {\n skipped.push({\n finding_id: finding.finding_id,\n claim_id: finding.claim_id ?? null,\n node: null,\n reason,\n })\n }\n const roots = lineageRoots(findings.flatMap((finding) => finding.evidence_units ?? []))\n const observations: Observation[] = []\n for (const finding of findings) {\n if (finding.layer !== 'run' || !finding.scope) continue\n if (!finding.claim_id) {\n skip(finding, 'no claim_id')\n continue\n }\n if (!finding.measure) {\n skip(finding, 'no measure to aggregate')\n continue\n }\n const run = lowestCommonAncestor(taxonomy, finding.scope.population)\n if (run === undefined || taxonomyLayerOf(taxonomy, run) !== 'run') {\n skip(finding, 'population is not one run in the taxonomy')\n continue\n }\n const units = finding.evidence_units\n const runRoots = new Set(\n units ? units.map((unit) => roots.get(unit.id) ?? UNKNOWN_LINEAGE) : [UNKNOWN_LINEAGE],\n )\n observations.push({\n finding,\n claimId: finding.claim_id,\n run,\n value: finding.measure.value,\n // A run whose units reach several roots is clustered on the first; one\n // run is one observation either way.\n cluster: [...runRoots].sort()[0]!,\n })\n }\n\n const groups = new Map<string, { play: string; members: Observation[] }>()\n for (const observation of observations) {\n const play = taxonomyParentOf(taxonomy, observation.run)!\n const key = JSON.stringify([observation.claimId, play])\n const group = groups.get(key) ?? { play, members: [] }\n group.members.push(observation)\n groups.set(key, group)\n }\n const aggregates: AnalystFinding[] = []\n for (const { play, members } of groups.values()) {\n const measure = members[0]!.finding.measure!\n if (\n members.some(\n ({ finding }) =>\n finding.measure!.name !== measure.name || finding.measure!.unit !== measure.unit,\n )\n ) {\n for (const member of members)\n skip(member.finding, `runs of play '${play}' measure different quantities`)\n continue\n }\n const pooled = pool(members, options, confidence)\n const findingsInGroup = members.map((member) => member.finding)\n const population = [...new Set(members.map((member) => member.run))].sort()\n const units = findingsInGroup.every((finding) => finding.evidence_units !== undefined)\n ? mergeEvidenceUnits(findingsInGroup.flatMap((finding) => finding.evidence_units!))\n : undefined\n const domainPath = domainPathOf(taxonomy, play)\n const first = findingsInGroup[0]!\n aggregates.push(\n makeFinding({\n analyst_id: ROLLUP_ANALYST_ID,\n area: first.area,\n claim: first.claim,\n claim_id: first.claim_id!,\n id_basis: `${first.claim_id}@${play}`,\n subject: play,\n severity: mostSevere(findingsInGroup),\n confidence: Math.min(...findingsInGroup.map((finding) => finding.confidence)),\n evidence_refs: findingsInGroup.map((finding) => ({\n kind: 'finding' as const,\n uri: `finding://${finding.finding_id}`,\n })),\n layer: 'play',\n scope: {\n population,\n n: population.length,\n window: spanningWindow(findingsInGroup),\n ...(domainPath.length > 0 ? { domain_path: domainPath } : {}),\n },\n method: { kind: 'computed', name: ROLLUP_ANALYST_ID, version: ROLLUP_VERSION },\n measure: { name: measure.name, unit: measure.unit, ...pooled.measure },\n ...(units ? { evidence_units: units } : {}),\n metadata: { denominators: pooled.denominators },\n ...(options.produced_at === undefined ? {} : { produced_at: options.produced_at }),\n }),\n )\n }\n\n const promotion = promote(aggregates, taxonomy, {\n ...(options.k === undefined ? {} : { k: options.k }),\n ...(options.produced_at === undefined ? {} : { produced_at: options.produced_at }),\n })\n const promoted = promotion.promoted.map((finding) => {\n const covered = new Set(finding.scope!.population)\n const members = observations.filter(\n (observation) => observation.claimId === finding.claim_id && covered.has(observation.run),\n )\n const pooled = pool(members, options, confidence)\n return {\n ...finding,\n measure: { name: finding.measure!.name, unit: finding.measure!.unit, ...pooled.measure },\n metadata: { ...finding.metadata, denominators: pooled.denominators },\n }\n })\n return {\n findings: [...aggregates, ...promoted],\n untestedAbove: promotion.untestedAbove,\n skipped: [...skipped, ...promotion.unplaced],\n }\n}\n\n/**\n * Cluster bootstrap of the run values. With one cluster there is no spread\n * between independent sources, so the measure carries no interval and cannot\n * vote in `promote`.\n */\nfunction pool(members: readonly Observation[], options: RollupOptions, confidence: number) {\n const result = clusterBootstrapMean(\n members.map((member) => ({ cluster: member.cluster, value: member.value })),\n {\n confidence,\n ...(options.seed === undefined ? {} : { seed: options.seed }),\n ...(options.resamples === undefined ? {} : { resamples: options.resamples }),\n },\n )\n return {\n measure:\n result.clusters >= 2\n ? {\n value: result.mean,\n interval: [result.low, result.high] as [number, number],\n level: confidence,\n }\n : { value: result.mean },\n denominators: { observations: result.n, independent_clusters: result.clusters },\n }\n}\n\nexport interface RollupInput {\n findings: readonly AnalystFinding[]\n taxonomy: DomainTaxonomy\n options?: RollupOptions\n}\n\n\n","/**\n * team-shape — classify how a supervision tree was organized, from a Runtime\n * spawn journal and its coordination log.\n *\n * Input rows come in either of two shapes, read by the same parser:\n * - Runtime envelopes, as `readRuntimeSupervisorRun` returns them in\n * `SupervisorRunSources.journal` and `.coordinationLog`\n * (`teamShapeInputFromSources`);\n * - the structure-only reduction under `tests/fixtures/team-shape`\n * (`extract.py`): spawn rows `{ kind, journal, id, at }`, coordination\n * rows `{ at, type, owner, toWorker?, from?, by?, delivered? }`.\n *\n * Three edge sets over the agents:\n * - E, command, parent → child. The parent is the child id minus its last\n * `:sN` segment (`R:s1:s0` is child `s0` of `R:s1`); the spawn journal has\n * no parent field. An id outside that path is an unplaced agent: its E\n * edge is not observable, and it is never read as depth 1.\n * - G, governance, receiver → child: the agent whose journal holds the\n * child's `settled` row, plus the sender of each `steer`.\n * - C, communication, sender → receiver: coordination rows that name a\n * receiver (`toWorker`). The sender is `from`/`by` when the row names an\n * agent, else the log owner's digest, which no record joins to an agent.\n * `instruction` and `delivery-attempt` rows are the queue and transport\n * stages of the steer row that follows them, so they are not counted.\n *\n * Classes, version 1, checked in order; the first the record shows wins:\n * 1. single — one agent.\n * 2. governed-swarm — E runs between peers, or a team's governor\n * changes over the run.\n * 3. fleet — one dispatcher, and governance from a non-parent\n * agent inside the team or lateral C ≥ 20%.\n * 4. partition — two or more lead subtrees with no C or G between\n * them, and no lead settles to the root.\n * 5. hive — depth ≥ 2 and at least half the root's children\n * delegate (`hive depth N`).\n * 6. star-with-sub-leads — depth ≥ 2, fewer than half delegate.\n * 7. flat-star — depth 1; qualified by root integration share.\n * The thresholds are provisional and travel in `method.version`. A check the\n * record cannot decide (an owner digest is not an agent id, so lateral C and\n * steer governance often are not) reads `not observable from this record`,\n * never `no`, and the classification moves on to the next class.\n */\n\nimport type { SupervisorRunSources } from '../supervisor-run/types'\nimport type { Analyst } from './types'\nimport { makeFinding } from './types'\n\nexport const TEAM_SHAPE_ANALYST_ID = 'team-shape'\n\nconst TEAM_SHAPE_THRESHOLDS = {\n /** Share of the root's children that delegate at or above which depth ≥ 2 is a hive. */\n hiveDelegatingShare: 0.5,\n /** Lateral share of C edges at or above which a one-dispatcher team is a fleet. */\n fleetLateralCShare: 0.2,\n /** Root share of integrating commits at or above which a flat star reads `root integrates`. */\n rootIntegrationShare: 0.5,\n} as const\n\n/** Version 1, provisional, with the thresholds it was decided at. */\nexport const TEAM_SHAPE_VERSION = `1-provisional;hive-delegating=${TEAM_SHAPE_THRESHOLDS.hiveDelegatingShare};fleet-lateral-c=${TEAM_SHAPE_THRESHOLDS.fleetLateralCShare};root-integration=${TEAM_SHAPE_THRESHOLDS.rootIntegrationShare}`\n\nexport const TEAM_SHAPE_CLASSES = [\n 'single',\n 'governed-swarm',\n 'fleet',\n 'partition',\n 'hive',\n 'star-with-sub-leads',\n 'flat-star',\n] as const\n\nexport type TeamShapeClass = (typeof TEAM_SHAPE_CLASSES)[number]\n\nexport const NOT_OBSERVABLE = 'not observable from this record'\nexport type NotObservable = typeof NOT_OBSERVABLE\nexport type TeamShapeObserved<T> = T | NotObservable\n\nexport interface TeamIntegration {\n commit: string\n /** Agent id, in the record's id space, that authored the integrating commit. */\n by: string\n}\n\nexport interface TeamShapeInput {\n /** The run the record came from, cited as the finding's evidence. */\n runRef: string\n /** Spawn journal JSONL. */\n spawnJournal: string\n /** Coordination log JSONL; null or absent when the run kept none. */\n coordinationLog?: string | null\n /** The release's integrating commits; disco derives them from commit trailers. */\n integrations?: readonly TeamIntegration[]\n}\n\nexport interface TeamShapeEdge {\n from: string\n to: string\n count: number\n}\n\nexport interface TeamShapeFeatures {\n agents: number\n /** Agents other than the root. */\n tasks: number\n /** Agents whose id is outside the root's `:sN` path; their E edge is not observable. */\n unplacedAgents: number\n depth: number\n fanOut: { root: number; max: number }\n /** Root's children that delegate ÷ root's children; null when the root has none. */\n delegatingShare: number | null\n /** Spawns after the first settlement. */\n reHires: number\n settlementsByReceiver: Record<string, number>\n steers: { sent: number; delivered: number }\n /** Coordination messages per task; null with no tasks or no coordination log. */\n messagesPerTask: number | null\n /** Lateral C edges ÷ C edges. */\n lateralCShare: TeamShapeObserved<number>\n /** G edges from a non-parent agent ÷ G edges. */\n nonParentGShare: TeamShapeObserved<number>\n /** Root-authored integrating commits ÷ integrating commits. */\n rootIntegrationShare: TeamShapeObserved<number>\n}\n\nexport interface TeamShapeCheck {\n result: 'yes' | 'no' | NotObservable\n reason: string\n}\n\nexport interface TeamShape {\n class: TeamShapeClass\n depth: number\n /** Only a flat star carries one: `root integrates`, `root does not integrate` or `integration unknown`. */\n qualifier: string | null\n /** Class in words: `hive depth 2`, `flat-star (integration unknown)`. */\n label: string\n rootId: string\n features: TeamShapeFeatures\n /** Every class's rule against this record, in check order. */\n checks: Record<TeamShapeClass, TeamShapeCheck>\n graph: { command: TeamShapeEdge[]; governance: TeamShapeEdge[]; communication: TeamShapeEdge[] }\n invalidRows: { spawn: number; coordination: number }\n window: { from: string; to: string } | null\n}\n\nexport type TeamShapeOutcome =\n | { succeeded: true; value: TeamShape }\n | { succeeded: false; error: { message: string } }\n\ninterface SpawnRow {\n kind: 'spawned' | 'settled'\n /** Agent whose journal holds the row: the last segment of the journal key. */\n owner: string\n /** The whole journal key, to find the root marker. */\n journal: string\n id: string\n at: number\n}\n\ninterface CoordinationRow {\n at: number | null\n type: string\n owner: string | null\n toWorker?: string\n from?: string\n by?: string\n delivered?: boolean\n}\n\n/** Team-shape input for a run read through a supervisor-run reader. */\nexport function teamShapeInputFromSources(\n sources: SupervisorRunSources,\n integrations?: readonly TeamIntegration[],\n): { succeeded: true; value: TeamShapeInput } | { succeeded: false; error: { message: string } } {\n if (sources.journal === null) {\n return {\n succeeded: false,\n error: { message: sources.journalMissingReason ?? `no spawn journal for ${sources.runRef}` },\n }\n }\n return {\n succeeded: true,\n value: {\n runRef: sources.runRef,\n spawnJournal: sources.journal,\n coordinationLog: sources.coordinationLog ?? null,\n ...(integrations === undefined ? {} : { integrations }),\n },\n }\n}\n\nexport function classifyTeamShape(input: TeamShapeInput): TeamShapeOutcome {\n const spawnLog = parseSpawnRows(input.spawnJournal)\n const coordination =\n typeof input.coordinationLog === 'string' ? parseCoordinationRows(input.coordinationLog) : null\n const spawnedAt = new Map<string, number>()\n for (const row of spawnLog.rows) {\n if (row.kind !== 'spawned') continue\n spawnedAt.set(row.id, Math.min(row.at, spawnedAt.get(row.id) ?? Number.POSITIVE_INFINITY))\n }\n const rootIds = [\n ...new Set(\n spawnLog.rows\n .filter((row) => row.kind === 'spawned' && row.journal === row.id)\n .map((r) => r.id),\n ),\n ]\n if (rootIds.length !== 1) {\n return {\n succeeded: false,\n error: {\n message: `spawn journal for ${input.runRef} has ${rootIds.length} root markers; team-shape needs exactly one`,\n },\n }\n }\n const rootId = rootIds[0]!\n const agents = new Set(spawnedAt.keys())\n\n // E: the id path. A parent outside the record leaves the agent unplaced.\n const parentOf = new Map<string, string>()\n let unplacedAgents = 0\n for (const id of agents) {\n if (id === rootId) continue\n const parent = pathParent(id)\n if (parent !== null && agents.has(parent) && id.startsWith(`${rootId}:`)) {\n parentOf.set(id, parent)\n } else unplacedAgents += 1\n }\n const children = new Map<string, string[]>()\n const command = new Map<string, TeamShapeEdge>()\n for (const [child, parent] of parentOf) {\n children.set(parent, [...(children.get(parent) ?? []), child])\n addEdge(command, parent, child)\n }\n const depthOf = (id: string): number => {\n let hops = 0\n for (let at = parentOf.get(id); at !== undefined; at = parentOf.get(at)) hops += 1\n return hops\n }\n const depth = Math.max(0, ...[...parentOf.keys()].map(depthOf))\n const rootChildren = children.get(rootId) ?? []\n const leads = rootChildren.filter((child) => (children.get(child)?.length ?? 0) > 0)\n const delegatingShare = rootChildren.length === 0 ? null : leads.length / rootChildren.length\n const subtreeOf = (id: string): string | null => {\n let at: string | undefined = id\n while (at !== undefined && parentOf.get(at) !== rootId) at = parentOf.get(at)\n return at ?? null\n }\n\n // A spawn row in a journal that belongs to neither the parent nor the child itself.\n let peerSpawns = 0\n for (const row of spawnLog.rows) {\n if (row.kind !== 'spawned' || row.id === rootId) continue\n if (row.owner !== row.id && row.owner !== parentOf.get(row.id)) peerSpawns += 1\n }\n\n // G: settlements, receiver → child.\n const governance = new Map<string, TeamShapeEdge>()\n const settlementsByReceiver: Record<string, number> = {}\n const governorsByParent = new Map<string, { agents: Set<string>; digests: Set<string> }>()\n const governorsOf = (child: string) => {\n const parent = parentOf.get(child) ?? `unplaced:${child}`\n const entry = governorsByParent.get(parent) ?? { agents: new Set(), digests: new Set() }\n governorsByParent.set(parent, entry)\n return entry\n }\n let gResolved = 0\n let gUnresolved = 0\n let gNonParent = 0\n let firstSettlement = Number.POSITIVE_INFINITY\n for (const row of spawnLog.rows) {\n if (row.kind !== 'settled' || row.owner === row.id) continue\n firstSettlement = Math.min(firstSettlement, row.at)\n settlementsByReceiver[row.owner] = (settlementsByReceiver[row.owner] ?? 0) + 1\n addEdge(governance, row.owner, row.id)\n governorsOf(row.id).agents.add(row.owner)\n gResolved += 1\n if (parentOf.get(row.id) !== row.owner) gNonParent += 1\n }\n const reHires = [...spawnedAt.entries()].filter(\n ([id, at]) => id !== rootId && at > firstSettlement,\n ).length\n\n // C, and G from steers.\n const communication = new Map<string, TeamShapeEdge>()\n let messages = 0\n let cResolved = 0\n let cUnresolved = 0\n let cLateral = 0\n let cCrossSubtree = 0\n let gCrossSubtree = 0\n const steers = { sent: 0, delivered: 0 }\n const isAgent = (value: string | undefined): value is string =>\n value !== undefined && agents.has(value)\n for (const row of coordination?.rows ?? []) {\n if (row.type === 'instruction' || row.type === 'delivery-attempt') continue\n if (row.toWorker === undefined && row.from === undefined && row.by === undefined) continue\n messages += 1\n if (row.type === 'steer') {\n steers.sent += 1\n if (row.delivered === true) steers.delivered += 1\n }\n // A refused steer reached nobody: it is counted as sent, not as an edge.\n if (!isAgent(row.toWorker) || row.delivered === false) continue\n const receiver = row.toWorker\n const agentSender = [row.from, row.by].find(isAgent)\n const sender = agentSender ?? (row.owner === null ? null : `owner:${row.owner}`)\n if (sender === null) continue\n addEdge(communication, sender, receiver)\n if (agentSender === undefined) cUnresolved += 1\n else {\n cResolved += 1\n const parent = parentOf.get(receiver)\n if (parent !== undefined && parent === parentOf.get(agentSender)) cLateral += 1\n if (crosses(subtreeOf(agentSender), subtreeOf(receiver))) cCrossSubtree += 1\n }\n if (row.type === 'steer') {\n addEdge(governance, sender, receiver)\n if (agentSender === undefined) {\n gUnresolved += 1\n governorsOf(receiver).digests.add(sender)\n } else {\n gResolved += 1\n governorsOf(receiver).agents.add(agentSender)\n if (parentOf.get(receiver) !== agentSender) gNonParent += 1\n if (crosses(subtreeOf(agentSender), subtreeOf(receiver))) gCrossSubtree += 1\n }\n }\n }\n for (const [child, receiver] of spawnLog.rows\n .filter((row) => row.kind === 'settled' && row.owner !== row.id)\n .map((row) => [row.id, row.owner] as const)) {\n if (crosses(subtreeOf(receiver), subtreeOf(child))) gCrossSubtree += 1\n }\n\n const cTotal = cResolved + cUnresolved\n const gTotal = gResolved + gUnresolved\n const lateralCShare: TeamShapeObserved<number> =\n coordination === null || cTotal === 0 || cUnresolved > 0 ? NOT_OBSERVABLE : cLateral / cTotal\n const nonParentGShare: TeamShapeObserved<number> =\n gTotal === 0 || gUnresolved > 0 ? NOT_OBSERVABLE : gNonParent / gTotal\n const integrations = input.integrations ?? []\n const rootIntegrationShare: TeamShapeObserved<number> =\n integrations.length === 0\n ? NOT_OBSERVABLE\n : integrations.filter((row) => row.by === rootId).length / integrations.length\n\n const features: TeamShapeFeatures = {\n agents: agents.size,\n tasks: agents.size - 1,\n unplacedAgents,\n depth,\n fanOut: {\n root: rootChildren.length,\n max: Math.max(0, ...[...children.values()].map((c) => c.length)),\n },\n delegatingShare,\n reHires,\n settlementsByReceiver,\n steers,\n messagesPerTask: coordination === null || agents.size < 2 ? null : messages / (agents.size - 1),\n lateralCShare,\n nonParentGShare,\n rootIntegrationShare,\n }\n\n const checks = {} as Record<TeamShapeClass, TeamShapeCheck>\n checks.single = verdict(agents.size === 1, `${agents.size} agents`)\n\n const rotating = [...governorsByParent.entries()].find(([, g]) => g.agents.size > 1)\n const digestTeams = [...governorsByParent.values()].filter((g) => g.digests.size > 1).length\n checks['governed-swarm'] =\n peerSpawns > 0\n ? { result: 'yes', reason: `${peerSpawns} spawns recorded by a peer, not the parent` }\n : rotating !== undefined\n ? {\n result: 'yes',\n reason: `children of ${rotating[0]} are governed by ${[...rotating[1].agents].join(', ')}`,\n }\n : digestTeams > 0\n ? {\n result: NOT_OBSERVABLE,\n reason: `${digestTeams} teams were steered by more than one owner digest; a digest is not an agent id, so a rotating governor cannot be told from the operator`,\n }\n : {\n result: 'no',\n reason: 'every E edge runs parent to child and no team changed governor',\n }\n\n const dispatchers = [...children.keys()]\n if (dispatchers.length !== 1 || unplacedAgents > 0) {\n checks.fleet = {\n result: unplacedAgents > 0 && dispatchers.length <= 1 ? NOT_OBSERVABLE : 'no',\n reason:\n unplacedAgents > 0 && dispatchers.length <= 1\n ? `${unplacedAgents} unplaced agents hide who dispatched their work`\n : `${dispatchers.length} agents dispatch work`,\n }\n } else if (gNonParent > 0) {\n checks.fleet = { result: 'yes', reason: `${gNonParent} G edges come from a non-parent agent` }\n } else if (cLateral / Math.max(cTotal, 1) >= TEAM_SHAPE_THRESHOLDS.fleetLateralCShare) {\n checks.fleet = { result: 'yes', reason: `lateral C ${cLateral} of ${cTotal}` }\n } else if (gUnresolved > 0 || lateralCShare === NOT_OBSERVABLE) {\n checks.fleet = {\n result: NOT_OBSERVABLE,\n reason: `one dispatcher; ${gUnresolved} steer G and ${cUnresolved} C edges are sent from owner digests that no record joins to an agent${coordination === null ? ', and the run has no coordination log' : ''}`,\n }\n } else {\n checks.fleet = verdict(\n false,\n `one dispatcher, no non-parent G, lateral C ${cLateral} of ${cTotal}`,\n )\n }\n\n const rootSettledByLeads = spawnLog.rows.filter(\n (row) => row.kind === 'settled' && row.owner === rootId && leads.includes(row.id),\n ).length\n if (leads.length < 2 || rootSettledByLeads > 0 || gCrossSubtree > 0 || cCrossSubtree > 0) {\n checks.partition = verdict(\n false,\n `${leads.length} lead subtrees, ${rootSettledByLeads} lead settlements to the root, ${gCrossSubtree + cCrossSubtree} edges between subtrees`,\n )\n } else if (gUnresolved > 0 || cUnresolved > 0 || coordination === null) {\n checks.partition = {\n result: NOT_OBSERVABLE,\n reason: `${leads.length} lead subtrees and no lead settles to the root, but edges sent from owner digests cannot be placed in a subtree`,\n }\n } else {\n checks.partition = verdict(true, `${leads.length} lead subtrees with no C or G between them`)\n }\n\n const delegating = `${leads.length} of ${rootChildren.length} root children delegate`\n const hive = depth >= 2 && (delegatingShare ?? 0) >= TEAM_SHAPE_THRESHOLDS.hiveDelegatingShare\n checks.hive = verdict(hive, `depth ${depth}; ${delegating}`)\n checks['star-with-sub-leads'] = verdict(depth >= 2 && !hive, `depth ${depth}; ${delegating}`)\n checks['flat-star'] = verdict(depth === 1, `depth ${depth}`)\n\n const shapeClass = TEAM_SHAPE_CLASSES.find((name) => checks[name].result === 'yes')\n if (shapeClass === undefined) {\n return {\n succeeded: false,\n error: { message: `no team-shape class matches ${input.runRef} (depth ${depth})` },\n }\n }\n const qualifier =\n shapeClass !== 'flat-star'\n ? null\n : rootIntegrationShare === NOT_OBSERVABLE\n ? 'integration unknown'\n : rootIntegrationShare >= TEAM_SHAPE_THRESHOLDS.rootIntegrationShare\n ? 'root integrates'\n : 'root does not integrate'\n const label =\n shapeClass === 'hive'\n ? `hive depth ${depth}`\n : qualifier === null\n ? shapeClass\n : `${shapeClass} (${qualifier})`\n\n const times = [\n ...spawnLog.rows.map((row) => row.at),\n ...(coordination?.rows ?? []).flatMap((row) => (row.at === null ? [] : [row.at])),\n ]\n return {\n succeeded: true,\n value: {\n class: shapeClass,\n depth,\n qualifier,\n label,\n rootId,\n features,\n checks,\n graph: {\n command: [...command.values()],\n governance: [...governance.values()],\n communication: [...communication.values()],\n },\n invalidRows: { spawn: spawnLog.invalid, coordination: coordination?.invalid ?? 0 },\n window:\n times.length === 0\n ? null\n : {\n from: new Date(Math.min(...times)).toISOString(),\n to: new Date(Math.max(...times)).toISOString(),\n },\n },\n }\n}\n\nfunction verdict(holds: boolean, reason: string): TeamShapeCheck {\n return { result: holds ? 'yes' : 'no', reason }\n}\n\nfunction crosses(a: string | null, b: string | null): boolean {\n return a !== null && b !== null && a !== b\n}\n\nfunction pathParent(id: string): string | null {\n const match = /^(.+):s\\d+$/.exec(id)\n return match ? match[1]! : null\n}\n\nfunction addEdge(edges: Map<string, TeamShapeEdge>, from: string, to: string): void {\n const key = JSON.stringify([from, to])\n const edge = edges.get(key)\n if (edge) edge.count += 1\n else edges.set(key, { from, to, count: 1 })\n}\n\nfunction jsonLines(text: string): Array<Record<string, unknown> | null> {\n return text\n .split('\\n')\n .filter((line) => line.trim())\n .map((line) => {\n try {\n const value: unknown = JSON.parse(line)\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null\n } catch {\n return null\n }\n })\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null\n}\n\nfunction epochMs(value: unknown): number | null {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string') {\n const ms = Date.parse(value)\n return Number.isNaN(ms) ? null : ms\n }\n return null\n}\n\n/**\n * Spawned and settled rows from a Runtime envelope (`{ root, event }`) or a\n * reduced row (`{ kind, journal, id, at }`). Other Runtime event kinds are\n * read and skipped; a spawned or settled row without an id, journal or time\n * is invalid.\n */\nfunction parseSpawnRows(text: string): { rows: SpawnRow[]; invalid: number } {\n const rows: SpawnRow[] = []\n let invalid = 0\n for (const line of jsonLines(text)) {\n if (line === null) {\n invalid += 1\n continue\n }\n const event = asRecord(line.event) ?? line\n const journal = event === line ? line.journal : line.root\n const { kind, id } = event\n if (kind !== 'spawned' && kind !== 'settled') continue\n const at = epochMs(event.at)\n if (typeof id !== 'string' || typeof journal !== 'string' || at === null) {\n invalid += 1\n continue\n }\n rows.push({ kind, journal, owner: journal.slice(journal.lastIndexOf('/') + 1), id, at })\n }\n return { rows, invalid }\n}\n\n/**\n * Coordination rows from a Runtime record (`{ at, ownerId, event: { type,\n * <body> } }`, endpoints inside the event's one object-valued field) or a\n * reduced row (`{ at, type, owner, ... }`).\n */\nfunction parseCoordinationRows(text: string): { rows: CoordinationRow[]; invalid: number } {\n const rows: CoordinationRow[] = []\n let invalid = 0\n for (const line of jsonLines(text)) {\n const event = line === null ? null : (asRecord(line.event) ?? line)\n if (line === null || event === null || typeof event.type !== 'string') {\n invalid += 1\n continue\n }\n const body =\n event === line\n ? line\n : (Object.entries(event)\n .filter(([key]) => key !== 'type')\n .map(([, value]) => asRecord(value))\n .find((value) => value !== null) ?? {})\n const owner = typeof line.owner === 'string' ? line.owner : line.ownerId\n const row: CoordinationRow = {\n at: epochMs(line.at),\n type: event.type,\n owner: typeof owner === 'string' && owner ? owner : null,\n }\n for (const key of ['toWorker', 'from', 'by'] as const) {\n const value = body[key]\n if (typeof value === 'string') row[key] = value\n }\n const delivered = body.delivered ?? line.delivered\n if (typeof delivered === 'boolean') row.delivered = delivered\n rows.push(row)\n }\n return { rows, invalid }\n}\n\n/**\n * The team-shape analyst: one `team`-layer finding per run naming its class,\n * with the features and every class check in metadata. A record with no\n * timestamps fails the analyst instead of emitting a shape it did not measure.\n */\nexport function teamShapeAnalyst(): Analyst<TeamShapeInput> {\n return {\n id: TEAM_SHAPE_ANALYST_ID,\n description:\n 'Classifies a supervision tree as single, governed swarm, fleet, partition, hive, star with sub-leads or flat star.',\n inputKind: 'custom',\n cost: { kind: 'deterministic' },\n version: TEAM_SHAPE_VERSION,\n async analyze(input) {\n const outcome = classifyTeamShape(input)\n if (!outcome.succeeded) throw new Error(`team-shape: ${outcome.error.message}`)\n const shape = outcome.value\n if (shape.window === null) {\n throw new Error(`team-shape: record for ${input.runRef} carries no event timestamps`)\n }\n return [\n makeFinding({\n analyst_id: TEAM_SHAPE_ANALYST_ID,\n area: 'team-shape',\n severity: 'info',\n confidence: 1,\n subject: shape.rootId,\n claim: `Team shape is ${shape.label}`,\n claim_id: `team-shape:${shape.class}`,\n evidence_refs: [{ kind: 'artifact', uri: input.runRef }],\n layer: 'team',\n scope: { population: [input.runRef], n: 1, window: shape.window },\n method: { kind: 'computed', name: TEAM_SHAPE_ANALYST_ID, version: TEAM_SHAPE_VERSION },\n metadata: {\n class: shape.class,\n depth: shape.depth,\n qualifier: shape.qualifier,\n features: shape.features,\n checks: shape.checks,\n edges: {\n command: shape.graph.command.length,\n governance: shape.graph.governance.length,\n communication: shape.graph.communication.length,\n },\n invalid_rows: shape.invalidRows,\n },\n }),\n ]\n },\n }\n}\n","/**\n * Many questions over one trace store, concurrently, under one cost ledger, with an independent\n * verifier for every finding.\n *\n * `traces ask` answered questions this way for people. A continuation panel (agent-runtime,\n * discovery `docs/38-one-loop-and-continuation.md`, section 5) asks dozens to hundreds of atomic\n * questions of a director's own trace every time the outside check fails, so the runner lives here,\n * beside `runTraceAnalyst`, where both callers reach one implementation.\n *\n * Each question is one `runTraceAnalyst` call, which already refuses a finding with fewer distinct\n * citations than required or with a citation the store cannot resolve. What this module adds:\n *\n * - a worker pool: at most `concurrency` investigations at once, and one failed question never\n * stops the others; its failure is its answer;\n * - one shared `CostLedger`, so a single ceiling bounds every question and every verifier;\n * - an independent verifier per admitted finding, shown only the spans the finding cites. Analysts\n * misattribute often: the best method in Who&When found the failing step 14.2% of the time. A\n * finding a verifier reading only its own evidence does not support never reaches a caller as\n * verified.\n */\n\nimport type { CostLedgerHandle } from '../cost-ledger'\nimport type { TraceAnalysisStore } from '../trace-analyst/store'\nimport { defineTraceAnalyst } from './define'\nimport type { TraceAnalysisEngine, TraceAnalystLimits } from './engine'\nimport { parseTraceSpanEvidenceUri, type RawAnalystFinding } from './finding-signature'\nimport { runTraceAnalyst } from './kind-factory'\n\n/** One question to ask of the store. */\nexport interface TraceQuestionSpec {\n /** Stable id: letters, digits, dot, underscore, hyphen. */\n readonly id: string\n readonly question: string\n /** Guidance for this question only, after the shared rules. */\n readonly instructions?: string\n}\n\nexport interface AskTraceQuestionsOptions {\n readonly questions: readonly TraceQuestionSpec[]\n readonly store: TraceAnalysisStore\n readonly engine: TraceAnalysisEngine\n /** Every question and verifier charges this ledger; its ceiling bounds the whole call. */\n readonly costLedger: CostLedgerHandle\n /** Stable id for cost attribution and logs. */\n readonly runId: string\n /** Material every question receives before its first model call, such as the check's verdict. */\n readonly context?: string\n /** Investigations running at once. Default 4. */\n readonly concurrency?: number\n /** Distinct citations a finding needs. Default 2. */\n readonly minimumEvidenceCitations?: number\n /** Run the independent verifier on every admitted finding. Default true. */\n readonly verify?: boolean\n readonly limits?: Partial<TraceAnalystLimits>\n readonly signal?: AbortSignal\n readonly log?: (message: string, fields?: Record<string, unknown>) => void\n}\n\n/** A finding and what the verifier, shown only its cited spans, concluded. */\nexport interface VerifiedTraceFinding {\n readonly finding: RawAnalystFinding\n /** The finding's trace citations, as `trace://` URIs. */\n readonly citations: readonly string[]\n /** `true` supported, `false` not supported, `null` when verification was off or failed. */\n readonly verified: boolean | null\n /** The verifier's own words, when it answered. */\n readonly verifierAnswer?: string\n}\n\nexport interface TraceQuestionOutcome {\n readonly id: string\n readonly question: string\n readonly status: 'answered' | 'failed'\n readonly failure?: string\n /** The engine's prose answer, verbatim; `null` when it returned none. */\n readonly answer: string | null\n readonly findings: readonly VerifiedTraceFinding[]\n /** `null` when the engine failed before reporting. */\n readonly modelCalls: number | null\n readonly toolCalls: number | null\n}\n\nconst QUESTION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u\nconst DEFINITION_VERSION = '1.0.0'\n\nconst QUESTION_RULES = [\n 'Answer QUESTION only from trace tool results retrieved in this run.',\n 'Cite each fact as trace://<trace_id>/span/<span_id>, and quote the span in the excerpt.',\n 'If the trace does not record a fact, say \"not in trace\". Never infer a trace fact from the question.',\n].join('\\n')\n\nconst VERIFIER_RULES = [\n 'You check one CLAIM against the spans it cites, and nothing else.',\n 'Read each cited span with viewSpans. No other trace is readable.',\n 'First line: SUPPORTED if the spans themselves establish the claim, otherwise NOT SUPPORTED.',\n 'Second line: one sentence naming the span that decides it.',\n 'Return no findings.',\n].join('\\n')\n\n/**\n * Ask every question, then verify every admitted finding. Never throws for a failed question or\n * verifier: each failure is recorded on its outcome. Throws before any model call for a malformed\n * question list or options.\n */\nexport async function askTraceQuestions(\n opts: AskTraceQuestionsOptions,\n): Promise<TraceQuestionOutcome[]> {\n const concurrency = opts.concurrency ?? 4\n if (!Number.isSafeInteger(concurrency) || concurrency < 1) {\n throw new RangeError('askTraceQuestions: concurrency must be an integer >= 1')\n }\n const minimum = opts.minimumEvidenceCitations ?? 2\n if (!Number.isSafeInteger(minimum) || minimum < 1) {\n throw new RangeError('askTraceQuestions: minimumEvidenceCitations must be an integer >= 1')\n }\n const seen = new Set<string>()\n for (const question of opts.questions) {\n if (!QUESTION_ID.test(question.id)) {\n throw new TypeError(\n `askTraceQuestions: question id ${JSON.stringify(question.id)} is malformed`,\n )\n }\n if (seen.has(question.id)) {\n throw new TypeError(`askTraceQuestions: duplicate question id ${JSON.stringify(question.id)}`)\n }\n seen.add(question.id)\n if (question.question.trim() === '') {\n throw new TypeError(`askTraceQuestions: question ${question.id} is empty`)\n }\n }\n\n const askOne = async (question: TraceQuestionSpec): Promise<TraceQuestionOutcome> => {\n if (opts.signal?.aborted) {\n return failed(question, 'the run was aborted before the question started')\n }\n let completed: Awaited<ReturnType<typeof runTraceAnalyst>>\n try {\n completed = await runTraceAnalyst({\n definition: defineTraceAnalyst({\n id: `question.${question.id}`,\n description: `trace question ${question.id}`,\n area: 'question',\n version: DEFINITION_VERSION,\n question: question.question.trim(),\n instructions: [QUESTION_RULES, question.instructions?.trim() ?? '']\n .filter(Boolean)\n .join('\\n\\n'),\n toolGroup: 'all',\n minimumEvidenceCitations: minimum,\n ...(opts.context ? { prepareContext: () => opts.context } : {}),\n ...(opts.limits ? { limits: opts.limits } : {}),\n }),\n engine: opts.engine,\n store: opts.store,\n context: {\n runId: opts.runId,\n correlationId: `${opts.runId}:${question.id}`,\n costLedger: opts.costLedger,\n costPhase: 'trace-question',\n ...(opts.signal ? { signal: opts.signal } : {}),\n ...(opts.log ? { log: opts.log } : {}),\n },\n })\n } catch (error) {\n return failed(question, errorText(error))\n }\n const findings: VerifiedTraceFinding[] = []\n for (const [index, finding] of completed.findings.entries()) {\n const citations = finding.evidence\n .map((citation) => citation.uri.trim())\n .filter((uri) => parseTraceSpanEvidenceUri(uri) !== null)\n findings.push(\n opts.verify === false\n ? { finding, citations, verified: null }\n : await verifyFinding(opts, `${question.id}.v${index + 1}`, finding, citations),\n )\n }\n const answer = completed.answer.trim() === '' ? null : completed.answer\n return {\n id: question.id,\n question: question.question,\n status: 'answered',\n answer,\n findings,\n modelCalls: completed.modelCalls,\n toolCalls: completed.toolCalls,\n }\n }\n\n // A pool, not Promise.all: at most `concurrency` engines exist at once.\n const outcomes = new Array<TraceQuestionOutcome>(opts.questions.length)\n let next = 0\n await Promise.all(\n Array.from({ length: Math.min(concurrency, opts.questions.length) }, async () => {\n while (next < opts.questions.length) {\n const index = next\n next += 1\n const question = opts.questions[index] as TraceQuestionSpec\n outcomes[index] = await askOne(question)\n }\n }),\n )\n return outcomes\n}\n\n/** The verifier reads only the spans the finding cites, through a store that holds nothing else. */\nasync function verifyFinding(\n opts: AskTraceQuestionsOptions,\n id: string,\n finding: RawAnalystFinding,\n citations: readonly string[],\n): Promise<VerifiedTraceFinding> {\n const allowed = new Map<string, Set<string>>()\n for (const uri of citations) {\n const location = parseTraceSpanEvidenceUri(uri)\n if (location === null) continue\n const spans = allowed.get(location.traceId) ?? new Set<string>()\n spans.add(location.spanId)\n allowed.set(location.traceId, spans)\n }\n if (allowed.size === 0) return { finding, citations, verified: false }\n try {\n const verdict = await runTraceAnalyst({\n definition: defineTraceAnalyst({\n id: `verify.${id}`,\n description: `independent check of finding ${id}`,\n area: 'question',\n version: DEFINITION_VERSION,\n question: `CLAIM: ${finding.claim}\\nCITED SPANS: ${citations.join(', ')}`,\n instructions: VERIFIER_RULES,\n toolGroup: 'targeted',\n ...(opts.limits ? { limits: opts.limits } : {}),\n }),\n engine: opts.engine,\n store: citedSpansOnly(opts.store, allowed),\n context: {\n runId: opts.runId,\n correlationId: `${opts.runId}:verify:${id}`,\n costLedger: opts.costLedger,\n costPhase: 'trace-question-verifier',\n ...(opts.signal ? { signal: opts.signal } : {}),\n ...(opts.log ? { log: opts.log } : {}),\n },\n })\n const first = verdict.answer.trim().split('\\n')[0]?.trim().toUpperCase() ?? ''\n return {\n finding,\n citations,\n verified: first.startsWith('SUPPORTED'),\n verifierAnswer: verdict.answer.trim(),\n }\n } catch (error) {\n opts.log?.('verifier failed', { finding: id, error: errorText(error) })\n return { finding, citations, verified: null }\n }\n}\n\n/**\n * A store that exposes exactly the cited spans. Discovery and whole-trace reads refuse, so the\n * verifier cannot go looking for other support; the underlying store's bounds still apply.\n */\nfunction citedSpansOnly(\n store: TraceAnalysisStore,\n allowed: ReadonlyMap<string, ReadonlySet<string>>,\n): TraceAnalysisStore {\n const refuse = (what: string) => async (): Promise<never> => {\n throw new Error(`${what} is not available to a verifier: read the cited spans with viewSpans`)\n }\n return {\n hasTrace: async (traceId) => allowed.has(traceId),\n hasSpans: async (input, context) => {\n const spans = allowed.get(input.trace_id)\n if (spans === undefined) return []\n return store.hasSpans(\n { trace_id: input.trace_id, span_ids: input.span_ids.filter((span) => spans.has(span)) },\n context,\n )\n },\n getOverview: refuse('getOverview'),\n queryTraces: refuse('queryTraces'),\n countTraces: refuse('countTraces'),\n viewTrace: refuse('viewTrace'),\n viewSpans: async (input, context) => {\n const spans = allowed.get(input.trace_id)\n const wanted = input.span_ids.filter((span) => spans?.has(span) === true)\n if (wanted.length === 0) {\n throw new Error('viewSpans: only the cited spans are readable')\n }\n return store.viewSpans({ ...input, span_ids: wanted }, context)\n },\n searchTrace: refuse('searchTrace'),\n searchSpan: async (input, context) => {\n if (allowed.get(input.trace_id)?.has(input.span_id) !== true) {\n throw new Error('searchSpan: only the cited spans are readable')\n }\n return store.searchSpan(input, context)\n },\n }\n}\n\nfunction failed(question: TraceQuestionSpec, failure: string): TraceQuestionOutcome {\n return {\n id: question.id,\n question: question.question,\n status: 'failed',\n failure,\n answer: null,\n findings: [],\n modelCalls: null,\n toolCalls: null,\n }\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? `${error.name}: ${error.message}` : String(error)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAgB,YACd,YACA,YAC0C;CA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