@tangle-network/agent-eval 0.220.1 → 0.221.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/adapters/http.d.ts +2 -2
  3. package/dist/{agent-profile-D01Io2Xw.d.ts → agent-profile-Bc7ADJY4.d.ts} +2 -2
  4. package/dist/{agent-profile-D01Io2Xw.d.ts.map → agent-profile-Bc7ADJY4.d.ts.map} +1 -1
  5. package/dist/analyst/index.d.ts +77 -78
  6. package/dist/analyst/index.d.ts.map +1 -1
  7. package/dist/analyst/index.js +204 -25
  8. package/dist/analyst/index.js.map +1 -1
  9. package/dist/{analyze-runs-DqPJaJ4X.js → analyze-runs-CHmsykNJ.js} +4 -4
  10. package/dist/{analyze-runs-DqPJaJ4X.js.map → analyze-runs-CHmsykNJ.js.map} +1 -1
  11. package/dist/{analyze-runs-BWAHBDAw.d.ts → analyze-runs-D7In4c3z.d.ts} +2 -2
  12. package/dist/{analyze-runs-BWAHBDAw.d.ts.map → analyze-runs-D7In4c3z.d.ts.map} +1 -1
  13. package/dist/{benchmark-command-BzmMTnvC.js → benchmark-command-8XQfpUK3.js} +13 -11
  14. package/dist/benchmark-command-8XQfpUK3.js.map +1 -0
  15. package/dist/benchmarks/index.d.ts +4 -4
  16. package/dist/benchmarks/index.js +3 -3
  17. package/dist/calibration-CTwxpJ-t.js +197 -0
  18. package/dist/calibration-CTwxpJ-t.js.map +1 -0
  19. package/dist/campaign/index.d.ts +6 -6
  20. package/dist/campaign/index.js +5 -5
  21. package/dist/{campaign-BVPC6ODQ.js → campaign-Bt6rbWIU.js} +9 -8
  22. package/dist/{campaign-BVPC6ODQ.js.map → campaign-Bt6rbWIU.js.map} +1 -1
  23. package/dist/cli.js +2 -2
  24. package/dist/{completion-verifier-Cigap8CG.js → completion-verifier-YwoeujPl.js} +2 -2
  25. package/dist/{completion-verifier-Cigap8CG.js.map → completion-verifier-YwoeujPl.js.map} +1 -1
  26. package/dist/contract/index.d.ts +10 -10
  27. package/dist/contract/index.js +7 -7
  28. package/dist/decision-point-Co3u3W8k.js +831 -0
  29. package/dist/decision-point-Co3u3W8k.js.map +1 -0
  30. package/dist/default-registry-BMHqNR6_.d.ts +257 -0
  31. package/dist/default-registry-BMHqNR6_.d.ts.map +1 -0
  32. package/dist/{default-registry-BrKmT01n.js → default-registry-BbFCkqvB.js} +608 -15
  33. package/dist/default-registry-BbFCkqvB.js.map +1 -0
  34. package/dist/{define-agent-eval-C2nFhHPu.d.ts → define-agent-eval-Bsoi2GUV.d.ts} +7 -7
  35. package/dist/{define-agent-eval-C2nFhHPu.d.ts.map → define-agent-eval-Bsoi2GUV.d.ts.map} +1 -1
  36. package/dist/{define-agent-eval-UQY3VbJ2.js → define-agent-eval-CJhECJNL.js} +4 -4
  37. package/dist/{define-agent-eval-UQY3VbJ2.js.map → define-agent-eval-CJhECJNL.js.map} +1 -1
  38. package/dist/diagnosis/index.d.ts +2 -2
  39. package/dist/diagnosis/index.js +1 -1
  40. package/dist/{dspy-rlm-engine-Bn_Mt_LW.js → dspy-rlm-engine-BTy7u0jQ.js} +3 -3
  41. package/dist/{dspy-rlm-engine-Bn_Mt_LW.js.map → dspy-rlm-engine-BTy7u0jQ.js.map} +1 -1
  42. package/dist/{engine-BpGGw6cd.d.ts → engine-BF95CWzH.d.ts} +2 -2
  43. package/dist/{engine-BpGGw6cd.d.ts.map → engine-BF95CWzH.d.ts.map} +1 -1
  44. package/dist/{eval-campaign-BUMIxKTE.js → eval-campaign-DoX5vz3E.js} +2 -2
  45. package/dist/{eval-campaign-BUMIxKTE.js.map → eval-campaign-DoX5vz3E.js.map} +1 -1
  46. package/dist/{evaluation-CBdQt_kr.d.ts → evaluation-D1PGzkPR.d.ts} +3 -3
  47. package/dist/{evaluation-CBdQt_kr.d.ts.map → evaluation-D1PGzkPR.d.ts.map} +1 -1
  48. package/dist/evaluation-wdGyZ7jV.js +147 -0
  49. package/dist/evaluation-wdGyZ7jV.js.map +1 -0
  50. package/dist/evaluation.d.ts +1 -1
  51. package/dist/evaluation.js +1 -136
  52. package/dist/{exact-types-BYFmYq44.d.ts → exact-types-CVn1QxFO.d.ts} +2 -2
  53. package/dist/{exact-types-BYFmYq44.d.ts.map → exact-types-CVn1QxFO.d.ts.map} +1 -1
  54. package/dist/experiment/index.d.ts +3 -3
  55. package/dist/experiment/index.js +2 -2
  56. package/dist/{external-optimizer-process-wOLfzsCC.js → external-optimizer-process-E5yY2SYS.js} +2 -2
  57. package/dist/{external-optimizer-process-wOLfzsCC.js.map → external-optimizer-process-E5yY2SYS.js.map} +1 -1
  58. package/dist/{external-optimizer-subprocess-D670Oxf2.js → external-optimizer-subprocess-DA02c_L6.js} +12 -19
  59. package/dist/{external-optimizer-subprocess-D670Oxf2.js.map → external-optimizer-subprocess-DA02c_L6.js.map} +1 -1
  60. package/dist/{feedback-trajectory-DhB9WzYg.d.ts → feedback-trajectory-BZhVCWuz.d.ts} +3 -3
  61. package/dist/{feedback-trajectory-DhB9WzYg.d.ts.map → feedback-trajectory-BZhVCWuz.d.ts.map} +1 -1
  62. package/dist/finding-composition-8n0fFgVI.js +131 -0
  63. package/dist/finding-composition-8n0fFgVI.js.map +1 -0
  64. package/dist/{findings-store-CvNo712L.js → findings-store-DRiFdoid.js} +4 -4
  65. package/dist/{findings-store-CvNo712L.js.map → findings-store-DRiFdoid.js.map} +1 -1
  66. package/dist/{index-CVFStrQD.d.ts → index-BJZ7s-sv.d.ts} +7 -58
  67. package/dist/index-BJZ7s-sv.d.ts.map +1 -0
  68. package/dist/{index-Q6DvdcwI.d.ts → index-BvX3CFNS.d.ts} +6 -6
  69. package/dist/{index-Q6DvdcwI.d.ts.map → index-BvX3CFNS.d.ts.map} +1 -1
  70. package/dist/index-DWd1gUwR.d.ts +1086 -0
  71. package/dist/index-DWd1gUwR.d.ts.map +1 -0
  72. package/dist/{index-DAXfpVf7.d.ts → index-y7i8l6Y_.d.ts} +8 -8
  73. package/dist/{index-DAXfpVf7.d.ts.map → index-y7i8l6Y_.d.ts.map} +1 -1
  74. package/dist/index.d.ts +18 -17
  75. package/dist/index.d.ts.map +1 -1
  76. package/dist/index.js +15 -15
  77. package/dist/{integrity-C8oUeB0g.js → integrity-D-s2iHiT.js} +2 -2
  78. package/dist/{integrity-C8oUeB0g.js.map → integrity-D-s2iHiT.js.map} +1 -1
  79. package/dist/{kind-factory-BhxbtUsQ.js → kind-factory-Dl0PmNQL.js} +2 -2
  80. package/dist/{kind-factory-BhxbtUsQ.js.map → kind-factory-Dl0PmNQL.js.map} +1 -1
  81. package/dist/{llm-judge-Cc8vDJh_.js → llm-judge-3uAeRawE.js} +4 -4
  82. package/dist/{llm-judge-Cc8vDJh_.js.map → llm-judge-3uAeRawE.js.map} +1 -1
  83. package/dist/{matrix-Cf-AGxGh.d.ts → matrix-BXo3PSqM.d.ts} +2 -2
  84. package/dist/{matrix-Cf-AGxGh.d.ts.map → matrix-BXo3PSqM.d.ts.map} +1 -1
  85. package/dist/meta-eval/index.d.ts +3 -638
  86. package/dist/meta-eval/index.js +3 -193
  87. package/dist/meta-eval/index.js.map +1 -1
  88. package/dist/multishot/golden/index.d.ts +1 -1
  89. package/dist/multishot/index.d.ts +2 -2
  90. package/dist/openapi.json +1 -1
  91. package/dist/outcome-observations-FLmRpgYa.js +78 -0
  92. package/dist/outcome-observations-FLmRpgYa.js.map +1 -0
  93. package/dist/{paired-arms-Ct4LTKc1.js → paired-arms-B2ttLc0_.js} +108 -31
  94. package/dist/paired-arms-B2ttLc0_.js.map +1 -0
  95. package/dist/{power-and-mde-N5nU4_Ly.js → power-and-mde-CQX-0weG.js} +2 -2
  96. package/dist/{power-and-mde-N5nU4_Ly.js.map → power-and-mde-CQX-0weG.js.map} +1 -1
  97. package/dist/{prime-protocol-CckHBxGu.d.ts → prime-protocol-BEaqBoQE.d.ts} +2 -2
  98. package/dist/{prime-protocol-CckHBxGu.d.ts.map → prime-protocol-BEaqBoQE.d.ts.map} +1 -1
  99. package/dist/{proposal-findings-E1aSC_cU.js → proposal-findings-D0_zkQ2l.js} +2 -2
  100. package/dist/{proposal-findings-E1aSC_cU.js.map → proposal-findings-D0_zkQ2l.js.map} +1 -1
  101. package/dist/{registry-B_yG-1jh.d.ts → registry-DDKaUrmM.d.ts} +3 -3
  102. package/dist/{registry-B_yG-1jh.d.ts.map → registry-DDKaUrmM.d.ts.map} +1 -1
  103. package/dist/{render-Cs34y0iX.js → render-BhJqXoBH.js} +15 -11
  104. package/dist/render-BhJqXoBH.js.map +1 -0
  105. package/dist/reporting.d.ts +1 -1
  106. package/dist/reporting.js +3 -3
  107. package/dist/rl.d.ts +4 -5
  108. package/dist/rl.d.ts.map +1 -1
  109. package/dist/rl.js +5 -4
  110. package/dist/rl.js.map +1 -1
  111. package/dist/{rubric-predictive-validity-noY7uE03.d.ts → rubric-predictive-validity-Cd5SCtAf.d.ts} +58 -3
  112. package/dist/rubric-predictive-validity-Cd5SCtAf.d.ts.map +1 -0
  113. package/dist/{rubric-predictive-validity-D3_oI72N.js → rubric-predictive-validity-CeKW2GQN.js} +3 -77
  114. package/dist/rubric-predictive-validity-CeKW2GQN.js.map +1 -0
  115. package/dist/search/index.d.ts +2 -2
  116. package/dist/{search-kernel-Dloxd6gs.d.ts → search-kernel-C6__V0IS.d.ts} +2 -2
  117. package/dist/{search-kernel-Dloxd6gs.d.ts.map → search-kernel-C6__V0IS.d.ts.map} +1 -1
  118. package/dist/{skillopt-optimization-method-DLKqdhcR.js → skillopt-optimization-method-D21dH_Bh.js} +4 -4
  119. package/dist/{skillopt-optimization-method-DLKqdhcR.js.map → skillopt-optimization-method-D21dH_Bh.js.map} +1 -1
  120. package/dist/{statistical-heldout-3z3I-kJN.d.ts → statistical-heldout-pD1Yah-0.d.ts} +58 -8
  121. package/dist/statistical-heldout-pD1Yah-0.d.ts.map +1 -0
  122. package/dist/{store-otlp-dyWE3wAG.js → store-otlp-BVZfR168.js} +2 -2
  123. package/dist/{store-otlp-dyWE3wAG.js.map → store-otlp-BVZfR168.js.map} +1 -1
  124. package/dist/{store-tool-spans-DIUgZbzu.js → store-tool-spans-CjYiF4fF.js} +3 -3
  125. package/dist/{store-tool-spans-DIUgZbzu.js.map → store-tool-spans-CjYiF4fF.js.map} +1 -1
  126. package/dist/{store-tool-spans-DPwXHQkH.d.ts → store-tool-spans-DfnwWMFR.d.ts} +4 -4
  127. package/dist/{store-tool-spans-DPwXHQkH.d.ts.map → store-tool-spans-DfnwWMFR.d.ts.map} +1 -1
  128. package/dist/{summary-report-BsXJoYX5.js → summary-report-DHDWxe6p.js} +3 -3
  129. package/dist/{summary-report-BsXJoYX5.js.map → summary-report-DHDWxe6p.js.map} +1 -1
  130. package/dist/supervisor-run/index.d.ts +6 -5
  131. package/dist/supervisor-run/index.d.ts.map +1 -1
  132. package/dist/supervisor-run/index.js +3 -3
  133. package/dist/systemone-D3MrW63C.d.ts +400 -0
  134. package/dist/systemone-D3MrW63C.d.ts.map +1 -0
  135. package/dist/{systemone-protocol-DKoi1NdK.d.ts → systemone-protocol-Bl2EI2KQ.d.ts} +4 -2
  136. package/dist/{systemone-protocol-DKoi1NdK.d.ts.map → systemone-protocol-Bl2EI2KQ.d.ts.map} +1 -1
  137. package/dist/systemone-protocol.d.ts +2 -2
  138. package/dist/systemone-protocol.js +7 -7
  139. package/dist/systemone-protocol.js.map +1 -1
  140. package/dist/{systemone-review-CUBMuTLi.d.ts → systemone-review-C8DRiT_-.d.ts} +3 -3
  141. package/dist/{systemone-review-CUBMuTLi.d.ts.map → systemone-review-C8DRiT_-.d.ts.map} +1 -1
  142. package/dist/{systemone-review-DzdOJ8I6.js → systemone-review-DFGtIUcf.js} +2 -2
  143. package/dist/{systemone-review-DzdOJ8I6.js.map → systemone-review-DFGtIUcf.js.map} +1 -1
  144. package/dist/systemone.d.ts +5 -5
  145. package/dist/systemone.js +5 -343
  146. package/dist/{terminal-record-D4Rv-j1W.js → terminal-record-CB9BFtjS.js} +77 -29
  147. package/dist/terminal-record-CB9BFtjS.js.map +1 -0
  148. package/dist/{tool-groups-LISbBWCg.d.ts → tool-groups-DK1bu5TD.d.ts} +3 -3
  149. package/dist/tool-groups-DK1bu5TD.d.ts.map +1 -0
  150. package/dist/{trace-questions-C42fYEE4.d.ts → trace-questions-D_OKYZ6u.d.ts} +3 -3
  151. package/dist/{trace-questions-C42fYEE4.d.ts.map → trace-questions-D_OKYZ6u.d.ts.map} +1 -1
  152. package/dist/trace-repair/index.d.ts +1 -1
  153. package/dist/traces.d.ts +3 -3
  154. package/dist/traces.js +3 -3
  155. package/dist/{types-DqFMNTgK.js → types-CnWmj8NW.js} +19 -6
  156. package/dist/types-CnWmj8NW.js.map +1 -0
  157. package/dist/{types-CHfn1zg5.d.ts → types-DDKfH-N6.d.ts} +2 -2
  158. package/dist/{types-CHfn1zg5.d.ts.map → types-DDKfH-N6.d.ts.map} +1 -1
  159. package/dist/{types-8yQzNm8u.d.ts → types-DGImvHIr.d.ts} +150 -4
  160. package/dist/types-DGImvHIr.d.ts.map +1 -0
  161. package/dist/{types-D8GXK9Z5.d.ts → types-IERw_HxR.d.ts} +2 -2
  162. package/dist/{types-D8GXK9Z5.d.ts.map → types-IERw_HxR.d.ts.map} +1 -1
  163. package/dist/wire/index.d.ts +1 -1
  164. package/docs/behavioral-trace-questions.md +99 -0
  165. package/docs/experiment.md +27 -0
  166. package/docs/finding-layers.md +54 -1
  167. package/docs/rollout.md +9 -0
  168. package/docs/systemone.md +107 -0
  169. package/package.json +1 -1
  170. package/dist/benchmark-command-BzmMTnvC.js.map +0 -1
  171. package/dist/default-registry-BrKmT01n.js.map +0 -1
  172. package/dist/default-registry-Cwg_QN3d.d.ts +0 -70
  173. package/dist/default-registry-Cwg_QN3d.d.ts.map +0 -1
  174. package/dist/evaluation.js.map +0 -1
  175. package/dist/index-CVFStrQD.d.ts.map +0 -1
  176. package/dist/judge-gate-Dc_mXQsL.d.ts +0 -453
  177. package/dist/judge-gate-Dc_mXQsL.d.ts.map +0 -1
  178. package/dist/meta-eval/index.d.ts.map +0 -1
  179. package/dist/outcome-store-CNt4iZ67.d.ts +0 -58
  180. package/dist/outcome-store-CNt4iZ67.d.ts.map +0 -1
  181. package/dist/paired-arms-Ct4LTKc1.js.map +0 -1
  182. package/dist/render-Cs34y0iX.js.map +0 -1
  183. package/dist/rubric-predictive-validity-D3_oI72N.js.map +0 -1
  184. package/dist/rubric-predictive-validity-noY7uE03.d.ts.map +0 -1
  185. package/dist/statistical-heldout-3z3I-kJN.d.ts.map +0 -1
  186. package/dist/systemone-DVA7t76V.d.ts +0 -135
  187. package/dist/systemone-DVA7t76V.d.ts.map +0 -1
  188. package/dist/systemone.js.map +0 -1
  189. package/dist/terminal-record-D4Rv-j1W.js.map +0 -1
  190. package/dist/tool-groups-LISbBWCg.d.ts.map +0 -1
  191. package/dist/types-8yQzNm8u.d.ts.map +0 -1
  192. package/dist/types-DqFMNTgK.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"paired-arms-Ct4LTKc1.js","names":[],"sources":["../src/math/normal.ts","../src/statistics/rank-tests.ts","../src/paired-arms.ts"],"sourcesContent":["/**\n * Standard normal cumulative distribution using Abramowitz and Stegun 7.1.26.\n *\n * The approximation is evaluated as erf(x / sqrt(2)). Computing the negative\n * tail from the complementary term avoids cancellation when x is far below 0.\n * The maximum absolute CDF error is approximately 7.5e-8.\n */\nexport function normalCdf(x: number): number {\n if (x === 0) return 0.5\n\n const a1 = 0.254829592\n const a2 = -0.284496736\n const a3 = 1.421413741\n const a4 = -1.453152027\n const a5 = 1.061405429\n const p = 0.3275911\n\n const scaled = Math.abs(x) / Math.SQRT2\n const t = 1 / (1 + p * scaled)\n const complement = ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp(-scaled * scaled)\n\n return x < 0 ? complement / 2 : 1 - complement / 2\n}\n","import { ValidationError } from '../errors'\nimport { normalCdf } from '../math/normal'\nimport { lnGamma } from '../math/special-functions'\nimport {\n assertFiniteSample,\n binomialSignTwoSided,\n makeRng,\n symmetricTwoSampleSeed,\n} from './internal'\n\n// ── Rank tests: exact by default ─────────────────────────────────────\n//\n// At 3–10 repetitions per arm the binding constraint on a rank test is\n// combinatorial, not numerical. Three versus three admits only 20 splits, so\n// the attainable two-sided p-grid starts at 0.1000 and α = 0.05 is out of\n// reach at that design; a normal approximation reports 0.0495, a p-value that\n// describes no attainable outcome. No better approximation fixes this — adding\n// the tie correction moves `[0,0,0]` versus `[1,1,1]` from 0.0495 to 0.0469,\n// further from its exact 0.1000, not closer.\n//\n// So both null distributions are enumerated exactly inside bounded state and\n// work budgets, by convolution over the observed midranks (identical to\n// enumerating every split / sign pattern, and cheaper), which conditions on the\n// realised tie pattern for free. Above those budgets the default is a seeded\n// Monte Carlo permutation. The asymptotic path is never chosen automatically,\n// and asking for it inside the exact-feasible range throws.\n//\n// Every result carries `method` and `pFloor` so a downstream gate can SEE the\n// discreteness rather than infer it: a gate handed data whose `pFloor` exceeds\n// its alpha is underpowered by construction, which is a true statement about\n// the experiment, not a false one about the effect.\n\n/** How a rank test's p-value was actually computed. */\nexport type RankTestMethod = 'exact' | 'permutation' | 'asymptotic'\n\n/**\n * What the caller asks for. `'auto'` selects `'exact'` inside the enumeration\n * threshold and `'permutation'` above it, and never selects `'asymptotic'`.\n */\nexport type RankTestMethodRequest = 'auto' | 'exact' | 'asymptotic'\n\nexport interface RankTestOptions {\n /** Default `'auto'`. `'asymptotic'` inside the exact-feasible range throws. */\n method?: RankTestMethodRequest\n /** Resamples on the Monte Carlo permutation path. Default 100000. */\n permutations?: number\n /** Seed for the permutation path. Omitted ⇒ derived from the data itself, so\n * the result is reproducible either way. */\n seed?: number\n}\n\n/** Maximum dynamic-programming cells used by an exact two-sample rank test. */\nconst MANN_WHITNEY_EXACT_MAX_STATES = 8_192\n/** Maximum inner-loop transitions used by an exact two-sample rank test. */\nconst MANN_WHITNEY_EXACT_MAX_WORK = 250_000\n/** Non-zero differences up to which the signed-rank null is enumerated exactly. */\nconst WILCOXON_EXACT_MAX_N = 20\n/** Resamples used when a rank test falls back to Monte Carlo permutation. */\nconst DEFAULT_PERMUTATIONS = 100_000\n\nexport interface MannWhitneyResult {\n /** `min(U_a, U_b)` — the conventional reported statistic. */\n u: number\n /** U for sample `a`. Carries the direction of the effect, which `u` discards. */\n uA: number\n /** Two-sided p-value. */\n p: number\n /** How `p` was computed. */\n method: RankTestMethod\n /** Smallest two-sided p this design can produce. `p` can never be below it. */\n pFloor: number\n}\n\n/**\n * Mann-Whitney U — two independent samples, no distributional assumption.\n *\n * Exact conditional (permutation) p by default when the dynamic program fits\n * {@link MANN_WHITNEY_EXACT_MAX_STATES} cells and\n * {@link MANN_WHITNEY_EXACT_MAX_WORK} transitions, seeded Monte Carlo\n * permutation above those limits. This keeps imbalanced designs such as 1+24\n * exact without admitting expensive balanced designs merely because they have\n * the same total size. Throws on non-finite input and on `method:\n * 'asymptotic'` where an exact answer is available. Empty input yields `p = 1,\n * pFloor = 1` — no design, no attainable evidence.\n */\nexport function mannWhitneyU(\n a: number[],\n b: number[],\n opts: RankTestOptions = {},\n): MannWhitneyResult {\n assertFiniteSample('mannWhitneyU', 'a', a)\n assertFiniteSample('mannWhitneyU', 'b', b)\n\n const n1 = a.length\n const n2 = b.length\n if (n1 === 0 || n2 === 0) return { u: 0, uA: 0, p: 1, method: 'exact', pFloor: 1 }\n\n const total = n1 + n2\n const combined = [\n ...a.map((v) => ({ v, fromA: true })),\n ...b.map((v) => ({ v, fromA: false })),\n ].sort((x, y) => x.v - y.v)\n\n const { midranks, tieTerm } = midranksWithTieTerm(combined.map((entry) => entry.v))\n let rankSumA = 0\n for (let k = 0; k < total; k++) {\n if (combined[k]!.fromA) rankSumA += midranks[k]!\n }\n\n const uA = rankSumA - (n1 * (n1 + 1)) / 2\n const u = Math.min(uA, n1 * n2 - uA)\n // Midranks are integers or halves, so doubling makes the null convolution\n // integral. U is centred on n₁n₂/2, hence a doubled centre of n₁n₂.\n const doubled = midranks.map((rank) => Math.round(rank * 2))\n const doubledDeviation = Math.abs(2 * uA - n1 * n2)\n const selectedN = Math.min(n1, n2)\n const otherN = total - selectedN\n const exactCost = exactTwoSampleCost(doubled, selectedN)\n\n const designFloor = exactTwoSampleFloor(doubled, selectedN)\n const method = selectRankTestMethod(\n 'mannWhitneyU',\n opts.method ?? 'auto',\n `n1=${n1}, n2=${n2}`,\n exactCost.states <= MANN_WHITNEY_EXACT_MAX_STATES &&\n exactCost.work <= MANN_WHITNEY_EXACT_MAX_WORK,\n designFloor,\n `${MANN_WHITNEY_EXACT_MAX_STATES.toLocaleString('en-US')} states and ` +\n `${MANN_WHITNEY_EXACT_MAX_WORK.toLocaleString('en-US')} transitions`,\n )\n\n if (method === 'exact') {\n const { p, pFloor } = exactTwoSampleP(doubled, selectedN, otherN, doubledDeviation)\n return { u, uA, p, method, pFloor }\n }\n\n if (method === 'asymptotic') {\n return {\n u,\n uA,\n p: asymptoticTwoSidedP(doubledDeviation / 2, twoSampleSigma(n1, n2, total, tieTerm)),\n method,\n pFloor: designFloor,\n }\n }\n\n const permutations = resolvePermutations('mannWhitneyU', opts.permutations)\n const rng = opts.seed === undefined ? makeRng(symmetricTwoSampleSeed(a, b)) : makeRng(opts.seed)\n let atLeastAsExtreme = 0\n const pool = [...doubled]\n for (let iteration = 0; iteration < permutations; iteration++) {\n let doubledRankSum = 0\n for (let k = 0; k < selectedN; k++) {\n const pick = k + Math.floor(rng() * (total - k))\n const swapped = pool[pick]!\n pool[pick] = pool[k]!\n pool[k] = swapped\n doubledRankSum += swapped\n }\n if (\n Math.abs(doubledRankSum - selectedN * (selectedN + 1) - selectedN * otherN) >=\n doubledDeviation\n ) {\n atLeastAsExtreme++\n }\n }\n const pFloor = Math.max(1 / (permutations + 1), designFloor)\n return {\n u,\n uA,\n p: Math.max((1 + atLeastAsExtreme) / (permutations + 1), pFloor),\n method,\n pFloor,\n }\n}\n\nexport interface WilcoxonSignedRankResult {\n /** W⁺, the rank sum of the positive differences. (scipy reports\n * `min(W⁺, W⁻)`; compare statistics only after converting.) */\n w: number\n /** Two-sided p-value. */\n p: number\n /** How `p` was computed. */\n method: RankTestMethod\n /** Smallest two-sided p this design can produce. */\n pFloor: number\n /** Non-zero differences — zero differences are dropped and carry no rank. */\n nNonZero: number\n}\n\n/**\n * Wilcoxon signed-rank — paired, no distributional assumption on the deltas.\n *\n * Exact conditional (sign-flip) p by default at `n ≤\n * {@link WILCOXON_EXACT_MAX_N}` non-zero differences, seeded Monte Carlo\n * permutation above it. Throws on non-finite input and on `method:\n * 'asymptotic'` where an exact answer is available.\n *\n * `n` is the count of NON-ZERO differences: exact ties are dropped before\n * ranking, so a run of tied pairs shrinks the design and raises `pFloor`.\n * All-tied input yields `p = 1, pFloor = 1` — no attainable evidence, which\n * `pFloor` states rather than leaving `p = 1` to be read as a measured null.\n */\nexport function wilcoxonSignedRank(\n before: number[],\n after: number[],\n opts: RankTestOptions = {},\n): WilcoxonSignedRankResult {\n if (before.length !== after.length) {\n throw new ValidationError(\n `wilcoxonSignedRank: unequal sample sizes (${before.length} vs ${after.length})`,\n )\n }\n assertFiniteSample('wilcoxonSignedRank', 'before', before)\n assertFiniteSample('wilcoxonSignedRank', 'after', after)\n\n const diffs = before.map((b, i) => after[i]! - b).filter((d) => d !== 0)\n const n = diffs.length\n if (n === 0) return { w: 0, p: 1, method: 'exact', pFloor: 1, nNonZero: 0 }\n\n // When every non-zero difference has the same magnitude, the signed-rank\n // null reduces exactly to a binomial sign distribution. This is the common\n // pass/fail shape ({-1, 0, +1}); recognizing it avoids a 100k-draw\n // permutation for every repeated gate evaluation while preserving the exact\n // p-value and attainable floor. Explicit method requests still retain their\n // documented behavior.\n const abs = Math.abs(diffs[0]!)\n const allEqualAbs = diffs.every((d) => Math.abs(d) === abs)\n if ((opts.method === undefined || opts.method === 'auto') && allEqualAbs) {\n const positive = diffs.filter((d) => d > 0).length\n const negative = n - positive\n return {\n w: (positive * (n + 1)) / 2,\n p: binomialSignTwoSided(positive, negative),\n method: 'exact',\n pFloor: Math.min(1, 2 ** (1 - n)),\n nNonZero: n,\n }\n }\n\n const order = diffs.map((d, i) => ({ abs: Math.abs(d), i })).sort((x, y) => x.abs - y.abs)\n const { midranks, tieTerm } = midranksWithTieTerm(order.map((entry) => entry.abs))\n const ranks: number[] = new Array(n)\n for (let k = 0; k < n; k++) ranks[order[k]!.i] = midranks[k]!\n\n let wPlus = 0\n for (let k = 0; k < n; k++) if (diffs[k]! > 0) wPlus += ranks[k]!\n\n // Midranks are integers or halves; doubling makes the convolution integral.\n // Σ midranks = n(n+1)/2 whatever the tie pattern, so E[W⁺] = n(n+1)/4 and\n // the doubled centre is n(n+1)/2.\n const doubled = midranks.map((rank) => Math.round(rank * 2))\n const doubledDeviation = Math.abs(2 * wPlus - (n * (n + 1)) / 2)\n\n const designFloor = Math.min(1, 2 ** (1 - n))\n const method = selectRankTestMethod(\n 'wilcoxonSignedRank',\n opts.method ?? 'auto',\n `n=${n} non-zero differences`,\n n <= WILCOXON_EXACT_MAX_N,\n designFloor,\n `${WILCOXON_EXACT_MAX_N} non-zero differences`,\n )\n\n if (method === 'exact') {\n const { p, pFloor } = exactSignedRankP(doubled, doubledDeviation)\n return { w: wPlus, p, method, pFloor, nNonZero: n }\n }\n\n if (method === 'asymptotic') {\n const variance = (n * (n + 1) * (2 * n + 1)) / 24 - tieTerm / 48\n return {\n w: wPlus,\n p: asymptoticTwoSidedP(doubledDeviation / 2, Math.sqrt(variance)),\n method,\n pFloor: designFloor,\n nNonZero: n,\n }\n }\n\n const permutations = resolvePermutations('wilcoxonSignedRank', opts.permutations)\n const rng = makeRng(opts.seed, before, after)\n const doubledCentre = (n * (n + 1)) / 2\n let atLeastAsExtreme = 0\n for (let iteration = 0; iteration < permutations; iteration++) {\n let doubledWPlus = 0\n for (let k = 0; k < n; k++) if (rng() < 0.5) doubledWPlus += doubled[k]!\n if (Math.abs(doubledWPlus - doubledCentre) >= doubledDeviation) atLeastAsExtreme++\n }\n return {\n w: wPlus,\n p: (1 + atLeastAsExtreme) / (permutations + 1),\n method,\n pFloor: Math.max(1 / (permutations + 1), designFloor),\n nNonZero: n,\n }\n}\n\n/**\n * Average ranks over an ASCENDING-sorted array, plus `Σ(t³ − t)` over tie\n * groups of size `t` — the correction term both asymptotic rank-test variances\n * need.\n */\nfunction midranksWithTieTerm(sorted: readonly number[]): { midranks: number[]; tieTerm: number } {\n const midranks = new Array<number>(sorted.length)\n let tieTerm = 0\n let i = 0\n while (i < sorted.length) {\n let j = i\n while (j < sorted.length && sorted[j] === sorted[i]) j++\n const average = (i + 1 + j) / 2\n for (let k = i; k < j; k++) midranks[k] = average\n const groupSize = j - i\n if (groupSize > 1) tieTerm += groupSize ** 3 - groupSize\n i = j\n }\n return { midranks, tieTerm }\n}\n\nfunction selectRankTestMethod(\n fn: string,\n request: RankTestMethodRequest,\n design: string,\n exactFeasible: boolean,\n designFloor: number,\n threshold: string,\n): RankTestMethod {\n if (request === 'auto') return exactFeasible ? 'exact' : 'permutation'\n if (request === 'exact') {\n if (exactFeasible) return 'exact'\n throw new ValidationError(\n `${fn}: method 'exact' is out of range at ${design} — enumeration is bounded by ` +\n `${threshold}. Use 'auto' for the seeded Monte Carlo permutation, which converges ` +\n 'to the same answer.',\n )\n }\n if (exactFeasible) {\n throw new ValidationError(\n `${fn}: method 'asymptotic' is refused at ${design} — the exact p-grid at this design ` +\n `starts at ${formatProbability(designFloor)}, so an asymptotic p below it describes no ` +\n `attainable outcome. Use method 'exact' (the default) or add repetitions past ` +\n `${threshold}.`,\n )\n }\n return 'asymptotic'\n}\n\nfunction resolvePermutations(fn: string, permutations: number | undefined): number {\n if (permutations === undefined) return DEFAULT_PERMUTATIONS\n if (!Number.isInteger(permutations) || permutations < 1) {\n throw new ValidationError(`${fn}: permutations must be a positive integer, got ${permutations}`)\n }\n return permutations\n}\n\n/** Two-sided normal-approximation tail with the continuity correction. */\nfunction asymptoticTwoSidedP(deviation: number, sigma: number): number {\n if (!(sigma > 0)) return 1\n return Math.min(1, 2 * (1 - normalCdf(Math.max(0, deviation - 0.5) / sigma)))\n}\n\n/** SD of U under the permutation null, corrected for the realised ties. The\n * tie term reduces (N+1) and reaches it exactly when every value is tied, so\n * the variance floors at 0 rather than going negative. */\nfunction twoSampleSigma(n1: number, n2: number, total: number, tieTerm: number): number {\n if (total < 2) return 0\n const variance = ((n1 * n2) / 12) * (total + 1 - tieTerm / (total * (total - 1)))\n return Math.sqrt(Math.max(0, variance))\n}\n\nfunction logChoose(n: number, k: number): number {\n return lnGamma(n + 1) - lnGamma(k + 1) - lnGamma(n - k + 1)\n}\n\nfunction formatProbability(value: number): string {\n return value >= 1e-4 || value === 0 ? value.toFixed(4) : value.toExponential(3)\n}\n\n/**\n * Exact DP allocation and loop count for this observed rank vector.\n *\n * The smaller arm is sufficient because selecting its complement produces the\n * same two-sided U deviation while using fewer rows in the state table.\n */\nfunction exactTwoSampleCost(\n doubledRanks: readonly number[],\n selectedN: number,\n): { states: number; work: number } {\n const maxSum = doubledRanks.reduce((sum, rank) => sum + rank, 0)\n let work = 0\n for (let placed = 0; placed < doubledRanks.length; placed++) {\n work += Math.min(selectedN, placed + 1) * (maxSum - doubledRanks[placed]! + 1)\n }\n return {\n states: (selectedN + 1) * (maxSum + 1),\n work,\n }\n}\n\n/**\n * Smallest attainable two-sided p under the observed ties.\n *\n * Only subsets with the minimum or maximum rank sum can attain the largest\n * deviation. Their multiplicity is the number of ways to choose within the\n * tie group at each boundary, so this calculation is exact without allocating\n * the full null distribution.\n */\nfunction exactTwoSampleFloor(doubledRanks: readonly number[], selectedN: number): number {\n const total = doubledRanks.length\n const otherN = total - selectedN\n const minimumSum = doubledRanks.slice(0, selectedN).reduce((sum, rank) => sum + rank, 0)\n const maximumSum = doubledRanks.slice(total - selectedN).reduce((sum, rank) => sum + rank, 0)\n if (minimumSum === maximumSum) return 1\n\n const centre = selectedN * (selectedN + 1) + selectedN * otherN\n const minimumDeviation = Math.abs(minimumSum - centre)\n const maximumDeviation = Math.abs(maximumSum - centre)\n const totalLogWays = logChoose(total, selectedN)\n const minimumMass = Math.exp(\n logExtremeSubsetWays(doubledRanks, selectedN, 'minimum') - totalLogWays,\n )\n const maximumMass = Math.exp(\n logExtremeSubsetWays(doubledRanks, selectedN, 'maximum') - totalLogWays,\n )\n\n if (minimumDeviation > maximumDeviation) return minimumMass\n if (maximumDeviation > minimumDeviation) return maximumMass\n return Math.min(1, minimumMass + maximumMass)\n}\n\nfunction logExtremeSubsetWays(\n sortedRanks: readonly number[],\n selectedN: number,\n side: 'minimum' | 'maximum',\n): number {\n const boundaryIndex = side === 'minimum' ? selectedN - 1 : sortedRanks.length - selectedN\n const boundary = sortedRanks[boundaryIndex]!\n let first = boundaryIndex\n let afterLast = boundaryIndex + 1\n while (first > 0 && sortedRanks[first - 1] === boundary) first--\n while (afterLast < sortedRanks.length && sortedRanks[afterLast] === boundary) afterLast++\n\n const tieSize = afterLast - first\n const fixed = side === 'minimum' ? first : sortedRanks.length - afterLast\n return logChoose(tieSize, selectedN - fixed)\n}\n\n/**\n * Exact conditional two-sided p for the two-sample rank test.\n *\n * Convolves the observed doubled midranks into the null distribution of group\n * a's rank sum over every `C(n₁+n₂, n₁)` split — identical to enumerating the\n * splits, but `O(N·n₁·ΣR)` instead of `O(C(N,n₁)·n₁n₂)`. Conditioning on the\n * realised multiset makes the tie handling exact rather than a correction.\n *\n * The null is symmetric about `n₁n₂/2` (negating every value maps `U → n₁n₂ −\n * U` and permutes the split set onto itself), so the two-sided p is the mass\n * at least as far from the centre as the observation.\n */\nfunction exactTwoSampleP(\n doubledRanks: readonly number[],\n n1: number,\n n2: number,\n doubledDeviation: number,\n): { p: number; pFloor: number } {\n const maxSum = doubledRanks.reduce((sum, rank) => sum + rank, 0)\n const width = maxSum + 1\n // ways[k][s] = number of size-k subsets whose doubled rank sum is s.\n const ways: Float64Array[] = Array.from({ length: n1 + 1 }, () => new Float64Array(width))\n ways[0]![0] = 1\n let placed = 0\n for (const rank of doubledRanks) {\n for (let k = Math.min(n1, placed + 1); k >= 1; k--) {\n const from = ways[k - 1]!\n const into = ways[k]!\n for (let sum = maxSum - rank; sum >= 0; sum--) {\n const count = from[sum]!\n if (count !== 0) into[sum + rank]! += count\n }\n }\n placed++\n }\n\n // U = rankSum − n₁(n₁+1)/2, so doubled U = s − n₁(n₁+1), and the doubled\n // centre 2·(n₁n₂/2) is n₁n₂.\n const shift = n1 * (n1 + 1) + n1 * n2\n const chosen = ways[n1]!\n let totalWays = 0\n let extremeWays = 0\n let tailWays = 0\n let maxDeviation = -1\n for (let sum = 0; sum < width; sum++) {\n const count = chosen[sum]!\n if (count === 0) continue\n totalWays += count\n const deviation = Math.abs(sum - shift)\n if (deviation >= doubledDeviation) tailWays += count\n if (deviation > maxDeviation) {\n maxDeviation = deviation\n extremeWays = count\n } else if (deviation === maxDeviation) {\n extremeWays += count\n }\n }\n return { p: tailWays / totalWays, pFloor: extremeWays / totalWays }\n}\n\n/**\n * Exact conditional two-sided p for the paired signed-rank test.\n *\n * Convolves the observed doubled absolute midranks over all `2ⁿ` sign\n * assignments in `O(n·ΣR)`. Probabilities rather than counts keep `2ⁿ` off the\n * arithmetic. The null is symmetric about `n(n+1)/4`.\n */\nfunction exactSignedRankP(\n doubledRanks: readonly number[],\n doubledDeviation: number,\n): { p: number; pFloor: number } {\n const maxSum = doubledRanks.reduce((sum, rank) => sum + rank, 0)\n const width = maxSum + 1\n let mass = new Float64Array(width)\n mass[0] = 1\n for (const rank of doubledRanks) {\n const next = new Float64Array(width)\n for (let sum = 0; sum < width; sum++) {\n const probability = mass[sum]!\n if (probability === 0) continue\n next[sum]! += probability * 0.5\n next[sum + rank]! += probability * 0.5\n }\n mass = next\n }\n\n const centre = maxSum / 2\n let tail = 0\n let extreme = 0\n let maxDeviation = -1\n for (let sum = 0; sum < width; sum++) {\n const probability = mass[sum]!\n if (probability === 0) continue\n const deviation = Math.abs(sum - centre)\n if (deviation >= doubledDeviation) tail += probability\n if (deviation > maxDeviation) {\n maxDeviation = deviation\n extreme = probability\n } else if (deviation === maxDeviation) {\n extreme += probability\n }\n }\n return { p: Math.min(1, tail), pFloor: Math.min(1, extreme) }\n}\n","/**\n * Matched-pair arm comparison — \"did the treatment arm beat the baseline arm\n * on the SAME work items?\"\n *\n * An arm A/B over run records is only trustworthy when it is PAIRED: the same\n * task/scenario/seed evaluated under both arms, compared item-by-item, so\n * inter-item difficulty variance cancels instead of masquerading as an arm\n * effect. This module owns the two error-prone steps every consumer otherwise\n * hand-rolls:\n *\n * 1. Pairing — matching rows across arms by `pairKey` (and by `repKey`\n * within multi-rep items), with leftovers REPORTED rather than silently\n * dropped (a silently unbalanced pairing biases every paired statistic\n * downstream). Pairing never keys on outcome content: matching reps by\n * their outcomes deflates discordant-pair counts and makes McNemar\n * anti-conservative, so reps pair only by (`pairKey`, `repKey`) identity.\n * 2. Composition — feeding the matched pairs to the correct paired\n * estimators that already live in `statistics`: `mcnemar` +\n * `pairedRiskDifference` for pass/fail, `pairedBootstrap` +\n * `wilcoxonSignedRank` for continuous metrics. No statistic is\n * re-implemented here.\n *\n * The row shape is deliberately structural — callers project a `RunRecord`\n * (or any record) into `{ pairKey, arm, pass?, metrics? }`. Arm names are\n * caller-supplied parameters; the module ships no domain literal.\n */\n\nimport { ValidationError } from './errors'\nimport type { RunRecord } from './run-record'\nimport type { McNemarResult, PairedBootstrapOptions, PairedBootstrapResult } from './statistics'\nimport {\n mcnemar,\n pairedBootstrap,\n pairedRiskDifference,\n type RiskDifferenceResult,\n wilcoxonSignedRank,\n} from './statistics'\n\n/** One arm observation of one work item. Structural on purpose: callers\n * project their own record type (e.g. a `RunRecord`) into this shape. */\nexport interface PairedArmRow {\n /** Matching key — rows sharing a `pairKey` across both arms form pairs\n * (typically the task/scenario/seed identity). */\n pairKey: string\n /** Rep identity within a `pairKey` (e.g. a seed or rep number). Required on\n * every row of a `pairKey` that has more than one rep in either arm; reps\n * then pair only on exact (`pairKey`, `repKey`) match, never on outcome\n * content. Optional when each arm has at most one rep of the item. */\n repKey?: string\n /** Arm label this row was produced under. */\n arm: string\n /** Binary outcome; omit when the comparison has no pass/fail notion. */\n pass?: boolean\n /** Named numeric measurements (score, cost, latency, …). */\n metrics?: Record<string, number>\n}\n\nexport interface PairArmsOptions {\n /** Arm treated as the control side of every pair. */\n baselineArm: string\n /** Arm treated as the treatment side of every pair. */\n treatmentArm: string\n}\n\n/** One matched (baseline, treatment) observation of the same work item. */\nexport interface MatchedPair {\n pairKey: string\n /** 0-based position of this pair within its `pairKey`, ordered by sorted\n * `repKey` (always 0 for a single-rep item). The rep identity itself is on\n * the rows (`baseline.repKey` / `treatment.repKey`). */\n repIndex: number\n baseline: PairedArmRow\n treatment: PairedArmRow\n}\n\nexport interface PairArmsResult {\n /** Matched pairs, ordered by (`pairKey`, `repIndex`). */\n pairs: MatchedPair[]\n /** Baseline rows left without a treatment counterpart — reported, never\n * silently dropped. */\n unpairedBaseline: PairedArmRow[]\n /** Treatment rows left without a baseline counterpart. */\n unpairedTreatment: PairedArmRow[]\n}\n\n/**\n * Match rows across two arms into (baseline, treatment) pairs by `pairKey`.\n *\n * A `pairKey` with at most one row per arm pairs directly, no `repKey`\n * needed. A `pairKey` with multiple reps in either arm requires `repKey` on\n * every one of its rows, and reps pair only on exact (`pairKey`, `repKey`)\n * match — pairing is keyed purely on row identity, never on outcome content\n * (outcome-keyed matching deflates discordant counts and biases McNemar), and\n * is therefore independent of input order. Reps whose `repKey` has no\n * counterpart in the other arm, and items present in only one arm, land in\n * the unpaired lists — reported, never truncated.\n *\n * Fail-loud: throws when either named arm has zero rows (an unknown arm\n * name would otherwise read as \"everything unpaired\"), when the two arm\n * names are equal, when a multi-rep `pairKey` has a row without `repKey`, or\n * when a (`pairKey`, arm) group repeats a `repKey` (the match would be\n * ambiguous).\n */\nexport function pairArms(rows: readonly PairedArmRow[], opts: PairArmsOptions): PairArmsResult {\n const { baselineArm, treatmentArm } = opts\n if (baselineArm === treatmentArm) {\n throw new ValidationError(\n `pairArms: baselineArm and treatmentArm are both '${baselineArm}' — an arm cannot be compared to itself`,\n )\n }\n\n // arm → pairKey → rows\n const byArm = new Map<string, Map<string, PairedArmRow[]>>()\n const armsSeen = new Set<string>()\n for (const row of rows) {\n armsSeen.add(row.arm)\n if (row.arm !== baselineArm && row.arm !== treatmentArm) continue\n const byKey = byArm.get(row.arm) ?? new Map<string, PairedArmRow[]>()\n const group = byKey.get(row.pairKey) ?? []\n group.push(row)\n byKey.set(row.pairKey, group)\n byArm.set(row.arm, byKey)\n }\n\n for (const arm of [baselineArm, treatmentArm]) {\n if (!byArm.has(arm)) {\n const seen = [...armsSeen].sort().join(', ') || '<none>'\n throw new ValidationError(`pairArms: no rows for arm '${arm}' (arms present: ${seen})`)\n }\n }\n\n const baselineByKey = byArm.get(baselineArm)!\n const treatmentByKey = byArm.get(treatmentArm)!\n\n const allKeys = [...new Set([...baselineByKey.keys(), ...treatmentByKey.keys()])].sort()\n const pairs: MatchedPair[] = []\n const unpairedBaseline: PairedArmRow[] = []\n const unpairedTreatment: PairedArmRow[] = []\n for (const pairKey of allKeys) {\n const b = baselineByKey.get(pairKey) ?? []\n const t = treatmentByKey.get(pairKey) ?? []\n\n if (b.length <= 1 && t.length <= 1) {\n if (b.length === 1 && t.length === 1) {\n const baseline = b[0]!\n const treatment = t[0]!\n if (baseline.repKey !== undefined || treatment.repKey !== undefined) {\n if (\n baseline.repKey === undefined ||\n treatment.repKey === undefined ||\n baseline.repKey !== treatment.repKey\n ) {\n unpairedBaseline.push(baseline)\n unpairedTreatment.push(treatment)\n continue\n }\n }\n pairs.push({ pairKey, repIndex: 0, baseline, treatment })\n } else {\n unpairedBaseline.push(...b)\n unpairedTreatment.push(...t)\n }\n continue\n }\n\n const bByRep = indexByRepKey(b, pairKey, baselineArm)\n const tByRep = indexByRepKey(t, pairKey, treatmentArm)\n const repKeys = [...new Set([...bByRep.keys(), ...tByRep.keys()])].sort()\n let repIndex = 0\n for (const repKey of repKeys) {\n const baseline = bByRep.get(repKey)\n const treatment = tByRep.get(repKey)\n if (baseline !== undefined && treatment !== undefined) {\n pairs.push({ pairKey, repIndex: repIndex++, baseline, treatment })\n } else if (baseline !== undefined) {\n unpairedBaseline.push(baseline)\n } else if (treatment !== undefined) {\n unpairedTreatment.push(treatment)\n }\n }\n }\n\n return { pairs, unpairedBaseline, unpairedTreatment }\n}\n\n/** Index a multi-rep (pairKey, arm) group by `repKey`, enforcing that every\n * row carries one and that no repKey repeats within the group. */\nfunction indexByRepKey(\n group: readonly PairedArmRow[],\n pairKey: string,\n arm: string,\n): Map<string, PairedArmRow> {\n const byRep = new Map<string, PairedArmRow>()\n for (const row of group) {\n if (row.repKey === undefined) {\n throw new ValidationError(\n `pairArms: pairKey '${pairKey}' has multiple reps in an arm, but a row in arm '${arm}' ` +\n `is missing repKey — multi-rep items require an explicit repKey on every row so reps ` +\n `pair by identity (pairing reps by outcome or by index would bias the paired statistics)`,\n )\n }\n if (byRep.has(row.repKey)) {\n throw new ValidationError(\n `pairArms: duplicate repKey '${row.repKey}' for pairKey '${pairKey}' in arm '${arm}' — ` +\n `(pairKey, repKey) must uniquely identify a rep within an arm`,\n )\n }\n byRep.set(row.repKey, row)\n }\n return byRep\n}\n\n/** Paired pass/fail comparison over the pairs where BOTH sides carry `pass`. */\nexport interface PairedCorrectness {\n /** Discordant pairs where the treatment passed and the baseline failed. */\n b10: number\n /** Discordant pairs where the baseline passed and the treatment failed. */\n b01: number\n /** Exact McNemar significance over the paired outcomes (`b === b10`, `c === b01`). */\n mcnemar: McNemarResult\n /** Paired effect size: p(treatment) − p(baseline) with a paired-variance CI. */\n riskDifference: RiskDifferenceResult\n}\n\n/** Paired delta summary for one named metric (delta = treatment − baseline). */\nexport interface PairedMetricDelta {\n name: string\n /** Pairs where BOTH sides carry a finite value for this metric. */\n n: number\n /** Pairs where at least one side does not carry the metric. */\n nMissing: number\n /** Median paired delta, or null when `n === 0`. */\n medianDelta: number | null\n /** Mean paired delta, or null when `n === 0`. */\n meanDelta: number | null\n /** Bootstrap CI on the paired delta (`pairedBootstrap`); null when\n * `n === 0` — a zero-width [0, 0] interval on no data would read as a\n * measured tight null. */\n bootstrapCi: PairedBootstrapResult | null\n /** Wilcoxon signed-rank test on the paired deltas; null when `n === 0`. */\n wilcoxon: { w: number; p: number } | null\n}\n\nexport interface ComparePairedArmsOptions extends PairArmsOptions {\n /** Metrics to compare. Default: every metric name observed on any matched\n * pair, sorted. A name that appears on no pair is still reported (with\n * `n = 0`) so a misspelled metric is visible instead of vanishing. */\n metricNames?: string[]\n /** Passed through to `pairedBootstrap` — set `seed` for reproducible CIs. */\n bootstrap?: PairedBootstrapOptions\n}\n\nexport interface PairedArmsComparison {\n nPairs: number\n nUnpairedBaseline: number\n nUnpairedTreatment: number\n /** null when no matched pair carries `pass` on both sides — a pass/fail\n * verdict over rows that never measured pass/fail would be fabricated. */\n correctness: PairedCorrectness | null\n metricDeltas: PairedMetricDelta[]\n}\n\n/**\n * Full matched-pair arm comparison: pair via {@link pairArms}, then compose\n * the paired estimators from `statistics` over the matched pairs.\n *\n * Correctness uses only the pairs where both sides carry `pass` (`mcnemar.n`\n * is that subset's size); each metric uses only the pairs where both sides\n * carry a finite value for it, with the remainder counted in `nMissing`.\n * Deltas are treatment − baseline throughout.\n *\n * Fail-loud: inherits {@link pairArms}'s unknown-arm throw, and throws on a\n * non-finite metric value — silently treating corrupt telemetry as \"metric\n * absent\" would misreport it as missing coverage.\n */\nexport function comparePairedArms(\n rows: readonly PairedArmRow[],\n opts: ComparePairedArmsOptions,\n): PairedArmsComparison {\n const { pairs, unpairedBaseline, unpairedTreatment } = pairArms(rows, opts)\n\n let correctness: PairedCorrectness | null = null\n const baselinePass: number[] = []\n const treatmentPass: number[] = []\n for (const pair of pairs) {\n if (pair.baseline.pass === undefined || pair.treatment.pass === undefined) continue\n baselinePass.push(pair.baseline.pass ? 1 : 0)\n treatmentPass.push(pair.treatment.pass ? 1 : 0)\n }\n if (baselinePass.length > 0) {\n const mc = mcnemar(baselinePass, treatmentPass)\n correctness = {\n b10: mc.b,\n b01: mc.c,\n mcnemar: mc,\n riskDifference: pairedRiskDifference(baselinePass, treatmentPass),\n }\n }\n\n const metricNames =\n opts.metricNames ??\n [\n ...new Set(\n pairs.flatMap((p) => [\n ...Object.keys(p.baseline.metrics ?? {}),\n ...Object.keys(p.treatment.metrics ?? {}),\n ]),\n ),\n ].sort()\n\n const metricDeltas: PairedMetricDelta[] = metricNames.map((name) => {\n const before: number[] = []\n const after: number[] = []\n let nMissing = 0\n for (const pair of pairs) {\n const b = metricValue(pair.baseline, name)\n const t = metricValue(pair.treatment, name)\n if (b === undefined || t === undefined) {\n nMissing++\n continue\n }\n before.push(b)\n after.push(t)\n }\n const bootstrapCi = before.length === 0 ? null : pairedBootstrap(before, after, opts.bootstrap)\n return {\n name,\n n: before.length,\n nMissing,\n medianDelta: bootstrapCi?.median ?? null,\n meanDelta: bootstrapCi?.mean ?? null,\n bootstrapCi,\n wilcoxon: before.length === 0 ? null : wilcoxonSignedRank(before, after),\n }\n })\n\n return {\n nPairs: pairs.length,\n nUnpairedBaseline: unpairedBaseline.length,\n nUnpairedTreatment: unpairedTreatment.length,\n correctness,\n metricDeltas,\n }\n}\n\nexport interface MatchedRunRecordPair {\n pairKey: string\n repKey: string\n baseline: RunRecord\n treatment: RunRecord\n}\n\nexport interface PairRunRecordsResult {\n pairs: MatchedRunRecordPair[]\n unpairedBaseline: RunRecord[]\n unpairedTreatment: RunRecord[]\n}\n\ninterface RunRecordArmRow extends PairedArmRow {\n run: RunRecord\n repKey: string\n}\n\n/**\n * Pair two RunRecord arms by the identity of the evaluated work:\n * `(experimentId, scenarioId, seed)`.\n *\n * Falling back to array order, candidate id, or experiment id can compare\n * different tasks and fabricate lift. Duplicate identities throw.\n */\nexport function pairRunRecords(\n baselineRuns: readonly RunRecord[],\n treatmentRuns: readonly RunRecord[],\n): PairRunRecordsResult {\n const baselineRows = runRecordArmRows(baselineRuns, 'baseline')\n const treatmentRows = runRecordArmRows(treatmentRuns, 'treatment')\n validateRunRecordArmRows(baselineRows, 'baseline')\n validateRunRecordArmRows(treatmentRows, 'treatment')\n if (baselineRows.length === 0 || treatmentRows.length === 0) {\n return {\n pairs: [],\n unpairedBaseline: baselineRows.map((row) => row.run),\n unpairedTreatment: treatmentRows.map((row) => row.run),\n }\n }\n\n const result = pairArms([...baselineRows, ...treatmentRows], {\n baselineArm: 'baseline',\n treatmentArm: 'treatment',\n })\n return {\n pairs: result.pairs.map((pair) => {\n const baseline = pair.baseline as RunRecordArmRow\n const treatment = pair.treatment as RunRecordArmRow\n return {\n pairKey: pair.pairKey,\n repKey: baseline.repKey,\n baseline: baseline.run,\n treatment: treatment.run,\n }\n }),\n unpairedBaseline: result.unpairedBaseline.map((row) => (row as RunRecordArmRow).run),\n unpairedTreatment: result.unpairedTreatment.map((row) => (row as RunRecordArmRow).run),\n }\n}\n\nfunction runRecordArmRows(runs: readonly RunRecord[], arm: string): RunRecordArmRow[] {\n return runs.map((run) => {\n const scenarioId = run.scenarioId.trim()\n if (!scenarioId) {\n throw new ValidationError(\n `pairRunRecords: run '${run.runId}' is missing scenarioId; paired comparisons require explicit scenario identity`,\n )\n }\n return {\n pairKey: JSON.stringify([run.experimentId, scenarioId]),\n repKey: String(run.seed),\n arm,\n run,\n }\n })\n}\n\nfunction validateRunRecordArmRows(rows: readonly RunRecordArmRow[], arm: string): void {\n const byPairKey = new Map<string, RunRecordArmRow[]>()\n for (const row of rows) {\n const group = byPairKey.get(row.pairKey) ?? []\n group.push(row)\n byPairKey.set(row.pairKey, group)\n }\n for (const [pairKey, group] of byPairKey) {\n if (group.length > 1) indexByRepKey(group, pairKey, arm)\n }\n}\n\nfunction metricValue(row: PairedArmRow, name: string): number | undefined {\n const v = row.metrics?.[name]\n if (v === undefined) return undefined\n if (!Number.isFinite(v)) {\n throw new ValidationError(\n `comparePairedArms: non-finite value for metric '${name}' on pairKey '${row.pairKey}' (arm '${row.arm}'): ${v}`,\n )\n }\n return v\n}\n"],"mappings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,WAAW,KAAK;GACtB,MAAM,YAAY,KAAK;GACvB,OAAO;IACL,SAAS,KAAK;IACd,QAAQ,SAAS;IACjB,UAAU,SAAS;IACnB,WAAW,UAAU;GACvB;EACF,CAAC;EACD,kBAAkB,OAAO,iBAAiB,KAAK,QAAS,IAAwB,GAAG;EACnF,mBAAmB,OAAO,kBAAkB,KAAK,QAAS,IAAwB,GAAG;CACvF;AACF;AAEA,SAAS,iBAAiB,MAA4B,KAAgC;CACpF,OAAO,KAAK,KAAK,QAAQ;EACvB,MAAM,aAAa,IAAI,WAAW,KAAK;EACvC,IAAI,CAAC,YACH,MAAM,IAAI,gBACR,wBAAwB,IAAI,MAAM,+EACpC;EAEF,OAAO;GACL,SAAS,KAAK,UAAU,CAAC,IAAI,cAAc,UAAU,CAAC;GACtD,QAAQ,OAAO,IAAI,IAAI;GACvB;GACA;EACF;CACF,CAAC;AACH;AAEA,SAAS,yBAAyB,MAAkC,KAAmB;CACrF,MAAM,4BAAY,IAAI,IAA+B;CACrD,KAAK,MAAM,OAAO,MAAM;EACtB,MAAM,QAAQ,UAAU,IAAI,IAAI,OAAO,KAAK,CAAC;EAC7C,MAAM,KAAK,GAAG;EACd,UAAU,IAAI,IAAI,SAAS,KAAK;CAClC;CACA,KAAK,MAAM,CAAC,SAAS,UAAU,WAC7B,IAAI,MAAM,SAAS,GAAG,cAAc,OAAO,SAAS,GAAG;AAE3D;AAEA,SAAS,YAAY,KAAmB,MAAkC;CACxE,MAAM,IAAI,IAAI,UAAU;CACxB,IAAI,MAAM,KAAA,GAAW,OAAO,KAAA;CAC5B,IAAI,CAAC,OAAO,SAAS,CAAC,GACpB,MAAM,IAAI,gBACR,mDAAmD,KAAK,gBAAgB,IAAI,QAAQ,UAAU,IAAI,IAAI,MAAM,GAC9G;CAEF,OAAO;AACT"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"render-Cs34y0iX.js","names":["round","round","round","record","record","round"],"sources":["../src/supervisor-run/analyze-context.ts","../src/supervisor-run/analyze-decision.ts","../src/supervisor-run/analyze-economics.ts","../src/supervisor-run/analyze-orchestration.ts","../src/supervisor-run/patch-stats.ts","../src/supervisor-run/analyze-outcome.ts","../src/supervisor-run/analyze-spend.ts","../src/supervisor-run/analyze.ts","../src/supervisor-run/coordination-reader.ts","../src/supervisor-run/runtime-source-limits.ts","../src/supervisor-run/runtime-reader.ts","../src/supervisor-run/reader.ts","../src/supervisor-run/render.ts"],"sourcesContent":["import { parseJsonRecord, parseSupervisorTree, type SpawnRow } from './source-facts'\nimport { readTerminalRecord } from './terminal-record'\nimport { type SupervisorRunSources, type Unavailable, unavailable } from './types'\n\n/** The parsed sources and shared lookups every metric group reads. `gap` records an unavailable measurement on the report. */\nexport function createAnalysis(src: SupervisorRunSources) {\n const gaps: string[] = []\n const gap = (what: string, reason: string): Unavailable => {\n gaps.push(`${what}: ${reason}`)\n return unavailable(reason)\n }\n\n const journalMissing =\n src.journalMissingReason ??\n (src.supRunDir === null ? 'no Runtime supervisor run directory' : 'journal.jsonl absent')\n const haveJournal = src.journal !== null\n const tree = parseSupervisorTree(src)\n const state = tree.state\n const result = parseJsonRecord(src.result)\n const judge = parseJsonRecord(src.judge)\n // Runtime's terminal record is named on the report so a status never arrives unlabeled.\n const terminal = readTerminalRecord({\n state,\n result,\n failure: src.failure === undefined ? undefined : parseJsonRecord(src.failure),\n })\n const { rootId, workerSpawns, workerCloses, startedAt, completedAt } = tree\n const rootSpawn =\n rootId === null ? null : (tree.spawns.find((spawn) => spawn.id === rootId) ?? null)\n const spawnById = new Map(workerSpawns.map((spawn) => [spawn.id, spawn]))\n const spawnsByLabel = new Map<string, SpawnRow[]>()\n for (const spawn of workerSpawns) {\n const matches = spawnsByLabel.get(spawn.label) ?? []\n matches.push(spawn)\n spawnsByLabel.set(spawn.label, matches)\n }\n const spawnsForSource = (\n worker: NonNullable<SupervisorRunSources['workers']>[number],\n ): readonly SpawnRow[] => {\n if (worker.workerId === undefined) return spawnsByLabel.get(worker.label) ?? []\n const spawn = spawnById.get(worker.workerId)\n return spawn === undefined ? [] : [spawn]\n }\n const spawnForSource = (\n worker: NonNullable<SupervisorRunSources['workers']>[number],\n ): SpawnRow | null => {\n const matches = spawnsForSource(worker)\n return matches.length === 1 ? (matches[0] ?? null) : null\n }\n const closeById = new Map(workerCloses.map((close) => [close.id, close]))\n const workersGapReason = src.workersMissingReason ?? 'workers/ directory absent'\n return {\n src,\n gaps,\n gap,\n journalMissing,\n haveJournal,\n tree,\n state,\n result,\n judge,\n terminal,\n rootId,\n rootSpawn,\n workerSpawns,\n workerCloses,\n startedAt,\n completedAt,\n spawnsForSource,\n spawnForSource,\n closeById,\n workersGapReason,\n }\n}\n\nexport type Analysis = ReturnType<typeof createAnalysis>\n","import type { Analysis } from './analyze-context'\nimport type { StepFacts } from './analyze-orchestration'\nimport { workerSourceKey } from './source-facts'\nimport { type DecisionMetrics, unavailable } from './types'\n\n/** Settled verdicts, acceptance and review effort, with a named gap wherever the store never said. */\nexport function measureDecision(a: Analysis, m: StepFacts): DecisionMetrics {\n const {\n src,\n gap,\n journalMissing,\n haveJournal,\n tree,\n workerCloses,\n spawnForSource,\n closeById,\n workersGapReason,\n } = a\n const {\n steerQueuedTotal,\n upLegMessages,\n queuedGapReason,\n workerEventsGapReason,\n observeThenRespawn,\n respawnWithoutEvidence,\n } = m\n // ── decision quality ───────────────────────────────────────────────────\n const settledByStatus: Record<string, number> = {}\n const settledVerdicts: Record<string, number> = {}\n for (const c of workerCloses) {\n const key = c.status ?? 'unknown'\n settledByStatus[key] = (settledByStatus[key] ?? 0) + 1\n if (c.verdict !== null) settledVerdicts[c.verdict] = (settledVerdicts[c.verdict] ?? 0) + 1\n }\n\n // A store with no verify step never says pass or fail. Counting its silent\n // workers as `rejected: 0 / accepted: 0` would read as \"nothing was accepted\".\n const verdictLimit = src.limits.workerVerdicts\n // A store that retains no delivered patch still SETTLES a verdict, and that verdict is\n // the acceptance decision it recorded. Only the split between a green verdict backed by\n // a patch and a green verdict with nothing behind it needs patch bytes, so the\n // deliverables limit takes `emptyPass` and leaves `accepted` measured.\n const deliverablesLimit = src.limits.deliverables\n let accepted = 0\n let emptyPass = 0\n let evidenceBytes = 0\n const sourceVerdicts: boolean[] = []\n for (const w of src.workers ?? []) {\n const f = tree.workerLogs.get(workerSourceKey(w))\n if (f?.finished) evidenceBytes += f.evidenceBytes\n const spawn = spawnForSource(w)\n const close = spawn === null ? null : (closeById.get(spawn.id) ?? null)\n const passed = close?.valid ?? f?.passed ?? null\n if (passed !== null) sourceVerdicts.push(passed)\n if (passed === true) {\n if (deliverablesLimit !== null || (w.patchBytes ?? f?.finishedPatchBytes ?? 0) > 0) {\n accepted += 1\n } else {\n emptyPass += 1\n }\n }\n }\n const settledCloses = workerCloses.filter((close) => close.kind === 'settled')\n const structuredVerdicts = settledCloses\n .map((close) => close.valid)\n .filter((valid): valid is boolean => valid !== null)\n const journalVerdictsComplete =\n settledCloses.length > 0 && structuredVerdicts.length === settledCloses.length\n const sourceVerdictsComplete =\n sourceVerdicts.length > 0 && sourceVerdicts.length >= settledCloses.length\n const rejected = journalVerdictsComplete\n ? structuredVerdicts.filter((valid) => !valid).length\n : sourceVerdictsComplete\n ? sourceVerdicts.filter((valid) => !valid).length\n : 0\n const rejectedLimit =\n journalVerdictsComplete || sourceVerdictsComplete\n ? null\n : settledCloses.length > 0\n ? (verdictLimit ?? 'a settled journal verdict has no validity and no matched worker log')\n : verdictLimit !== null\n ? verdictLimit\n : !haveJournal && src.workers === null\n ? workersGapReason\n : null\n\n const decision: DecisionMetrics = {\n settledByStatus: haveJournal ? settledByStatus : gap('settledByStatus', journalMissing),\n settledVerdicts:\n verdictLimit !== null\n ? unavailable(verdictLimit)\n : haveJournal\n ? settledVerdicts\n : unavailable(journalMissing),\n accepted:\n verdictLimit !== null\n ? gap('accepted', verdictLimit)\n : src.workers === null\n ? unavailable(workersGapReason)\n : accepted,\n rejected: rejectedLimit === null ? rejected : unavailable(rejectedLimit),\n emptyPass:\n verdictLimit !== null\n ? gap('emptyPass', verdictLimit)\n : deliverablesLimit !== null\n ? gap('emptyPass', deliverablesLimit)\n : src.workers === null\n ? unavailable(workersGapReason)\n : emptyPass,\n observeThenRespawn: haveJournal ? observeThenRespawn : unavailable(journalMissing),\n respawnWithoutEvidence: haveJournal ? respawnWithoutEvidence : unavailable(journalMissing),\n reviewActions:\n src.workers === null\n ? unavailable(workersGapReason)\n : queuedGapReason === null\n ? steerQueuedTotal + upLegMessages\n : unavailable(queuedGapReason),\n workerEvidenceBytes:\n src.workers === null\n ? unavailable(workersGapReason)\n : workerEventsGapReason === null\n ? evidenceBytes\n : unavailable(workerEventsGapReason),\n }\n return decision\n}\n","import { roundDecimal as round } from '../math/round-decimal'\nimport { summarizeNumberSeries } from '../statistics'\nimport type { Analysis } from './analyze-context'\nimport type { SpendFacts, TotalUsd, WorkerTokens } from './analyze-spend'\nimport { parseJsonl, workerSourceKey } from './source-facts'\nimport {\n type DecisionMetrics,\n type EconomicsMetrics,\n isUnavailable,\n type PerWorkerRow,\n type SpendMeasurements,\n type SupervisorRunSources,\n unavailable,\n} from './types'\n\nconst NO_CACHE_COUNTERS = 'the journal carries no cache-token counters for this role'\n\nconst NO_CACHE_BREAKDOWN =\n 'Runtime recorded cacheBreakdownKnown:false — the provider reported a total without splitting cache reads from writes'\n\n/** One row per worker log, plus the capture gaps of the root and every worker. */\nexport function buildPerWorker(a: Analysis, f: SpendFacts, t: TotalUsd): PerWorkerRow[] {\n const { src, gaps, tree, rootId, spawnsForSource, spawnForSource, closeById } = a\n const { workerUsdById, workerUsdByLabel } = f\n const { usdLimit } = t\n const noteCaptureGaps = (\n owner: string,\n captures: SupervisorRunSources['rootWorkspaceCaptures'],\n ): void => {\n if (captures === null || captures?.length === 0) {\n gaps.push(`${owner} workspaceCapture: no retained output capture evidence`)\n } else if (captures !== undefined) {\n for (const [index, capture] of captures.entries()) {\n const source = `${owner} workspaceCapture[${index + 1}]`\n if (capture.projectionGap !== null) gaps.push(`${source}: ${capture.projectionGap}`)\n if (capture.coverageComplete === false) {\n gaps.push(\n `${source}: ${capture.incompleteReason ?? 'provider reported incomplete coverage'}`,\n )\n }\n if (capture.coverageComplete === null && capture.projectionGap === null) {\n gaps.push(`${source}: capture coverage was not recorded`)\n }\n }\n }\n }\n noteCaptureGaps(`root ${rootId ?? src.runRef}`, src.rootWorkspaceCaptures)\n const perWorker: PerWorkerRow[] = (src.workers ?? []).map((w) => {\n noteCaptureGaps(`worker ${w.workerId ?? w.label}`, w.workspaceCaptures)\n const f = tree.workerLogs.get(workerSourceKey(w))\n const matchingSpawns = spawnsForSource(w)\n const spawn = spawnForSource(w)\n const close = spawn === null ? null : (closeById.get(spawn.id) ?? null)\n const passed = close?.valid ?? f?.passed ?? null\n const matchingRoles = new Set(matchingSpawns.map((candidate) => candidate.role))\n const matchingRuntimes = new Set(matchingSpawns.map((candidate) => candidate.runtime))\n const matchingProfiles = new Set(matchingSpawns.map((candidate) => candidate.profileDigest))\n const journalWallMs =\n spawn?.at !== null &&\n spawn?.at !== undefined &&\n close?.at !== null &&\n close?.at !== undefined &&\n close.at >= spawn.at\n ? close.at - spawn.at\n : null\n return {\n workerId: w.workerId ?? null,\n worker: w.label,\n role: matchingRoles.size === 1 ? (matchingSpawns[0]?.role ?? null) : null,\n runtime: matchingRuntimes.size === 1 ? (matchingSpawns[0]?.runtime ?? null) : null,\n profileDigest:\n matchingProfiles.size === 1 ? (matchingSpawns[0]?.profileDigest ?? null) : null,\n status: close?.status ?? null,\n failure: close?.reason ?? null,\n infra: close?.infra ?? null,\n wallMs: f?.started != null && f.finishedAt != null ? f.finishedAt - f.started : journalWallMs,\n tokensIn:\n w.tokensIn ??\n (close?.hasSpend === true && close.spend.tokensKnown ? close.spend.tokens.input : null),\n tokensOut:\n w.tokensOut ??\n (close?.hasSpend === true && close.spend.tokensKnown ? close.spend.tokens.output : null),\n usd:\n usdLimit !== null\n ? null\n : w.workerId === undefined\n ? (workerUsdByLabel.get(w.label) ?? null)\n : (workerUsdById.get(w.workerId) ?? null),\n patchBytes: w.patchBytes ?? f?.finishedPatchBytes ?? null,\n passed,\n score: close?.score ?? f?.score ?? null,\n workspaceCaptures: w.workspaceCaptures ?? null,\n }\n })\n return perWorker\n}\n\n/** The supervisor brain's tokens, cache and USD. */\nfunction buildBrainSpend(\n a: Analysis,\n f: SpendFacts,\n t: TotalUsd,\n): EconomicsMetrics['brain'] {\n const { src, gap, journalMissing, haveJournal, tree } = a\n const { brainTokensUnreported, brainUsdUnreported } = f\n const { usdLimit } = t\n const managerTokenLimit = src.limits.managerTokens\n return {\n tokensIn:\n managerTokenLimit !== null\n ? gap('brain.tokensIn', managerTokenLimit)\n : !haveJournal\n ? gap('brain.tokensIn', journalMissing)\n : brainTokensUnreported !== null\n ? gap('brain.tokensIn', brainTokensUnreported)\n : tree.brain.tokensIn,\n tokensOut:\n managerTokenLimit !== null\n ? unavailable(managerTokenLimit)\n : !haveJournal\n ? unavailable(journalMissing)\n : brainTokensUnreported !== null\n ? unavailable(brainTokensUnreported)\n : tree.brain.tokensOut,\n usd:\n usdLimit !== null\n ? unavailable(usdLimit)\n : !haveJournal\n ? unavailable(journalMissing)\n : brainUsdUnreported !== null\n ? unavailable(brainUsdUnreported)\n : round(tree.brain.usd, 6),\n cacheRead:\n managerTokenLimit !== null\n ? unavailable(managerTokenLimit)\n : !haveJournal\n ? unavailable(journalMissing)\n : brainTokensUnreported !== null\n ? unavailable(brainTokensUnreported)\n : !tree.brain.hasCache\n ? unavailable(NO_CACHE_COUNTERS)\n : tree.brain.cacheBreakdownKnown\n ? tree.brain.cacheRead\n : unavailable(NO_CACHE_BREAKDOWN),\n cacheWrite:\n managerTokenLimit !== null\n ? unavailable(managerTokenLimit)\n : !haveJournal\n ? unavailable(journalMissing)\n : brainTokensUnreported !== null\n ? unavailable(brainTokensUnreported)\n : !tree.brain.hasCache\n ? unavailable(NO_CACHE_COUNTERS)\n : tree.brain.cacheBreakdownKnown\n ? tree.brain.cacheWrite\n : unavailable(NO_CACHE_BREAKDOWN),\n source:\n managerTokenLimit ??\n (haveJournal\n ? `journal metered events (n=${tree.brain.meteredCount})${\n tree.brain.usdKnownCount > 0 && tree.brain.usdUnknownCount > 0\n ? ` — ${tree.brain.usdUnknownCount} unpriced`\n : ''\n }`\n : journalMissing),\n }\n}\n\n/** The workers' tokens, cache and USD. */\nfunction buildWorkerSpend(\n a: Analysis,\n f: SpendFacts,\n t: TotalUsd,\n w: WorkerTokens,\n): EconomicsMetrics['workers'] {\n const { src, journalMissing, haveJournal } = a\n const { rootChildSpends, workerUsdUnknownNodes, journalWorkerUsd, workerUsdUnreported } = f\n const { usdLimit } = t\n const { sq, workerTokenLimit, workerIn, workerOut } = w\n return {\n tokensIn: workerIn,\n tokensOut: workerOut,\n cacheRead:\n workerTokenLimit !== null\n ? unavailable(workerTokenLimit)\n : sq?.cacheRead !== undefined\n ? sq.cacheRead\n : unavailable(NO_CACHE_COUNTERS),\n cacheWrite:\n workerTokenLimit !== null\n ? unavailable(workerTokenLimit)\n : sq?.cacheWrite !== undefined\n ? sq.cacheWrite\n : unavailable(NO_CACHE_COUNTERS),\n usd:\n usdLimit !== null\n ? unavailable(usdLimit)\n : !haveJournal\n ? unavailable(journalMissing)\n : workerUsdUnreported !== null\n ? unavailable(workerUsdUnreported)\n : round(journalWorkerUsd, 6),\n source: `${\n workerTokenLimit !== null\n ? workerTokenLimit\n : sq !== null\n ? `journal settled spend + ${sq.store} sessions (n=${sq.sessions})`\n : `journal settled spend only — ${src.harnessMissingReason ?? 'harness session store unavailable'}`\n }${\n workerUsdUnknownNodes.length > 0 && workerUsdUnknownNodes.length < rootChildSpends.length\n ? ` — ${workerUsdUnknownNodes.length} unpriced`\n : ''\n }`,\n }\n}\n\nexport function buildEconomics(\n a: Analysis,\n f: SpendFacts,\n t: TotalUsd,\n w: WorkerTokens,\n e: EconomicsParts,\n): EconomicsMetrics {\n const { src, gap, journalMissing, haveJournal, tree, workersGapReason } = a\n const { rootChildCloses, journalWorkerUsd, usdUnknownRecords } = f\n const { stateUsd, usdLimit, totalUsd, usdUnreportedReason } = t\n const { decision, spend, perWorker } = e\n const wallDistribution = summarizeNumberSeries(\n perWorker.map((w) => w.wallMs).filter((w): w is number => w !== null),\n )\n\n const brainCalls = parseJsonl(src.brainLog)\n return {\n resourceRecords:\n src.journal === null && !tree.resourceRecords?.length\n ? unavailable(journalMissing)\n : (tree.resourceRecords ?? []),\n brain: buildBrainSpend(a, f, t),\n brainTruncations:\n src.brainLog === null\n ? gap(\n 'brain.brainTruncations',\n src.brainLogMissingReason ??\n (src.supRunDir === null\n ? 'no Runtime supervisor run directory'\n : 'brain.jsonl absent — this source has no brain-call tap, so truncation cannot be ruled out'),\n )\n : brainCalls.filter((c) => c.finish_reason === 'length').length,\n workers: buildWorkerSpend(a, f, t, w),\n spend,\n totalUsd,\n totalUsdSource:\n usdLimit !== null\n ? usdLimit\n : stateUsd !== null\n ? `state.json result.spentUsd${rootChildCloses.length > 0 && journalWorkerUsd === 0 ? ' — brain-priced only; worker CLI inference is unpriced (see worker token counts)' : ''}`\n : !haveJournal\n ? journalMissing\n : usdUnknownRecords > 0\n ? usdUnreportedReason\n : 'journal metered + settled usd',\n costPerAcceptedPatchUsd: isUnavailable(totalUsd)\n ? unavailable(totalUsd.unavailable)\n : isUnavailable(decision.accepted)\n ? unavailable(decision.accepted.unavailable)\n : decision.accepted === 0\n ? unavailable('no accepted worker patch (cost has no denominator)')\n : round(totalUsd / decision.accepted, 6),\n workerWallMsDistribution:\n wallDistribution === null\n ? unavailable(\n src.workers === null ? workersGapReason : 'no worker start/finish pairs captured',\n )\n : wallDistribution,\n perWorker: src.workers === null ? unavailable(workersGapReason) : perWorker,\n }\n}\n\nexport interface EconomicsParts {\n decision: DecisionMetrics\n spend: SpendMeasurements\n perWorker: PerWorkerRow[]\n}\n","import { roundDecimal as round } from '../math/round-decimal'\nimport type { Analysis } from './analyze-context'\nimport { type SpawnRow, type WorkerLogFacts, workerSourceKey } from './source-facts'\nimport {\n isUnavailable,\n type Measured,\n type OrchestrationMetrics,\n type SteerBreakdown,\n unavailable,\n} from './types'\n\n/** Supervisor wall time and where it ends. Explicit stamps win; the journal span is a lower bound; an inverted stamp pair stays unavailable. */\nexport function measureWall(a: Analysis) {\n const { gap, journalMissing, haveJournal, tree, startedAt, completedAt } = a\n // Wall provenance: explicit stamps when the store wrote both; otherwise the\n // journal event span (a lower bound) when there is no completion stamp at\n // all. A present-but-inverted stamp pair is corruption, not absence, and\n // stays unavailable.\n const wallSpanStart = startedAt ?? tree.firstEventAt\n const wallSpanEnd = tree.lastEventAt\n let supervisorWallMs: Measured<number>\n let supervisorWallSource: Measured<'stamps' | 'journal-span'>\n if (startedAt !== null && completedAt !== null && completedAt >= startedAt) {\n supervisorWallMs = completedAt - startedAt\n supervisorWallSource = 'stamps'\n } else if (\n completedAt === null &&\n wallSpanStart !== null &&\n wallSpanEnd !== null &&\n wallSpanEnd >= wallSpanStart\n ) {\n supervisorWallMs = wallSpanEnd - wallSpanStart\n supervisorWallSource = 'journal-span'\n } else {\n const reason = !haveJournal\n ? journalMissing\n : 'no parseable start/complete timestamps in state.json or journal'\n supervisorWallMs = gap('supervisorWallMs', reason)\n supervisorWallSource = unavailable(reason)\n }\n // Where the measured wall ends — the completion stamp, or the last stamped\n // journal event on the journal-span path. Idle and utilization integrate to\n // this bound so their denominator is the wall they are reported against.\n const wallEndAt = completedAt ?? (supervisorWallSource === 'journal-span' ? wallSpanEnd : null)\n return { supervisorWallMs, supervisorWallSource, wallEndAt }\n}\n\n/** Steer counts from worker inboxes and the driver log. */\nexport function measureSteers(a: Analysis) {\n const { src, gap, tree, workersGapReason } = a\n // ── steers (worker inbox + control events) ─────────────────────────────\n const steerRows: SteerBreakdown[] = []\n let steerQueuedTotal = 0\n let steerDeliveredTotal = 0\n let upLegMessages = 0\n if (src.workers !== null) {\n for (const w of src.workers) {\n const facts = tree.workerLogs.get(workerSourceKey(w))\n const queued = facts?.steersQueued ?? null\n const delivered = facts?.steersDelivered ?? null\n upLegMessages += facts?.questions ?? 0\n if (queued !== null && delivered !== null) {\n steerRows.push({ workerId: w.workerId ?? null, worker: w.label, queued, delivered })\n }\n if (queued !== null) steerQueuedTotal += queued\n if (delivered !== null) steerDeliveredTotal += delivered\n }\n }\n const unavailableReasons = (pick: (facts: WorkerLogFacts) => string | null): string | null => {\n const reasons = tree.workerLogRows\n .map((facts) => pick(facts))\n .filter((reason): reason is string => reason !== null)\n return reasons.length === 0\n ? null\n : `exact steer accounting unavailable for ${reasons.length} worker row(s): ${[...new Set(reasons)].join(' | ')}`\n }\n const queuedGapReason = unavailableReasons((facts) => facts.steersQueuedUnavailable)\n const deliveredGapReason = unavailableReasons((facts) => facts.steersDeliveredUnavailable)\n const workerEventsGapReason = unavailableReasons((facts) =>\n !facts.eventsCaptured\n ? 'events absent'\n : facts.eventsInvalidRows > 0\n ? 'events contain malformed rows'\n : null,\n )\n const steers: Measured<number> =\n src.workers === null\n ? gap('steers', workersGapReason)\n : queuedGapReason === null\n ? steerQueuedTotal\n : gap('steers', queuedGapReason)\n const steersDelivered: Measured<number> =\n src.workers === null\n ? unavailable(workersGapReason)\n : deliveredGapReason === null\n ? steerDeliveredTotal\n : unavailable(deliveredGapReason)\n const steersByWorker: Measured<readonly SteerBreakdown[]> =\n src.workers === null\n ? unavailable(workersGapReason)\n : queuedGapReason === null && deliveredGapReason === null\n ? steerRows\n : unavailable(queuedGapReason ?? deliveredGapReason ?? workersGapReason)\n\n // The `[driver] registered tools: …supervisor_steer…` banner names the verb without\n // invoking it, so banner lines are subtracted from the raw mention count.\n const driverSteerCalls: Measured<number> =\n src.driverLog === null\n ? gap('driverSteerCalls', 'driver.log absent')\n : Math.max(\n 0,\n (src.driverLog.match(/supervisor_steer/g) ?? []).length -\n registrationMentions(src.driverLog),\n )\n return {\n steers,\n steersDelivered,\n steersByWorker,\n driverSteerCalls,\n steerQueuedTotal,\n upLegMessages,\n queuedGapReason,\n workerEventsGapReason,\n }\n}\n\n/** Waves, peak concurrency, idle time and summed worker wall from the spawn/close timeline. */\nexport function measureConcurrency(a: Analysis, wallEndAt: number | null) {\n const { workerSpawns, workerCloses, startedAt } = a\n const timeline: { at: number; delta: 1 | -1 }[] = []\n for (const s of workerSpawns) if (s.at !== null) timeline.push({ at: s.at, delta: 1 })\n for (const c of workerCloses) if (c.at !== null) timeline.push({ at: c.at, delta: -1 })\n timeline.sort((a, b) => a.at - b.at || a.delta - b.delta)\n\n let waves = 0\n const waveSizes: number[] = []\n let closedSinceWaveStart = true\n for (const step of timeline) {\n if (step.delta === 1) {\n if (closedSinceWaveStart) {\n waves += 1\n waveSizes.push(0)\n closedSinceWaveStart = false\n }\n waveSizes[waveSizes.length - 1] = (waveSizes[waveSizes.length - 1] ?? 0) + 1\n } else {\n closedSinceWaveStart = true\n }\n }\n\n let live = 0\n let maxConcurrency = 0\n let idleMs = 0\n let sumWorkerWallMs = 0\n let prev = startedAt\n for (const step of timeline) {\n if (prev !== null && step.at >= prev) {\n const span = step.at - prev\n if (live === 0) idleMs += span\n sumWorkerWallMs += span * live\n }\n live += step.delta\n if (live > maxConcurrency) maxConcurrency = live\n prev = step.at\n }\n if (prev !== null && wallEndAt !== null && wallEndAt >= prev) {\n const span = wallEndAt - prev\n if (live === 0) idleMs += span\n sumWorkerWallMs += span * live\n }\n return { waves, waveSizes, maxConcurrency, idleMs, sumWorkerWallMs }\n}\n\n/** Respawn counts per parent, split by whether a sibling closed in between. */\nexport function measureRespawns(a: Analysis) {\n const { workerSpawns, closeById } = a\n const childSpawnsByParent = new Map<string, SpawnRow[]>()\n for (const spawn of workerSpawns) {\n if (spawn.parent === null) continue\n const siblings = childSpawnsByParent.get(spawn.parent) ?? []\n siblings.push(spawn)\n childSpawnsByParent.set(spawn.parent, siblings)\n }\n\n let respawns = 0\n let observeThenRespawn = 0\n let respawnWithoutEvidence = 0\n const repeatedLabelSet = new Set<string>()\n for (const siblings of childSpawnsByParent.values()) {\n const labelCounts = new Map<string, number>()\n for (const spawn of siblings) {\n labelCounts.set(spawn.label, (labelCounts.get(spawn.label) ?? 0) + 1)\n }\n for (const [label, count] of labelCounts) {\n if (count > 1) repeatedLabelSet.add(label)\n }\n\n const orderedSpawns = siblings\n .map((spawn, index) => ({ spawn, index }))\n .filter(\n (row): row is { spawn: SpawnRow & { at: number }; index: number } => row.spawn.at !== null,\n )\n .sort((a, b) => a.spawn.at - b.spawn.at || a.index - b.index)\n const directCloseTimes = siblings\n .map((spawn) => closeById.get(spawn.id)?.at ?? null)\n .filter((at): at is number => at !== null)\n .sort((a, b) => a - b)\n const firstDirectClose = directCloseTimes[0] ?? null\n\n for (let i = 1; i < orderedSpawns.length; i += 1) {\n const previous = orderedSpawns[i - 1]?.spawn.at\n const current = orderedSpawns[i]?.spawn.at\n if (previous === undefined || current === undefined) continue\n if (firstDirectClose === null || current <= firstDirectClose) continue\n respawns += 1\n const sawEvidence = hasNumberBetween(directCloseTimes, previous, current)\n if (sawEvidence) observeThenRespawn += 1\n else respawnWithoutEvidence += 1\n }\n }\n const repeatedLabels = [...repeatedLabelSet]\n return { respawns, observeThenRespawn, respawnWithoutEvidence, repeatedLabels }\n}\n\n/** The deepest chain of spawns below the root. */\nexport function measureDelegationDepth(a: Analysis) {\n const { tree, rootId, workerSpawns } = a\n const parentOf = new Map(tree.spawns.map((s) => [s.id, s.parent]))\n let delegationDepth = 0\n for (const s of workerSpawns) {\n let d = 0\n let cur: string | null = s.id\n const seen = new Set<string>()\n while (cur !== null && cur !== rootId && !seen.has(cur)) {\n seen.add(cur)\n d += 1\n cur = parentOf.get(cur) ?? null\n }\n if (d > delegationDepth) delegationDepth = d\n }\n return delegationDepth\n}\n\nexport function buildOrchestration(a: Analysis, m: StepFacts): OrchestrationMetrics {\n const { gap, journalMissing, haveJournal, workerSpawns, workerCloses, startedAt } = a\n const {\n supervisorWallMs,\n supervisorWallSource,\n steers,\n steersDelivered,\n steersByWorker,\n driverSteerCalls,\n waves,\n waveSizes,\n maxConcurrency,\n idleMs,\n sumWorkerWallMs,\n respawns,\n repeatedLabels,\n delegationDepth,\n } = m\n const firstWorkerSpawnAt = workerSpawns.reduce<number | null>(\n (acc, s) => (s.at === null ? acc : acc === null ? s.at : Math.min(acc, s.at)),\n null,\n )\n\n const orchestration: OrchestrationMetrics = {\n workersSpawned: haveJournal ? workerSpawns.length : gap('workersSpawned', journalMissing),\n workersSettled: haveJournal\n ? workerCloses.filter((c) => c.kind === 'settled').length\n : unavailable(journalMissing),\n workersCancelled: haveJournal\n ? workerCloses.filter((c) => c.kind === 'cancelled').length\n : unavailable(journalMissing),\n steers,\n steersDelivered,\n steersByWorker,\n driverSteerCalls,\n waves: haveJournal ? waves : unavailable(journalMissing),\n waveSizes: haveJournal ? waveSizes : unavailable(journalMissing),\n maxConcurrency: haveJournal ? maxConcurrency : unavailable(journalMissing),\n respawns: haveJournal ? respawns : unavailable(journalMissing),\n repeatedLabels: haveJournal ? repeatedLabels : unavailable(journalMissing),\n delegationDepth: haveJournal ? delegationDepth : unavailable(journalMissing),\n timeToFirstSpawnMs:\n startedAt !== null && firstWorkerSpawnAt !== null\n ? firstWorkerSpawnAt - startedAt\n : haveJournal\n ? unavailable('no worker spawn timestamps')\n : unavailable(journalMissing),\n supervisorWallMs,\n supervisorWallSource,\n idleMs: isUnavailable(supervisorWallMs) ? unavailable(supervisorWallMs.unavailable) : idleMs,\n idlePct:\n isUnavailable(supervisorWallMs) || supervisorWallMs === 0\n ? isUnavailable(supervisorWallMs)\n ? unavailable(supervisorWallMs.unavailable)\n : unavailable('supervisor wall is 0ms')\n : round((idleMs / supervisorWallMs) * 100, 1),\n workerUtilization:\n isUnavailable(supervisorWallMs) || supervisorWallMs === 0\n ? isUnavailable(supervisorWallMs)\n ? unavailable(supervisorWallMs.unavailable)\n : unavailable('supervisor wall is 0ms')\n : round(sumWorkerWallMs / supervisorWallMs, 3),\n }\n return orchestration\n}\n\n/** Whether sorted values contain one value in the inclusive interval. */\nfunction hasNumberBetween(sorted: readonly number[], low: number, high: number): boolean {\n let left = 0\n let right = sorted.length\n while (left < right) {\n const middle = left + Math.floor((right - left) / 2)\n if ((sorted[middle] as number) < low) left = middle + 1\n else right = middle\n }\n return left < sorted.length && (sorted[left] as number) <= high\n}\n\n/** `[driver] registered tools: …supervisor_steer…` is a banner, not an invocation. */\nfunction registrationMentions(driverLog: string): number {\n let n = 0\n for (const line of driverLog.split('\\n')) {\n if (line.includes('registered tools:') && line.includes('supervisor_steer')) n += 1\n }\n return n\n}\n\nexport type StepFacts = ReturnType<typeof measureWall> &\n ReturnType<typeof measureSteers> &\n ReturnType<typeof measureConcurrency> &\n ReturnType<typeof measureRespawns> & { delegationDepth: number }\n","/** Unified-diff target, line, and test-file touch counts. */\nimport type { PatchStats } from './types'\n\n/** Unified-diff stats. Counts `+++ b/<path>` targets, body +/- lines, and test-file touches. */\nexport function parsePatch(text: string): PatchStats {\n const files = new Set<string>()\n const testFiles = new Set<string>()\n let added = 0\n let removed = 0\n for (const line of text.split('\\n')) {\n if (line.startsWith('+++ ')) {\n const p = line.slice(4).trim().replace(/^b\\//, '')\n if (p !== '/dev/null') {\n files.add(p)\n if (isTestPath(p)) testFiles.add(p)\n }\n continue\n }\n if (line.startsWith('--- ') || line.startsWith('diff --git') || line.startsWith('index ')) {\n continue\n }\n if (line.startsWith('+')) added += 1\n else if (line.startsWith('-')) removed += 1\n }\n return {\n files: files.size,\n linesAdded: added,\n linesRemoved: removed,\n testFilesTouched: [...testFiles].sort(),\n }\n}\n\nfunction isTestPath(p: string): boolean {\n const base = p.split('/').pop() ?? p\n return (\n /(^|\\/)(tests?|__tests__|testing|spec)(\\/|$)/.test(p) ||\n /\\.(test|spec)\\.[cm]?[jt]sx?$/.test(base) ||\n /^test_.*\\.py$/.test(base) ||\n /_test\\.py$/.test(base)\n )\n}\n","import type { Analysis } from './analyze-context'\nimport type { TotalUsd } from './analyze-spend'\nimport { parsePatch } from './patch-stats'\nimport {\n isUnavailable,\n type Measured,\n type OutcomeMetrics,\n type PatchStats,\n unavailable,\n} from './types'\n\n/** Terminal status, verdicts, judge result and the delivered patch. */\nexport function buildOutcome(a: Analysis, t: TotalUsd): OutcomeMetrics {\n const { src, gap, state, result, judge, terminal } = a\n const { stateResult } = t\n const patchStats: Measured<PatchStats> =\n src.patch === null\n ? gap('patch', src.limits.deliverables ?? 'delivered patch file absent')\n : parsePatch(src.patch)\n\n const outcome: OutcomeMetrics = {\n supStatus: isUnavailable(terminal.supStatus)\n ? gap('supStatus', terminal.supStatus.unavailable)\n : terminal.supStatus,\n supStatusSource: terminal.supStatusSource,\n supReason: terminal.supReason,\n failure: terminal.failure,\n supVerdict:\n pickString(state, 'verdict') ??\n pickString(result, 'sup_verdict') ??\n unavailable('no state.json / result.json verdict'),\n delivered:\n typeof stateResult.delivered === 'boolean'\n ? stateResult.delivered\n : typeof result?.delivered === 'boolean'\n ? result.delivered\n : unavailable('no delivered flag in state.json or result.json'),\n judgeResolved:\n judge === null\n ? gap('judge', 'judge.json absent')\n : typeof judge.resolved === 'boolean'\n ? judge.resolved\n : null,\n judgeScore:\n judge === null\n ? unavailable('judge.json absent')\n : typeof judge.score === 'number'\n ? judge.score\n : null,\n judgePassed:\n judge === null\n ? unavailable('judge.json absent')\n : typeof judge.passed === 'number'\n ? judge.passed\n : null,\n judgeTotal:\n judge === null\n ? unavailable('judge.json absent')\n : typeof judge.total === 'number'\n ? judge.total\n : null,\n verifyPass:\n typeof result?.verify_pass === 'boolean'\n ? result.verify_pass\n : gap('verifyPass', 'result.json absent or has no verify_pass'),\n verifyRc:\n typeof result?.verify_rc === 'number'\n ? result.verify_rc\n : unavailable('result.json absent or has no verify_rc'),\n patch: patchStats,\n judgeSource: src.judgeSource,\n }\n return outcome\n}\n\nfunction pickString(rec: Record<string, unknown> | null, key: string): string | null {\n const v = rec?.[key]\n return typeof v === 'string' ? v : null\n}\n","import { roundDecimal as round } from '../math/round-decimal'\nimport type { Analysis } from './analyze-context'\nimport { asRecord } from './source-facts'\nimport { type Measured, type SpendMeasurements, unavailable } from './types'\n\n/** Spend records of the root and its children, split into reporting and unreporting. */\nexport function collectSpendFacts(a: Analysis) {\n const { tree, rootId, workerSpawns, workerCloses } = a\n const rootChildIds = new Set(\n workerSpawns.filter((spawn) => spawn.parent === rootId).map((spawn) => spawn.id),\n )\n const rootChildCloses = workerCloses.filter((close) => rootChildIds.has(close.id))\n // Runtime marks a spend record `usdKnown: false` / `tokensKnown: false` when the work\n // HAPPENED but no provider receipt covered its price or its tokens. Folding such a record\n // in prices unreported work at zero; dropping the whole channel discards every record that\n // DID report. So each channel sums only the reporting records and names the rest.\n const rootChildSpends = rootChildCloses.filter((close) => close.hasSpend)\n const workerUsdUnknownNodes = rootChildSpends\n .filter((close) => !close.spend.usdKnown)\n .map((close) => close.id)\n const workerTokensUnknownNodes = rootChildSpends\n .filter((close) => !close.spend.tokensKnown)\n .map((close) => close.id)\n const workerTokenSpends = rootChildSpends.filter((close) => close.spend.tokensKnown)\n const journalWorkerIn = workerTokenSpends.reduce((a, c) => a + c.spend.tokens.input, 0)\n const journalWorkerOut = workerTokenSpends.reduce((a, c) => a + c.spend.tokens.output, 0)\n const journalWorkerUsd = rootChildSpends\n .filter((close) => close.spend.usdKnown)\n .reduce((a, c) => a + c.spend.usd, 0)\n const usdUnknownIds = new Set(\n workerCloses.filter((close) => close.hasSpend && !close.spend.usdKnown).map((c) => c.id),\n )\n const workerUsdById = new Map<string, number>()\n for (const c of workerCloses) {\n if (usdUnknownIds.has(c.id)) continue\n workerUsdById.set(c.id, (workerUsdById.get(c.id) ?? 0) + c.spend.usd)\n }\n const labelById = new Map(workerSpawns.map((spawn) => [spawn.id, spawn.label]))\n const usdUnknownLabels = new Set(\n [...usdUnknownIds].map((id) => labelById.get(id)).filter((l): l is string => l !== undefined),\n )\n const workerUsdByLabel = new Map<string, number>()\n for (const close of workerCloses) {\n const label = labelById.get(close.id)\n if (label === undefined || usdUnknownLabels.has(label)) continue\n workerUsdByLabel.set(label, (workerUsdByLabel.get(label) ?? 0) + close.spend.usd)\n }\n const brainUsdUnknownNodes =\n tree.brain.usdUnknownCount > 0 && rootId !== null ? ([rootId] as const) : []\n const brainTokensUnknownNodes =\n tree.brain.tokensUnknownCount > 0 && rootId !== null ? ([rootId] as const) : []\n const usdKnownRecords =\n tree.brain.usdKnownCount + rootChildSpends.filter((close) => close.spend.usdKnown).length\n const usdUnknownRecords = tree.brain.usdUnknownCount + workerUsdUnknownNodes.length\n const usdUnknownNodes = [...brainUsdUnknownNodes, ...workerUsdUnknownNodes]\n // The named nodes are what makes the gap actionable, but a fleet run can have hundreds,\n // and this string lands in a report line. Name the first few and count the rest.\n const NAMED_NODE_LIMIT = 5\n const nameNodes = (nodes: readonly string[]): string => {\n if (nodes.length === 0) return ''\n const shown = nodes.slice(0, NAMED_NODE_LIMIT)\n const rest = nodes.length - shown.length\n return ` (${shown.join(', ')}${rest === 0 ? '' : ` +${rest} more`})`\n }\n const unpriced = (unknown: number, total: number, nodes: readonly string[]): string =>\n `Runtime recorded usdKnown:false on ${unknown} of ${total} spend record(s)${nameNodes(nodes)}`\n // A token total is a bare `Measured<number>` with no record denominator beside it, so a\n // partial sum there would be an unlabelled floor — the exact collapse this module refuses.\n // Spend has `SpendMeasurement.records`/`unknownRecords` to carry the split, so it stays\n // partial; tokens go absent with the unreporting nodes named.\n const unreportedTokens = (unknown: number, total: number, nodes: readonly string[]): string =>\n `Runtime recorded tokensKnown:false on ${unknown} of ${total} spend record(s)${nameNodes(nodes)}`\n const usdPartial = usdKnownRecords > 0 && usdUnknownRecords > 0\n const usdAllUnknown = usdKnownRecords === 0 && usdUnknownRecords > 0\n // A role whose records are ALL unreported has nothing measured to report, so it stays\n // unavailable. A role with some of each keeps its sum and labels it in `source`.\n const brainTokensUnreported =\n tree.brain.tokensUnknownCount === 0\n ? null\n : unreportedTokens(\n tree.brain.tokensUnknownCount,\n tree.brain.meteredCount,\n brainTokensUnknownNodes,\n )\n const brainUsdUnreported =\n tree.brain.usdKnownCount > 0 || tree.brain.usdUnknownCount === 0\n ? null\n : unpriced(tree.brain.usdUnknownCount, tree.brain.meteredCount, brainUsdUnknownNodes)\n const workerUsdUnreported =\n workerUsdUnknownNodes.length === 0 || workerUsdUnknownNodes.length < rootChildSpends.length\n ? null\n : unpriced(workerUsdUnknownNodes.length, rootChildSpends.length, workerUsdUnknownNodes)\n return {\n rootChildCloses,\n rootChildSpends,\n workerUsdUnknownNodes,\n workerTokensUnknownNodes,\n journalWorkerIn,\n journalWorkerOut,\n journalWorkerUsd,\n workerUsdById,\n workerUsdByLabel,\n usdKnownRecords,\n usdUnknownRecords,\n usdUnknownNodes,\n brainUsdUnknownNodes,\n brainTokensUnknownNodes,\n unpriced,\n unreportedTokens,\n usdPartial,\n usdAllUnknown,\n brainTokensUnreported,\n brainUsdUnreported,\n workerUsdUnreported,\n }\n}\n\n/** Worker token totals: journal spend plus harness session counts, or the reason they are absent. */\nexport function measureWorkerTokens(a: Analysis, f: SpendFacts) {\n const { src, gap, haveJournal } = a\n const {\n rootChildSpends,\n workerTokensUnknownNodes,\n journalWorkerIn,\n journalWorkerOut,\n unreportedTokens,\n } = f\n const sq = src.harnessWorkerTokens\n const harnessGapReason =\n src.harnessMissingReason ?? 'harness session store unavailable and journal settled spend is 0'\n const workerTokenLimit = src.limits.workerTokens\n const workerTokensUnreported =\n workerTokensUnknownNodes.length === 0\n ? null\n : unreportedTokens(\n workerTokensUnknownNodes.length,\n rootChildSpends.length,\n workerTokensUnknownNodes,\n )\n const workerIn: Measured<number> =\n workerTokenLimit !== null\n ? gap('workers.tokensIn', workerTokenLimit)\n : workerTokensUnreported !== null\n ? gap('workers.tokensIn', workerTokensUnreported)\n : sq !== null\n ? journalWorkerIn + sq.input\n : haveJournal\n ? journalWorkerIn\n : gap('workers.tokensIn', harnessGapReason)\n const workerOut: Measured<number> =\n workerTokenLimit !== null\n ? unavailable(workerTokenLimit)\n : workerTokensUnreported !== null\n ? unavailable(workerTokensUnreported)\n : sq !== null\n ? journalWorkerOut + sq.output\n : haveJournal\n ? journalWorkerOut\n : unavailable(harnessGapReason)\n return { sq, workerTokenLimit, workerIn, workerOut }\n}\n\n/** Total USD and the close record it is read against. */\nexport function measureTotalUsd(a: Analysis, f: SpendFacts) {\n const { src, gap, journalMissing, haveJournal, tree, state, result } = a\n const { journalWorkerUsd, usdKnownRecords, usdUnknownRecords, usdUnknownNodes, unpriced } = f\n const stateResult = asRecord(state?.result)\n const stateUsd = typeof stateResult.spentUsd === 'number' ? stateResult.spentUsd : null\n const resultSpentTotal = asRecord(result?.spentTotal)\n const resultCloseUsd =\n typeof resultSpentTotal.usd === 'number' && Number.isFinite(resultSpentTotal.usd)\n ? resultSpentTotal.usd\n : null\n // The close record: what the store wrote as settled when the run closed.\n const closeUsd = stateUsd ?? resultCloseUsd\n // A store that logs tokens but never a price yields usd 0 from every sum. That\n // 0 is the store's silence, not a free run, so the limit outranks the sum.\n const usdLimit = src.limits.spendUsd\n // The close record carries its own completeness flag: `spentTotal.usdKnown: false` means\n // Runtime priced part of the run from a catalog, so the number is a floor, not a total.\n const closeUsdUnreported =\n stateUsd === null && resultCloseUsd !== null && resultSpentTotal.usdKnown === false\n const usdUnreportedReason = unpriced(\n usdUnknownRecords,\n usdKnownRecords + usdUnknownRecords,\n usdUnknownNodes,\n )\n // Which numbers may be partial, and which must go absent: a number may be a floor only\n // when its own record carries the known/unknown split beside it — `SpendMeasurement`\n // has `records`/`unknownRecords`, and `RoleSpend` has `source`. `totalUsd` is a bare\n // scalar, so a floor there is an unlabelled understatement and stays unavailable; the\n // partial sum with its denominators lives in `spend.journalDerived`, which this type's\n // own doc already names as the field to prefer.\n const totalUsd: Measured<number> =\n usdLimit !== null\n ? gap('totalUsd', usdLimit)\n : stateUsd !== null\n ? round(stateUsd, 6)\n : !haveJournal\n ? gap('totalUsd', journalMissing)\n : usdUnknownRecords > 0\n ? gap('totalUsd', usdUnreportedReason)\n : round(tree.brain.usd + journalWorkerUsd, 6)\n return {\n stateResult,\n stateUsd,\n usdLimit,\n totalUsd,\n closeUsd,\n closeUsdUnreported,\n usdUnreportedReason,\n }\n}\n\nexport function buildSpend(a: Analysis, f: SpendFacts, t: TotalUsd): SpendMeasurements {\n const { journalMissing, haveJournal, tree, rootId } = a\n const {\n journalWorkerUsd,\n usdKnownRecords,\n usdUnknownRecords,\n usdUnknownNodes,\n usdPartial,\n usdAllUnknown,\n } = f\n const { usdLimit, closeUsd, closeUsdUnreported, usdUnreportedReason } = t\n const journalSpendRecords = usdKnownRecords\n // `journalDerived` keeps its partial sum: `records` and `unknownRecords` state exactly\n // how much of the run it covers. Only an all-unreported channel has nothing to report.\n const journalDerivedAvailable = usdLimit === null && haveJournal && !usdAllUnknown\n const closeRecordAvailable = usdLimit === null && closeUsd !== null && !closeUsdUnreported\n const spend: SpendMeasurements = {\n journalDerived: {\n usd: journalDerivedAvailable\n ? round(tree.brain.usd + journalWorkerUsd, 6)\n : unavailable(usdLimit ?? (haveJournal ? usdUnreportedReason : journalMissing)),\n records: journalDerivedAvailable ? journalSpendRecords : 0,\n unknownRecords: usdLimit === null && haveJournal ? usdUnknownRecords : 0,\n partial: journalDerivedAvailable && usdPartial,\n unknownNodes: usdLimit === null && haveJournal ? usdUnknownNodes : [],\n },\n closeRecord: {\n usd: closeRecordAvailable\n ? round(closeUsd as number, 6)\n : unavailable(\n usdLimit ??\n (closeUsdUnreported\n ? 'close record incomplete: result.json spentTotal.usdKnown is false'\n : 'no close record: neither state.json result.spentUsd nor result.json spentTotal.usd is present'),\n ),\n records: closeRecordAvailable ? 1 : 0,\n unknownRecords: closeUsdUnreported ? 1 : 0,\n partial: false,\n unknownNodes: closeUsdUnreported && rootId !== null ? [rootId] : [],\n },\n }\n return spend\n}\n\nexport type SpendFacts = ReturnType<typeof collectSpendFacts>\nexport type WorkerTokens = ReturnType<typeof measureWorkerTokens>\nexport type TotalUsd = ReturnType<typeof measureTotalUsd>\n","/**\n * The pure analyzer. Takes already-read bytes (`SupervisorRunSources`) and\n * returns the report — every metric derivable from a synthetic journal string\n * with no filesystem, no process, and no network. All I/O lives in a reader\n * (`reader.ts` is one).\n *\n * The metric groups live in `analyze-*.ts`; this file only runs them in the\n * order the report's `gaps` list is written.\n */\n\nimport { createAnalysis } from './analyze-context'\nimport { measureDecision } from './analyze-decision'\nimport { buildEconomics, buildPerWorker } from './analyze-economics'\nimport {\n buildOrchestration,\n measureConcurrency,\n measureDelegationDepth,\n measureRespawns,\n measureSteers,\n measureWall,\n} from './analyze-orchestration'\nimport { buildOutcome } from './analyze-outcome'\nimport {\n buildSpend,\n collectSpendFacts,\n measureTotalUsd,\n measureWorkerTokens,\n} from './analyze-spend'\nimport {\n SUPERVISOR_RUN_SCHEMA,\n type SupervisorRunReport,\n type SupervisorRunSources,\n unavailable,\n} from './types'\n\n/**\n * Analyze already-read supervisor-run bytes. Pure and synchronous: same bytes\n * in, same report out (modulo `generatedAt`, which `now` pins in tests).\n */\nexport function analyzeSupervisorRunSources(\n src: SupervisorRunSources,\n now: () => number = Date.now,\n): SupervisorRunReport {\n const a = createAnalysis(src)\n const { gap, gaps, rootId, rootSpawn, journalMissing } = a\n // Measurements record their gaps as they run, so the order below is the order of `report.gaps`.\n const wall = measureWall(a)\n const steerFacts = measureSteers(a)\n const concurrency = measureConcurrency(a, wall.wallEndAt)\n const respawns = measureRespawns(a)\n const steps = {\n ...wall,\n ...steerFacts,\n ...concurrency,\n ...respawns,\n delegationDepth: measureDelegationDepth(a),\n }\n const orchestration = buildOrchestration(a, steps)\n const decision = measureDecision(a, steps)\n const spendFacts = collectSpendFacts(a)\n const tokens = measureWorkerTokens(a, spendFacts)\n const totals = measureTotalUsd(a, spendFacts)\n const spend = buildSpend(a, spendFacts, totals)\n const perWorker = buildPerWorker(a, spendFacts, totals)\n const economics = buildEconomics(a, spendFacts, totals, tokens, { decision, spend, perWorker })\n const outcome = buildOutcome(a, totals)\n return {\n schema: SUPERVISOR_RUN_SCHEMA,\n runRef: src.runRef,\n instanceId: src.instanceId,\n arm: src.arm,\n supervisorId: rootId !== null ? rootId : unavailable(journalMissing),\n supervisorProfileDigest:\n rootSpawn?.profileDigest !== null && rootSpawn?.profileDigest !== undefined\n ? rootSpawn.profileDigest\n : gap('supervisorProfileDigest', 'root spawned event has no profile digest'),\n generatedAt: new Date(now()).toISOString(),\n orchestration,\n decision,\n economics,\n outcome,\n rootWorkspaceCaptures: src.rootWorkspaceCaptures ?? null,\n gaps,\n traceCommand:\n src.traceCommand ??\n 'npx --yes @tangle-network/traces@latest analyze --harness opencode --cwd <worker-clone-cwd>',\n }\n}\n","/**\n * Optional Runtime run-dir files, read as bytes.\n *\n * `coordination-log.jsonl` is Runtime's JSONL of `{ runId, seq, at, event }`:\n * questions, steers, answers and peer mail between nodes. The `team-shape`\n * analyst reads communication and steer edges from it.\n */\n\nimport { readFile } from 'node:fs/promises'\nimport { join } from 'node:path'\n\nconst COORDINATION_FILE = 'coordination-log.jsonl'\n\n/** File text, or null when the file does not exist. Any other read error throws. */\nexport async function readMaybe(path: string): Promise<string | null> {\n return readFile(path, 'utf8').catch((error: unknown) => {\n if (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code: unknown }).code === 'ENOENT'\n ) {\n return null\n }\n throw error\n })\n}\n\n/** The run's coordination log, or null when Runtime wrote none. */\nexport function readCoordinationLog(runDir: string): Promise<string | null> {\n return readMaybe(join(runDir, COORDINATION_FILE))\n}\n","import { nonEmptyString, recordOrNull as record } from './source-facts'\nimport type { SourceLimits } from './types'\n\nfunction spendRecord(value: unknown): Record<string, unknown> | null {\n const spend = record(value)\n if (spend === null) return null\n const tokens = record(spend.tokens)\n if (\n tokens === null ||\n typeof tokens.input !== 'number' ||\n !Number.isFinite(tokens.input) ||\n tokens.input < 0 ||\n typeof tokens.output !== 'number' ||\n !Number.isFinite(tokens.output) ||\n tokens.output < 0 ||\n typeof spend.usd !== 'number' ||\n !Number.isFinite(spend.usd) ||\n spend.usd < 0 ||\n (spend.usdKnown !== undefined && typeof spend.usdKnown !== 'boolean')\n ) {\n return null\n }\n return spend\n}\n\nexport function sourceLimits(\n root: string,\n events: readonly Record<string, unknown>[],\n workerIds: ReadonlySet<string>,\n): SourceLimits {\n const rootMeters = events.filter((event) => event.kind === 'metered' && event.id === root)\n const invalidRootMeters = rootMeters.filter((event) => spendRecord(event.spend) === null)\n const rootMeterReason =\n rootMeters.length === 0\n ? 'Runtime journal has no root metered event'\n : invalidRootMeters.length > 0\n ? `${invalidRootMeters.length} root metered event(s) lack complete spend`\n : null\n const closes = events.filter(\n (event) =>\n workerIds.has(nonEmptyString(event.id) ?? '') &&\n (event.kind === 'settled' || event.kind === 'cancelled'),\n )\n const settledById = new Map<string, Record<string, unknown>[]>()\n for (const event of closes) {\n const id = nonEmptyString(event.id)\n if (id === null) continue\n const matches = settledById.get(id) ?? []\n matches.push(event)\n settledById.set(id, matches)\n }\n const incompleteWorkers = [...workerIds].filter((id) => {\n const terminal = settledById.get(id)\n return (\n terminal?.length !== 1 ||\n terminal[0]?.kind !== 'settled' ||\n spendRecord(terminal[0]?.spent) === null\n )\n })\n const missingVerdicts = [...workerIds].filter((id) => {\n const terminal = settledById.get(id)?.[0]\n if (terminal?.kind !== 'settled') return true\n const verdict = record(terminal.verdict)\n return typeof verdict?.valid !== 'boolean'\n })\n\n return {\n managerTokens: rootMeterReason,\n workerTokens:\n incompleteWorkers.length === 0\n ? null\n : `${incompleteWorkers.length}/${workerIds.size} child invocation(s) lack one settled spend record`,\n // `usdKnown: false` on ONE record is not a limit of this store: the store priced every\n // other record, and a limit here discards them all. The analyzer folds the flag per\n // record instead, and reports a partial total with the unpriced nodes named.\n spendUsd:\n rootMeterReason !== null\n ? rootMeterReason\n : incompleteWorkers.length > 0\n ? 'at least one child invocation lacks a settled spend record'\n : null,\n workerVerdicts:\n missingVerdicts.length === 0\n ? null\n : `${missingVerdicts.length}/${workerIds.size} child invocation(s) lack a structured validity verdict`,\n deliverables:\n workerIds.size === 0\n ? null\n : 'Runtime FileRunContext does not retain per-child delivered patches',\n }\n}\n","/**\n * Reader for agent-runtime's file-backed supervision context.\n *\n * Runtime stores multiple recursive trees in one `spawn-journal.jsonl`.\n * Each line is an envelope whose `root` identifies the local tree. A journal\n * can connect a nested tree with `spawned.ownedTreeRoot`. It can also use the\n * spawned child id as the nested root when no owned tree is recorded. Either\n * way the nested tree may repeat its owner's spawn as a parentless marker: the\n * owner's id, not the tree key, identifies it (an owned tree's key is a path\n * such as `root/root:s0`). Descendant spawns must occur in the tree their\n * parent owns. This reader removes a duplicate marker and preserves the other\n * envelopes for the supervisor-run analyzer. Runtime stores profile\n * identity below `identity` and does not emit Eval's role field. This boundary\n * projects those fields without changing Runtime's dialect.\n *\n * Transcripts come from Runtime's own records too: `root-stream.jsonl` is the root's, each\n * worker's turn outputs and native-session receipt are read from the journal, and every blob\n * a record names is checked on disk (see `nodeTranscripts`).\n *\n * The run's terminal record is Runtime's own: `result.json` is the\n * `SupervisedResult` that `supervise()` returned, verbatim, and its `kind`\n * (`winner`, `no-winner`, or whatever a later arm is called) is the status.\n * `failure.json` (`{ runId, pursuitId, at, error: { name, message } }`) is the\n * record Runtime writes when `supervise()` threw before a result landed. Both\n * pass through as bytes; `terminal-record.ts` reads them. The reader does not\n * decide which kinds count: a kind it refuses is a run that recorded its\n * outcome and got reported as having none. The reader does not synthesize status fields. The analyzer names the Runtime\n * record that supplied a status, so status provenance cannot be mislabelled.\n *\n * `usdKnown: false` / `tokensKnown: false` on ONE record is not a limit of this\n * store. The store recorded every other record completely, so the flags travel\n * through to the analyzer per record, which reports the measured nodes and\n * names the unreported ones.\n */\n\nimport { readFile, stat } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { hashCanonical } from '../ledger-core/canonical'\nimport type { RolloutWorkspaceCapture } from '../rollout/schema'\nimport { readCoordinationLog, readMaybe } from './coordination-reader'\nimport { sourceLimits } from './runtime-source-limits'\nimport { nonEmptyString, recordOrNull as record } from './source-facts'\nimport {\n NO_SOURCE_LIMITS,\n type SupervisorRunSources,\n type WorkerLogSource,\n type WorkerNativeSession,\n} from './types'\n\nconst JOURNAL_FILE = 'spawn-journal.jsonl'\nconst OBSERVER_FILE = 'observer.jsonl'\nconst ROOT_STREAM_FILE = 'root-stream.jsonl'\nconst BLOB_DIR = 'blobs'\nconst RESULT_FILE = 'result.json'\nconst FAILURE_FILE = 'failure.json'\n\n/**\n * The files only Runtime's durable layer writes. Any one of them marks a\n * Runtime run directory: `supervise()` opens the spawn journal on its first\n * event, and `supervisePursuit` appends the observer's `before` event and, on\n * a throw, the failure record before any spawn.\n *\n * Measured motive (discovery-lab recursive smoke r1, 2026-09-06): the first\n * attempt threw on a caller input error 16 minutes before the corrected attempt\n * opened the spawn journal. At that instant the directory held `observer.jsonl`\n * (2 records) and the failure record and no journal, so a journal-only test\n * routed it to an unrelated reader, which reads neither file, and the recorded\n * throw was reported as no run at all.\n */\nconst RUNTIME_RUN_DIR_MARKERS: readonly string[] = [JOURNAL_FILE, OBSERVER_FILE, FAILURE_FILE]\n\ninterface BeginRecord {\n readonly root: string\n readonly at: string\n readonly line: number\n}\n\ninterface EventRecord {\n readonly root: string\n readonly event: Record<string, unknown>\n readonly line: number\n}\n\ninterface NormalizedRuntimeJournal {\n readonly root: string\n readonly startedAt: string\n readonly journal: string\n readonly events: readonly Record<string, unknown>[]\n}\n\nfunction profileDigest(event: Record<string, unknown>): string | null {\n const direct = nonEmptyString(event.profileDigest)\n if (direct !== null) return direct\n const identity = record(event.identity)\n return identity === null ? null : nonEmptyString(identity.profileDigest)\n}\n\nfunction formatError(path: string, line: number, detail: string): Error {\n return new Error(`${path}:${line}: invalid Runtime spawn journal: ${detail}`)\n}\n\nfunction parseEnvelopeJournal(text: string, path: string): NormalizedRuntimeJournal {\n const begins: BeginRecord[] = []\n const events: EventRecord[] = []\n const begun = new Map<string, BeginRecord>()\n\n for (const [index, sourceLine] of text.split('\\n').entries()) {\n const line = index + 1\n const trimmed = sourceLine.trim()\n if (trimmed.length === 0) continue\n let parsed: unknown\n try {\n parsed = JSON.parse(trimmed)\n } catch {\n throw formatError(path, line, 'line is not JSON')\n }\n const envelope = record(parsed)\n if (envelope === null) throw formatError(path, line, 'line is not an object')\n const kind = nonEmptyString(envelope.kind)\n const root = nonEmptyString(envelope.root)\n if (root === null) throw formatError(path, line, 'root must be a non-empty string')\n\n if (kind === 'begin') {\n const at = nonEmptyString(envelope.at)\n if (at === null || !Number.isFinite(Date.parse(at))) {\n throw formatError(path, line, 'begin.at must be an ISO timestamp')\n }\n if (begun.has(root)) throw formatError(path, line, `tree ${JSON.stringify(root)} began twice`)\n const begin = { root, at, line }\n begun.set(root, begin)\n begins.push(begin)\n continue\n }\n\n if (kind !== 'event') {\n throw formatError(path, line, \"kind must be 'begin' or 'event'\")\n }\n if (!begun.has(root)) {\n throw formatError(path, line, `event for tree ${JSON.stringify(root)} precedes begin`)\n }\n const event = record(envelope.event)\n if (event === null) throw formatError(path, line, 'event must be an object')\n if (nonEmptyString(event.kind) === null) {\n throw formatError(path, line, 'event.kind must be a non-empty string')\n }\n events.push({ root, event: { ...event }, line })\n }\n\n if (begins.length === 0) throw formatError(path, 1, 'no begin record')\n\n const parentSpawnsById = new Map<string, EventRecord[]>()\n const parentSpawnsByOwnedTreeRoot = new Map<string, EventRecord[]>()\n for (const entry of events) {\n if (entry.event.kind !== 'spawned') continue\n const id = nonEmptyString(entry.event.id)\n if (id === null) continue\n if (nonEmptyString(entry.event.parent) !== null) {\n const ownedTreeRoot = nonEmptyString(entry.event.ownedTreeRoot)\n if (ownedTreeRoot !== null) {\n const owners = parentSpawnsByOwnedTreeRoot.get(ownedTreeRoot) ?? []\n owners.push(entry)\n parentSpawnsByOwnedTreeRoot.set(ownedTreeRoot, owners)\n } else {\n const matches = parentSpawnsById.get(id) ?? []\n matches.push(entry)\n parentSpawnsById.set(id, matches)\n }\n }\n }\n\n const nestedRoots = new Set<string>()\n const nestedParentSpawns = new Map<string, EventRecord>()\n for (const begin of begins) {\n const parentSpawns = [\n ...new Set([\n ...(parentSpawnsByOwnedTreeRoot.get(begin.root) ?? []),\n ...(parentSpawnsById.get(begin.root) ?? []),\n ]),\n ].filter((entry) => entry.root !== begin.root)\n if (parentSpawns.length > 1) {\n throw formatError(\n path,\n begin.line,\n `tree ${JSON.stringify(begin.root)} has ${parentSpawns.length} parent spawns`,\n )\n }\n if (parentSpawns.length === 1) {\n nestedRoots.add(begin.root)\n nestedParentSpawns.set(begin.root, parentSpawns[0] as EventRecord)\n }\n }\n\n const topRoots = begins.filter((begin) => !nestedRoots.has(begin.root))\n if (topRoots.length !== 1) {\n throw formatError(\n path,\n topRoots[0]?.line ?? 1,\n `expected one top-level tree, found ${topRoots.length}`,\n )\n }\n const top = topRoots[0] as BeginRecord\n\n // A tree's root marker is a parentless spawn of the node that owns the tree: the top root\n // itself, or the parent spawn that owns a nested tree. An owned tree's key is a path, so\n // the owner's id is compared, never the tree key.\n const ownerIdByTree = new Map<string, string>([[top.root, top.root]])\n for (const [nestedRoot, parentSpawn] of nestedParentSpawns) {\n const ownerId = nonEmptyString(parentSpawn.event.id)\n if (ownerId !== null) ownerIdByTree.set(nestedRoot, ownerId)\n }\n const isRootMarker = (entry: EventRecord): boolean =>\n entry.event.kind === 'spawned' &&\n (entry.event.parent === undefined || entry.event.parent === null) &&\n nonEmptyString(entry.event.id) !== null &&\n entry.event.id === ownerIdByTree.get(entry.root)\n const rootMarkersByTree = new Map<string, EventRecord[]>()\n for (const entry of events) {\n if (!isRootMarker(entry)) continue\n const markers = rootMarkersByTree.get(entry.root) ?? []\n markers.push(entry)\n rootMarkersByTree.set(entry.root, markers)\n }\n\n for (const nestedRoot of nestedRoots) {\n const markers = rootMarkersByTree.get(nestedRoot) ?? []\n if (markers.length > 1) {\n throw formatError(\n path,\n begun.get(nestedRoot)?.line ?? 1,\n `nested tree ${JSON.stringify(nestedRoot)} contains ${markers.length} root markers`,\n )\n }\n const parentSpawn = nestedParentSpawns.get(nestedRoot)\n if (parentSpawn === undefined) {\n throw formatError(\n path,\n begun.get(nestedRoot)?.line ?? 1,\n `nested tree ${JSON.stringify(nestedRoot)} has no parent spawn`,\n )\n }\n const markerDigest = profileDigest(markers[0]?.event ?? {})\n const parentDigest = profileDigest(parentSpawn.event)\n if (markerDigest !== null && parentDigest !== null && markerDigest !== parentDigest) {\n throw formatError(\n path,\n markers[0]?.line ?? 1,\n `nested tree ${JSON.stringify(nestedRoot)} disagrees with its parent profile digest`,\n )\n }\n if (parentDigest === null && markerDigest !== null) {\n parentSpawn.event.profileDigest = markerDigest\n }\n }\n\n const ownedTreeBySupervisorId = new Map<string, string>([[top.root, top.root]])\n for (const [nestedRoot, parentSpawn] of nestedParentSpawns) {\n const supervisorId = nonEmptyString(parentSpawn.event.id)\n if (supervisorId === null) continue\n const priorTree = ownedTreeBySupervisorId.get(supervisorId)\n if (priorTree !== undefined && priorTree !== nestedRoot) {\n throw formatError(\n path,\n parentSpawn.line,\n `spawn ${JSON.stringify(supervisorId)} owns both ${JSON.stringify(priorTree)} and ${JSON.stringify(nestedRoot)}`,\n )\n }\n ownedTreeBySupervisorId.set(supervisorId, nestedRoot)\n }\n for (const entry of events) {\n if (entry.event.kind !== 'spawned') continue\n const parentId = nonEmptyString(entry.event.parent)\n if (parentId === null) continue\n const parentTree = ownedTreeBySupervisorId.get(parentId)\n if (parentTree === undefined) {\n throw formatError(\n path,\n entry.line,\n `spawn ${JSON.stringify(entry.event.id)} names parent ${JSON.stringify(parentId)}, which owns no journal tree`,\n )\n }\n if (entry.root !== parentTree) {\n throw formatError(\n path,\n entry.line,\n `spawn ${JSON.stringify(entry.event.id)} is in tree ${JSON.stringify(entry.root)}, but parent ${JSON.stringify(parentId)} owns tree ${JSON.stringify(parentTree)}`,\n )\n }\n }\n\n // Runtime's recursive atom has no supervisor/worker role field. A tree root\n // is a supervisor; a child without its own tree is a worker.\n const supervisorIds = new Set([\n top.root,\n ...[...nestedParentSpawns.values()]\n .map((entry) => nonEmptyString(entry.event.id))\n .filter((id): id is string => id !== null),\n ])\n const normalized = events\n .filter((entry) => !(nestedRoots.has(entry.root) && isRootMarker(entry)))\n .map((entry) => {\n const event = { ...entry.event }\n if (event.kind === 'spawned') {\n const digest = profileDigest(event)\n if (event.profileDigest === undefined && digest !== null) {\n event.profileDigest = digest\n }\n if (event.role === undefined) {\n event.role = supervisorIds.has(nonEmptyString(event.id) ?? '') ? 'supervisor' : 'worker'\n }\n }\n return { root: entry.root, event }\n })\n\n const rootMarkers = rootMarkersByTree.get(top.root) ?? []\n if (rootMarkers.length !== 1) {\n throw formatError(\n path,\n top.line,\n `top-level tree ${JSON.stringify(top.root)} must contain one root marker`,\n )\n }\n\n return {\n root: top.root,\n startedAt: top.at,\n // Keep Runtime's event envelope intact. The pure source parser uses the envelope to\n // distinguish an understood-but-unmodeled Runtime event from an unreadable flat record.\n journal: `${normalized\n .map((entry) => JSON.stringify({ kind: 'event', root: entry.root, event: entry.event }))\n .join('\\n')}\\n`,\n events: normalized.map((entry) => entry.event),\n }\n}\n\nfunction parseOptionalRecord(text: string | null, path: string): Record<string, unknown> | null {\n if (text === null) return null\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n throw new Error(`${path}: invalid JSON`)\n }\n const value = record(parsed)\n if (value === null) throw new Error(`${path}: expected a JSON object`)\n return value\n}\n\n/**\n * Refuse a `result.json` that belongs to another run. Runtime's result carries\n * its own `tree.root`; a settled record with a different root is a copied or\n * misplaced file, and reading its status onto this journal misreports the run.\n */\nfunction assertResultMatchesJournal(\n root: string,\n result: Record<string, unknown> | null,\n resultPath: string,\n): void {\n const resultKind = result === null ? null : nonEmptyString(result.kind)\n if (resultKind === null || result === null) return\n const resultRoot = nonEmptyString(record(result.tree)?.root)\n if (resultRoot === null) {\n throw new Error(`${resultPath}: Runtime ${resultKind} result has no tree.root`)\n }\n if (resultRoot !== root) {\n throw new Error(\n `${resultPath}: root ${JSON.stringify(resultRoot)} does not match journal root ${JSON.stringify(root)}`,\n )\n }\n}\n\n/**\n * Refuse a `failure.json` that is not a failure record. Runtime writes\n * `{ runId, pursuitId, at, error: { name, message } }`; a document without an\n * `error` object is not one, and reading it as a failure invents a terminal\n * state the run never recorded. The record carries no tree root, so its\n * identity is not checked against the journal.\n */\nfunction assertFailureRecord(failure: Record<string, unknown> | null, failurePath: string): void {\n if (failure === null) return\n if (record(failure.error) === null) {\n throw new Error(`${failurePath}: Runtime failure record has no error object`)\n }\n}\n\n/**\n * The journal's begin stamp in the analyzer's state-document shape. It carries\n * the run identity and start instant only; the terminal status lives in\n * Runtime's own `result.json` / `failure.json`, which the analyzer reads by\n * name, so no synthetic status field is fabricated here.\n */\nfunction runtimeBeginState(root: string, startedAt: string): string {\n return JSON.stringify({ id: root, startedAt })\n}\n\n/**\n * The file Runtime's `FileResultBlobStore` writes for one content address\n * (`sha256:<hex>` → `blobs/sha256-<hex>.json`), or null for anything that is not one.\n */\nfunction blobFile(runDir: string, ref: unknown): string | null {\n return typeof ref === 'string' && /^sha256:[0-9a-f]{64}$/u.test(ref)\n ? join(runDir, BLOB_DIR, `${ref.replace(':', '-')}.json`)\n : null\n}\n\ntype NodeTranscript = Pick<\n WorkerLogSource,\n 'transcriptRef' | 'turns' | 'nativeSession' | 'workspaceCaptures'\n>\n\ninterface NodeTranscriptFacts {\n dispatched: number\n readonly outputRefs: { value: unknown; turn: boolean }[]\n readonly outputPositions: Map<string, number>\n receipt: Record<string, unknown> | null\n}\n\n/** A later receipt replaces an earlier one, except that an absence never replaces an available one. */\nfunction keepReceipt(fact: NodeTranscriptFacts, receipt: Record<string, unknown> | null): void {\n if (receipt === null) return\n if (fact.receipt?.status === 'available' && receipt.status !== 'available') return\n fact.receipt = receipt\n}\n\n/**\n * The files each harness writes its conversation to. A receipt can be available and complete\n * while holding none of them: on the 2026-10-04 trace proof a Pi worker that never wrote a session\n * stored only `.pi/agent/models-store.json`, and this summary counted it as a transcript.\n */\nconst HARNESS_SESSION_FILE: Readonly<Record<string, RegExp>> = {\n 'claude-code': /(^|\\/)\\.claude\\/projects\\/.+\\.jsonl$/u,\n codex: /(^|\\/)\\.codex\\/sessions\\/.+\\.jsonl$/u,\n pi: /(^|\\/)\\.pi\\/agent\\/sessions\\/.+\\.jsonl$/u,\n opencode:\n /(^|\\/)(\\.local\\/share\\/opencode\\/(opencode\\.db|storage\\/session\\/.+\\.json|export\\/.+\\.json)|\\.opencode\\/sessions\\/.+)$/u,\n}\n\n/** Session files the receipt's transcript blob lists, or undefined when it cannot say. */\nasync function receiptSessionFiles(file: string): Promise<number | undefined> {\n let descriptor: unknown\n try {\n descriptor = JSON.parse(await readFile(file, 'utf8'))\n } catch {\n return undefined\n }\n const harness = record(descriptor)?.harness\n const files = record(descriptor)?.files\n const pattern = typeof harness === 'string' ? HARNESS_SESSION_FILE[harness] : undefined\n if (pattern === undefined || !Array.isArray(files)) return undefined\n return files.filter((entry) => {\n const path = record(entry)?.path\n return typeof path === 'string' && pattern.test(path)\n }).length\n}\n\ntype NativeSessionState = 'complete' | 'partial' | 'no-session-file' | 'unavailable' | 'none'\n\nfunction nativeSessionState(session: WorkerNativeSession | null | undefined): NativeSessionState {\n if (session === null || session === undefined) return 'none'\n if (session.status !== 'available') return 'unavailable'\n if (session.coverageComplete === false) return 'partial'\n if (session.sessionFiles === 0) return 'no-session-file'\n return 'complete'\n}\n\n/**\n * What this reader can say about harness-session traces. Every spawned worker counts, including\n * one that recorded nothing; the root is reported apart because its receipt lives in result.json\n * (`rootHarnessTranscript`), not on a worker. Runtime records the session identity on each\n * receipt, so the sessions are read per node, not through one command. A receipt counts as a\n * session only when its copy is complete and holds a file the harness writes its conversation to.\n */\nfunction nativeTraceSummary(\n workers: readonly WorkerLogSource[],\n root: NodeTranscript | undefined,\n): string {\n const states = workers.map((worker) => nativeSessionState(worker.nativeSession))\n const count = (state: NativeSessionState): number => states.filter((s) => s === state).length\n const rootSession = root?.nativeSession ?? null\n const rootState = nativeSessionState(rootSession)\n const rootText =\n rootSession === null\n ? 'no receipt'\n : rootSession.status === 'unavailable'\n ? `unavailable (${rootSession.reason})`\n : rootState === 'complete'\n ? 'complete'\n : rootState === 'partial'\n ? 'partial copy'\n : 'no session file'\n if (rootSession === null && states.every((state) => state === 'none'))\n return 'unavailable — no node carries a Runtime harness transcript receipt'\n const gaps = [\n count('partial') > 0 ? `${count('partial')} only a partial copy` : null,\n count('no-session-file') > 0\n ? `${count('no-session-file')} a receipt with no session file`\n : null,\n ].filter((gap): gap is string => gap !== null)\n return `per node — ${count('complete')} of ${workers.length} workers carry a complete native session receipt (workers[].nativeSession)${gaps.length > 0 ? `; ${gaps.join('; ')}` : ''}; root: ${rootText} (result.json rootHarnessTranscript)`\n}\n\nasync function workspaceCapturesFromOutput(\n runDir: string,\n ref: unknown,\n): Promise<RolloutWorkspaceCapture[]> {\n const outRef = typeof ref === 'string' ? ref : null\n const blobPath = blobFile(runDir, ref)\n const missing = (projectionGap: string): RolloutWorkspaceCapture => ({\n outRef,\n blobPath,\n receiptPointer: null,\n receipt: null,\n attempts: null,\n coverageComplete: null,\n incompleteReason: null,\n projectionGap,\n })\n if (blobPath === null) return [missing('Runtime output has no valid content address')]\n if (!(await isFile(blobPath))) return [missing('Runtime output blob is missing or not a file')]\n const raw = await readMaybe(blobPath)\n if (raw === null) return [missing('Runtime output blob is missing')]\n let output: unknown\n try {\n output = JSON.parse(raw)\n } catch {\n return [missing('Runtime output blob is not JSON')]\n }\n let addressGap: string | null = null\n try {\n if (hashCanonical(output) !== outRef) {\n addressGap = 'Runtime output content address does not match output blob'\n }\n } catch {\n addressGap = 'Runtime output cannot be canonically hashed'\n }\n const project = (rawReceipt: unknown, receiptPointer: string | null): RolloutWorkspaceCapture => {\n const receipt = record(rawReceipt)\n if (receipt === null) {\n return {\n ...missing(\n `workspaceCapture receipt is absent or malformed${addressGap === null ? '' : `; ${addressGap}`}`,\n ),\n receiptPointer,\n receipt: rawReceipt,\n }\n }\n const provenance = record(receipt.provenance)\n const attempts = Array.isArray(provenance?.attempts) ? provenance.attempts : null\n const coverageComplete =\n typeof receipt.coverageComplete === 'boolean' ? receipt.coverageComplete : null\n const incompleteReason =\n typeof receipt.incompleteReason === 'string' ? receipt.incompleteReason : null\n const gaps: string[] = []\n if (addressGap !== null) gaps.push(addressGap)\n if (coverageComplete === null) gaps.push('workspaceCapture.coverageComplete is absent')\n if (record(receipt.snapshot) === null) gaps.push('workspaceCapture.snapshot is absent')\n if (provenance === null) gaps.push('workspaceCapture.provenance is absent')\n if (attempts === null) gaps.push('workspaceCapture.provenance.attempts is absent')\n else if (attempts.length === 0 || attempts.some((attempt) => record(attempt) === null)) {\n gaps.push('workspaceCapture.provenance.attempts is empty or malformed')\n }\n return {\n outRef,\n blobPath,\n receiptPointer,\n receipt,\n attempts,\n coverageComplete,\n incompleteReason,\n projectionGap: gaps.length > 0 ? gaps.join('; ') : null,\n }\n }\n const result = record(output)\n const captures: RolloutWorkspaceCapture[] = []\n // Use the record's field order and each array's order so every retained source stays ordered.\n for (const key of Object.keys(result ?? {})) {\n if (key === 'workspaceCapture') {\n captures.push(project(result?.[key], '/workspaceCapture'))\n } else if (key === 'workspaceCaptures') {\n const receipts = result?.[key]\n if (Array.isArray(receipts) && receipts.length > 0) {\n for (const [index, receipt] of receipts.entries()) {\n captures.push(project(receipt, `/workspaceCaptures/${index}`))\n }\n } else {\n captures.push({\n ...missing(\n `workspaceCaptures is empty or malformed${addressGap === null ? '' : `; ${addressGap}`}`,\n ),\n receiptPointer: '/workspaceCaptures',\n receipt: receipts ?? null,\n })\n }\n }\n }\n return captures.length > 0 ? captures : [project(null, null)]\n}\n\n/**\n * What Runtime retained of each node's decisions, from its own records.\n *\n * - A turn is one `execution-admitted` event in the `dispatched` phase. Its `execution-result`\n * names an output blob holding that turn's provider event stream (reasoning, tool calls and\n * results as the harness reported them). A dispatched turn with no retained output lost its\n * record, which is how a worker that went down mid-turn shows up.\n * - Every event's `outRef` enters the same collector, once per node and address. Terminal\n * records retain ordinary and steerable results; they are not counted as dispatched turns.\n * - The terminal event's `harnessTranscript` receipt covers the harness's native session files.\n * Those are the only record of the harness's own subagents, so an unavailable receipt is a\n * separate gap from a missing turn, and its reason is Runtime's, verbatim. `settled`,\n * `cancelled` and `reconciled` all carry one; an available receipt is never replaced by a later\n * absence. The root has no terminal event, so its receipt is the settle record's\n * `rootHarnessTranscript`.\n *\n * Blob files are checked on disk: a receipt that names a blob the directory no longer holds is\n * not a retained transcript.\n */\nasync function nodeTranscripts(\n runDir: string,\n events: readonly Record<string, unknown>[],\n nodeIds: ReadonlySet<string>,\n root?: { readonly id: string; readonly receipt: Record<string, unknown> | null },\n): Promise<Map<string, NodeTranscript>> {\n const facts = new Map<string, NodeTranscriptFacts>()\n const entry = (id: string): NodeTranscriptFacts => {\n let found = facts.get(id)\n if (found === undefined) {\n found = { dispatched: 0, outputRefs: [], outputPositions: new Map(), receipt: null }\n facts.set(id, found)\n }\n return found\n }\n for (const event of events) {\n const id = nonEmptyString(event.id)\n if (id === null || !nodeIds.has(id)) continue\n if (Object.hasOwn(event, 'outRef')) {\n const fact = entry(id)\n const ref = event.outRef\n const position = typeof ref === 'string' ? fact.outputPositions.get(ref) : undefined\n if (position !== undefined) {\n if (event.kind === 'execution-result') fact.outputRefs[position]!.turn = true\n } else {\n if (typeof ref === 'string') fact.outputPositions.set(ref, fact.outputRefs.length)\n fact.outputRefs.push({ value: ref, turn: event.kind === 'execution-result' })\n }\n }\n if (event.kind === 'execution-admitted' && record(event.admission)?.phase === 'dispatched') {\n entry(id).dispatched += 1\n } else if (\n event.kind === 'settled' ||\n event.kind === 'cancelled' ||\n event.kind === 'reconciled'\n ) {\n // A reconciled node carries its receipt on `reconciled`, which 15 available transcripts of\n // the 2026-10-04 Discovery archives did and this reader once skipped.\n keepReceipt(entry(id), record(event.harnessTranscript))\n }\n }\n if (root !== undefined && nodeIds.has(root.id)) keepReceipt(entry(root.id), root.receipt)\n const out = new Map<string, NodeTranscript>()\n for (const [id, fact] of facts) {\n const retained: string[] = []\n let retainedTurns = 0\n const workspaceCaptures: RolloutWorkspaceCapture[] = []\n for (const { value: ref, turn } of fact.outputRefs) {\n const file = blobFile(runDir, ref)\n if (file !== null && (await isFile(file))) {\n retained.push(file)\n if (turn) retainedTurns += 1\n }\n workspaceCaptures.push(...(await workspaceCapturesFromOutput(runDir, ref)))\n }\n let nativeSession: WorkerNativeSession | null = null\n if (fact.receipt !== null) {\n if (fact.receipt.status === 'available') {\n const file = blobFile(runDir, fact.receipt.transcriptRef)\n if (file !== null && (await isFile(file))) {\n const sessionFiles = await receiptSessionFiles(file)\n const coverageComplete = fact.receipt.coverageComplete\n nativeSession = {\n status: 'available',\n ref: file,\n ...(typeof coverageComplete === 'boolean' ? { coverageComplete } : {}),\n ...(sessionFiles === undefined ? {} : { sessionFiles }),\n }\n } else {\n nativeSession = { status: 'unavailable', reason: 'receipt-blob-missing' }\n }\n } else {\n nativeSession = {\n status: 'unavailable',\n reason: nonEmptyString(fact.receipt.reason) ?? 'unavailable',\n }\n }\n }\n out.set(id, {\n // The native session is the fuller record; the newest turn output is the next best.\n transcriptRef:\n nativeSession?.status === 'available' ? nativeSession.ref : (retained.at(-1) ?? null),\n turns: { dispatched: fact.dispatched, retained: retainedTurns },\n nativeSession,\n workspaceCaptures: workspaceCaptures.length > 0 ? workspaceCaptures : null,\n })\n }\n return out\n}\n\nexport interface RuntimeReaderOptions {\n /**\n * Throw on a missing spawn journal instead of returning absent-shaped\n * sources. The default (false) models a journal-less run dir — a\n * pre-supervise death, a backfilled zombie — as a readable absence.\n */\n readonly strict?: boolean\n}\n\n/**\n * Sources for a run dir whose spawn journal does not exist. Mirrors the\n * absent shape the reader returns for a missing store: every\n * journal-dependent metric downstream reads `unavailable`, never 0.\n */\n/**\n * The run identity a terminal record names when no journal exists yet: the\n * settle record's `tree.root`, else the failure record's `runId`. Both are\n * Runtime's own `runId`, so the report names the run the record is about\n * instead of `?`.\n */\nfunction recordedRunId(\n result: Record<string, unknown> | null,\n failure: Record<string, unknown> | null,\n): string | null {\n return nonEmptyString(record(result?.tree)?.root) ?? nonEmptyString(failure?.runId)\n}\n\nfunction absentRuntimeSupervisorRun(\n runDir: string,\n resultText: string | null,\n failureText: string | null,\n instanceId: string | null,\n): SupervisorRunSources {\n const reason = `no Runtime spawn journal (${JOURNAL_FILE}) under ${runDir}`\n return {\n runRef: runDir,\n instanceId,\n arm: null,\n supRunDir: null,\n journal: null,\n journalMissingReason: reason,\n brainLog: null,\n brainLogMissingReason:\n 'Runtime FileRunContext records spend but not model completion finish reasons',\n state: null,\n progress: null,\n workers: null,\n workersMissingReason: reason,\n result: resultText,\n failure: failureText,\n judge: null,\n judgeSource: null,\n patch: null,\n driverLog: null,\n harnessWorkerTokens: null,\n harnessMissingReason: 'Runtime FileRunContext has no external worker-token join',\n limits: NO_SOURCE_LIMITS,\n rootTranscriptRef: null,\n rootWorkspaceCaptures: null,\n traceCommand: 'unavailable — Runtime FileRunContext records no provider-session trace identity',\n }\n}\n\n/**\n * Read one agent-runtime `createFileRunContext(dir)` directory.\n *\n * A run dir without `spawn-journal.jsonl` returns the same absent-shaped\n * sources the reader returns for a missing store: `journal` and\n * `workers` null, each with its reason, so every dependent metric reads\n * `unavailable` — never 0 and never a throw. Its `result.json` and\n * `failure.json` are still read, so a run that died before its first spawn\n * reports the failure Runtime recorded. Pass `strict: true` to throw on the\n * missing journal instead. A journal, result, or failure document that exists\n * but cannot be parsed always throws: a corrupt record is a defect, not an\n * absence.\n *\n * The reader translates storage envelopes only. It does not assign research\n * roles, interpret artifacts, or turn process completion into a quality\n * verdict.\n */\nexport async function readRuntimeSupervisorRun(\n runDir: string,\n opts: RuntimeReaderOptions = {},\n): Promise<SupervisorRunSources> {\n const journalPath = join(runDir, JOURNAL_FILE)\n const rawJournal =\n opts.strict === true ? await readFile(journalPath, 'utf8') : await readMaybe(journalPath)\n const resultPath = join(runDir, RESULT_FILE)\n const failurePath = join(runDir, FAILURE_FILE)\n const resultText = await readMaybe(resultPath)\n const failureText = await readMaybe(failurePath)\n const failure = parseOptionalRecord(failureText, failurePath)\n assertFailureRecord(failure, failurePath)\n const result = parseOptionalRecord(resultText, resultPath)\n if (rawJournal === null) {\n return absentRuntimeSupervisorRun(\n runDir,\n resultText,\n failureText,\n recordedRunId(result, failure),\n )\n }\n const normalized = parseEnvelopeJournal(rawJournal, journalPath)\n assertResultMatchesJournal(normalized.root, result, resultPath)\n\n const spawns = normalized.events.filter(\n (event) => event.kind === 'spawned' && nonEmptyString(event.id) !== null,\n )\n const childSpawns = spawns.filter((event) => event.id !== normalized.root)\n const workerIds = new Set(\n childSpawns.map((event) => nonEmptyString(event.id)).filter((id): id is string => id !== null),\n )\n const transcripts = await nodeTranscripts(\n runDir,\n normalized.events,\n new Set([normalized.root, ...workerIds]),\n { id: normalized.root, receipt: record(result?.rootHarnessTranscript) },\n )\n const workers: WorkerLogSource[] = childSpawns.map((event) => {\n const workerId = nonEmptyString(event.id) as string\n const transcript = transcripts.get(workerId)\n return {\n workerId,\n label: nonEmptyString(event.label) ?? String(event.id),\n events: null,\n inbox: null,\n patchBytes: null,\n transcriptRef: transcript?.transcriptRef ?? null,\n turns: transcript?.turns ?? { dispatched: 0, retained: 0 },\n nativeSession: transcript?.nativeSession ?? null,\n workspaceCaptures: transcript?.workspaceCaptures ?? null,\n patchPath: null,\n }\n })\n // Runtime appends every root provider event to the root stream as it arrives.\n const rootStream = join(runDir, ROOT_STREAM_FILE)\n\n return {\n runRef: runDir,\n instanceId: normalized.root,\n arm: null,\n supRunDir: runDir,\n journal: normalized.journal,\n brainLog: null,\n brainLogMissingReason:\n 'Runtime FileRunContext records spend but not model completion finish reasons',\n state: runtimeBeginState(normalized.root, normalized.startedAt),\n progress: null,\n workers,\n workersMissingReason: null,\n result: resultText,\n failure: failureText,\n judge: null,\n judgeSource: null,\n patch: null,\n driverLog: null,\n coordinationLog: await readCoordinationLog(runDir),\n harnessWorkerTokens: null,\n harnessMissingReason: 'Runtime FileRunContext has no external worker-token join',\n limits: sourceLimits(normalized.root, normalized.events, workerIds),\n rootTranscriptRef: (await isFile(rootStream)) ? rootStream : null,\n rootWorkspaceCaptures: transcripts.get(normalized.root)?.workspaceCaptures ?? null,\n traceCommand: nativeTraceSummary(workers, transcripts.get(normalized.root)),\n }\n}\n\n\n\n/**\n * True when a directory holds any file only Runtime's durable layer writes:\n * the spawn journal, the observer journal, or the failure record. A run that\n * threw before its first spawn has no journal yet and is still a Runtime run.\n */\nexport async function isRuntimeSupervisorRunDir(runDir: string): Promise<boolean> {\n for (const marker of RUNTIME_RUN_DIR_MARKERS) {\n if (await isFile(join(runDir, marker))) return true\n }\n return false\n}\n\nasync function isFile(path: string): Promise<boolean> {\n return stat(path)\n .then((entry) => entry.isFile())\n .catch((error: unknown) => {\n if (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n ((error as { code: unknown }).code === 'ENOENT' ||\n (error as { code: unknown }).code === 'ENOTDIR')\n ) {\n return false\n }\n throw error\n })\n}\n","/**\n * Runtime supervisor-run reader and report writers.\n *\n * Runtime's file-backed supervision context is the only live on-disk contract.\n * Other stores implement `SupervisorRunReader` and feed the same pure analyzer;\n * this module owns path discovery and report output for Runtime runs.\n */\n\nimport { readdir } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { analyzeSupervisorRunSources } from './analyze'\n\nimport { isRuntimeSupervisorRunDir, readRuntimeSupervisorRun } from './runtime-reader'\nimport type { SupervisorRunReader, SupervisorRunReport, SupervisorRunSources } from './types'\n\n/**\n * Analyze a supervisor run. Accepts a Runtime run directory, any\n * `SupervisorRunReader`, or already-read source bytes — so a\n * caller with its own store never has to touch the filesystem layout.\n */\nexport async function analyzeSupervisorRun(\n input: string | SupervisorRunReader | SupervisorRunSources,\n): Promise<SupervisorRunReport> {\n if (typeof input === 'string') {\n return analyzeSupervisorRunSources(await readRuntimeSupervisorRun(input))\n }\n if (isReader(input)) return analyzeSupervisorRunSources(await input.read())\n return analyzeSupervisorRunSources(input)\n}\n\nfunction isReader(input: SupervisorRunReader | SupervisorRunSources): input is SupervisorRunReader {\n return typeof (input as SupervisorRunReader).read === 'function'\n}\n\nexport interface WriteSupervisorRunOptions {\n /** Append the headline block here (the experiment's run log). */\n readonly appendHeadlineTo?: string\n /** Also console.log the headline (default true). */\n readonly echo?: boolean\n /**\n * Write `run-report.{json,md}` here instead of into the run dir. Set when\n * reporting over a run directory that must stay READ-ONLY (a live run, an\n * archived generation).\n */\n readonly reportDir?: string\n}\n\n\n\n\n\n\n\n/**\n * Every Runtime supervisor run below `root`.\n *\n * When `root` itself is one run, return no children so callers can distinguish\n * a single report from a parent-directory rollup.\n */\nexport async function findSupervisorRunDirs(root: string): Promise<string[]> {\n if (await isRuntimeSupervisorRunDir(root)) {\n return []\n }\n const found: string[] = []\n const walk = async (dir: string, depth: number): Promise<void> => {\n if (depth > 8) return\n const entries = await readdir(dir, { withFileTypes: true }).catch(() => [])\n for (const e of entries) {\n if (!e.isDirectory()) continue\n if (e.name === 'node_modules' || e.name === '.git') continue\n const full = join(dir, e.name)\n if (await isRuntimeSupervisorRunDir(full)) {\n found.push(full)\n continue\n }\n await walk(full, depth + 1)\n }\n }\n await walk(root, 0)\n return found.sort()\n}\n","/**\n * Human-readable renderings of a supervisor-run report. Zero and unavailable\n * render differently on purpose (`0` vs `unavailable — <reason>`), because the\n * two have driven opposite conclusions about the same architecture.\n */\n\nimport { roundDecimal as round } from '../math/round-decimal'\nimport {\n isUnavailable,\n type Measured,\n type ResourceSpendRecord,\n type SupervisorRunReport,\n type SupervisorRunRollup,\n showMeasured,\n type TerminalFailure,\n} from './types'\n\n/**\n * The block appended to a run log after every run — the answers an operator asks\n * for, in the log tail, with no extra command.\n */\nexport function renderSupervisorRunHeadline(r: SupervisorRunReport): string {\n const o = r.orchestration\n const steerNote = isUnavailable(o.steers)\n ? `unavailable — ${o.steers.unavailable}`\n : o.steers === 0\n ? '0 (spawn→wait→respawn only; no mid-task steering)'\n : `${o.steers} queued / ${showMeasured(o.steersDelivered)} delivered`\n return [\n `RUN-REPORT ${r.instanceId ?? '?'} [${r.arm ?? '?'}]`,\n ` status=${showMeasured(r.outcome.supStatus)} source=${showMeasured(r.outcome.supStatusSource)}` +\n ` reason=${showMeasured(r.outcome.supReason)} failure=${fmtFailure(r.outcome.failure)}`,\n ` steers=${steerNote}`,\n ` waves=${showMeasured(o.waves)} sizes=${isUnavailable(o.waveSizes) ? `unavailable — ${o.waveSizes.unavailable}` : `[${o.waveSizes.join(',')}]`}` +\n ` workers=${showMeasured(o.workersSpawned)} settled=${showMeasured(o.workersSettled)} cancelled=${showMeasured(o.workersCancelled)}`,\n ` concurrency max=${showMeasured(o.maxConcurrency)} utilization=${showMeasured(o.workerUtilization)}` +\n ` idle=${fmtMs(o.idleMs)} (${showMeasured(o.idlePct)}%) wall=${fmtMs(o.supervisorWallMs)}` +\n `${o.supervisorWallSource === 'journal-span' ? ' (journal-span lower bound)' : ''}`,\n ` respawns=${showMeasured(o.respawns)} evidence→respawn=${showMeasured(r.decision.observeThenRespawn)}` +\n ` blind-respawn=${showMeasured(r.decision.respawnWithoutEvidence)} depth=${showMeasured(o.delegationDepth)}`,\n ` accepted=${showMeasured(r.decision.accepted)} rejected=${showMeasured(r.decision.rejected)} empty-pass=${showMeasured(r.decision.emptyPass)}`,\n ` brain=$${showMeasured(r.economics.brain.usd)} total=$${showMeasured(r.economics.totalUsd)}` +\n ` judge.resolved=${showMeasured(r.outcome.judgeResolved)} score=${showMeasured(r.outcome.judgeScore)}` +\n ` verify=${showMeasured(r.outcome.verifyPass)}`,\n r.gaps.length > 0 ? ` gaps(${r.gaps.length}): ${r.gaps.join('; ')}` : ' gaps: none',\n ].join('\\n')\n}\n\n/**\n * The recorded error on one line; `none recorded` and `unavailable` stay\n * distinct, and a throw the run outlived is labeled so it is not read as the\n * outcome of the settled result beside it.\n */\nfunction fmtFailure(v: Measured<TerminalFailure | null>): string {\n if (isUnavailable(v)) return `unavailable — ${v.unavailable}`\n if (v === null) return 'none recorded'\n const name = v.name ?? 'unavailable — record has no error.name'\n const message = v.message ?? 'unavailable — record has no error.message'\n const attempt = v.earlierAttempt ? ', earlier attempt' : ''\n return `${name}: ${message} [${v.source}${v.at === null ? '' : ` at ${v.at}`}${attempt}]`\n}\n\nfunction resourceRows(records: Measured<readonly ResourceSpendRecord[]>): string[] {\n if (isUnavailable(records)) return [`unavailable — ${records.unavailable}`, '']\n const out = [\n 'Receipts are source records, not additive totals.',\n 'A false completeness flag means the amount is a recorded subtotal, not complete usage.',\n '',\n '| Node | Source | Resource | Unit | Amount | Known |',\n '|---|---|---|---|---:|---|',\n ]\n const cell = (value: string) => value.replace(/\\|/g, '\\\\|').replace(/\\r?\\n/g, ' ')\n for (const record of records) {\n const prefix = `| ${cell(record.nodeId ?? 'unavailable')} | ${cell(record.source)} |`\n if (isUnavailable(record.resources)) {\n out.push(`${prefix} ${cell(showMeasured(record.resources))} | — | — | — |`)\n } else if (record.resources.length === 0) {\n out.push(`${prefix} recorded empty map | — | — | — |`)\n } else {\n for (const receipt of record.resources) {\n out.push(\n `${prefix} ${cell(showMeasured(receipt.name))} | ${cell(showMeasured(receipt.unit))} | ${cell(showMeasured(receipt.amount))} | ${cell(showMeasured(receipt.known))} |`,\n )\n }\n }\n }\n if (!records.length) out.push('| — | — | no spend records | — | — | — |')\n out.push('')\n return out\n}\n\nfunction fmtMs(v: Measured<number>): string {\n if (isUnavailable(v)) return `unavailable — ${v.unavailable}`\n if (v < 1000) return `${v}ms`\n const s = v / 1000\n if (s < 120) return `${round(s, 1)}s`\n return `${round(s / 60, 1)}min`\n}\n\nexport function renderSupervisorRunMarkdown(r: SupervisorRunReport): string {\n const o = r.orchestration\n const d = r.decision\n const e = r.economics\n const out: string[] = []\n out.push(`# Run report — ${r.instanceId ?? 'unknown instance'} [${r.arm ?? 'unknown arm'}]`)\n out.push('')\n out.push('```')\n out.push(renderSupervisorRunHeadline(r))\n out.push('```')\n out.push('')\n out.push(`- Run: \\`${r.runRef}\\``)\n out.push(`- Supervisor: \\`${showMeasured(r.supervisorId)}\\``)\n out.push(`- Supervisor profile: \\`${showMeasured(r.supervisorProfileDigest)}\\``)\n out.push(`- Generated: ${r.generatedAt}`)\n out.push('')\n\n out.push('## Orchestration')\n out.push('')\n out.push('| Metric | Value |')\n out.push('|---|---|')\n out.push(`| Workers spawned | ${showMeasured(o.workersSpawned)} |`)\n out.push(`| Workers settled | ${showMeasured(o.workersSettled)} |`)\n out.push(`| Workers cancelled | ${showMeasured(o.workersCancelled)} |`)\n out.push(`| **Steers (mid-task messages to live workers)** | **${showMeasured(o.steers)}** |`)\n out.push(`| Steers delivered | ${showMeasured(o.steersDelivered)} |`)\n out.push(`| Outer-driver \\`supervisor_steer\\` calls | ${showMeasured(o.driverSteerCalls)} |`)\n out.push(`| Spawn waves | ${showMeasured(o.waves)} |`)\n out.push(\n `| Wave sizes | ${isUnavailable(o.waveSizes) ? showMeasured(o.waveSizes) : `[${o.waveSizes.join(', ')}]`} |`,\n )\n out.push(`| Max concurrency | ${showMeasured(o.maxConcurrency)} |`)\n out.push(`| Respawns (after same parent's first settle) | ${showMeasured(o.respawns)} |`)\n out.push(\n `| Repeated labels | ${isUnavailable(o.repeatedLabels) ? showMeasured(o.repeatedLabels) : o.repeatedLabels.length === 0 ? 'none' : o.repeatedLabels.join(', ')} |`,\n )\n out.push(`| Delegation depth | ${showMeasured(o.delegationDepth)} |`)\n out.push(`| Time to first spawn | ${fmtMs(o.timeToFirstSpawnMs)} |`)\n out.push(\n `| Supervisor wall | ${fmtMs(o.supervisorWallMs)}${isUnavailable(o.supervisorWallSource) ? '' : ` (source: ${o.supervisorWallSource}${o.supervisorWallSource === 'journal-span' ? ', lower bound' : ''})`} |`,\n )\n out.push(`| Idle (zero live workers) | ${fmtMs(o.idleMs)} (${showMeasured(o.idlePct)}%) |`)\n out.push(\n `| Worker utilization (Σ worker wall ÷ supervisor wall) | ${showMeasured(o.workerUtilization)} |`,\n )\n out.push('')\n\n if (!isUnavailable(o.steersByWorker) && o.steersByWorker.length > 0) {\n out.push('### Steers per worker')\n out.push('')\n out.push('| Worker id | Label | Queued | Delivered |')\n out.push('|---|---|---:|---:|')\n for (const s of o.steersByWorker) {\n out.push(\n `| ${s.workerId === null ? 'unavailable — worker id absent; label join used' : `\\`${s.workerId}\\``} | \\`${s.worker}\\` | ${s.queued} | ${s.delivered} |`,\n )\n }\n out.push('')\n } else if (isUnavailable(o.steersByWorker)) {\n out.push(`### Steers per worker\\n\\nunavailable — ${o.steersByWorker.unavailable}\\n`)\n }\n\n out.push('## Decision quality')\n out.push('')\n out.push('| Metric | Value |')\n out.push('|---|---|')\n out.push(`| Settled by status | ${fmtCounts(d.settledByStatus)} |`)\n out.push(`| Settled verdicts | ${fmtCounts(d.settledVerdicts)} |`)\n out.push(`| Accepted (verify green + patch bytes) | ${showMeasured(d.accepted)} |`)\n out.push(`| Rejected (verify red) | ${showMeasured(d.rejected)} |`)\n out.push(`| Empty pass (green, no patch) | ${showMeasured(d.emptyPass)} |`)\n out.push(`| Evidence → respawn sequences | ${showMeasured(d.observeThenRespawn)} |`)\n out.push(\n `| Respawn with no same-parent settled evidence in front | ${showMeasured(d.respawnWithoutEvidence)} |`,\n )\n out.push(`| Review actions (steers + worker questions) | ${showMeasured(d.reviewActions)} |`)\n out.push(\n `| Worker evidence returned | ${isUnavailable(d.workerEvidenceBytes) ? showMeasured(d.workerEvidenceBytes) : `${d.workerEvidenceBytes} bytes`} |`,\n )\n out.push('')\n\n out.push('## Economics')\n out.push('')\n out.push('| Role | Tokens in | Tokens out | Cache read | Cache write | USD | Source |')\n out.push('|---|---:|---:|---:|---:|---:|---|')\n out.push(\n `| brain | ${showMeasured(e.brain.tokensIn)} | ${showMeasured(e.brain.tokensOut)} | ${showMeasured(e.brain.cacheRead)} | ${showMeasured(e.brain.cacheWrite)} | ${showMeasured(e.brain.usd)} | ${e.brain.source} |`,\n )\n out.push(\n `| workers | ${showMeasured(e.workers.tokensIn)} | ${showMeasured(e.workers.tokensOut)} | ${showMeasured(e.workers.cacheRead)} | ${showMeasured(e.workers.cacheWrite)} | ${showMeasured(e.workers.usd)} | ${e.workers.source} |`,\n )\n out.push('')\n if (!isUnavailable(e.brainTruncations) && e.brainTruncations > 0) {\n out.push(\n `- **BRAIN OUTPUT TRUNCATED: ${e.brainTruncations} completion(s) hit \\`finish_reason: \"length\"\\`** — the supervisor ` +\n 'acted on a half-written plan. Its output ceiling is too low; see `brain.jsonl` for the per-call `req_max_tokens`.',\n )\n } else {\n out.push(\n `- Brain completions truncated (finish_reason=length): ${showMeasured(e.brainTruncations)}`,\n )\n }\n out.push(`- Total USD: ${showMeasured(e.totalUsd)} (source: ${e.totalUsdSource})`)\n out.push(\n `- Spend measured two ways: journal-derived $${showMeasured(e.spend.journalDerived.usd)} over ${e.spend.journalDerived.records} journal record(s) (execution accounting) · ` +\n `close-record $${showMeasured(e.spend.closeRecord.usd)} over ${e.spend.closeRecord.records} close record(s) (billing-shaped). Divergence is a signal, not an error.`,\n )\n out.push(`- Cost per accepted patch: ${showMeasured(e.costPerAcceptedPatchUsd)}`)\n if (isUnavailable(e.workerWallMsDistribution)) {\n out.push(`- Worker wall distribution: unavailable — ${e.workerWallMsDistribution.unavailable}`)\n } else {\n const w = e.workerWallMsDistribution\n out.push(\n `- Worker wall (n=${w.n}): min ${fmtMs(w.min)} / p50 ${fmtMs(w.p50)} / p90 ${fmtMs(w.p90)} / max ${fmtMs(w.max)} / Σ ${fmtMs(w.sum)}`,\n )\n }\n out.push('')\n if (!isUnavailable(e.perWorker) && e.perWorker.length > 0) {\n out.push(\n '| Worker id | Label | Role | Runtime | Profile digest | Status | Failure | Infra | Wall | Tokens in | Tokens out | Patch bytes | Verify passed | Score |',\n )\n out.push('|---|---|---|---|---|---|---|---|---:|---:|---:|---:|---|---:|')\n for (const w of e.perWorker) {\n out.push(\n `| ${w.workerId === null ? 'unavailable — worker id absent; label join used' : `\\`${w.workerId}\\``} | \\`${w.worker}\\` | ${w.role ?? 'unavailable — source recorded no role'} | ${w.runtime ?? 'unavailable — source recorded no runtime'} | ${w.profileDigest === null ? 'unavailable — source recorded no profile digest' : `\\`${w.profileDigest}\\``} | ${w.status ?? 'unavailable — no terminal event'} | ${w.failure ?? 'none recorded'} | ${w.infra ?? 'unavailable'} | ${w.wallMs === null ? 'unavailable — no spawn/finish pair' : fmtMs(w.wallMs)} | ${w.tokensIn ?? 'unavailable — store does not attribute tokens per worker'} | ${w.tokensOut ?? 'unavailable — store does not attribute tokens per worker'} | ${w.patchBytes ?? 'unavailable — no worker patch file'} | ${w.passed === null ? 'unavailable — no verdict' : String(w.passed)} | ${w.score ?? 'unavailable — no numeric score'} |`,\n )\n }\n out.push('')\n }\n\n if (e.resourceRecords !== undefined) {\n out.push('## Named resource receipts', '', ...resourceRows(e.resourceRecords))\n }\n\n out.push('## Outcome')\n out.push('')\n out.push('| Metric | Value |')\n out.push('|---|---|')\n out.push(`| Supervisor status | ${showMeasured(r.outcome.supStatus)} |`)\n out.push(`| Status source | ${showMeasured(r.outcome.supStatusSource)} |`)\n out.push(`| Terminal reason | ${showMeasured(r.outcome.supReason)} |`)\n out.push(`| Failure | ${fmtFailure(r.outcome.failure)} |`)\n out.push(`| Supervisor verdict | ${showMeasured(r.outcome.supVerdict)} |`)\n out.push(`| Delivered | ${showMeasured(r.outcome.delivered)} |`)\n out.push(`| Judge resolved | ${showMeasured(r.outcome.judgeResolved)} |`)\n out.push(`| Judge score | ${showMeasured(r.outcome.judgeScore)} |`)\n out.push(\n `| Judge passed / total | ${showMeasured(r.outcome.judgePassed)} / ${showMeasured(r.outcome.judgeTotal)} |`,\n )\n out.push(\n `| Judge source | ${r.outcome.judgeSource ?? 'unavailable — no judge.json and no ledger row'} |`,\n )\n out.push(\n `| Verify gate | pass=${showMeasured(r.outcome.verifyPass)} rc=${showMeasured(r.outcome.verifyRc)} |`,\n )\n if (isUnavailable(r.outcome.patch)) {\n out.push(`| Patch | unavailable — ${r.outcome.patch.unavailable} |`)\n } else {\n const p = r.outcome.patch\n out.push(\n `| Patch | ${p.files} file(s), +${p.linesAdded}/-${p.linesRemoved}, test files touched: ${p.testFilesTouched.length === 0 ? 'none' : p.testFilesTouched.join(', ')} |`,\n )\n }\n out.push('')\n out.push('## Gaps')\n out.push('')\n if (r.gaps.length === 0) out.push('None — every metric above is backed by a present artifact.')\n else for (const g of r.gaps) out.push(`- ${g}`)\n out.push('')\n out.push(\n `> Harness-session view of the same run (model calls, stuck loops, tool errors): \\`${r.traceCommand}\\``,\n )\n out.push('')\n return out.join('\\n')\n}\n\nfunction fmtCounts(v: Measured<Record<string, number>>): string {\n if (isUnavailable(v)) return showMeasured(v as unknown as Measured<string>)\n const entries = Object.entries(v)\n return entries.length === 0 ? 'none' : entries.map(([k, n]) => `${k}=${n}`).join(', ')\n}\n\nexport function renderSupervisorRollupMarkdown(\n rollup: SupervisorRunRollup,\n title = 'Round rollup',\n): string {\n const out: string[] = []\n out.push(`# ${title}`)\n out.push('')\n out.push(`- Cells: ${rollup.cells}`)\n out.push(\n `- **Steers across all cells: ${showMeasured(rollup.steersTotal)}** (cells with ≥1 steer: ${showMeasured(rollup.cellsWithSteers)}; cells where the steer count is unavailable: ${rollup.cellsWithUnavailableSteers})`,\n )\n out.push(`- Waves per cell (mean): ${showMeasured(rollup.wavesMean)}`)\n out.push(`- Max concurrency observed: ${showMeasured(rollup.maxConcurrencyMax)}`)\n out.push(`- Worker utilization (mean): ${showMeasured(rollup.utilizationMean)}`)\n out.push(`- Idle share (mean): ${showMeasured(rollup.idlePctMean)}%`)\n out.push(\n `- Workers spawned: ${showMeasured(rollup.workersSpawnedTotal)} · accepted: ${showMeasured(rollup.acceptedTotal)}`,\n )\n out.push(\n `- Spend: $${showMeasured(rollup.usdTotal)} · judged resolved: ${showMeasured(rollup.resolvedCount)}/${rollup.cells}`,\n )\n out.push(\n `- Spend measured two ways: journal-derived $${showMeasured(rollup.spendUsd.journalDerived.value)} over ${rollup.spendUsd.journalDerived.runs}/${rollup.cells} runs (execution accounting) · ` +\n `close-record $${showMeasured(rollup.spendUsd.closeRecord.value)} over ${rollup.spendUsd.closeRecord.runs}/${rollup.cells} runs (billing-shaped)`,\n )\n out.push('')\n out.push('| Instance | Arm | Steers | Waves | Utilization | Idle % | Resolved | USD |')\n out.push('|---|---|---:|---:|---:|---:|---|---:|')\n for (const c of rollup.perCell) {\n out.push(\n `| ${c.instanceId ?? '?'} | ${c.arm ?? '?'} | ${showMeasured(c.steers)} | ${showMeasured(c.waves)} | ${showMeasured(c.utilization)} | ${showMeasured(c.idlePct)} | ${showMeasured(c.resolved)} | ${showMeasured(c.usd)} |`,\n )\n }\n out.push('')\n for (const cell of rollup.perCell) {\n if (cell.resourceRecords !== undefined) {\n out.push(\n `## Resource receipts — ${cell.instanceId ?? '?'} [${cell.arm ?? '?'}]`,\n '',\n ...resourceRows(cell.resourceRecords),\n )\n }\n }\n return out.join('\\n')\n}\n"],"mappings":";;;;;;;;AAKA,SAAgB,eAAe,KAA2B;CACxD,MAAM,OAAiB,CAAC;CACxB,MAAM,OAAO,MAAc,WAAgC;EACzD,KAAK,KAAK,GAAG,KAAK,IAAI,QAAQ;EAC9B,OAAO,YAAY,MAAM;CAC3B;CAEA,MAAM,iBACJ,IAAI,yBACH,IAAI,cAAc,OAAO,wCAAwC;CACpE,MAAM,cAAc,IAAI,YAAY;CACpC,MAAM,OAAO,oBAAoB,GAAG;CACpC,MAAM,QAAQ,KAAK;CACnB,MAAM,SAAS,gBAAgB,IAAI,MAAM;CACzC,MAAM,QAAQ,gBAAgB,IAAI,KAAK;CAEvC,MAAM,WAAW,mBAAmB;EAClC;EACA;EACA,SAAS,IAAI,YAAY,KAAA,IAAY,KAAA,IAAY,gBAAgB,IAAI,OAAO;CAC9E,CAAC;CACD,MAAM,EAAE,QAAQ,cAAc,cAAc,WAAW,gBAAgB;CACvE,MAAM,YACJ,WAAW,OAAO,OAAQ,KAAK,OAAO,MAAM,UAAU,MAAM,OAAO,MAAM,KAAK;CAChF,MAAM,YAAY,IAAI,IAAI,aAAa,KAAK,UAAU,CAAC,MAAM,IAAI,KAAK,CAAC,CAAC;CACxE,MAAM,gCAAgB,IAA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KAAK,OAAO,SACrB,IAAI,KACF,KAAK,EAAE,cAAc,IAAI,KAAK,EAAE,OAAO,IAAI,KAAK,aAAa,EAAE,MAAM,EAAE,KAAK,aAAa,EAAE,KAAK,EAAE,KAAK,aAAa,EAAE,WAAW,EAAE,KAAK,aAAa,EAAE,OAAO,EAAE,KAAK,aAAa,EAAE,QAAQ,EAAE,KAAK,aAAa,EAAE,GAAG,EAAE,GACzN;CAEF,IAAI,KAAK,EAAE;CACX,KAAK,MAAM,QAAQ,OAAO,SACxB,IAAI,KAAK,oBAAoB,KAAA,GAC3B,IAAI,KACF,0BAA0B,KAAK,cAAc,IAAI,IAAI,KAAK,OAAO,IAAI,IACrE,IACA,GAAG,aAAa,KAAK,eAAe,CACtC;CAGJ,OAAO,IAAI,KAAK,IAAI;AACtB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"rubric-predictive-validity-D3_oI72N.js","names":[],"sources":["../src/meta-eval/outcome-observations.ts","../src/meta-eval/rubric-predictive-validity.ts"],"sourcesContent":["import { pearsonR, spearmanR } from '../statistics'\nimport { makeRng } from '../statistics/internal'\nimport type { DeploymentOutcome } from './outcome-store'\n\nexport type OutcomeReduction = 'latest' | 'mean' | 'max'\n\nexport interface CorrelationInterval {\n lower: number\n upper: number\n}\n\n/** Reduce observations of one named metric; unrelated keys cannot supply a value. */\nexport function reduceOutcomeMetric(\n outcomes: readonly DeploymentOutcome[],\n metric: string,\n reduction: OutcomeReduction,\n): number | null {\n const observations = outcomes.flatMap((outcome) => {\n const value = outcome.metrics[metric]\n return Number.isFinite(outcome.capturedAt) &&\n typeof value === 'number' &&\n Number.isFinite(value)\n ? [{ capturedAt: outcome.capturedAt, value }]\n : []\n })\n if (observations.length === 0) return null\n if (reduction === 'mean') {\n return observations.reduce(\n (sum, observation) => sum + observation.value / observations.length,\n 0,\n )\n }\n if (reduction === 'max') return Math.max(...observations.map((observation) => observation.value))\n return observations.reduce((a, b) => (b.capturedAt > a.capturedAt ? b : a)).value\n}\n\nexport function hasVariation(values: readonly number[]): boolean {\n return values.some((value) => value !== values[0])\n}\n\nexport function correlationSummary(\n xs: number[],\n ys: number[],\n iterations: number,\n seed: number | undefined,\n): {\n pearson: number\n spearman: number\n pearsonCi95: CorrelationInterval | null\n spearmanCi95: CorrelationInterval | null\n} {\n const rng = makeRng(seed, xs, ys)\n const pearsons: number[] = []\n const spearmans: number[] = []\n for (let b = 0; b < iterations; b++) {\n const rx: number[] = []\n const ry: number[] = []\n for (let i = 0; i < xs.length; i++) {\n const index = Math.floor(rng() * xs.length)\n rx.push(xs[index]!)\n ry.push(ys[index]!)\n }\n // A constant resample has no estimable correlation, even when both sides agree.\n if (!hasVariation(rx) || !hasVariation(ry)) continue\n const pearson = pearsonR(rx, ry)\n const spearman = spearmanR(rx, ry)\n if (Number.isFinite(pearson)) pearsons.push(pearson)\n if (Number.isFinite(spearman)) spearmans.push(spearman)\n }\n return {\n pearson: pearsonR(xs, ys),\n spearman: spearmanR(xs, ys),\n pearsonCi95: interval(pearsons),\n spearmanCi95: interval(spearmans),\n }\n}\n\nexport function validateObservationOptions(\n reduction: OutcomeReduction,\n iterations: number,\n seed: number | undefined,\n): void {\n if (!['latest', 'mean', 'max'].includes(reduction)) {\n throw new Error('outcome reduction must be latest, mean, or max')\n }\n if (!Number.isSafeInteger(iterations) || iterations < 1) {\n throw new Error('bootstrap iterations must be a positive safe integer')\n }\n if (seed !== undefined && !Number.isFinite(seed)) {\n throw new Error('bootstrap seed must be finite')\n }\n}\n\nexport function assertUniqueObservationIds(ids: readonly string[], name: string): void {\n if (ids.some((id) => typeof id !== 'string' || id.trim().length === 0)) {\n throw new Error(`${name} must be a nonempty string`)\n }\n if (new Set(ids).size !== ids.length) throw new Error(`duplicate ${name} in outcome study`)\n}\n\nexport function validateOutcomeMetricSpecifications(\n metrics: readonly { id: string; direction: string }[],\n): void {\n if (!Array.isArray(metrics) || metrics.length === 0) {\n throw new Error('outcomeMetrics must declare at least one outcome metric and direction')\n }\n for (const metric of metrics) {\n if (!metric || typeof metric.id !== 'string' || metric.id.trim().length === 0) {\n throw new Error('each outcome metric must have a nonempty id and explicit direction')\n }\n if (metric.direction !== 'higher-is-better' && metric.direction !== 'lower-is-better') {\n throw new Error(\n `outcome metric ${metric.id} must declare higher-is-better or lower-is-better`,\n )\n }\n }\n assertUniqueObservationIds(\n metrics.map((metric) => metric.id),\n 'outcome metric',\n )\n}\n\nfunction interval(values: number[]): CorrelationInterval | null {\n if (values.length === 0) return null\n values.sort((a, b) => a - b)\n return {\n lower: Math.max(-1, values[Math.floor(0.025 * values.length)]!),\n upper: Math.min(1, values[Math.min(values.length - 1, Math.floor(0.975 * values.length))]!),\n }\n}\n","/**\n * Join rubric scores to deployment outcomes and measure their association.\n * Higher rubric scores always mean better evaluated behavior.\n * Outcome directions are explicit because success rate and failure rate have opposite meanings.\n * These descriptive associations neither establish causation nor validate a change to rubric weights.\n */\n\nimport type { RunRecord } from '../run-record'\nimport {\n assertUniqueObservationIds,\n type CorrelationInterval,\n correlationSummary,\n hasVariation,\n reduceOutcomeMetric,\n validateObservationOptions,\n validateOutcomeMetricSpecifications,\n} from './outcome-observations'\nimport type { DeploymentOutcome, OutcomeStore } from './outcome-store'\n\nexport interface OutcomeMetricSpec {\n /** Exact key in DeploymentOutcome.metrics. */\n id: string\n direction: 'higher-is-better' | 'lower-is-better'\n}\n\nexport interface RubricPredictiveValidityInput {\n /** One record per independent run; rubric scores come from outcome.raw. */\n runs: RunRecord[]\n outcomes: OutcomeStore\n /** Declare desired directions before inspecting associations. */\n outcomeMetrics: readonly OutcomeMetricSpec[]\n /** Higher is better for each rubric. Omit to discover finite numeric outcome.raw keys. */\n rubrics?: readonly string[]\n /** Minimum joined runs for an estimate; an integer at least 3. Default 8. */\n minSamples?: number\n /** Bootstrap resamples for both correlation intervals. Default 500. */\n bootstrapResamples?: number\n /** Omit to derive a reproducible seed from the paired observations. */\n seed?: number\n /** Reduce finite observations of each named outcome within a run. Default latest. */\n reduction?: 'latest' | 'mean' | 'max'\n}\n\nexport interface RubricOutcomePair {\n rubric: string\n outcome: string\n outcomeDirection: OutcomeMetricSpec['direction']\n n: number\n /** Raw association with the recorded outcome, before direction alignment. */\n pearson: number\n spearman: number\n pearsonCi95: CorrelationInterval | null\n spearmanCi95: CorrelationInterval | null\n /** Positive values associate higher rubric scores with better outcomes. */\n alignedPearson: number\n alignedSpearman: number\n alignedSpearmanCi95: CorrelationInterval | null\n /** Descriptive buckets at aligned Spearman +/-0.4; no causal or release authority. */\n verdict: 'aligned' | 'inverse' | 'weak'\n}\n\nexport interface RubricRanking extends Omit<RubricOutcomePair, 'outcome'> {\n /** Outcome with the greatest direction-aligned Spearman for this rubric. */\n bestOutcome: string\n}\n\nexport interface RubricOutcomeExclusion {\n rubric: string\n outcome: string\n outcomeDirection: OutcomeMetricSpec['direction']\n /** Finite joined observations, including measured zeros. */\n n: number\n reason: 'insufficient_samples' | 'constant_rubric' | 'constant_outcome'\n}\n\nexport interface RubricPredictiveValidityReport {\n outcomeMetrics: OutcomeMetricSpec[]\n pairs: RubricOutcomePair[]\n /** All declared pairs lacking an estimate, with their usable observation count. */\n excludedPairs: RubricOutcomeExclusion[]\n /** Exploratory ordering by aligned Spearman; never use outcome selection as confirmatory evidence. */\n ranked: RubricRanking[]\n /** Runs contributing at least one finite pair, including pairs below minSamples. */\n joinedSamples: number\n /** Runs contributing no finite pair; joinedSamples + skippedRuns equals the input run count. */\n skippedRuns: number\n /** Declared rubrics with no finite score, distinct from too few outcomes or constant observations. */\n rubricsWithoutData: string[]\n}\n\nexport async function rubricPredictiveValidity(\n input: RubricPredictiveValidityInput,\n): Promise<RubricPredictiveValidityReport> {\n const minSamples = input.minSamples ?? 8\n const reduction = input.reduction ?? 'latest'\n const resamples = input.bootstrapResamples ?? 500\n const seed = input.seed\n if (!Number.isSafeInteger(minSamples) || minSamples < 3) {\n throw new Error('minSamples must be a safe integer at least 3')\n }\n validateObservationOptions(reduction, resamples, seed)\n validateOutcomeMetricSpecifications(input.outcomeMetrics)\n assertUniqueObservationIds(\n input.runs.map((run) => run.runId),\n 'runId',\n )\n\n const outcomeMetrics = input.outcomeMetrics.map((metric) => ({ ...metric }))\n const runs = input.runs.map((run) => ({ runId: run.runId, scores: { ...run.outcome.raw } }))\n const declaredRubrics = input.rubrics === undefined ? undefined : [...input.rubrics]\n if (declaredRubrics !== undefined) assertUniqueObservationIds(declaredRubrics, 'rubric')\n\n const outcomes = await input.outcomes.list()\n const outcomesByRun = new Map<string, DeploymentOutcome[]>()\n for (const outcome of outcomes) {\n const rows = outcomesByRun.get(outcome.runId) ?? []\n rows.push(outcome)\n outcomesByRun.set(outcome.runId, rows)\n }\n\n const observedRubrics = new Set<string>()\n for (const run of runs) {\n for (const [rubric, value] of Object.entries(run.scores)) {\n if (typeof value === 'number' && Number.isFinite(value)) observedRubrics.add(rubric)\n }\n }\n const rubrics = declaredRubrics ?? [...observedRubrics]\n const buckets = rubrics.flatMap((rubric) =>\n outcomeMetrics.map((outcome) => ({\n rubric,\n outcome,\n xs: [] as number[],\n ys: [] as number[],\n })),\n )\n\n let joined = 0\n for (const run of runs) {\n const rows = outcomesByRun.get(run.runId) ?? []\n let joinedThisRun = false\n for (const bucket of buckets) {\n const x = run.scores[bucket.rubric]\n if (typeof x !== 'number' || !Number.isFinite(x)) continue\n const y = reduceOutcomeMetric(rows, bucket.outcome.id, reduction)\n if (y === null) continue\n bucket.xs.push(x)\n bucket.ys.push(y)\n joinedThisRun = true\n }\n if (joinedThisRun) joined++\n }\n\n const pairs: RubricOutcomePair[] = []\n const excludedPairs: RubricOutcomeExclusion[] = []\n for (const bucket of buckets) {\n const identity = {\n rubric: bucket.rubric,\n outcome: bucket.outcome.id,\n outcomeDirection: bucket.outcome.direction,\n n: bucket.xs.length,\n }\n const reason =\n bucket.xs.length < minSamples\n ? 'insufficient_samples'\n : !hasVariation(bucket.xs)\n ? 'constant_rubric'\n : !hasVariation(bucket.ys)\n ? 'constant_outcome'\n : null\n if (reason !== null) {\n excludedPairs.push({ ...identity, reason })\n continue\n }\n const summary = correlationSummary(bucket.xs, bucket.ys, resamples, seed)\n const sign = bucket.outcome.direction === 'higher-is-better' ? 1 : -1\n const alignedSpearman = summary.spearman * sign\n const alignedSpearmanCi95 =\n summary.spearmanCi95 === null\n ? null\n : sign === 1\n ? summary.spearmanCi95\n : { lower: -summary.spearmanCi95.upper, upper: -summary.spearmanCi95.lower }\n pairs.push({\n ...identity,\n ...summary,\n alignedPearson: summary.pearson * sign,\n alignedSpearman,\n alignedSpearmanCi95,\n verdict: alignedSpearman >= 0.4 ? 'aligned' : alignedSpearman <= -0.4 ? 'inverse' : 'weak',\n })\n }\n\n const bestByRubric = new Map<string, RubricOutcomePair>()\n for (const pair of pairs) {\n const best = bestByRubric.get(pair.rubric)\n if (!best || pair.alignedSpearman > best.alignedSpearman) bestByRubric.set(pair.rubric, pair)\n }\n const ranked = [...bestByRubric.values()]\n .map(({ outcome, ...pair }) => ({ ...pair, bestOutcome: outcome }))\n .sort((a, b) => b.alignedSpearman - a.alignedSpearman)\n\n return {\n outcomeMetrics,\n pairs,\n excludedPairs,\n ranked,\n joinedSamples: joined,\n skippedRuns: runs.length - joined,\n rubricsWithoutData: rubrics.filter((rubric) => !observedRubrics.has(rubric)),\n }\n}\n"],"mappings":";;;;AAYA,SAAgB,oBACd,UACA,QACA,WACe;CACf,MAAM,eAAe,SAAS,SAAS,YAAY;EACjD,MAAM,QAAQ,QAAQ,QAAQ;EAC9B,OAAO,OAAO,SAAS,QAAQ,UAAU,KACvC,OAAO,UAAU,YACjB,OAAO,SAAS,KAAK,IACnB,CAAC;GAAE,YAAY,QAAQ;GAAY;EAAM,CAAC,IAC1C,CAAC;CACP,CAAC;CACD,IAAI,aAAa,WAAW,GAAG,OAAO;CACtC,IAAI,cAAc,QAChB,OAAO,aAAa,QACjB,KAAK,gBAAgB,MAAM,YAAY,QAAQ,aAAa,QAC7D,CACF;CAEF,IAAI,cAAc,OAAO,OAAO,KAAK,IAAI,GAAG,a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,MAAM,OAAO,aAAa,IAAI,KAAK,MAAM;EACzC,IAAI,CAAC,QAAQ,KAAK,kBAAkB,KAAK,iBAAiB,aAAa,IAAI,KAAK,QAAQ,IAAI;CAC9F;CAKA,OAAO;EACL;EACA;EACA;EACA,QARa,CAAC,GAAG,aAAa,OAAO,CAAC,CAAC,CACtC,KAAK,EAAE,SAAS,GAAG,YAAY;GAAE,GAAG;GAAM,aAAa;EAAQ,EAAE,CAAC,CAClE,MAAM,GAAG,MAAM,EAAE,kBAAkB,EAAE,eAMjC;EACL,eAAe;EACf,aAAa,KAAK,SAAS;EAC3B,oBAAoB,QAAQ,QAAQ,WAAW,CAAC,gBAAgB,IAAI,MAAM,CAAC;CAC7E;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"rubric-predictive-validity-noY7uE03.d.ts","names":[],"sources":["../src/meta-eval/outcome-observations.ts","../src/meta-eval/rubric-predictive-validity.ts"],"mappings":";;;KAIY;UAEK;EACf;EACA;;;;UCWe;;EAEf;EACA;;UAGe;;EAEf,MAAM;EACN,UAAU;;EAEV,yBAAyB;;EAEzB;;EAEA;;EAEA;;EAEA;;EAEA;;UAGe;EACf;EACA;EACA,kBAAkB;EAClB;;EAEA;EACA;EACA,aAAa;EACb,cAAc;;EAEd;EACA;EACA,qBAAqB;;EAErB;;UAGe,sBAAsB,KAAK;;EAE1C;;UAGe;EACf;EACA;EACA,kBAAkB;;EAElB;EACA;;UAGe;EACf,gBAAgB;EAChB,OAAO;;EAEP,eAAe;;EAEf,QAAQ;;EAER;;EAEA;;EAEA;;iBAGoB,yBACpB,OAAO,gCACN,QAAQ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"statistical-heldout-3z3I-kJN.d.ts","names":["_$__evidence_receipt0.EvidenceReceipt"],"sources":["../src/statistics/paired-binary.ts","../src/statistics/sequential-eprocess.ts","../src/experiment/final-evidence.ts","../src/attestation.ts","../src/experiment/evidence-receipt.ts","../src/experiment/campaign-evidence.ts","../src/pareto.ts","../src/campaign/gates/promotion-policy.ts","../src/campaign/gates/power-preflight.ts","../src/paired-arms.ts","../src/pre-registration.ts","../src/campaign/gates/sequential.ts","../src/campaign/gates/statistical-heldout.ts"],"mappings":";;;;;;;UAgBiB;;EAEf;;EAEA;;EAEA;;;;;;;;;;;;iBAac,OAAO,mBAAmB,WAAW,sBAAoB;;UA2DxD;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;;;;;;;;;;;;;iBAec,QACd,SAAS,6BACT,WAAW,8BACV;;UAmBc;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;;;;;;;;;;;;;;;;;iBAmBc,qBACd,SAAS,6BACT,WAAW,6BACX,sBACC;;;;UAkCc;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgCc,0BACd,SAAS,6BACT,WAAW,6BACX,sBACC;;;UAyEc;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA8Dc,0BACd,SAAS,6BACT,WAAW,6BACX,sBACC;;;;;;;;;;;iBA6Ga,QAAQ,WAAW,WAAW;;;UChhB7B;;;EAGf;;;;EAIA;;;;EAIA;;;;;;;;EAQA,SAAS;;UAGM;;EAEf;;EAEA;;EAEA;;;;;;;;;;UAWe,sBAAsB;EACrC;EACA;EACA;;EAEA;;EAEA;;EAEA;;;EAGA;;UAGe;;;EAGf,OAAO,YAAY;EACnB,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA8BK,SAAS,OAAM,kBAAuB;;;cCnFhD,mBAAiB,EAAA;;;;;;GAQZ,EAAA,KAAA;;KAGC,2BAA2B,EAAE,aAAa;cAEhD,mBAAiB,EAAA;;;GAKZ,EAAA,KAAA;KAEC,2BAA2B,EAAE,aAAa;UAgCrC;EACf,aAAa;EACb,iBAAiB;EACjB;IAA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