opencastle 1.3.1 → 1.4.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 (486) hide show
  1. package/README.md +16 -10
  2. package/bin/cli.mjs +8 -9
  3. package/dist/cli/agent-roster.test.js +0 -48
  4. package/dist/cli/agent-roster.test.js.map +1 -1
  5. package/dist/cli/boundary.test.js +9 -7
  6. package/dist/cli/boundary.test.js.map +1 -1
  7. package/dist/cli/convoy/artifacts.d.ts +9 -2
  8. package/dist/cli/convoy/artifacts.d.ts.map +1 -1
  9. package/dist/cli/convoy/artifacts.js +13 -10
  10. package/dist/cli/convoy/artifacts.js.map +1 -1
  11. package/dist/cli/convoy/artifacts.test.js +4 -2
  12. package/dist/cli/convoy/artifacts.test.js.map +1 -1
  13. package/dist/cli/convoy/engine.d.ts +53 -23
  14. package/dist/cli/convoy/engine.d.ts.map +1 -1
  15. package/dist/cli/convoy/engine.git.test.d.ts +2 -0
  16. package/dist/cli/convoy/engine.git.test.d.ts.map +1 -0
  17. package/dist/cli/convoy/engine.git.test.js +435 -0
  18. package/dist/cli/convoy/engine.git.test.js.map +1 -0
  19. package/dist/cli/convoy/engine.js +1746 -2305
  20. package/dist/cli/convoy/engine.js.map +1 -1
  21. package/dist/cli/convoy/engine.test.js +698 -678
  22. package/dist/cli/convoy/engine.test.js.map +1 -1
  23. package/dist/cli/convoy/event-schemas.d.ts +2 -0
  24. package/dist/cli/convoy/event-schemas.d.ts.map +1 -1
  25. package/dist/cli/convoy/event-schemas.js +59 -57
  26. package/dist/cli/convoy/event-schemas.js.map +1 -1
  27. package/dist/cli/convoy/events.d.ts +4 -1
  28. package/dist/cli/convoy/events.d.ts.map +1 -1
  29. package/dist/cli/convoy/events.js +69 -84
  30. package/dist/cli/convoy/events.js.map +1 -1
  31. package/dist/cli/convoy/events.test.js +50 -9
  32. package/dist/cli/convoy/events.test.js.map +1 -1
  33. package/dist/cli/convoy/gates.d.ts +9 -4
  34. package/dist/cli/convoy/gates.d.ts.map +1 -1
  35. package/dist/cli/convoy/gates.js +29 -14
  36. package/dist/cli/convoy/gates.js.map +1 -1
  37. package/dist/cli/convoy/isolation.d.ts +32 -6
  38. package/dist/cli/convoy/isolation.d.ts.map +1 -1
  39. package/dist/cli/convoy/isolation.js +72 -34
  40. package/dist/cli/convoy/isolation.js.map +1 -1
  41. package/dist/cli/convoy/isolation.test.js +66 -42
  42. package/dist/cli/convoy/isolation.test.js.map +1 -1
  43. package/dist/cli/convoy/lock.d.ts.map +1 -1
  44. package/dist/cli/convoy/lock.js +25 -10
  45. package/dist/cli/convoy/lock.js.map +1 -1
  46. package/dist/cli/convoy/lock.test.js +12 -0
  47. package/dist/cli/convoy/lock.test.js.map +1 -1
  48. package/dist/cli/convoy/merge.d.ts +21 -4
  49. package/dist/cli/convoy/merge.d.ts.map +1 -1
  50. package/dist/cli/convoy/merge.js +69 -53
  51. package/dist/cli/convoy/merge.js.map +1 -1
  52. package/dist/cli/convoy/merge.test.js +23 -1
  53. package/dist/cli/convoy/merge.test.js.map +1 -1
  54. package/dist/cli/convoy/progress.d.ts +35 -0
  55. package/dist/cli/convoy/progress.d.ts.map +1 -0
  56. package/dist/cli/convoy/progress.js +103 -0
  57. package/dist/cli/convoy/progress.js.map +1 -0
  58. package/dist/cli/convoy/progress.test.d.ts +2 -0
  59. package/dist/cli/convoy/progress.test.d.ts.map +1 -0
  60. package/dist/cli/convoy/progress.test.js +53 -0
  61. package/dist/cli/convoy/progress.test.js.map +1 -0
  62. package/dist/cli/convoy/read-model.d.ts +468 -0
  63. package/dist/cli/convoy/read-model.d.ts.map +1 -0
  64. package/dist/cli/convoy/read-model.js +1132 -0
  65. package/dist/cli/convoy/read-model.js.map +1 -0
  66. package/dist/cli/convoy/read-model.test.d.ts +2 -0
  67. package/dist/cli/convoy/read-model.test.d.ts.map +1 -0
  68. package/dist/cli/convoy/read-model.test.js +609 -0
  69. package/dist/cli/convoy/read-model.test.js.map +1 -0
  70. package/dist/cli/convoy/redact.d.ts +34 -0
  71. package/dist/cli/convoy/redact.d.ts.map +1 -0
  72. package/dist/cli/convoy/redact.js +66 -0
  73. package/dist/cli/convoy/redact.js.map +1 -0
  74. package/dist/cli/convoy/redact.test.d.ts +2 -0
  75. package/dist/cli/convoy/redact.test.d.ts.map +1 -0
  76. package/dist/cli/convoy/redact.test.js +43 -0
  77. package/dist/cli/convoy/redact.test.js.map +1 -0
  78. package/dist/cli/convoy/reviewer.d.ts +65 -0
  79. package/dist/cli/convoy/reviewer.d.ts.map +1 -0
  80. package/dist/cli/convoy/reviewer.js +141 -0
  81. package/dist/cli/convoy/reviewer.js.map +1 -0
  82. package/dist/cli/convoy/reviewer.test.d.ts +2 -0
  83. package/dist/cli/convoy/reviewer.test.d.ts.map +1 -0
  84. package/dist/cli/convoy/reviewer.test.js +96 -0
  85. package/dist/cli/convoy/reviewer.test.js.map +1 -0
  86. package/dist/cli/convoy/schedule.d.ts +30 -0
  87. package/dist/cli/convoy/schedule.d.ts.map +1 -0
  88. package/dist/cli/convoy/schedule.js +111 -0
  89. package/dist/cli/convoy/schedule.js.map +1 -0
  90. package/dist/cli/convoy/schedule.test.d.ts +2 -0
  91. package/dist/cli/convoy/schedule.test.d.ts.map +1 -0
  92. package/dist/cli/convoy/schedule.test.js +45 -0
  93. package/dist/cli/convoy/schedule.test.js.map +1 -0
  94. package/dist/cli/convoy/spec-builder.d.ts +120 -30
  95. package/dist/cli/convoy/spec-builder.d.ts.map +1 -1
  96. package/dist/cli/convoy/spec-builder.js +438 -114
  97. package/dist/cli/convoy/spec-builder.js.map +1 -1
  98. package/dist/cli/convoy/spec-builder.test.js +419 -435
  99. package/dist/cli/convoy/spec-builder.test.js.map +1 -1
  100. package/dist/cli/convoy/spec-types.d.ts +46 -92
  101. package/dist/cli/convoy/spec-types.d.ts.map +1 -1
  102. package/dist/cli/convoy/store.d.ts +6 -1
  103. package/dist/cli/convoy/store.d.ts.map +1 -1
  104. package/dist/cli/convoy/store.js +111 -15
  105. package/dist/cli/convoy/store.js.map +1 -1
  106. package/dist/cli/convoy/store.test.js +59 -13
  107. package/dist/cli/convoy/store.test.js.map +1 -1
  108. package/dist/cli/convoy/types.d.ts +76 -113
  109. package/dist/cli/convoy/types.d.ts.map +1 -1
  110. package/dist/cli/convoy/types.js +6 -13
  111. package/dist/cli/convoy/types.js.map +1 -1
  112. package/dist/cli/convoy/worktree.d.ts +88 -3
  113. package/dist/cli/convoy/worktree.d.ts.map +1 -1
  114. package/dist/cli/convoy/worktree.js +282 -56
  115. package/dist/cli/convoy/worktree.js.map +1 -1
  116. package/dist/cli/convoy/worktree.test.js +132 -1
  117. package/dist/cli/convoy/worktree.test.js.map +1 -1
  118. package/dist/cli/convoy-args.test.js +9 -27
  119. package/dist/cli/convoy-args.test.js.map +1 -1
  120. package/dist/cli/convoy-cmd.d.ts +31 -6
  121. package/dist/cli/convoy-cmd.d.ts.map +1 -1
  122. package/dist/cli/convoy-cmd.js +150 -201
  123. package/dist/cli/convoy-cmd.js.map +1 -1
  124. package/dist/cli/convoy-cmd.test.d.ts +2 -0
  125. package/dist/cli/convoy-cmd.test.d.ts.map +1 -0
  126. package/dist/cli/convoy-cmd.test.js +144 -0
  127. package/dist/cli/convoy-cmd.test.js.map +1 -0
  128. package/dist/cli/dashboard.d.ts +24 -11
  129. package/dist/cli/dashboard.d.ts.map +1 -1
  130. package/dist/cli/dashboard.js +241 -303
  131. package/dist/cli/dashboard.js.map +1 -1
  132. package/dist/cli/dashboard.test.d.ts +2 -0
  133. package/dist/cli/dashboard.test.d.ts.map +1 -0
  134. package/dist/cli/dashboard.test.js +340 -0
  135. package/dist/cli/dashboard.test.js.map +1 -0
  136. package/dist/cli/dispatcher.test.js +35 -2
  137. package/dist/cli/dispatcher.test.js.map +1 -1
  138. package/dist/cli/docs-accuracy.test.js +3 -3
  139. package/dist/cli/docs-accuracy.test.js.map +1 -1
  140. package/dist/cli/log.d.ts +39 -0
  141. package/dist/cli/log.d.ts.map +1 -1
  142. package/dist/cli/log.js +267 -93
  143. package/dist/cli/log.js.map +1 -1
  144. package/dist/cli/log.test.d.ts +2 -0
  145. package/dist/cli/log.test.d.ts.map +1 -0
  146. package/dist/cli/log.test.js +208 -0
  147. package/dist/cli/log.test.js.map +1 -0
  148. package/dist/cli/nearest.d.ts +18 -0
  149. package/dist/cli/nearest.d.ts.map +1 -0
  150. package/dist/cli/nearest.js +38 -0
  151. package/dist/cli/nearest.js.map +1 -0
  152. package/dist/cli/nearest.test.d.ts +2 -0
  153. package/dist/cli/nearest.test.d.ts.map +1 -0
  154. package/dist/cli/nearest.test.js +24 -0
  155. package/dist/cli/nearest.test.js.map +1 -0
  156. package/dist/cli/pipeline.d.ts +61 -0
  157. package/dist/cli/pipeline.d.ts.map +1 -1
  158. package/dist/cli/pipeline.flow.test.d.ts +2 -0
  159. package/dist/cli/pipeline.flow.test.d.ts.map +1 -0
  160. package/dist/cli/pipeline.flow.test.js +524 -0
  161. package/dist/cli/pipeline.flow.test.js.map +1 -0
  162. package/dist/cli/pipeline.js +471 -690
  163. package/dist/cli/pipeline.js.map +1 -1
  164. package/dist/cli/plan.d.ts +82 -31
  165. package/dist/cli/plan.d.ts.map +1 -1
  166. package/dist/cli/plan.js +167 -507
  167. package/dist/cli/plan.js.map +1 -1
  168. package/dist/cli/plan.test.d.ts +2 -0
  169. package/dist/cli/plan.test.d.ts.map +1 -0
  170. package/dist/cli/plan.test.js +158 -0
  171. package/dist/cli/plan.test.js.map +1 -0
  172. package/dist/cli/run/adapters/agent-process.d.ts +82 -0
  173. package/dist/cli/run/adapters/agent-process.d.ts.map +1 -0
  174. package/dist/cli/run/adapters/agent-process.js +224 -0
  175. package/dist/cli/run/adapters/agent-process.js.map +1 -0
  176. package/dist/cli/run/adapters/agent-process.test.d.ts +2 -0
  177. package/dist/cli/run/adapters/agent-process.test.d.ts.map +1 -0
  178. package/dist/cli/run/adapters/agent-process.test.js +159 -0
  179. package/dist/cli/run/adapters/agent-process.test.js.map +1 -0
  180. package/dist/cli/run/adapters/claude.d.ts +53 -2
  181. package/dist/cli/run/adapters/claude.d.ts.map +1 -1
  182. package/dist/cli/run/adapters/claude.js +147 -171
  183. package/dist/cli/run/adapters/claude.js.map +1 -1
  184. package/dist/cli/run/adapters/claude.test.js +197 -254
  185. package/dist/cli/run/adapters/claude.test.js.map +1 -1
  186. package/dist/cli/run/adapters/codex.d.ts +25 -2
  187. package/dist/cli/run/adapters/codex.d.ts.map +1 -1
  188. package/dist/cli/run/adapters/codex.js +113 -81
  189. package/dist/cli/run/adapters/codex.js.map +1 -1
  190. package/dist/cli/run/adapters/codex.test.js +116 -95
  191. package/dist/cli/run/adapters/codex.test.js.map +1 -1
  192. package/dist/cli/run/adapters/copilot.d.ts +35 -1
  193. package/dist/cli/run/adapters/copilot.d.ts.map +1 -1
  194. package/dist/cli/run/adapters/copilot.js +104 -287
  195. package/dist/cli/run/adapters/copilot.js.map +1 -1
  196. package/dist/cli/run/adapters/copilot.test.js +122 -282
  197. package/dist/cli/run/adapters/copilot.test.js.map +1 -1
  198. package/dist/cli/run/adapters/cursor.d.ts +25 -7
  199. package/dist/cli/run/adapters/cursor.d.ts.map +1 -1
  200. package/dist/cli/run/adapters/cursor.js +103 -156
  201. package/dist/cli/run/adapters/cursor.js.map +1 -1
  202. package/dist/cli/run/adapters/cursor.test.js +106 -218
  203. package/dist/cli/run/adapters/cursor.test.js.map +1 -1
  204. package/dist/cli/run/adapters/index.d.ts +34 -5
  205. package/dist/cli/run/adapters/index.d.ts.map +1 -1
  206. package/dist/cli/run/adapters/index.js +147 -21
  207. package/dist/cli/run/adapters/index.js.map +1 -1
  208. package/dist/cli/run/adapters/index.test.d.ts +2 -0
  209. package/dist/cli/run/adapters/index.test.d.ts.map +1 -0
  210. package/dist/cli/run/adapters/index.test.js +129 -0
  211. package/dist/cli/run/adapters/index.test.js.map +1 -0
  212. package/dist/cli/run/adapters/opencode.d.ts +25 -9
  213. package/dist/cli/run/adapters/opencode.d.ts.map +1 -1
  214. package/dist/cli/run/adapters/opencode.js +136 -152
  215. package/dist/cli/run/adapters/opencode.js.map +1 -1
  216. package/dist/cli/run/adapters/opencode.test.js +99 -218
  217. package/dist/cli/run/adapters/opencode.test.js.map +1 -1
  218. package/dist/cli/run/adapters/permission-modes.d.ts +47 -4
  219. package/dist/cli/run/adapters/permission-modes.d.ts.map +1 -1
  220. package/dist/cli/run/adapters/permission-modes.js +113 -37
  221. package/dist/cli/run/adapters/permission-modes.js.map +1 -1
  222. package/dist/cli/run/adapters/permission-modes.test.js +55 -40
  223. package/dist/cli/run/adapters/permission-modes.test.js.map +1 -1
  224. package/dist/cli/run/adapters/stub-cli.test-helper.d.ts +22 -0
  225. package/dist/cli/run/adapters/stub-cli.test-helper.d.ts.map +1 -0
  226. package/dist/cli/run/adapters/stub-cli.test-helper.js +73 -0
  227. package/dist/cli/run/adapters/stub-cli.test-helper.js.map +1 -0
  228. package/dist/cli/run/platform.d.ts +52 -0
  229. package/dist/cli/run/platform.d.ts.map +1 -0
  230. package/dist/cli/run/platform.js +207 -0
  231. package/dist/cli/run/platform.js.map +1 -0
  232. package/dist/cli/run/platform.test.d.ts +2 -0
  233. package/dist/cli/run/platform.test.d.ts.map +1 -0
  234. package/dist/cli/run/platform.test.js +119 -0
  235. package/dist/cli/run/platform.test.js.map +1 -0
  236. package/dist/cli/run/schema.d.ts +6 -8
  237. package/dist/cli/run/schema.d.ts.map +1 -1
  238. package/dist/cli/run/schema.js +44 -68
  239. package/dist/cli/run/schema.js.map +1 -1
  240. package/dist/cli/run/schema.test.js +59 -279
  241. package/dist/cli/run/schema.test.js.map +1 -1
  242. package/dist/cli/run.d.ts +34 -56
  243. package/dist/cli/run.d.ts.map +1 -1
  244. package/dist/cli/run.js +379 -1132
  245. package/dist/cli/run.js.map +1 -1
  246. package/dist/cli/run.test.d.ts +2 -0
  247. package/dist/cli/run.test.d.ts.map +1 -0
  248. package/dist/cli/run.test.js +318 -0
  249. package/dist/cli/run.test.js.map +1 -0
  250. package/dist/cli/team-config.d.ts.map +1 -1
  251. package/dist/cli/team-config.js +2 -21
  252. package/dist/cli/team-config.js.map +1 -1
  253. package/dist/cli/tiers.test.js +4 -13
  254. package/dist/cli/tiers.test.js.map +1 -1
  255. package/package.json +3 -10
  256. package/src/cli/agent-roster.test.ts +0 -55
  257. package/src/cli/boundary.test.ts +9 -7
  258. package/src/cli/convoy/TELEMETRY.md +131 -125
  259. package/src/cli/convoy/artifacts.test.ts +4 -2
  260. package/src/cli/convoy/artifacts.ts +13 -12
  261. package/src/cli/convoy/engine.git.test.ts +462 -0
  262. package/src/cli/convoy/engine.test.ts +817 -850
  263. package/src/cli/convoy/engine.ts +1864 -2596
  264. package/src/cli/convoy/event-schemas.ts +63 -59
  265. package/src/cli/convoy/events.test.ts +58 -9
  266. package/src/cli/convoy/events.ts +69 -91
  267. package/src/cli/convoy/gates.ts +31 -12
  268. package/src/cli/convoy/isolation.test.ts +76 -43
  269. package/src/cli/convoy/isolation.ts +100 -38
  270. package/src/cli/convoy/lock.test.ts +16 -0
  271. package/src/cli/convoy/lock.ts +25 -8
  272. package/src/cli/convoy/merge.test.ts +25 -1
  273. package/src/cli/convoy/merge.ts +74 -61
  274. package/src/cli/convoy/progress.test.ts +59 -0
  275. package/src/cli/convoy/progress.ts +121 -0
  276. package/src/cli/convoy/read-model.test.ts +685 -0
  277. package/src/cli/convoy/read-model.ts +1469 -0
  278. package/src/cli/convoy/redact.test.ts +49 -0
  279. package/src/cli/convoy/redact.ts +73 -0
  280. package/src/cli/convoy/reviewer.test.ts +112 -0
  281. package/src/cli/convoy/reviewer.ts +196 -0
  282. package/src/cli/convoy/schedule.test.ts +56 -0
  283. package/src/cli/convoy/schedule.ts +109 -0
  284. package/src/cli/convoy/spec-builder.test.ts +460 -464
  285. package/src/cli/convoy/spec-builder.ts +460 -129
  286. package/src/cli/convoy/spec-types.ts +46 -108
  287. package/src/cli/convoy/store.test.ts +64 -13
  288. package/src/cli/convoy/store.ts +143 -33
  289. package/src/cli/convoy/types.ts +59 -71
  290. package/src/cli/convoy/worktree.test.ts +140 -1
  291. package/src/cli/convoy/worktree.ts +311 -61
  292. package/src/cli/convoy-args.test.ts +10 -30
  293. package/src/cli/convoy-cmd.test.ts +163 -0
  294. package/src/cli/convoy-cmd.ts +173 -216
  295. package/src/cli/dashboard/dashboard.css +2086 -0
  296. package/src/cli/dashboard/dashboard.js +1687 -0
  297. package/src/cli/dashboard/index.html +307 -0
  298. package/src/cli/dashboard.test.ts +382 -0
  299. package/src/cli/dashboard.ts +243 -339
  300. package/src/cli/dispatcher.test.ts +36 -2
  301. package/src/cli/docs-accuracy.test.ts +3 -3
  302. package/src/cli/log.test.ts +228 -0
  303. package/src/cli/log.ts +302 -83
  304. package/src/cli/nearest.test.ts +27 -0
  305. package/src/cli/nearest.ts +38 -0
  306. package/src/cli/pipeline.flow.test.ts +607 -0
  307. package/src/cli/pipeline.ts +544 -759
  308. package/src/cli/plan.test.ts +193 -0
  309. package/src/cli/plan.ts +209 -545
  310. package/src/cli/run/adapters/agent-process.test.ts +175 -0
  311. package/src/cli/run/adapters/agent-process.ts +252 -0
  312. package/src/cli/run/adapters/claude.test.ts +205 -260
  313. package/src/cli/run/adapters/claude.ts +151 -162
  314. package/src/cli/run/adapters/codex.test.ts +120 -100
  315. package/src/cli/run/adapters/codex.ts +115 -91
  316. package/src/cli/run/adapters/copilot.test.ts +135 -306
  317. package/src/cli/run/adapters/copilot.ts +105 -274
  318. package/src/cli/run/adapters/cursor.test.ts +111 -220
  319. package/src/cli/run/adapters/cursor.ts +105 -156
  320. package/src/cli/run/adapters/index.test.ts +148 -0
  321. package/src/cli/run/adapters/index.ts +168 -20
  322. package/src/cli/run/adapters/opencode.test.ts +106 -227
  323. package/src/cli/run/adapters/opencode.ts +139 -151
  324. package/src/cli/run/adapters/permission-modes.test.ts +63 -41
  325. package/src/cli/run/adapters/permission-modes.ts +118 -37
  326. package/src/cli/run/adapters/stub-cli.test-helper.ts +88 -0
  327. package/src/cli/run/platform.test.ts +128 -0
  328. package/src/cli/run/platform.ts +213 -0
  329. package/src/cli/run/schema.test.ts +62 -344
  330. package/src/cli/run/schema.ts +48 -78
  331. package/src/cli/run.test.ts +351 -0
  332. package/src/cli/run.ts +366 -1151
  333. package/src/cli/team-config.ts +2 -21
  334. package/src/cli/tiers.test.ts +4 -17
  335. package/src/orchestrator/agents/team-lead.agent.md +1 -1
  336. package/src/orchestrator/prompts/assess-complexity.prompt.md +43 -26
  337. package/src/orchestrator/prompts/brainstorm.prompt.md +1 -1
  338. package/src/orchestrator/prompts/bug-fix.prompt.md +2 -2
  339. package/src/orchestrator/prompts/fix-convoy.prompt.md +43 -29
  340. package/src/orchestrator/prompts/fix-prd.prompt.md +26 -22
  341. package/src/orchestrator/prompts/generate-convoy.prompt.md +139 -147
  342. package/src/orchestrator/prompts/generate-prd.prompt.md +75 -68
  343. package/src/orchestrator/prompts/implement-feature.prompt.md +2 -2
  344. package/src/orchestrator/prompts/validate-convoy.prompt.md +29 -28
  345. package/src/orchestrator/prompts/validate-prd.prompt.md +28 -21
  346. package/src/orchestrator/skills/agent-hooks/HOOKS-REFERENCE.md +3 -3
  347. package/src/orchestrator/skills/agent-hooks/SKILL.md +1 -1
  348. package/src/orchestrator/skills/fast-review/SKILL.md +3 -1
  349. package/src/orchestrator/skills/orchestration-protocols/SKILL.md +7 -8
  350. package/dist/cli/convoy/dag-analysis.d.ts +0 -39
  351. package/dist/cli/convoy/dag-analysis.d.ts.map +0 -1
  352. package/dist/cli/convoy/dag-analysis.js +0 -279
  353. package/dist/cli/convoy/dag-analysis.js.map +0 -1
  354. package/dist/cli/convoy/dag-analysis.test.d.ts +0 -2
  355. package/dist/cli/convoy/dag-analysis.test.d.ts.map +0 -1
  356. package/dist/cli/convoy/dag-analysis.test.js +0 -289
  357. package/dist/cli/convoy/dag-analysis.test.js.map +0 -1
  358. package/dist/cli/convoy/formula.d.ts +0 -19
  359. package/dist/cli/convoy/formula.d.ts.map +0 -1
  360. package/dist/cli/convoy/formula.js +0 -142
  361. package/dist/cli/convoy/formula.js.map +0 -1
  362. package/dist/cli/convoy/formula.test.d.ts +0 -2
  363. package/dist/cli/convoy/formula.test.d.ts.map +0 -1
  364. package/dist/cli/convoy/formula.test.js +0 -342
  365. package/dist/cli/convoy/formula.test.js.map +0 -1
  366. package/dist/cli/convoy/health.d.ts +0 -34
  367. package/dist/cli/convoy/health.d.ts.map +0 -1
  368. package/dist/cli/convoy/health.js +0 -123
  369. package/dist/cli/convoy/health.js.map +0 -1
  370. package/dist/cli/convoy/health.test.d.ts +0 -2
  371. package/dist/cli/convoy/health.test.d.ts.map +0 -1
  372. package/dist/cli/convoy/health.test.js +0 -448
  373. package/dist/cli/convoy/health.test.js.map +0 -1
  374. package/dist/cli/convoy/last-run.d.ts +0 -53
  375. package/dist/cli/convoy/last-run.d.ts.map +0 -1
  376. package/dist/cli/convoy/last-run.js +0 -54
  377. package/dist/cli/convoy/last-run.js.map +0 -1
  378. package/dist/cli/convoy/last-run.test.d.ts +0 -2
  379. package/dist/cli/convoy/last-run.test.d.ts.map +0 -1
  380. package/dist/cli/convoy/last-run.test.js +0 -110
  381. package/dist/cli/convoy/last-run.test.js.map +0 -1
  382. package/dist/cli/convoy/pipeline.d.ts +0 -41
  383. package/dist/cli/convoy/pipeline.d.ts.map +0 -1
  384. package/dist/cli/convoy/pipeline.js +0 -414
  385. package/dist/cli/convoy/pipeline.js.map +0 -1
  386. package/dist/cli/convoy/pipeline.test.d.ts +0 -2
  387. package/dist/cli/convoy/pipeline.test.d.ts.map +0 -1
  388. package/dist/cli/convoy/pipeline.test.js +0 -837
  389. package/dist/cli/convoy/pipeline.test.js.map +0 -1
  390. package/dist/cli/convoy/review-stages.d.ts +0 -9
  391. package/dist/cli/convoy/review-stages.d.ts.map +0 -1
  392. package/dist/cli/convoy/review-stages.js +0 -134
  393. package/dist/cli/convoy/review-stages.js.map +0 -1
  394. package/dist/cli/convoy/review-stages.test.d.ts +0 -2
  395. package/dist/cli/convoy/review-stages.test.d.ts.map +0 -1
  396. package/dist/cli/convoy/review-stages.test.js +0 -197
  397. package/dist/cli/convoy/review-stages.test.js.map +0 -1
  398. package/dist/cli/run/executor.d.ts +0 -15
  399. package/dist/cli/run/executor.d.ts.map +0 -1
  400. package/dist/cli/run/executor.js +0 -249
  401. package/dist/cli/run/executor.js.map +0 -1
  402. package/dist/cli/run/executor.test.d.ts +0 -2
  403. package/dist/cli/run/executor.test.d.ts.map +0 -1
  404. package/dist/cli/run/executor.test.js +0 -297
  405. package/dist/cli/run/executor.test.js.map +0 -1
  406. package/dist/cli/run/reporter.d.ts +0 -10
  407. package/dist/cli/run/reporter.d.ts.map +0 -1
  408. package/dist/cli/run/reporter.js +0 -142
  409. package/dist/cli/run/reporter.js.map +0 -1
  410. package/dist/cli/run-dry-run.test.d.ts +0 -2
  411. package/dist/cli/run-dry-run.test.d.ts.map +0 -1
  412. package/dist/cli/run-dry-run.test.js +0 -83
  413. package/dist/cli/run-dry-run.test.js.map +0 -1
  414. package/dist/cli/run-executor-flags.test.d.ts +0 -2
  415. package/dist/cli/run-executor-flags.test.d.ts.map +0 -1
  416. package/dist/cli/run-executor-flags.test.js +0 -31
  417. package/dist/cli/run-executor-flags.test.js.map +0 -1
  418. package/dist/cli/run-finish.test.d.ts +0 -2
  419. package/dist/cli/run-finish.test.d.ts.map +0 -1
  420. package/dist/cli/run-finish.test.js +0 -77
  421. package/dist/cli/run-finish.test.js.map +0 -1
  422. package/dist/cli/watch.d.ts +0 -15
  423. package/dist/cli/watch.d.ts.map +0 -1
  424. package/dist/cli/watch.js +0 -277
  425. package/dist/cli/watch.js.map +0 -1
  426. package/dist/dashboard/scripts/etl.d.ts +0 -10
  427. package/dist/dashboard/scripts/etl.d.ts.map +0 -1
  428. package/dist/dashboard/scripts/etl.js +0 -141
  429. package/dist/dashboard/scripts/etl.js.map +0 -1
  430. package/src/cli/convoy/dag-analysis.test.ts +0 -349
  431. package/src/cli/convoy/dag-analysis.ts +0 -367
  432. package/src/cli/convoy/formula.test.ts +0 -404
  433. package/src/cli/convoy/formula.ts +0 -174
  434. package/src/cli/convoy/health.test.ts +0 -519
  435. package/src/cli/convoy/health.ts +0 -189
  436. package/src/cli/convoy/last-run.test.ts +0 -130
  437. package/src/cli/convoy/last-run.ts +0 -87
  438. package/src/cli/convoy/pipeline.test.ts +0 -999
  439. package/src/cli/convoy/pipeline.ts +0 -492
  440. package/src/cli/convoy/review-stages.test.ts +0 -235
  441. package/src/cli/convoy/review-stages.ts +0 -166
  442. package/src/cli/run/executor.test.ts +0 -338
  443. package/src/cli/run/executor.ts +0 -292
  444. package/src/cli/run/reporter.ts +0 -160
  445. package/src/cli/run-dry-run.test.ts +0 -97
  446. package/src/cli/run-executor-flags.test.ts +0 -38
  447. package/src/cli/run-finish.test.ts +0 -91
  448. package/src/cli/watch.ts +0 -295
  449. package/src/dashboard/astro.config.mjs +0 -6
  450. package/src/dashboard/dist/_astro/index.CADNhRPS.css +0 -1
  451. package/src/dashboard/dist/data/.gitkeep +0 -0
  452. package/src/dashboard/dist/data/convoy-list.json +0 -1
  453. package/src/dashboard/dist/data/overall-stats.json +0 -29
  454. package/src/dashboard/dist/index.html +0 -1963
  455. package/src/dashboard/node_modules/.vite/deps/_metadata.json +0 -31
  456. package/src/dashboard/node_modules/.vite/deps/astro___aria-query.js +0 -6776
  457. package/src/dashboard/node_modules/.vite/deps/astro___aria-query.js.map +0 -7
  458. package/src/dashboard/node_modules/.vite/deps/astro___axobject-query.js +0 -3754
  459. package/src/dashboard/node_modules/.vite/deps/astro___axobject-query.js.map +0 -7
  460. package/src/dashboard/node_modules/.vite/deps/astro___cssesc.js +0 -99
  461. package/src/dashboard/node_modules/.vite/deps/astro___cssesc.js.map +0 -7
  462. package/src/dashboard/node_modules/.vite/deps/chunk-BUSYA2B4.js +0 -8
  463. package/src/dashboard/node_modules/.vite/deps/chunk-BUSYA2B4.js.map +0 -7
  464. package/src/dashboard/node_modules/.vite/deps/package.json +0 -3
  465. package/src/dashboard/package-lock.json +0 -6
  466. package/src/dashboard/public/data/.gitkeep +0 -0
  467. package/src/dashboard/public/data/convoy-list.json +0 -1
  468. package/src/dashboard/public/data/overall-stats.json +0 -29
  469. package/src/dashboard/public/icon-192.png +0 -0
  470. package/src/dashboard/scripts/etl.test.ts +0 -166
  471. package/src/dashboard/scripts/etl.ts +0 -170
  472. package/src/dashboard/scripts/generate-demo-db.test.ts +0 -30
  473. package/src/dashboard/scripts/generate-demo-db.ts +0 -529
  474. package/src/dashboard/scripts/integration-test.ts +0 -504
  475. package/src/dashboard/scripts/verify-demo-data.sh +0 -51
  476. package/src/dashboard/seed-data/delegations.ndjson +0 -35
  477. package/src/dashboard/seed-data/events.ndjson +0 -104
  478. package/src/dashboard/seed-data/panels.ndjson +0 -13
  479. package/src/dashboard/seed-data/reviews.ndjson +0 -6
  480. package/src/dashboard/seed-data/sessions.ndjson +0 -50
  481. package/src/dashboard/src/env.d.ts +0 -1
  482. package/src/dashboard/src/layouts/Layout.astro +0 -25
  483. package/src/dashboard/src/pages/index.astro +0 -2313
  484. package/src/dashboard/src/styles/dashboard.css +0 -2943
  485. package/src/dashboard/tsconfig.json +0 -6
  486. /package/src/{dashboard/dist → cli/dashboard}/icon-192.png +0 -0
@@ -0,0 +1,1469 @@
1
+ /**
2
+ * The one read path into a project's convoy history.
3
+ *
4
+ * The status screen and the viewer both describe the same runs, and two readers
5
+ * of the same state eventually contradict each other. Both read through here.
6
+ *
7
+ * Read-only by construction: the database is opened with `readOnly: true`,
8
+ * queried and closed again. Opening it through the store used to run schema
9
+ * migrations, copy `.bak` files and switch the journal mode — writes, from a
10
+ * page that only looks. A viewer started against an older project must not
11
+ * upgrade that project's database behind the engine's back.
12
+ *
13
+ * The schema is read as it is found, not as this file expects it. Columns are
14
+ * selected only when the table has them, so a database from an older release
15
+ * reads with those fields `undefined`, and one from a newer release (a cost
16
+ * flag, cache token counts, an adapter column) reads without this file knowing
17
+ * about every addition first.
18
+ */
19
+ import { closeSync, existsSync, fstatSync, openSync, readSync, statSync } from 'node:fs'
20
+ import { hostname } from 'node:os'
21
+ import { dirname, join, resolve } from 'node:path'
22
+ import { DatabaseSync } from 'node:sqlite'
23
+ import { KNOWN_EVENT_TYPES } from './types.js'
24
+
25
+ /** A run in one of these states may still have a process working on it. */
26
+ const ACTIVE_STATUSES = new Set(['pending', 'running'])
27
+ const FAILED_TASK_STATUSES = ['failed', 'gate-failed', 'timed-out', 'review-blocked', 'hook-failed', 'disputed']
28
+ const RUNNING_TASK_STATUSES = new Set(['running', 'assigned'])
29
+
30
+ /**
31
+ * The engine beats every 10 seconds. A minute of silence is six missed beats:
32
+ * long enough not to flicker, short enough that a killed run stops reading as
33
+ * live within one glance.
34
+ */
35
+ const HEARTBEAT_STALE_MS = 60_000
36
+
37
+ /** How much of a failed task's output is shown as its reason. */
38
+ const TAIL_LINES = 20
39
+ const TAIL_CHARS = 2000
40
+
41
+ /**
42
+ * Runtime names the engine has written into `task.model` when the runtime
43
+ * reported no model. They name an adapter, not a model, so they read as unknown.
44
+ */
45
+ const RUNTIME_NAMES = new Set(['claude', 'codex', 'copilot', 'cursor', 'opencode'])
46
+
47
+ export interface RunSummary {
48
+ id: string
49
+ name: string
50
+ status: string
51
+ branch: string | null
52
+ pipeline_id: string | null
53
+ created_at: string
54
+ started_at: string | null
55
+ finished_at: string | null
56
+ /** Finished minus started; null until the run has finished. */
57
+ duration_ms: number | null
58
+ tasks_total: number
59
+ tasks_done: number
60
+ tasks_failed: number
61
+ tasks_running: number
62
+ /** The run's recorded total, or the sum of what its tasks have recorded so far. Null when nothing was recorded. */
63
+ tokens: number | null
64
+ cost_usd: number | null
65
+ /** True when any part of the cost is an estimate; undefined when the store does not say. */
66
+ cost_estimated: boolean | undefined
67
+ /** A process is still working on this run (see `isRunAlive`). */
68
+ alive: boolean
69
+ /**
70
+ * The status to show: the recorded one, except that a run recorded as pending
71
+ * or running with no live process is `interrupted`. A crash or a kill leaves
72
+ * the status column saying "running" for ever; nothing is running it.
73
+ */
74
+ display_status: string
75
+ }
76
+
77
+ export interface TaskRow {
78
+ id: string
79
+ phase: number
80
+ agent: string
81
+ status: string
82
+ /** `interrupted` for a task recorded as running or assigned in a run nothing is working on. */
83
+ display_status: string
84
+ depends_on: string[]
85
+ adapter: string | null
86
+ /** The model the runtime reported; null when it reported none. */
87
+ model: string | null
88
+ retries: number
89
+ started_at: string | null
90
+ finished_at: string | null
91
+ duration_ms: number | null
92
+ prompt_tokens: number | null
93
+ completion_tokens: number | null
94
+ total_tokens: number | null
95
+ cache_read_tokens: number | null | undefined
96
+ cache_write_tokens: number | null | undefined
97
+ cost_usd: number | null
98
+ cost_estimated: boolean | undefined
99
+ /**
100
+ * The review's verdict: `pass`, `block`, or `skipped` when a review was due
101
+ * and reached no verdict — which is not a pass. Null when none was recorded;
102
+ * undefined when the store has no review columns.
103
+ */
104
+ review_verdict: ReviewVerdict | null | undefined
105
+ /** `auto-pass`, `fast` or `panel`; auto-pass means no reviewer read it. */
106
+ review_level: string | null | undefined
107
+ /** Why the engine says it failed (the `task_failed` reason), when it failed. */
108
+ failure_reason: string | null
109
+ /** The last lines of the failed attempt's output. */
110
+ error_tail: string | null
111
+ }
112
+
113
+ export type ReviewVerdict = 'pass' | 'block' | 'skipped'
114
+
115
+ export interface RunDetail extends RunSummary {
116
+ adapters: string[]
117
+ models: string[]
118
+ tasks: TaskRow[]
119
+ }
120
+
121
+ export type EventCategory = 'run' | 'task' | 'check' | 'review' | 'merge' | 'other'
122
+
123
+ export interface EventRow {
124
+ /** Monotonic per database: pass the last one seen as `sinceId` to read only what is new. */
125
+ id: number
126
+ type: string
127
+ task_id: string | null
128
+ worker_id: string | null
129
+ data: unknown
130
+ created_at: string
131
+ category: EventCategory
132
+ /** A failure or warning worth surfacing on its own. */
133
+ problem: boolean
134
+ }
135
+
136
+ /**
137
+ * A session: a `type: "session"` record appended with `opencastle log`
138
+ * (`source: 'log'`), or the `session` event the engine writes for each task it
139
+ * finishes (`source: 'convoy'`, with the run's id).
140
+ */
141
+ export interface SessionRow {
142
+ source: 'log' | 'convoy'
143
+ convoy_id: string | null
144
+ timestamp: string | null
145
+ agent: string | null
146
+ task: string | null
147
+ tracker_issue: string | null
148
+ outcome: string | null
149
+ model: string | null
150
+ duration_min: number | null
151
+ files_changed: number | null
152
+ retries: number | null
153
+ }
154
+
155
+ type Row = Record<string, unknown>
156
+
157
+ // ── Project discovery ─────────────────────────────────────────────────────────
158
+
159
+ /**
160
+ * The nearest directory at or above `start` holding `.opencastle/`.
161
+ *
162
+ * The same walk `opencastle log` does. The dashboard used to read the current
163
+ * directory only, so started from `proj/src` it showed nothing while `log`,
164
+ * from the same place, was writing to `proj/.opencastle`.
165
+ */
166
+ export function findProjectRoot(start: string): string | null {
167
+ let dir = resolve(start)
168
+ for (;;) {
169
+ try {
170
+ if (statSync(join(dir, '.opencastle')).isDirectory()) return dir
171
+ } catch {
172
+ // not here; keep walking
173
+ }
174
+ const parent = dirname(dir)
175
+ if (parent === dir) return null
176
+ dir = parent
177
+ }
178
+ }
179
+
180
+ export function convoyDbPath(projectRoot: string): string {
181
+ return join(projectRoot, '.opencastle', 'convoy.db')
182
+ }
183
+
184
+ // ── Database access ───────────────────────────────────────────────────────────
185
+
186
+ /** A read-only connection that knows which tables and columns this database has. */
187
+ class Reader {
188
+ private readonly cols = new Map<string, Set<string>>()
189
+
190
+ constructor(readonly db: DatabaseSync) {}
191
+
192
+ columns(table: string): Set<string> {
193
+ let found = this.cols.get(table)
194
+ if (!found) {
195
+ // Table names here are constants from this file, never request input.
196
+ const rows = this.db.prepare(`PRAGMA table_info(${table})`).all() as Row[]
197
+ found = new Set(rows.map((r) => String(r.name)))
198
+ this.cols.set(table, found)
199
+ }
200
+ return found
201
+ }
202
+
203
+ hasTable(table: string): boolean {
204
+ return this.columns(table).size > 0
205
+ }
206
+
207
+ /** A SELECT list of the wanted columns this database has. The others read as undefined. */
208
+ select(table: string, wanted: readonly string[]): string {
209
+ const have = this.columns(table)
210
+ const list = wanted.filter((c) => have.has(c))
211
+ return list.length > 0 ? list.join(', ') : 'NULL AS _none'
212
+ }
213
+
214
+ all(sql: string, ...params: Array<string | number | null>): Row[] {
215
+ return this.db.prepare(sql).all(...params) as Row[]
216
+ }
217
+
218
+ get(sql: string, ...params: Array<string | number | null>): Row | undefined {
219
+ return this.db.prepare(sql).get(...params) as Row | undefined
220
+ }
221
+ }
222
+
223
+ /**
224
+ * Run `fn` against a read-only connection, or return `fallback` when the project
225
+ * has no database yet. Query errors are not swallowed: a page that says "no
226
+ * runs" when the truth is "could not read them" is the kind of quiet wrongness
227
+ * this module exists to stop.
228
+ */
229
+ function withDb<T>(projectRoot: string, fallback: T, fn: (r: Reader) => T): T {
230
+ const path = convoyDbPath(projectRoot)
231
+ if (!existsSync(path)) return fallback
232
+ const db = new DatabaseSync(path, { readOnly: true })
233
+ try {
234
+ // A connection setting, not a write: wait out a checkpoint instead of failing.
235
+ db.exec('PRAGMA busy_timeout = 2000')
236
+ return fn(new Reader(db))
237
+ } finally {
238
+ db.close()
239
+ }
240
+ }
241
+
242
+ // ── Value helpers ─────────────────────────────────────────────────────────────
243
+
244
+ function str(v: unknown): string | null {
245
+ return typeof v === 'string' && v !== '' ? v : null
246
+ }
247
+
248
+ function num(v: unknown): number | null {
249
+ if (typeof v === 'number' && Number.isFinite(v)) return v
250
+ if (typeof v === 'bigint') return Number(v)
251
+ if (typeof v === 'string' && v.trim() !== '' && Number.isFinite(Number(v))) return Number(v)
252
+ return null
253
+ }
254
+
255
+ /** A column that may not exist: undefined when absent, null when empty. */
256
+ function optNum(row: Row, key: string): number | null | undefined {
257
+ return key in row ? num(row[key]) : undefined
258
+ }
259
+
260
+ function optFlag(row: Row, key: string): boolean | undefined {
261
+ if (!(key in row)) return undefined
262
+ const v = row[key]
263
+ return v === 1 || v === true || v === '1' || v === 'true'
264
+ }
265
+
266
+ function span(from: string | null, to: string | null): number | null {
267
+ if (!from || !to) return null
268
+ const ms = Date.parse(to) - Date.parse(from)
269
+ return Number.isFinite(ms) && ms >= 0 ? ms : null
270
+ }
271
+
272
+ function sumOrNull(values: Array<number | null>): number | null {
273
+ let total: number | null = null
274
+ for (const v of values) if (v !== null) total = (total ?? 0) + v
275
+ return total
276
+ }
277
+
278
+ function parseJson(text: unknown): unknown {
279
+ if (typeof text !== 'string') return text ?? null
280
+ try {
281
+ return JSON.parse(text)
282
+ } catch {
283
+ return text
284
+ }
285
+ }
286
+
287
+ function stringList(text: unknown): string[] {
288
+ const parsed = parseJson(text)
289
+ return Array.isArray(parsed) ? parsed.filter((x): x is string => typeof x === 'string') : []
290
+ }
291
+
292
+ function tail(text: unknown): string | null {
293
+ if (typeof text !== 'string') return null
294
+ const lines = text.trimEnd().split('\n')
295
+ let out = lines.slice(-TAIL_LINES).join('\n')
296
+ if (out.length > TAIL_CHARS) out = out.slice(-TAIL_CHARS)
297
+ return out.trim() === '' ? null : out
298
+ }
299
+
300
+ function costOf(row: Row): number | null {
301
+ // `*_num` is the REAL copy; older rows have only the TEXT column.
302
+ return num(row.cost_usd_num) ?? num(row.cost_usd)
303
+ }
304
+
305
+ function placeholders(n: number): string {
306
+ return Array.from({ length: n }, () => '?').join(', ')
307
+ }
308
+
309
+ // ── Liveness ──────────────────────────────────────────────────────────────────
310
+
311
+ interface LockRow {
312
+ pid: number | null
313
+ hostname: string | null
314
+ started_at: string | null
315
+ last_heartbeat: string | null
316
+ }
317
+
318
+ function readLock(r: Reader): LockRow | null {
319
+ if (!r.hasTable('engine_lock')) return null
320
+ const row = r.get(`SELECT ${r.select('engine_lock', ['pid', 'hostname', 'started_at', 'last_heartbeat'])} FROM engine_lock LIMIT 1`)
321
+ if (!row) return null
322
+ return { pid: num(row.pid), hostname: str(row.hostname), started_at: str(row.started_at), last_heartbeat: str(row.last_heartbeat) }
323
+ }
324
+
325
+ function pidAlive(pid: number): boolean {
326
+ try {
327
+ process.kill(pid, 0)
328
+ return true
329
+ } catch (err) {
330
+ // EPERM: the process exists, it just is not ours to signal.
331
+ return (err as NodeJS.ErrnoException).code === 'EPERM'
332
+ }
333
+ }
334
+
335
+ /** Whether the lock's holder is still working: a recent heartbeat, and on this host, a live pid. */
336
+ function lockHeld(lock: LockRow, now: number): boolean {
337
+ const beat = lock.last_heartbeat ? Date.parse(lock.last_heartbeat) : NaN
338
+ if (!Number.isFinite(beat) || now - beat > HEARTBEAT_STALE_MS) return false
339
+ if (lock.hostname === hostname()) return lock.pid !== null && pidAlive(lock.pid)
340
+ return true
341
+ }
342
+
343
+ /**
344
+ * The lock covers the whole database, not one run, so a held lock only proves
345
+ * that *some* run is alive. A run that a crash left reading "running" must not
346
+ * borrow that liveness: it counts only if it was created, or wrote an event,
347
+ * after the current holder took the lock.
348
+ */
349
+ function runAlive(r: Reader, convoy: Row, lock: LockRow | null, now: number): boolean {
350
+ if (!ACTIVE_STATUSES.has(String(convoy.status))) return false
351
+ if (!lock || !lockHeld(lock, now)) return false
352
+ const since = lock.started_at
353
+ if (!since) return true
354
+ if (String(convoy.created_at ?? '') >= since) return true
355
+ if (!r.hasTable('event')) return false
356
+ const last = r.get('SELECT MAX(created_at) AS t FROM event WHERE convoy_id = ?', String(convoy.id))
357
+ return typeof last?.t === 'string' && last.t >= since
358
+ }
359
+
360
+ // ── Runs ──────────────────────────────────────────────────────────────────────
361
+
362
+ const CONVOY_COLS = [
363
+ 'id', 'name', 'status', 'branch', 'pipeline_id', 'created_at', 'started_at', 'finished_at',
364
+ 'total_tokens', 'total_cost_usd', 'total_cost_usd_num', 'cost_estimated', 'adapter',
365
+ ] as const
366
+
367
+ const TASK_SUMMARY_COLS = ['convoy_id', 'status', 'total_tokens', 'cost_usd', 'cost_usd_num', 'cost_estimated'] as const
368
+
369
+ function summarize(r: Reader, convoy: Row, tasks: Row[], lock: LockRow | null, now: number): RunSummary {
370
+ const started = str(convoy.started_at)
371
+ const finished = str(convoy.finished_at)
372
+ const costed = tasks.filter((t) => costOf(t) !== null)
373
+ const taskEstimated = costed.some((t) => optFlag(t, 'cost_estimated'))
374
+ const storeSays = r.columns('task').has('cost_estimated') || r.columns('convoy').has('cost_estimated')
375
+ const runEstimated = optFlag(convoy, 'cost_estimated')
376
+ const status = String(convoy.status ?? 'unknown')
377
+ const alive = runAlive(r, convoy, lock, now)
378
+
379
+ return {
380
+ id: String(convoy.id),
381
+ name: String(convoy.name ?? convoy.id),
382
+ status,
383
+ branch: str(convoy.branch),
384
+ pipeline_id: str(convoy.pipeline_id),
385
+ created_at: String(convoy.created_at ?? ''),
386
+ started_at: started,
387
+ finished_at: finished,
388
+ duration_ms: span(started ?? str(convoy.created_at), finished),
389
+ tasks_total: tasks.length,
390
+ tasks_done: tasks.filter((t) => t.status === 'done').length,
391
+ tasks_failed: tasks.filter((t) => FAILED_TASK_STATUSES.includes(String(t.status))).length,
392
+ tasks_running: tasks.filter((t) => RUNNING_TASK_STATUSES.has(String(t.status))).length,
393
+ tokens: num(convoy.total_tokens) ?? sumOrNull(tasks.map((t) => num(t.total_tokens))),
394
+ cost_usd: num(convoy.total_cost_usd_num) ?? num(convoy.total_cost_usd) ?? sumOrNull(costed.map(costOf)),
395
+ cost_estimated: storeSays ? Boolean(runEstimated) || taskEstimated : undefined,
396
+ alive,
397
+ display_status: displayStatus(status, alive),
398
+ }
399
+ }
400
+
401
+ /** A task's status to show: `interrupted` for one recorded as running or assigned in a run nothing is working on. */
402
+ export function taskDisplayStatus(status: string, runAlive: boolean): string {
403
+ return RUNNING_TASK_STATUSES.has(status) && !runAlive ? 'interrupted' : status
404
+ }
405
+
406
+ /** The recorded status, or `interrupted` for a run that claims to be active with nothing running it. */
407
+ export function displayStatus(status: string, alive: boolean): string {
408
+ return ACTIVE_STATUSES.has(status) && !alive ? 'interrupted' : status
409
+ }
410
+
411
+ /** Summaries of the newest `limit` runs, or of every run when `limit` is null. */
412
+ function summaries(r: Reader, limit: number | null): RunSummary[] {
413
+ if (!r.hasTable('convoy')) return []
414
+ const convoys = r.all(
415
+ `SELECT ${r.select('convoy', CONVOY_COLS)} FROM convoy ORDER BY created_at DESC, rowid DESC LIMIT ?`,
416
+ limit === null ? -1 : Math.max(1, Math.floor(limit)),
417
+ )
418
+ if (convoys.length === 0) return []
419
+ const wanted = new Set(convoys.map((c) => String(c.id)))
420
+ // One pass over the task table rather than an IN list, which SQLite caps.
421
+ const tasks = r.hasTable('task') ? r.all(`SELECT ${r.select('task', TASK_SUMMARY_COLS)} FROM task`) : []
422
+ const byConvoy = new Map<string, Row[]>()
423
+ for (const t of tasks) {
424
+ const key = String(t.convoy_id)
425
+ if (!wanted.has(key)) continue
426
+ let list = byConvoy.get(key)
427
+ if (!list) byConvoy.set(key, (list = []))
428
+ list.push(t)
429
+ }
430
+ const lock = readLock(r)
431
+ const now = Date.now()
432
+ return convoys.map((c) => summarize(r, c, byConvoy.get(String(c.id)) ?? [], lock, now))
433
+ }
434
+
435
+ /** Runs, newest first. An empty list when the project has never run a convoy. */
436
+ export function readRuns(projectRoot: string, limit = 50): RunSummary[] {
437
+ return withDb(projectRoot, [] as RunSummary[], (r) => summaries(r, limit))
438
+ }
439
+
440
+ const TASK_COLS = [
441
+ 'id', 'convoy_id', 'phase', 'agent', 'status', 'depends_on', 'adapter', 'model', 'retries', 'worker_id',
442
+ 'started_at', 'finished_at', 'prompt_tokens', 'completion_tokens', 'total_tokens',
443
+ 'cache_read_tokens', 'cache_write_tokens', 'cost_usd', 'cost_usd_num', 'cost_estimated',
444
+ 'review_verdict', 'review_level',
445
+ ] as const
446
+
447
+ function failureReasons(r: Reader, convoyId: string): Map<string, string> {
448
+ const out = new Map<string, string>()
449
+ if (!r.hasTable('event')) return out
450
+ const rows = r.all(
451
+ "SELECT task_id, data FROM event WHERE convoy_id = ? AND type = 'task_failed' ORDER BY id",
452
+ convoyId,
453
+ )
454
+ for (const row of rows) {
455
+ const data = parseJson(row.data)
456
+ if (!row.task_id || typeof data !== 'object' || data === null) continue
457
+ const d = data as Record<string, unknown>
458
+ const reason = str(d.reason)
459
+ if (!reason) continue
460
+ // The message says what went wrong; the reason is the engine's code for the kind of failure.
461
+ const message = str(d.message)?.split('\n')[0].trim().slice(0, 300) || null
462
+ const detail = [message ? reason : null, str(d.gate) ?? str(d.hook), typeof d.exit_code === 'number' ? `exit ${d.exit_code}` : null].filter(Boolean)
463
+ const head = message ?? reason
464
+ out.set(String(row.task_id), detail.length ? `${head} (${detail.join(', ')})` : head)
465
+ }
466
+ return out
467
+ }
468
+
469
+ function errorTails(r: Reader, convoyId: string): Map<string, string> {
470
+ const out = new Map<string, string>()
471
+ // The DLQ copy first, so the task's own output wins where both exist.
472
+ if (r.columns('dlq').has('error_output')) {
473
+ for (const row of r.all('SELECT task_id, substr(error_output, -4000) AS t FROM dlq WHERE convoy_id = ? ORDER BY rowid', convoyId)) {
474
+ const text = tail(row.t)
475
+ if (text) out.set(String(row.task_id), text)
476
+ }
477
+ }
478
+ if (r.columns('task').has('output')) {
479
+ const rows = r.all(
480
+ `SELECT id, substr(output, -4000) AS t FROM task WHERE convoy_id = ? AND status IN (${placeholders(FAILED_TASK_STATUSES.length)})`,
481
+ convoyId,
482
+ ...FAILED_TASK_STATUSES,
483
+ )
484
+ for (const row of rows) {
485
+ const text = tail(row.t)
486
+ if (text) out.set(String(row.id), text)
487
+ }
488
+ }
489
+ return out
490
+ }
491
+
492
+ function workerAdapters(r: Reader, convoyId: string): Map<string, string> {
493
+ const out = new Map<string, string>()
494
+ if (!r.columns('worker').has('adapter') || !r.columns('task').has('worker_id')) return out
495
+ const rows = r.all('SELECT id, adapter FROM worker WHERE id IN (SELECT worker_id FROM task WHERE convoy_id = ?)', convoyId)
496
+ for (const row of rows) if (str(row.adapter)) out.set(String(row.id), String(row.adapter))
497
+ return out
498
+ }
499
+
500
+ function reviewVerdict(row: Row): ReviewVerdict | null | undefined {
501
+ if (!('review_verdict' in row)) return undefined
502
+ const v = str(row.review_verdict)
503
+ return v === 'pass' || v === 'block' || v === 'skipped' ? v : null
504
+ }
505
+
506
+ function toTask(t: Row, workers: Map<string, string>, reasons: Map<string, string>, tails: Map<string, string>, alive: boolean): TaskRow {
507
+ const id = String(t.id)
508
+ const status = String(t.status ?? 'unknown')
509
+ const failed = FAILED_TASK_STATUSES.includes(String(t.status))
510
+ const model = str(t.model)
511
+ const started = str(t.started_at)
512
+ const finished = str(t.finished_at)
513
+ return {
514
+ id,
515
+ phase: num(t.phase) ?? 0,
516
+ agent: String(t.agent ?? ''),
517
+ status,
518
+ display_status: taskDisplayStatus(status, alive),
519
+ depends_on: stringList(t.depends_on),
520
+ adapter: str(t.adapter) ?? (t.worker_id ? workers.get(String(t.worker_id)) ?? null : null),
521
+ model: model && !RUNTIME_NAMES.has(model) ? model : null,
522
+ retries: num(t.retries) ?? 0,
523
+ started_at: started,
524
+ finished_at: finished,
525
+ duration_ms: span(started, finished),
526
+ prompt_tokens: num(t.prompt_tokens),
527
+ completion_tokens: num(t.completion_tokens),
528
+ total_tokens: num(t.total_tokens),
529
+ cache_read_tokens: optNum(t, 'cache_read_tokens'),
530
+ cache_write_tokens: optNum(t, 'cache_write_tokens'),
531
+ cost_usd: costOf(t),
532
+ cost_estimated: optFlag(t, 'cost_estimated'),
533
+ review_verdict: reviewVerdict(t),
534
+ review_level: 'review_level' in t ? str(t.review_level) : undefined,
535
+ failure_reason: failed ? reasons.get(id) ?? null : null,
536
+ error_tail: failed ? tails.get(id) ?? null : null,
537
+ }
538
+ }
539
+
540
+ /** One run with its tasks, or null when there is no such run. */
541
+ export function readRun(projectRoot: string, convoyId: string): RunDetail | null {
542
+ return withDb(projectRoot, null as RunDetail | null, (r) => {
543
+ if (!r.hasTable('convoy')) return null
544
+ const convoy = r.get(`SELECT ${r.select('convoy', CONVOY_COLS)} FROM convoy WHERE id = ?`, convoyId)
545
+ if (!convoy) return null
546
+ const rows = r.hasTable('task')
547
+ ? r.all(`SELECT ${r.select('task', TASK_COLS)} FROM task WHERE convoy_id = ? ORDER BY phase, rowid`, convoyId)
548
+ : []
549
+ const workers = workerAdapters(r, convoyId)
550
+ const reasons = failureReasons(r, convoyId)
551
+ const tails = errorTails(r, convoyId)
552
+ const summary = summarize(r, convoy, rows, readLock(r), Date.now())
553
+ const tasks = rows.map((t) => toTask(t, workers, reasons, tails, summary.alive))
554
+
555
+ const adapters = new Set<string>()
556
+ if (str(convoy.adapter)) adapters.add(String(convoy.adapter))
557
+ for (const t of tasks) if (t.adapter) adapters.add(t.adapter)
558
+ for (const a of workers.values()) adapters.add(a)
559
+ const models = new Set(tasks.map((t) => t.model).filter((m): m is string => m !== null))
560
+
561
+ return { ...summary, adapters: [...adapters].sort(), models: [...models].sort(), tasks }
562
+ })
563
+ }
564
+
565
+ /**
566
+ * The spec a run was started from, and the runtime it recorded, for `resume`
567
+ * and its `--dry-run` preview. Read here so a preview never opens the store,
568
+ * which migrates.
569
+ */
570
+ export function readRunSpec(projectRoot: string, convoyId: string): { specYaml: string; adapter: string | null } | null {
571
+ return withDb(projectRoot, null as { specYaml: string; adapter: string | null } | null, (r) => {
572
+ if (!r.hasTable('convoy')) return null
573
+ const row = r.get(`SELECT ${r.select('convoy', ['spec_yaml', 'adapter'])} FROM convoy WHERE id = ?`, convoyId)
574
+ if (!row || typeof row.spec_yaml !== 'string') return null
575
+ return { specYaml: row.spec_yaml, adapter: str(row.adapter) }
576
+ })
577
+ }
578
+
579
+ // ── Events ────────────────────────────────────────────────────────────────────
580
+
581
+ /**
582
+ * The feed's grouping, from the event type's own prefix.
583
+ *
584
+ * Read from the name rather than kept as a list so a type the engine adds later
585
+ * lands in the right group without this file changing — the old dashboard kept
586
+ * a hand-written list, offered nine filters for types that did not exist, and
587
+ * hid the real ones under "All".
588
+ */
589
+ export function eventCategory(type: string): EventCategory {
590
+ if (type.startsWith('merge_') || type === 'task_merged') return 'merge'
591
+ if (/^(review_|dispute_)/.test(type)) return 'review'
592
+ if (/^(gate_|built_in_gate|tdd_|drift_|contract_|partition_|file_partition_|secret_|circuit_breaker_)/.test(type)) return 'check'
593
+ if (/^(task_|worker_|dlq_|file_injection_|artifact|agent_identity_)|^(session|delegation)$/.test(type)) return 'task'
594
+ if (/^(convoy_|post_convoy_|swarm_|watch_|ndjson_)/.test(type)) return 'run'
595
+ return 'other'
596
+ }
597
+
598
+ const PROBLEM_TYPE =
599
+ /_failed$|violation|conflict|killed|tripped|blocked|rejected|leak|limit_reached|^dlq_|^drift_detected$|^task_skipped$|^task_retried$|^review_skipped$|interrupted|fallback/
600
+
601
+ /**
602
+ * A failure or a warning: by type, a check whose data says it did not pass, or
603
+ * a review that blocked. A review that reached no verdict is `review_skipped`:
604
+ * the work went unreviewed, which is worth seeing, not a pass.
605
+ */
606
+ export function isProblemEvent(type: string, data: unknown): boolean {
607
+ if (PROBLEM_TYPE.test(type)) return true
608
+ if (typeof data !== 'object' || data === null) return false
609
+ const d = data as Record<string, unknown>
610
+ if (type === 'review_verdict') return d.verdict === 'block' || d.verdict === 'skipped'
611
+ return d.passed === false
612
+ }
613
+
614
+ /** Every type the engine can emit, grouped as the feed groups them. */
615
+ export function eventCategories(): Record<EventCategory, string[]> {
616
+ const out: Record<EventCategory, string[]> = { run: [], task: [], check: [], review: [], merge: [], other: [] }
617
+ for (const type of [...KNOWN_EVENT_TYPES].sort()) out[eventCategory(type)].push(type)
618
+ return out
619
+ }
620
+
621
+ /** Events of one run after `sinceId`, oldest first. */
622
+ export function readEventsSince(projectRoot: string, convoyId: string, sinceId: number, limit = 500): EventRow[] {
623
+ const cap = Math.min(2000, Math.max(1, Math.floor(limit)))
624
+ return withDb(projectRoot, [] as EventRow[], (r) => {
625
+ if (!r.hasTable('event')) return []
626
+ const rows = r.all(
627
+ `SELECT ${r.select('event', ['id', 'type', 'task_id', 'worker_id', 'data', 'created_at'])}
628
+ FROM event WHERE convoy_id = ? AND id > ? ORDER BY id LIMIT ?`,
629
+ convoyId,
630
+ Math.max(0, Math.floor(sinceId)),
631
+ cap,
632
+ )
633
+ return rows.map((e) => {
634
+ const type = String(e.type)
635
+ const data = parseJson(e.data)
636
+ return {
637
+ id: num(e.id) ?? 0,
638
+ type,
639
+ task_id: str(e.task_id),
640
+ worker_id: str(e.worker_id),
641
+ data,
642
+ created_at: String(e.created_at ?? ''),
643
+ category: eventCategory(type),
644
+ problem: isProblemEvent(type, data),
645
+ }
646
+ })
647
+ })
648
+ }
649
+
650
+ /**
651
+ * Whether a process is still working on this run.
652
+ *
653
+ * The run must be pending or running, and the engine lock must be held: a
654
+ * heartbeat within the last minute, and — on this host, where it can be
655
+ * checked — a pid that is alive. A dead pid means not alive, whatever the
656
+ * status column says.
657
+ */
658
+ export function isRunAlive(projectRoot: string, convoyId: string): boolean {
659
+ return withDb(projectRoot, false, (r) => {
660
+ if (!r.hasTable('convoy')) return false
661
+ const convoy = r.get('SELECT id, status, created_at FROM convoy WHERE id = ?', convoyId)
662
+ return convoy ? runAlive(r, convoy, readLock(r), Date.now()) : false
663
+ })
664
+ }
665
+
666
+ // ── Agent sessions (`opencastle log`) ─────────────────────────────────────────
667
+
668
+ /** Read at most this much of the end of the log; sessions are shown newest first. */
669
+ const SESSION_LOG_TAIL_BYTES = 2 * 1024 * 1024
670
+
671
+ function readTail(path: string, bytes: number): string {
672
+ const fd = openSync(path, 'r')
673
+ try {
674
+ const size = fstatSync(fd).size
675
+ const start = Math.max(0, size - bytes)
676
+ const buf = Buffer.alloc(size - start)
677
+ readSync(fd, buf, 0, buf.length, start)
678
+ const text = buf.toString('utf8')
679
+ // Starting mid-file means the first line is a fragment.
680
+ return start > 0 ? text.slice(text.indexOf('\n') + 1) : text
681
+ } finally {
682
+ closeSync(fd)
683
+ }
684
+ }
685
+
686
+ /** Session records from `.opencastle/logs/events.ndjson`, newest first. */
687
+ export function readSessions(projectRoot: string, limit = 50): SessionRow[] {
688
+ const path = join(projectRoot, '.opencastle', 'logs', 'events.ndjson')
689
+ if (!existsSync(path)) return []
690
+ const out: SessionRow[] = []
691
+ const lines = readTail(path, SESSION_LOG_TAIL_BYTES).split('\n')
692
+ for (let i = lines.length - 1; i >= 0 && out.length < limit; i--) {
693
+ const line = lines[i].trim()
694
+ if (!line) continue
695
+ let rec: unknown
696
+ try {
697
+ rec = JSON.parse(line)
698
+ } catch {
699
+ continue
700
+ }
701
+ if (typeof rec !== 'object' || rec === null) continue
702
+ const r = rec as Row
703
+ if (r.type !== 'session') continue
704
+ out.push({
705
+ source: 'log',
706
+ convoy_id: null,
707
+ timestamp: str(r.timestamp),
708
+ agent: str(r.agent),
709
+ task: str(r.task),
710
+ tracker_issue: str(r.tracker_issue),
711
+ outcome: str(r.outcome),
712
+ model: str(r.model),
713
+ duration_min: num(r.duration_min),
714
+ files_changed: num(r.files_changed),
715
+ retries: num(r.retries),
716
+ })
717
+ }
718
+ return out
719
+ }
720
+
721
+ /**
722
+ * Agent sessions from both places they are recorded, newest first: what
723
+ * `opencastle log` appended (`source: 'log'`) and the engine's `session` event
724
+ * for each task it finished (`source: 'convoy'`). Each keeps its source, so a
725
+ * page can say which is which.
726
+ */
727
+ export function readAllSessions(projectRoot: string, limit = 50): SessionRow[] {
728
+ const merged = [...readSessions(projectRoot, limit), ...readEngineSessions(projectRoot, null, limit)]
729
+ merged.sort((a, b) => String(b.timestamp ?? '').localeCompare(String(a.timestamp ?? '')))
730
+ return merged.slice(0, limit)
731
+ }
732
+
733
+ /** The engine's `session` events, newest first: of one run, or of every run when `convoyId` is null. */
734
+ export function readEngineSessions(projectRoot: string, convoyId: string | null, limit = 50): SessionRow[] {
735
+ return withDb(projectRoot, [] as SessionRow[], (r) => engineSessions(r, convoyId, limit))
736
+ }
737
+
738
+ function engineSessions(r: Reader, convoyId: string | null, limit: number): SessionRow[] {
739
+ if (!r.hasTable('event')) return []
740
+ const rows = r.all(
741
+ `SELECT ${r.select('event', ['convoy_id', 'task_id', 'data', 'created_at'])} FROM event
742
+ WHERE type = 'session'${convoyId === null ? '' : ' AND convoy_id = ?'} ORDER BY id DESC LIMIT ?`,
743
+ ...(convoyId === null ? [] : [convoyId]),
744
+ Math.max(1, Math.floor(limit)),
745
+ )
746
+ return rows.map((e) => {
747
+ const d = asRecord(parseJson(e.data))
748
+ return {
749
+ source: 'convoy' as const,
750
+ convoy_id: str(e.convoy_id) ?? str(d.convoy_id),
751
+ timestamp: str(e.created_at),
752
+ agent: str(d.agent),
753
+ task: str(d.task) ?? str(e.task_id),
754
+ tracker_issue: null,
755
+ outcome: str(d.outcome),
756
+ model: modelOrNull(d.model),
757
+ duration_min: num(d.duration_min),
758
+ files_changed: num(d.files_changed),
759
+ retries: num(d.retries),
760
+ }
761
+ })
762
+ }
763
+
764
+ // ── Aggregates for the dashboard ──────────────────────────────────────────────
765
+ //
766
+ // Every figure here is counted from rows the engine wrote: the run, task, dlq
767
+ // and artifact tables, and the events. Nothing is estimated or filled in. A
768
+ // figure the store does not hold reads as null (shown as "not reported"), never
769
+ // as 0: a project whose database predates the event table has no reviews on
770
+ // record, which is not the same as having had none.
771
+
772
+ export type Tally = Record<string, number>
773
+
774
+ export interface ReviewStats {
775
+ /** Reviews that reached a reviewer: `fast` and `panel` verdicts. */
776
+ ran: number
777
+ passed: number
778
+ blocked: number
779
+ /** A review was due and reached no verdict (`review_skipped`). The work went unreviewed. */
780
+ skipped: number
781
+ /** Passed without a reviewer reading it (`level: auto-pass`). Not a review. */
782
+ auto_pass: number
783
+ /** Tokens the reviews that ran spent, as recorded on their verdicts. */
784
+ tokens: number
785
+ by_level: Record<string, { pass: number; block: number }>
786
+ /** The reviewer model each verdict names; `not reported` where it names none. */
787
+ models: Tally
788
+ disputes: number
789
+ }
790
+
791
+ export interface CheckStats {
792
+ ran: number
793
+ passed: number
794
+ failed: number
795
+ /** The spec's own `gates` (`gate_result`) and the built-in gates (`built_in_gate_result`). */
796
+ gates: { passed: number; failed: number }
797
+ built_in: { passed: number; failed: number }
798
+ by_scope: { task: { passed: number; failed: number }; convoy: { passed: number; failed: number } }
799
+ /** Warnings that kept the work: `contract_violation`, `partition_violation`. */
800
+ warnings: number
801
+ /** `secret_leak_prevented` events: a secret found and masked or withheld. */
802
+ secrets_prevented: number
803
+ }
804
+
805
+ export interface ReviewRow {
806
+ event_id: number
807
+ task_id: string | null
808
+ level: string | null
809
+ verdict: string | null
810
+ tokens: number | null
811
+ model: string | null
812
+ /** Panel votes, when the verdict is a panel's. */
813
+ passes: number | null
814
+ blocks: number | null
815
+ feedback_length: number | null
816
+ /** The attempt of the task this review read: the `attempt` of its latest `task_started`. */
817
+ attempt: number | null
818
+ created_at: string
819
+ }
820
+
821
+ export interface SkippedReviewRow {
822
+ event_id: number
823
+ task_id: string | null
824
+ level: string | null
825
+ reason: string | null
826
+ attempt: number | null
827
+ created_at: string
828
+ }
829
+
830
+ export interface CheckRow {
831
+ event_id: number
832
+ /** `gate` for a command in the spec, `built-in` for one of OpenCastle's own gates. */
833
+ kind: 'gate' | 'built-in'
834
+ /** `task` ran in a task's worktree; `convoy` ran once on the merged result. */
835
+ scope: 'task' | 'convoy'
836
+ task_id: string | null
837
+ /** The command, or the built-in gate's name. */
838
+ name: string
839
+ passed: boolean | null
840
+ exit_code: number | null
841
+ level: string | null
842
+ /** The end of the output the event kept, when it kept any. */
843
+ output: string | null
844
+ /** Task scope: the attempt it checked, from the task's latest `task_started`. */
845
+ attempt: number | null
846
+ /**
847
+ * Convoy scope: which time this check ran on the merged result. Round 2 and
848
+ * later follow a gate-fix attempt, the run's `gate_retries`.
849
+ */
850
+ round: number | null
851
+ created_at: string
852
+ }
853
+
854
+ export interface DlqRow {
855
+ id: string
856
+ task_id: string | null
857
+ agent: string | null
858
+ failure_type: string | null
859
+ attempts: number | null
860
+ tokens_spent: number | null
861
+ resolved: boolean
862
+ resolution: string | null
863
+ created_at: string | null
864
+ resolved_at: string | null
865
+ error_tail: string | null
866
+ }
867
+
868
+ export interface ArtifactRow {
869
+ name: string
870
+ /** `file` is a path from the task's `files`; `summary` and `json` hold what the agent answered. */
871
+ type: string
872
+ task_id: string | null
873
+ created_at: string | null
874
+ size_bytes: number | null
875
+ }
876
+
877
+ export interface RunInsights {
878
+ /** Tasks by the tier their `delegation` event recorded (the latest one per task). */
879
+ tiers: Array<{ tier: string; tasks: number }>
880
+ /** Tasks with no `delegation` event: not finished yet, skipped, or from an engine that wrote none. */
881
+ tiers_not_recorded: number
882
+ task_tiers: Record<string, string>
883
+ /** Task attempts by the `mechanism` and `adapter` their `task_started` event recorded. */
884
+ mechanisms: Array<{ mechanism: string; attempts: number }>
885
+ runtimes: Array<{ runtime: string; attempts: number }>
886
+ /** `task_started` events per task: one per attempt, plus any restart after an interrupt. */
887
+ starts: Record<string, number>
888
+ reviews: ReviewRow[]
889
+ reviews_skipped: SkippedReviewRow[]
890
+ review_stats: ReviewStats
891
+ disputes: Array<{ event_id: number; task_id: string | null; dispute_id: string | null; reason: string | null; panel_attempts: number | null; created_at: string }>
892
+ checks: CheckRow[]
893
+ check_stats: CheckStats
894
+ warnings: Array<{ event_id: number; type: string; task_id: string | null; items: string[]; created_at: string }>
895
+ secrets_prevented: Array<{ event_id: number; task_id: string | null; context: string | null; patterns: string[]; created_at: string }>
896
+ /** Files each merged task changed, from `task_merged`. */
897
+ merges: Record<string, number>
898
+ retries: Array<{ event_id: number; task_id: string | null; attempt: number | null; previous_status: string | null; reason: string | null; created_at: string }>
899
+ interruptions: Array<{ event_id: number; type: string; task_id: string | null; signal: string | null; created_at: string }>
900
+ sessions: SessionRow[]
901
+ /** Null when the database has no dlq or artifact table. */
902
+ dlq: DlqRow[] | null
903
+ artifacts: ArtifactRow[] | null
904
+ /** False when the database has no event table: every event-derived figure is unknown, not zero. */
905
+ events_recorded: boolean
906
+ }
907
+
908
+ export interface OverviewTask {
909
+ convoy_id: string
910
+ id: string
911
+ agent: string
912
+ display_status: string
913
+ model: string | null
914
+ retries: number
915
+ }
916
+
917
+ /**
918
+ * One project's share of the overview, in a form several projects' shares can
919
+ * be combined from: lists and counts, never a ratio or a percentile. The live
920
+ * dashboard combines one project's; the website snapshot combines several.
921
+ */
922
+ export interface OverviewParts {
923
+ runs: RunSummary[]
924
+ tasks: OverviewTask[]
925
+ tiers: Tally
926
+ mechanisms: Tally
927
+ runtimes: Tally
928
+ reviews: ReviewStats | null
929
+ checks: CheckStats | null
930
+ dlq: { entries: number; unresolved: number } | null
931
+ artifacts: number | null
932
+ }
933
+
934
+ export interface Overview {
935
+ runs: { total: number; alive: number; by_status: Tally; ended: number; done: number; success_rate: number | null }
936
+ /** Over runs that have finished: finished minus started. */
937
+ duration: { measured: number; avg_ms: number | null; p95_ms: number | null; max_ms: number | null }
938
+ tokens: { total: number | null; runs_reported: number; runs_not_reported: number }
939
+ cost: { total_usd: number | null; estimated: boolean | undefined; runs_reported: number; runs_not_reported: number }
940
+ /** Runs per UTC day they were created on, oldest first. */
941
+ activity: Array<{ date: string; total: number; done: number; failed: number; interrupted: number; other: number }>
942
+ tasks: { total: number; retries: number; by_status: Tally }
943
+ agents: Array<{ agent: string; total: number; done: number; failed: number; running: number; other: number }>
944
+ models: Array<{ model: string; tasks: number }>
945
+ models_not_reported: number
946
+ tiers: Array<{ tier: string; tasks: number }>
947
+ tiers_not_recorded: number
948
+ mechanisms: Array<{ mechanism: string; attempts: number }>
949
+ runtimes: Array<{ runtime: string; attempts: number }>
950
+ reviews: ReviewStats | null
951
+ checks: CheckStats | null
952
+ dlq: { entries: number; unresolved: number } | null
953
+ artifacts: number | null
954
+ }
955
+
956
+ const INSIGHT_TYPES = [
957
+ 'task_started', 'delegation', 'review_verdict', 'review_skipped', 'dispute_opened',
958
+ 'gate_result', 'built_in_gate_result', 'contract_violation', 'partition_violation', 'secret_leak_prevented',
959
+ 'task_merged', 'task_retried', 'worker_killed', 'convoy_interrupted', 'convoy_resumed',
960
+ ] as const
961
+
962
+ interface EventLite {
963
+ id: number
964
+ convoy_id: string | null
965
+ task_id: string | null
966
+ type: string
967
+ data: Record<string, unknown>
968
+ created_at: string
969
+ }
970
+
971
+ function asRecord(v: unknown): Record<string, unknown> {
972
+ return typeof v === 'object' && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : {}
973
+ }
974
+
975
+ function modelOrNull(v: unknown): string | null {
976
+ const m = str(v)
977
+ return m && !RUNTIME_NAMES.has(m) ? m : null
978
+ }
979
+
980
+ function bump(t: Tally, key: string, by = 1): void {
981
+ t[key] = (t[key] ?? 0) + by
982
+ }
983
+
984
+ function addTally(into: Tally, from: Tally): void {
985
+ for (const [k, v] of Object.entries(from)) bump(into, k, v)
986
+ }
987
+
988
+ function sortedTally<K extends string>(t: Tally, key: K, count: string): Array<Record<K, string> & Record<string, number | string>> {
989
+ return Object.entries(t)
990
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
991
+ .map(([k, v]) => ({ [key]: k, [count]: v }) as Record<K, string> & Record<string, number | string>)
992
+ }
993
+
994
+ function flag(v: unknown): boolean | null {
995
+ if (v === true || v === 1 || v === 'true') return true
996
+ if (v === false || v === 0 || v === 'false') return false
997
+ return null
998
+ }
999
+
1000
+ function stringItems(v: unknown): string[] {
1001
+ return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []
1002
+ }
1003
+
1004
+ function insightEvents(r: Reader, convoyId: string | null): EventLite[] {
1005
+ if (!r.hasTable('event')) return []
1006
+ const rows = r.all(
1007
+ `SELECT ${r.select('event', ['id', 'convoy_id', 'task_id', 'type', 'data', 'created_at'])} FROM event
1008
+ WHERE type IN (${placeholders(INSIGHT_TYPES.length)})${convoyId === null ? '' : ' AND convoy_id = ?'} ORDER BY id`,
1009
+ ...INSIGHT_TYPES,
1010
+ ...(convoyId === null ? [] : [convoyId]),
1011
+ )
1012
+ return rows.map((e) => {
1013
+ const data = asRecord(parseJson(e.data))
1014
+ return {
1015
+ id: num(e.id) ?? 0,
1016
+ convoy_id: str(e.convoy_id),
1017
+ task_id: str(e.task_id) ?? str(data.task_id),
1018
+ type: String(e.type),
1019
+ data,
1020
+ created_at: String(e.created_at ?? ''),
1021
+ }
1022
+ })
1023
+ }
1024
+
1025
+ function emptyReviewStats(): ReviewStats {
1026
+ return { ran: 0, passed: 0, blocked: 0, skipped: 0, auto_pass: 0, tokens: 0, by_level: {}, models: {}, disputes: 0 }
1027
+ }
1028
+
1029
+ function emptyCheckStats(): CheckStats {
1030
+ return {
1031
+ ran: 0, passed: 0, failed: 0,
1032
+ gates: { passed: 0, failed: 0 }, built_in: { passed: 0, failed: 0 },
1033
+ by_scope: { task: { passed: 0, failed: 0 }, convoy: { passed: 0, failed: 0 } },
1034
+ warnings: 0, secrets_prevented: 0,
1035
+ }
1036
+ }
1037
+
1038
+ /**
1039
+ * Reviews, checks and the rest, read from one run's events (or every run's,
1040
+ * for the overview) in the order they were written. The attempt a review or a
1041
+ * gate belongs to is the `attempt` of the task's latest `task_started` before
1042
+ * it; a check on the merged result counts its rounds by how often that check
1043
+ * has run in the run so far.
1044
+ */
1045
+ function digest(events: EventLite[]) {
1046
+ const reviews: ReviewRow[] = []
1047
+ const skipped: SkippedReviewRow[] = []
1048
+ const disputes: RunInsights['disputes'] = []
1049
+ const checks: CheckRow[] = []
1050
+ const warnings: RunInsights['warnings'] = []
1051
+ const secrets: RunInsights['secrets_prevented'] = []
1052
+ const retries: RunInsights['retries'] = []
1053
+ const interruptions: RunInsights['interruptions'] = []
1054
+ const merges: Record<string, number> = {}
1055
+ const starts: Record<string, number> = {}
1056
+ const mechanisms: Tally = {}
1057
+ const runtimes: Tally = {}
1058
+ const taskTiers: Record<string, string> = {}
1059
+ const reviewStats = emptyReviewStats()
1060
+ const checkStats = emptyCheckStats()
1061
+
1062
+ const attempt = new Map<string, number>()
1063
+ const rounds = new Map<string, number>()
1064
+ const key = (e: EventLite): string => `${e.convoy_id ?? ''}\u0000${e.task_id ?? ''}`
1065
+ const taskKey = (e: EventLite): string => (e.task_id ?? '')
1066
+
1067
+ for (const e of events) {
1068
+ const d = e.data
1069
+ switch (e.type) {
1070
+ case 'task_started': {
1071
+ const n = num(d.attempt)
1072
+ if (n !== null) attempt.set(key(e), n)
1073
+ if (e.task_id) starts[e.task_id] = (starts[e.task_id] ?? 0) + 1
1074
+ bump(mechanisms, str(d.mechanism) ?? 'not recorded')
1075
+ bump(runtimes, str(d.adapter) ?? 'not recorded')
1076
+ break
1077
+ }
1078
+ case 'delegation': {
1079
+ const tier = str(d.tier)
1080
+ // The latest per task: a task that failed and was resumed reports twice.
1081
+ if (tier && e.task_id) taskTiers[`${e.convoy_id ?? ''}\u0000${e.task_id}`] = tier
1082
+ break
1083
+ }
1084
+ case 'review_verdict': {
1085
+ const level = str(d.level)
1086
+ const verdict = str(d.verdict)
1087
+ if (level === 'auto-pass') {
1088
+ reviewStats.auto_pass++
1089
+ } else {
1090
+ reviewStats.ran++
1091
+ if (verdict === 'pass') reviewStats.passed++
1092
+ if (verdict === 'block') reviewStats.blocked++
1093
+ if (verdict === 'skipped') reviewStats.skipped++
1094
+ const byLevel = (reviewStats.by_level[level ?? 'not recorded'] ??= { pass: 0, block: 0 })
1095
+ if (verdict === 'pass') byLevel.pass++
1096
+ if (verdict === 'block') byLevel.block++
1097
+ reviewStats.tokens += num(d.tokens) ?? 0
1098
+ bump(reviewStats.models, str(d.model) ?? 'not reported')
1099
+ }
1100
+ reviews.push({
1101
+ event_id: e.id, task_id: e.task_id, level, verdict,
1102
+ tokens: num(d.tokens), model: str(d.model), passes: num(d.passes), blocks: num(d.blocks),
1103
+ feedback_length: num(d.feedback_length), attempt: attempt.get(key(e)) ?? null, created_at: e.created_at,
1104
+ })
1105
+ break
1106
+ }
1107
+ case 'review_skipped':
1108
+ reviewStats.skipped++
1109
+ skipped.push({
1110
+ event_id: e.id, task_id: e.task_id, level: str(d.level), reason: str(d.reason),
1111
+ attempt: attempt.get(key(e)) ?? null, created_at: e.created_at,
1112
+ })
1113
+ break
1114
+ case 'dispute_opened':
1115
+ reviewStats.disputes++
1116
+ disputes.push({
1117
+ event_id: e.id, task_id: e.task_id, dispute_id: str(d.dispute_id), reason: str(d.reason),
1118
+ panel_attempts: num(d.panel_attempts), created_at: e.created_at,
1119
+ })
1120
+ break
1121
+ case 'gate_result':
1122
+ case 'built_in_gate_result': {
1123
+ const builtIn = e.type === 'built_in_gate_result'
1124
+ const name = (builtIn ? str(d.gate) : str(d.command)) ?? 'unnamed'
1125
+ const scope: 'task' | 'convoy' = builtIn
1126
+ ? (e.task_id ? 'task' : 'convoy')
1127
+ : str(d.scope) === 'convoy' || (!str(d.scope) && !e.task_id) ? 'convoy' : 'task'
1128
+ const passed = flag(d.passed)
1129
+ let round: number | null = null
1130
+ if (scope === 'convoy') {
1131
+ const roundKey = `${e.convoy_id ?? ''}\u0000${builtIn ? 'b' : 'g'}\u0000${name}`
1132
+ round = (rounds.get(roundKey) ?? 0) + 1
1133
+ rounds.set(roundKey, round)
1134
+ }
1135
+ checks.push({
1136
+ event_id: e.id, kind: builtIn ? 'built-in' : 'gate', scope, task_id: e.task_id, name, passed,
1137
+ exit_code: num(d.exit_code), level: str(d.level), output: tail(d.output),
1138
+ attempt: scope === 'task' ? attempt.get(key(e)) ?? null : null, round, created_at: e.created_at,
1139
+ })
1140
+ if (passed !== null) {
1141
+ checkStats.ran++
1142
+ const outcome = passed ? 'passed' : 'failed'
1143
+ checkStats[outcome]++
1144
+ checkStats[builtIn ? 'built_in' : 'gates'][outcome]++
1145
+ checkStats.by_scope[scope][outcome]++
1146
+ }
1147
+ break
1148
+ }
1149
+ case 'contract_violation':
1150
+ case 'partition_violation':
1151
+ checkStats.warnings++
1152
+ warnings.push({
1153
+ event_id: e.id, type: e.type, task_id: e.task_id,
1154
+ // `__contract_block` is the engine's name for an answer with no output
1155
+ // summary block at all; say that, not the key.
1156
+ items: e.type === 'partition_violation'
1157
+ ? stringItems(d.violations)
1158
+ : [...stringItems(d.missing), ...stringItems(d.warnings)].map((m) => (m === '__contract_block' ? 'no output summary block in the answer' : m)),
1159
+ created_at: e.created_at,
1160
+ })
1161
+ break
1162
+ case 'secret_leak_prevented':
1163
+ checkStats.secrets_prevented++
1164
+ secrets.push({ event_id: e.id, task_id: e.task_id, context: str(d.context), patterns: stringItems(d.patterns), created_at: e.created_at })
1165
+ break
1166
+ case 'task_merged':
1167
+ if (e.task_id) merges[taskKey(e)] = num(d.files) ?? 0
1168
+ break
1169
+ case 'task_retried':
1170
+ retries.push({
1171
+ event_id: e.id, task_id: e.task_id, attempt: num(d.attempt), previous_status: str(d.previous_status),
1172
+ reason: str(d.reason), created_at: e.created_at,
1173
+ })
1174
+ break
1175
+ case 'worker_killed':
1176
+ case 'convoy_interrupted':
1177
+ case 'convoy_resumed':
1178
+ interruptions.push({ event_id: e.id, type: e.type, task_id: e.task_id, signal: str(d.signal) ?? str(d.reason), created_at: e.created_at })
1179
+ break
1180
+ }
1181
+ }
1182
+ return {
1183
+ reviews, skipped, disputes, checks, warnings, secrets, retries, interruptions, merges, starts,
1184
+ mechanisms, runtimes, taskTiers, reviewStats, checkStats,
1185
+ }
1186
+ }
1187
+
1188
+ function tierTally(taskTiers: Record<string, string>): Tally {
1189
+ const out: Tally = {}
1190
+ for (const tier of Object.values(taskTiers)) bump(out, tier)
1191
+ return out
1192
+ }
1193
+
1194
+ function dlqRows(r: Reader, convoyId: string | null): DlqRow[] | null {
1195
+ if (!r.hasTable('dlq')) return null
1196
+ const rows = r.all(
1197
+ `SELECT ${r.select('dlq', ['id', 'task_id', 'agent', 'failure_type', 'attempts', 'tokens_spent', 'resolved', 'resolution', 'created_at', 'resolved_at'])}
1198
+ ${r.columns('dlq').has('error_output') ? ', substr(error_output, -4000) AS tail_text' : ''}
1199
+ FROM dlq${convoyId === null ? '' : ' WHERE convoy_id = ?'} ORDER BY rowid`,
1200
+ ...(convoyId === null ? [] : [convoyId]),
1201
+ )
1202
+ return rows.map((d) => ({
1203
+ id: String(d.id ?? ''),
1204
+ task_id: str(d.task_id),
1205
+ agent: str(d.agent),
1206
+ failure_type: str(d.failure_type),
1207
+ attempts: num(d.attempts),
1208
+ tokens_spent: num(d.tokens_spent),
1209
+ resolved: flag(d.resolved) === true,
1210
+ resolution: str(d.resolution),
1211
+ created_at: str(d.created_at),
1212
+ resolved_at: str(d.resolved_at),
1213
+ error_tail: tail(d.tail_text),
1214
+ }))
1215
+ }
1216
+
1217
+ function artifactRows(r: Reader, convoyId: string): ArtifactRow[] | null {
1218
+ if (!r.hasTable('artifact')) return null
1219
+ const size = r.columns('artifact').has('content') ? ', length(content) AS size_bytes' : ''
1220
+ return r.all(
1221
+ `SELECT ${r.select('artifact', ['name', 'type', 'task_id', 'created_at'])}${size} FROM artifact WHERE convoy_id = ? ORDER BY created_at, rowid`,
1222
+ convoyId,
1223
+ ).map((a) => ({
1224
+ name: String(a.name ?? ''),
1225
+ type: String(a.type ?? 'unknown'),
1226
+ task_id: str(a.task_id),
1227
+ created_at: str(a.created_at),
1228
+ size_bytes: num(a.size_bytes),
1229
+ }))
1230
+ }
1231
+
1232
+ /**
1233
+ * What the run's events and side tables say beyond its tasks: tiers,
1234
+ * mechanisms, every review and check with the attempt it belonged to, retries,
1235
+ * interrupts, the dead-letter queue, artifacts and the engine's sessions.
1236
+ * Null when there is no such run.
1237
+ */
1238
+ export function readRunInsights(projectRoot: string, convoyId: string): RunInsights | null {
1239
+ return withDb(projectRoot, null as RunInsights | null, (r) => {
1240
+ if (!r.hasTable('convoy') || !r.get('SELECT id FROM convoy WHERE id = ?', convoyId)) return null
1241
+ const events = r.hasTable('event')
1242
+ const g = digest(insightEvents(r, convoyId))
1243
+ const taskIds = r.hasTable('task')
1244
+ ? r.all('SELECT id FROM task WHERE convoy_id = ?', convoyId).map((t) => String(t.id))
1245
+ : []
1246
+ const tiers: Record<string, string> = {}
1247
+ for (const [k, tier] of Object.entries(g.taskTiers)) tiers[k.split('\u0000')[1]] = tier
1248
+ return {
1249
+ tiers: sortedTally(tierTally(g.taskTiers), 'tier', 'tasks') as RunInsights['tiers'],
1250
+ tiers_not_recorded: taskIds.filter((id) => !(id in tiers)).length,
1251
+ task_tiers: tiers,
1252
+ mechanisms: sortedTally(g.mechanisms, 'mechanism', 'attempts') as RunInsights['mechanisms'],
1253
+ runtimes: sortedTally(g.runtimes, 'runtime', 'attempts') as RunInsights['runtimes'],
1254
+ starts: g.starts,
1255
+ reviews: g.reviews,
1256
+ reviews_skipped: g.skipped,
1257
+ review_stats: g.reviewStats,
1258
+ disputes: g.disputes,
1259
+ checks: g.checks,
1260
+ check_stats: g.checkStats,
1261
+ warnings: g.warnings,
1262
+ secrets_prevented: g.secrets,
1263
+ merges: g.merges,
1264
+ retries: g.retries,
1265
+ interruptions: g.interruptions,
1266
+ sessions: engineSessions(r, convoyId, 500),
1267
+ dlq: dlqRows(r, convoyId),
1268
+ artifacts: artifactRows(r, convoyId),
1269
+ events_recorded: events,
1270
+ }
1271
+ })
1272
+ }
1273
+
1274
+ /** One project's share of the overview. See `OverviewParts`. */
1275
+ export function readOverviewParts(projectRoot: string): OverviewParts {
1276
+ const empty: OverviewParts = {
1277
+ runs: [], tasks: [], tiers: {}, mechanisms: {}, runtimes: {}, reviews: null, checks: null, dlq: null, artifacts: null,
1278
+ }
1279
+ return withDb(projectRoot, empty, (r) => {
1280
+ const runs = summaries(r, null)
1281
+ const alive = new Map(runs.map((run) => [run.id, run.alive]))
1282
+ const tasks: OverviewTask[] = r.hasTable('task')
1283
+ ? r.all(`SELECT ${r.select('task', ['id', 'convoy_id', 'agent', 'status', 'model', 'retries'])} FROM task`).map((t) => ({
1284
+ convoy_id: String(t.convoy_id ?? ''),
1285
+ id: String(t.id ?? ''),
1286
+ agent: str(t.agent) ?? 'not recorded',
1287
+ display_status: taskDisplayStatus(String(t.status ?? 'unknown'), alive.get(String(t.convoy_id)) ?? false),
1288
+ model: modelOrNull(t.model),
1289
+ retries: num(t.retries) ?? 0,
1290
+ }))
1291
+ : []
1292
+ const events = r.hasTable('event')
1293
+ const g = digest(insightEvents(r, null))
1294
+ const dlq = dlqRows(r, null)
1295
+ let artifacts: number | null = null
1296
+ if (r.hasTable('artifact')) artifacts = num(r.get('SELECT COUNT(*) AS n FROM artifact')?.n) ?? 0
1297
+ return {
1298
+ runs,
1299
+ tasks,
1300
+ tiers: tierTally(g.taskTiers),
1301
+ mechanisms: g.mechanisms,
1302
+ runtimes: g.runtimes,
1303
+ reviews: events ? g.reviewStats : null,
1304
+ checks: events ? g.checkStats : null,
1305
+ dlq: dlq === null ? null : { entries: dlq.length, unresolved: dlq.filter((d) => !d.resolved).length },
1306
+ artifacts,
1307
+ }
1308
+ })
1309
+ }
1310
+
1311
+ const ENDED = new Set(['done', 'failed', 'gate-failed', 'hook-failed', 'interrupted'])
1312
+ const FAILED_RUN = new Set(['failed', 'gate-failed', 'hook-failed'])
1313
+
1314
+ function mergeReviews(a: ReviewStats | null, b: ReviewStats | null): ReviewStats | null {
1315
+ if (!a) return b && { ...b, by_level: structuredClone(b.by_level), models: { ...b.models } }
1316
+ if (!b) return a
1317
+ const out: ReviewStats = { ...a, by_level: structuredClone(a.by_level), models: { ...a.models } }
1318
+ for (const k of ['ran', 'passed', 'blocked', 'skipped', 'auto_pass', 'tokens', 'disputes'] as const) out[k] += b[k]
1319
+ for (const [level, v] of Object.entries(b.by_level)) {
1320
+ const into = (out.by_level[level] ??= { pass: 0, block: 0 })
1321
+ into.pass += v.pass
1322
+ into.block += v.block
1323
+ }
1324
+ addTally(out.models, b.models)
1325
+ return out
1326
+ }
1327
+
1328
+ function mergeChecks(a: CheckStats | null, b: CheckStats | null): CheckStats | null {
1329
+ if (!a) return b && structuredClone(b)
1330
+ if (!b) return a
1331
+ const out = structuredClone(a)
1332
+ out.ran += b.ran
1333
+ out.passed += b.passed
1334
+ out.failed += b.failed
1335
+ out.warnings += b.warnings
1336
+ out.secrets_prevented += b.secrets_prevented
1337
+ for (const group of ['gates', 'built_in'] as const) {
1338
+ out[group].passed += b[group].passed
1339
+ out[group].failed += b[group].failed
1340
+ }
1341
+ for (const scope of ['task', 'convoy'] as const) {
1342
+ out.by_scope[scope].passed += b.by_scope[scope].passed
1343
+ out.by_scope[scope].failed += b.by_scope[scope].failed
1344
+ }
1345
+ return out
1346
+ }
1347
+
1348
+ /** The nearest-rank percentile of an ascending list. */
1349
+ function percentile(sorted: number[], p: number): number | null {
1350
+ if (sorted.length === 0) return null
1351
+ return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(p * sorted.length) - 1))]
1352
+ }
1353
+
1354
+ /** The overview of one or more projects' shares. */
1355
+ export function overviewFrom(parts: OverviewParts[]): Overview {
1356
+ const runs = parts.flatMap((p) => p.runs)
1357
+ const tasks = parts.flatMap((p) => p.tasks)
1358
+
1359
+ const byStatus: Tally = {}
1360
+ for (const run of runs) bump(byStatus, run.display_status)
1361
+ const ended = runs.filter((run) => ENDED.has(run.display_status))
1362
+ const done = ended.filter((run) => run.display_status === 'done').length
1363
+
1364
+ const durations = runs
1365
+ .filter((run) => run.finished_at !== null && run.duration_ms !== null)
1366
+ .map((run) => run.duration_ms as number)
1367
+ .sort((a, b) => a - b)
1368
+
1369
+ const tokenRuns = runs.filter((run) => run.tokens !== null)
1370
+ const costRuns = runs.filter((run) => run.cost_usd !== null)
1371
+ const flagKnown = costRuns.some((run) => run.cost_estimated !== undefined)
1372
+
1373
+ const days = new Map<string, Overview['activity'][number]>()
1374
+ for (const run of runs) {
1375
+ const date = run.created_at.slice(0, 10)
1376
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) continue
1377
+ let day = days.get(date)
1378
+ if (!day) days.set(date, (day = { date, total: 0, done: 0, failed: 0, interrupted: 0, other: 0 }))
1379
+ day.total++
1380
+ if (run.display_status === 'done') day.done++
1381
+ else if (FAILED_RUN.has(run.display_status)) day.failed++
1382
+ else if (run.display_status === 'interrupted') day.interrupted++
1383
+ else day.other++
1384
+ }
1385
+
1386
+ const taskStatus: Tally = {}
1387
+ const agents = new Map<string, Overview['agents'][number]>()
1388
+ const models: Tally = {}
1389
+ let modelsNotReported = 0
1390
+ for (const t of tasks) {
1391
+ bump(taskStatus, t.display_status)
1392
+ let a = agents.get(t.agent)
1393
+ if (!a) agents.set(t.agent, (a = { agent: t.agent, total: 0, done: 0, failed: 0, running: 0, other: 0 }))
1394
+ a.total++
1395
+ if (t.display_status === 'done') a.done++
1396
+ else if (FAILED_TASK_STATUSES.includes(t.display_status)) a.failed++
1397
+ else if (RUNNING_TASK_STATUSES.has(t.display_status)) a.running++
1398
+ else a.other++
1399
+ if (t.model) bump(models, t.model)
1400
+ else modelsNotReported++
1401
+ }
1402
+
1403
+ const tiers: Tally = {}
1404
+ const mechanisms: Tally = {}
1405
+ const runtimes: Tally = {}
1406
+ for (const p of parts) {
1407
+ addTally(tiers, p.tiers)
1408
+ addTally(mechanisms, p.mechanisms)
1409
+ addTally(runtimes, p.runtimes)
1410
+ }
1411
+ const tiered = Object.values(tiers).reduce((s, n) => s + n, 0)
1412
+
1413
+ let dlq = null as Overview['dlq']
1414
+ let artifacts = null as number | null
1415
+ let reviews = null as ReviewStats | null
1416
+ let checks = null as CheckStats | null
1417
+ for (const p of parts) {
1418
+ if (p.dlq) dlq = { entries: (dlq?.entries ?? 0) + p.dlq.entries, unresolved: (dlq?.unresolved ?? 0) + p.dlq.unresolved }
1419
+ if (p.artifacts !== null) artifacts = (artifacts ?? 0) + p.artifacts
1420
+ reviews = mergeReviews(reviews, p.reviews)
1421
+ checks = mergeChecks(checks, p.checks)
1422
+ }
1423
+
1424
+ return {
1425
+ runs: {
1426
+ total: runs.length,
1427
+ alive: runs.filter((run) => run.alive).length,
1428
+ by_status: byStatus,
1429
+ ended: ended.length,
1430
+ done,
1431
+ success_rate: ended.length > 0 ? done / ended.length : null,
1432
+ },
1433
+ duration: {
1434
+ measured: durations.length,
1435
+ avg_ms: durations.length > 0 ? durations.reduce((s, n) => s + n, 0) / durations.length : null,
1436
+ p95_ms: percentile(durations, 0.95),
1437
+ max_ms: durations.length > 0 ? durations[durations.length - 1] : null,
1438
+ },
1439
+ tokens: {
1440
+ total: tokenRuns.length > 0 ? tokenRuns.reduce((s, run) => s + (run.tokens as number), 0) : null,
1441
+ runs_reported: tokenRuns.length,
1442
+ runs_not_reported: runs.length - tokenRuns.length,
1443
+ },
1444
+ cost: {
1445
+ total_usd: costRuns.length > 0 ? costRuns.reduce((s, run) => s + (run.cost_usd as number), 0) : null,
1446
+ estimated: flagKnown ? costRuns.some((run) => run.cost_estimated === true) : undefined,
1447
+ runs_reported: costRuns.length,
1448
+ runs_not_reported: runs.length - costRuns.length,
1449
+ },
1450
+ activity: [...days.values()].sort((a, b) => a.date.localeCompare(b.date)),
1451
+ tasks: { total: tasks.length, retries: tasks.reduce((s, t) => s + t.retries, 0), by_status: taskStatus },
1452
+ agents: [...agents.values()].sort((a, b) => b.total - a.total || a.agent.localeCompare(b.agent)),
1453
+ models: sortedTally(models, 'model', 'tasks') as Overview['models'],
1454
+ models_not_reported: modelsNotReported,
1455
+ tiers: sortedTally(tiers, 'tier', 'tasks') as Overview['tiers'],
1456
+ tiers_not_recorded: Math.max(0, tasks.length - tiered),
1457
+ mechanisms: sortedTally(mechanisms, 'mechanism', 'attempts') as Overview['mechanisms'],
1458
+ runtimes: sortedTally(runtimes, 'runtime', 'attempts') as Overview['runtimes'],
1459
+ reviews,
1460
+ checks,
1461
+ dlq,
1462
+ artifacts,
1463
+ }
1464
+ }
1465
+
1466
+ /** The overview of one project. */
1467
+ export function readOverview(projectRoot: string): Overview {
1468
+ return overviewFrom([readOverviewParts(projectRoot)])
1469
+ }