opencastle 1.3.1 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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,1687 @@
1
+ /*
2
+ * OpenCastle Observability dashboard — the page's script.
3
+ *
4
+ * Reads the JSON API of `opencastle convoy dashboard` (live mode), or the same
5
+ * responses saved under data/ by tools/dashboard-demo/export.mjs (static mode).
6
+ * Every figure on the page is one the API returned: counts and sums of rows the
7
+ * engine wrote. Nothing is estimated here. A value the API did not return is
8
+ * shown as "not reported", never as 0.
9
+ */
10
+ 'use strict'
11
+
12
+ ;(() => {
13
+ const modeMeta = document.querySelector('meta[name="opencastle-dashboard"]')
14
+ const LIVE = !modeMeta || modeMeta.getAttribute('content') !== 'static'
15
+ const FAST_MS = 2000
16
+ const SLOW_MS = 10000
17
+ const EVENT_PAGE = 200
18
+ const LIST_PAGE = 10
19
+ const EXEC_PAGE = 10
20
+
21
+ const FAILED = ['failed', 'gate-failed', 'timed-out', 'review-blocked', 'hook-failed', 'disputed']
22
+ const RUNNING = ['running', 'assigned']
23
+ const CATEGORY_LABELS = { run: 'Run', task: 'Tasks', check: 'Checks', review: 'Reviews', merge: 'Merge', other: 'Other' }
24
+ const TIER_ORDER = ['premium', 'standard', 'utility', 'economy']
25
+
26
+ const TASK_STATUS_TIPS = {
27
+ done: 'Finished, and its work merged.',
28
+ running: 'An agent is working on it now.',
29
+ assigned: 'Given to a worker; starting.',
30
+ pending: 'Waiting for what it depends on, or for a free slot.',
31
+ failed: 'Stopped by an error, out of retries.',
32
+ 'gate-failed': "One of the task's gates failed, out of retries.",
33
+ 'timed-out': 'Ran past its time limit.',
34
+ 'review-blocked': 'A reviewer blocked the change, out of retries.',
35
+ skipped: 'Never ran: something it depends on did not finish.',
36
+ 'hook-failed': 'A lifecycle script failed.',
37
+ disputed: 'A review panel blocked it three times; see DISPUTES.md.',
38
+ 'wait-for-input': 'Paused until you answer.',
39
+ interrupted: 'Recorded as running, but no process is working on it.',
40
+ }
41
+
42
+ const RUN_EXPLANATIONS = {
43
+ running: 'A process is working on this run now.',
44
+ pending: 'Started, waiting for its first task.',
45
+ done: 'Every task finished and every check passed.',
46
+ failed: 'At least one task did not finish.',
47
+ 'gate-failed': 'A check on the merged result failed.',
48
+ 'hook-failed': 'A lifecycle script failed.',
49
+ interrupted: 'Stopped before it finished: Ctrl+C, a kill, or a crash. `opencastle convoy resume` continues it.',
50
+ }
51
+
52
+ const ICONS = {
53
+ timeline: '<svg width="32" height="32" viewBox="0 0 40 40" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="6" y="8" width="28" height="26" rx="3"/><line x1="6" y1="16" x2="34" y2="16"/><line x1="14" y1="8" x2="14" y2="12"/><line x1="26" y1="8" x2="26" y2="12"/></svg>',
54
+ agents: '<svg width="32" height="32" viewBox="0 0 40 40" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="20" cy="14" r="6"/><path d="M8 34c0-6.6 5.4-12 12-12s12 5.4 12 12"/></svg>',
55
+ tiers: '<svg width="32" height="32" viewBox="0 0 40 40" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><ellipse cx="20" cy="10" rx="14" ry="5"/><path d="M6 10v8c0 2.8 6.3 5 14 5s14-2.2 14-5v-8"/><path d="M6 18v8c0 2.8 6.3 5 14 5s14-2.2 14-5v-8" opacity="0.5"/></svg>',
56
+ mechanism: '<svg width="32" height="32" viewBox="0 0 40 40" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="20" cy="20" r="6"/><path d="M20 6v6M20 28v6M6 20h6M28 20h6"/></svg>',
57
+ models: '<svg width="32" height="32" viewBox="0 0 40 40" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="8" y="8" width="24" height="24" rx="4"/><circle cx="20" cy="20" r="4"/></svg>',
58
+ log: '<svg width="32" height="32" viewBox="0 0 40 40" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M14 8h18a2 2 0 0 1 2 2v20a2 2 0 0 1-2 2H14"/><circle cx="10" cy="14" r="3"/><circle cx="10" cy="24" r="3" opacity="0.4"/></svg>',
59
+ review: '<svg width="32" height="32" viewBox="0 0 40 40" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6l2 4h4l-3 3 1 5-4-2.5L16 18l1-5-3-3h4l2-4z"/><rect x="8" y="22" width="24" height="12" rx="3" opacity="0.4"/></svg>',
60
+ table: '<svg width="32" height="32" viewBox="0 0 40 40" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="6" y="6" width="28" height="28" rx="3"/><line x1="6" y1="14" x2="34" y2="14"/><line x1="14" y1="6" x2="14" y2="34" opacity="0.3"/></svg>',
61
+ deps: '<svg width="32" height="32" viewBox="0 0 40 40" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="8" width="10" height="8" rx="2"/><rect x="26" y="24" width="10" height="8" rx="2"/><path d="M14 12c8 0 4 16 12 16"/></svg>',
62
+ }
63
+
64
+ const state = {
65
+ project: '',
66
+ generatedAt: null,
67
+ runs: [],
68
+ categories: {},
69
+ overview: null,
70
+ projects: 1,
71
+ sessions: [],
72
+ sessionsError: null,
73
+ listError: null,
74
+ view: 'home',
75
+ selected: null,
76
+ /** Show the run that is working now, and the next one when it starts. Off once the reader picks something. */
77
+ follow: true,
78
+ gen: 0,
79
+ fastTimer: null,
80
+ settling: false,
81
+ run: null,
82
+ insights: null,
83
+ events: [],
84
+ cursor: 0,
85
+ more: false,
86
+ eventsLoading: false,
87
+ detailError: null,
88
+ ui: {
89
+ listPage: 1,
90
+ chainOpen: new Set(),
91
+ sortCol: 'started',
92
+ sortAsc: true,
93
+ execLimit: EXEC_PAGE,
94
+ filter: 'all',
95
+ eventOpen: new Set(),
96
+ open: new Set(),
97
+ },
98
+ }
99
+
100
+ // ── helpers ────────────────────────────────────────────────────────────────
101
+
102
+ const $ = (id) => document.getElementById(id)
103
+ const esc = (v) => String(v ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c])
104
+ const pad = (n) => String(n).padStart(2, '0')
105
+ const fileId = (id) => String(id).replace(/[^\w.-]/g, '_')
106
+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
107
+ const sum = (list, pick) => list.reduce((s, x) => s + (pick(x) || 0), 0)
108
+ const plural = (n, one, many) => `${n} ${n === 1 ? one : many || one + 's'}`
109
+
110
+ function nr(label) {
111
+ return `<span class="nr">${esc(label || 'not reported')}</span>`
112
+ }
113
+
114
+ function parseTime(iso) {
115
+ const t = Date.parse(iso)
116
+ return Number.isFinite(t) ? new Date(t) : null
117
+ }
118
+
119
+ function fmtClock(iso) {
120
+ const d = parseTime(iso)
121
+ return d ? `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}` : '—'
122
+ }
123
+
124
+ function fmtDay(d) {
125
+ const year = d.getFullYear() !== new Date().getFullYear() ? `, ${d.getFullYear()}` : ''
126
+ return `${MONTHS[d.getMonth()]} ${d.getDate()}${year}`
127
+ }
128
+
129
+ function fmtWhen(iso) {
130
+ const d = parseTime(iso)
131
+ return d ? `${fmtDay(d)} ${pad(d.getHours())}:${pad(d.getMinutes())}` : '—'
132
+ }
133
+
134
+ function fmtWhenSec(iso) {
135
+ const d = parseTime(iso)
136
+ return d ? `${fmtDay(d)} ${fmtClock(iso)}` : '—'
137
+ }
138
+
139
+ function timeTag(iso, text) {
140
+ return iso ? `<time datetime="${esc(iso)}" title="${esc(iso)}">${esc(text)}</time>` : '—'
141
+ }
142
+
143
+ function fmtDuration(ms) {
144
+ if (ms == null || !Number.isFinite(ms) || ms < 0) return null
145
+ const s = Math.floor(ms / 1000)
146
+ if (s < 1) return '<1s'
147
+ if (s < 60) return `${s}s`
148
+ const m = Math.floor(s / 60)
149
+ if (m < 60) return `${m}m ${pad(s % 60)}s`
150
+ return `${Math.floor(m / 60)}h ${pad(m % 60)}m`
151
+ }
152
+
153
+ function since(iso) {
154
+ const d = parseTime(iso)
155
+ return d ? Date.now() - d.getTime() : null
156
+ }
157
+
158
+ function fmtTokens(n) {
159
+ if (n == null) return null
160
+ if (n < 1000) return String(n)
161
+ if (n < 1e6) return `${(n / 1e3).toFixed(1)}K`
162
+ return `${(n / 1e6).toFixed(2)}M`
163
+ }
164
+
165
+ function fmtCost(n, estimated) {
166
+ if (n == null) return null
167
+ const text = n > 0 && n < 0.01 ? `$${n.toFixed(4)}` : `$${n.toFixed(2)}`
168
+ return estimated ? `${text}<span class="est" title="Part of this is an estimate: the runtime did not report it">est.</span>` : text
169
+ }
170
+
171
+ function fmtPct(x) {
172
+ return x == null ? null : `${Math.round(x * 1000) / 10}%`
173
+ }
174
+
175
+ function tone(status) {
176
+ if (status === 'done' || status === 'pass' || status === 'success' || status === 'passed') return 'tone-done'
177
+ if (FAILED.includes(status) || status === 'block' || status === 'failed') return 'tone-failed'
178
+ if (RUNNING.includes(status)) return 'tone-running'
179
+ if (['interrupted', 'wait-for-input', 'skipped', 'partial', 'no verdict'].includes(status)) return 'tone-warn'
180
+ if (status === 'auto-pass') return 'tone-review'
181
+ return 'tone-muted'
182
+ }
183
+
184
+ function badge(status, title) {
185
+ const tip = title ?? TASK_STATUS_TIPS[status] ?? ''
186
+ return `<span class="status-badge ${tone(status)}"${tip ? ` title="${esc(tip)}"` : ''}>${esc(status)}</span>`
187
+ }
188
+
189
+ function fillOf(status) {
190
+ if (status === 'done') return 'fill-done'
191
+ if (FAILED.includes(status)) return 'fill-failed'
192
+ if (RUNNING.includes(status)) return 'fill-running'
193
+ if (status === 'interrupted') return 'fill-interrupted'
194
+ return 'fill-other'
195
+ }
196
+
197
+ function info(text) {
198
+ return `<span class="tooltip-trigger" tabindex="0" role="note" aria-label="${esc(text)}" data-tooltip="${esc(text)}"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg></span>`
199
+ }
200
+
201
+ function empty(icon, title, desc) {
202
+ return `<div class="empty-state"><div class="empty-state__icon-wrap">${ICONS[icon] || ICONS.table}</div><p class="empty-state__title">${esc(title)}</p>${desc ? `<p class="empty-state__desc">${desc}</p>` : ''}</div>`
203
+ }
204
+
205
+ function card(label, value, opts = {}) {
206
+ const shown = value == null ? nr(opts.missing) : value
207
+ return `<div class="task-summary-card task-summary-card--${opts.mod || 'waiting'}">
208
+ <span class="task-summary-card__label">${esc(label)}${opts.tip ? ` ${info(opts.tip)}` : ''}</span>
209
+ <span class="task-summary-card__value">${shown}</span>
210
+ ${opts.sub ? `<span class="task-summary-card__sub">${opts.sub}</span>` : ''}
211
+ </div>`
212
+ }
213
+
214
+ function toggle(key, label) {
215
+ const open = state.ui.open.has(key)
216
+ return `<button type="button" class="toggle-btn" data-toggle="${esc(key)}" aria-expanded="${open}">${esc(label)}</button>`
217
+ }
218
+
219
+ function eventsMissing() {
220
+ return empty('timeline', 'Not recorded', 'This database has no event table, so nothing derived from events is known for it.')
221
+ }
222
+
223
+ // ── data ───────────────────────────────────────────────────────────────────
224
+
225
+ async function getJson(path) {
226
+ const res = await fetch(path, { cache: 'no-store' })
227
+ let body = null
228
+ try {
229
+ body = await res.json()
230
+ } catch {
231
+ // not JSON; the status says what went wrong
232
+ }
233
+ if (!res.ok) throw new Error((body && body.error) || `${res.status} ${res.statusText}`)
234
+ return body || {}
235
+ }
236
+
237
+ const staticEvents = new Map()
238
+ const api = LIVE
239
+ ? {
240
+ runs: () => getJson('api/runs'),
241
+ run: (id) => getJson(`api/runs/${encodeURIComponent(id)}`),
242
+ events: (id, after, limit) => getJson(`api/runs/${encodeURIComponent(id)}/events?since=${after}&limit=${limit}`),
243
+ sessions: () => getJson('api/sessions'),
244
+ }
245
+ : {
246
+ runs: () => getJson('data/runs.json'),
247
+ run: (id) => getJson(`data/runs/${fileId(id)}.json`),
248
+ // The snapshot holds every event in one file; it is paged here the way the API pages it.
249
+ events: async (id, after, limit) => {
250
+ let all = staticEvents.get(id)
251
+ if (!all) {
252
+ all = (await getJson(`data/events/${fileId(id)}.json`)).events || []
253
+ staticEvents.set(id, all)
254
+ }
255
+ const rest = all.filter((e) => e.id > after)
256
+ return { events: rest.slice(0, limit), more: rest.length > limit }
257
+ },
258
+ sessions: () => getJson('data/sessions.json'),
259
+ }
260
+
261
+ async function loadRuns() {
262
+ const body = await api.runs()
263
+ state.project = body.project || ''
264
+ state.generatedAt = body.generated_at || null
265
+ state.runs = body.runs || []
266
+ state.categories = body.categories || {}
267
+ state.overview = body.overview || null
268
+ state.projects = body.projects || 1
269
+ state.listError = null
270
+ }
271
+
272
+ async function loadSessions() {
273
+ try {
274
+ state.sessions = (await api.sessions()).sessions || []
275
+ state.sessionsError = null
276
+ } catch (err) {
277
+ state.sessionsError = err.message
278
+ }
279
+ if (state.view === 'home') renderSessions()
280
+ }
281
+
282
+ // ── navigation ─────────────────────────────────────────────────────────────
283
+
284
+ function hashRun() {
285
+ const m = /^#run=(.+)$/.exec(location.hash)
286
+ if (!m) return null
287
+ try {
288
+ return decodeURIComponent(m[1])
289
+ } catch {
290
+ return null
291
+ }
292
+ }
293
+
294
+ function route() {
295
+ const id = hashRun()
296
+ if (id) {
297
+ if (state.view !== 'detail' || state.selected !== id) openRun(id, false)
298
+ } else if (state.view !== 'home') {
299
+ showHome()
300
+ }
301
+ }
302
+
303
+ function goHome() {
304
+ state.follow = false
305
+ if (location.hash) history.pushState(null, '', location.pathname + location.search)
306
+ showHome()
307
+ }
308
+
309
+ function setViewVisibility(view) {
310
+ $('view-home').toggleAttribute('data-view-hidden', view !== 'home')
311
+ $('view-convoy-detail').toggleAttribute('data-view-hidden', view !== 'detail')
312
+ $('breadcrumbs').toggleAttribute('data-view-hidden', view !== 'detail')
313
+ document.querySelectorAll('.dash-sidebar__link').forEach((a) => {
314
+ const li = a.closest('li')
315
+ const hidden = a.dataset.view !== view || (a.id === 'panel-nav' && $('panel-section').hidden)
316
+ li.hidden = hidden
317
+ })
318
+ if (window.scrollY < 40) activateFirstSection()
319
+ }
320
+
321
+ function showHome() {
322
+ clearTimeout(state.fastTimer)
323
+ state.gen++
324
+ Object.assign(state, { view: 'home', selected: null, run: null, insights: null, events: [], cursor: 0, more: false, detailError: null })
325
+ setViewVisibility('home')
326
+ renderPicker()
327
+ renderHome()
328
+ renderNotices()
329
+ renderFooter()
330
+ }
331
+
332
+ async function openRun(id, follow) {
333
+ clearTimeout(state.fastTimer)
334
+ const gen = ++state.gen
335
+ Object.assign(state, {
336
+ view: 'detail', selected: id, follow, run: null, insights: null, events: [], cursor: 0, more: false,
337
+ detailError: null, settling: false,
338
+ })
339
+ Object.assign(state.ui, { filter: 'all', execLimit: EXEC_PAGE, sortCol: 'started', sortAsc: true })
340
+ state.ui.eventOpen.clear()
341
+ state.ui.open.clear()
342
+ setViewVisibility('detail')
343
+ renderPicker()
344
+ renderDetail()
345
+ window.scrollTo(0, 0)
346
+ await loadDetail(gen, true)
347
+ }
348
+
349
+ /** Show the run a process is working on, without adding to the history. */
350
+ function followRun(id) {
351
+ history.replaceState(null, '', `${location.pathname}${location.search}#run=${encodeURIComponent(id)}`)
352
+ openRun(id, true)
353
+ }
354
+
355
+ // ── polling ────────────────────────────────────────────────────────────────
356
+
357
+ function appendEvents(page) {
358
+ const fresh = page.events || []
359
+ if (fresh.length) {
360
+ state.events = state.events.concat(fresh)
361
+ state.cursor = fresh[fresh.length - 1].id
362
+ }
363
+ state.more = Boolean(page.more)
364
+ }
365
+
366
+ /**
367
+ * One read of the shown run: its detail, and — unless older events are still
368
+ * waiting behind "Load more" — the events after the cursor. While the run is
369
+ * alive this repeats every 2 seconds; once it stops, one last read picks up
370
+ * what it wrote on the way out, and polling ends.
371
+ */
372
+ async function loadDetail(gen, initial) {
373
+ const id = state.selected
374
+ const wasAlive = Boolean(state.run && state.run.alive)
375
+ try {
376
+ const wantEvents = initial || !state.more
377
+ const [detail, page] = await Promise.all([
378
+ api.run(id),
379
+ wantEvents ? api.events(id, state.cursor, EVENT_PAGE) : Promise.resolve(null),
380
+ ])
381
+ if (gen !== state.gen) return
382
+ state.run = detail.run
383
+ state.insights = detail.insights || null
384
+ if (page) appendEvents(page)
385
+ state.detailError = null
386
+ syncListEntry(state.run)
387
+ renderHeader()
388
+ renderDetail()
389
+ } catch (err) {
390
+ if (gen !== state.gen) return
391
+ state.detailError = err.message
392
+ renderDetail()
393
+ }
394
+ if (gen !== state.gen || !LIVE) return
395
+ const alive = Boolean(state.run && state.run.alive)
396
+ if (alive || (state.detailError && !state.run)) {
397
+ state.fastTimer = setTimeout(() => loadDetail(gen, false), state.detailError ? 5000 : FAST_MS)
398
+ } else if (wasAlive && !state.settling) {
399
+ state.settling = true
400
+ state.fastTimer = setTimeout(() => loadDetail(gen, false), 600)
401
+ }
402
+ }
403
+
404
+ function syncListEntry(run) {
405
+ const i = state.runs.findIndex((r) => r.id === run.id)
406
+ if (i === -1) return
407
+ const { tasks, adapters, models, ...summary } = run
408
+ state.runs[i] = { ...state.runs[i], ...summary }
409
+ }
410
+
411
+ async function loadMoreEvents() {
412
+ if (state.eventsLoading || !state.more || !state.selected) return
413
+ const gen = state.gen
414
+ state.eventsLoading = true
415
+ renderTimeline()
416
+ try {
417
+ const page = await api.events(state.selected, state.cursor, EVENT_PAGE)
418
+ if (gen !== state.gen) return
419
+ appendEvents(page)
420
+ } catch (err) {
421
+ state.detailError = `Could not read more events: ${err.message}`
422
+ renderNotices()
423
+ } finally {
424
+ state.eventsLoading = false
425
+ if (gen === state.gen) renderTimeline()
426
+ }
427
+ }
428
+
429
+ /** Every 10 seconds: the run list, the totals and the sessions, and a run that started since. */
430
+ async function slowTick() {
431
+ try {
432
+ await loadRuns()
433
+ } catch (err) {
434
+ state.listError = `Lost contact with the dashboard server (${err.message}). Retrying every 10 seconds.`
435
+ renderNotices()
436
+ return
437
+ }
438
+ loadSessions()
439
+ renderPicker()
440
+ renderHeader()
441
+ if (state.view === 'home') renderHome()
442
+ renderNotices()
443
+
444
+ const working = state.runs.find((r) => r.alive)
445
+ if (state.follow && working && working.id !== state.selected) return followRun(working.id)
446
+ if (state.view !== 'detail' || !state.run) return
447
+ const listed = state.runs.find((r) => r.id === state.selected)
448
+ const shown = state.run
449
+ if (listed && !shown.alive && (listed.alive || listed.status !== shown.status || listed.tasks_done !== shown.tasks_done || listed.finished_at !== shown.finished_at)) {
450
+ clearTimeout(state.fastTimer)
451
+ state.settling = false
452
+ loadDetail(state.gen, false)
453
+ }
454
+ }
455
+
456
+ // ── header, picker, notices, footer ────────────────────────────────────────
457
+
458
+ function renderHeader() {
459
+ $('project-name').textContent = state.project ? `· ${state.project}` : ''
460
+ const badgeEl = $('source-badge')
461
+ if (!LIVE) {
462
+ badgeEl.className = 'source-badge'
463
+ badgeEl.textContent = state.generatedAt ? `Snapshot · ${fmtWhen(state.generatedAt)}` : 'Snapshot'
464
+ badgeEl.title = 'A static copy of recorded runs. Not live.'
465
+ return
466
+ }
467
+ const working = state.runs.filter((r) => r.alive).length
468
+ badgeEl.className = working ? 'source-badge source-badge--live' : 'source-badge'
469
+ badgeEl.innerHTML = working ? `<span class="live-dot" aria-hidden="true"></span>${esc(plural(working, 'run'))} live` : 'Live · nothing running'
470
+ badgeEl.title = 'Read from .opencastle/convoy.db on every refresh'
471
+ }
472
+
473
+ let pickerHtml = ''
474
+
475
+ function renderPicker() {
476
+ const sel = $('run-picker')
477
+ const opts = ['<option value="">Overview of every run</option>']
478
+ for (const r of state.runs.slice(0, 200)) {
479
+ const label = `${r.name} · ${r.alive ? 'live' : r.display_status} · ${fmtWhen(r.started_at || r.created_at)}`
480
+ opts.push(`<option value="${esc(r.id)}">${esc(label)}</option>`)
481
+ }
482
+ if (state.selected && !state.runs.some((r) => r.id === state.selected)) {
483
+ opts.push(`<option value="${esc(state.selected)}">${esc(state.selected)}</option>`)
484
+ }
485
+ const html = opts.join('')
486
+ // Rebuilding the options closes a list the reader has open; only do it when they changed.
487
+ if (pickerHtml !== html) {
488
+ sel.innerHTML = html
489
+ pickerHtml = html
490
+ }
491
+ sel.value = state.view === 'detail' ? state.selected : ''
492
+ }
493
+
494
+ function renderNotices() {
495
+ const notes = []
496
+ if (state.listError) notes.push(`<p class="notice notice--error">${esc(state.listError)}</p>`)
497
+ if (state.view === 'detail' && state.detailError && state.run) notes.push(`<p class="notice notice--error">${esc(state.detailError)}</p>`)
498
+ $('notices').innerHTML = notes.join('')
499
+ }
500
+
501
+ function renderFooter() {
502
+ $('footer').innerHTML = LIVE
503
+ ? 'Read-only. Every figure is read from <code>.opencastle/convoy.db</code> and <code>.opencastle/logs/events.ndjson</code>. A live run refreshes every 2 seconds; the run list every 10.'
504
+ : `A static snapshot of recorded runs${state.generatedAt ? `, exported ${esc(fmtWhen(state.generatedAt))}` : ''}. Every figure was read from the projects' own <code>.opencastle/convoy.db</code>. Not live.`
505
+ }
506
+
507
+ // ── shared charts ──────────────────────────────────────────────────────────
508
+
509
+ function stackedBars(rows, segments) {
510
+ const max = Math.max(1, ...rows.map((r) => r.total))
511
+ return rows.map((r) => `<div class="bar-row">
512
+ <span class="bar-label" title="${esc(r.label)}">${esc(r.label)}</span>
513
+ <div class="bar-track" role="img" aria-label="${esc(`${r.label}: ${segments.filter((s) => r[s.key]).map((s) => `${r[s.key]} ${s.label}`).join(', ')}`)}">
514
+ ${segments.filter((s) => r[s.key] > 0).map((s) => `<div class="bar-segment ${s.fill}" style="width:${((r[s.key] / max) * 100).toFixed(2)}%" title="${esc(`${s.label}: ${r[s.key]}`)}"></div>`).join('')}
515
+ </div>
516
+ <span class="bar-value">${r.total}</span>
517
+ </div>`).join('')
518
+ }
519
+
520
+ function legend(segments) {
521
+ return `<div class="legend-inline">${segments.map((s) => `<span><i class="swatch ${s.fill}"></i>${esc(s.label)}</span>`).join('')}</div>`
522
+ }
523
+
524
+ const AGENT_SEGMENTS = [
525
+ { key: 'done', label: 'done', fill: 'fill-done' },
526
+ { key: 'running', label: 'running', fill: 'fill-running' },
527
+ { key: 'failed', label: 'failed', fill: 'fill-failed' },
528
+ { key: 'other', label: 'other (pending, skipped, interrupted)', fill: 'fill-other' },
529
+ ]
530
+
531
+ function renderAgentChart(el, agents) {
532
+ if (!agents.length) {
533
+ el.innerHTML = empty('agents', 'No tasks recorded', 'Tasks per agent appear here once a run records tasks.')
534
+ return
535
+ }
536
+ el.innerHTML = stackedBars(agents.map((a) => ({ ...a, label: a.agent })), AGENT_SEGMENTS) + legend(AGENT_SEGMENTS)
537
+ }
538
+
539
+ function agentsOf(tasks) {
540
+ const map = new Map()
541
+ for (const t of tasks) {
542
+ const name = t.agent || 'not recorded'
543
+ let a = map.get(name)
544
+ if (!a) map.set(name, (a = { agent: name, total: 0, done: 0, failed: 0, running: 0, other: 0 }))
545
+ a.total++
546
+ const s = t.display_status
547
+ if (s === 'done') a.done++
548
+ else if (FAILED.includes(s)) a.failed++
549
+ else if (RUNNING.includes(s)) a.running++
550
+ else a.other++
551
+ }
552
+ return [...map.values()].sort((x, y) => y.total - x.total || x.agent.localeCompare(y.agent))
553
+ }
554
+
555
+ function simpleBars(rows, fill) {
556
+ const max = Math.max(1, ...rows.map((r) => r.n))
557
+ return rows.map((r) => `<div class="bar-row">
558
+ <span class="bar-label" title="${esc(r.label)}">${r.labelHtml || esc(r.label)}</span>
559
+ <div class="bar-track"><div class="bar-segment ${r.fill || fill}" style="width:${((r.n / max) * 100).toFixed(2)}%"></div></div>
560
+ <span class="bar-value">${r.n}</span>
561
+ </div>`).join('')
562
+ }
563
+
564
+ function renderModelChart(el, models, notReported, reviewModels) {
565
+ const rows = models.map((m) => ({ label: m.model, n: m.tasks }))
566
+ if (notReported > 0) rows.push({ label: 'not reported', labelHtml: nr(), n: notReported, fill: 'fill-unknown' })
567
+ if (!rows.length) {
568
+ el.innerHTML = empty('models', 'No tasks recorded', 'Tasks by the model their runtime reported appear here.')
569
+ return
570
+ }
571
+ let html = simpleBars(rows, 'fill-accent')
572
+ const reviewers = Object.entries(reviewModels || {}).sort((a, b) => b[1] - a[1])
573
+ if (reviewers.length) {
574
+ html += `<h3 class="section-subtitle">Reviews by reviewer model</h3>`
575
+ html += simpleBars(reviewers.map(([model, n]) => (model === 'not reported' ? { label: model, labelHtml: nr(), n, fill: 'fill-unknown' } : { label: model, n })), 'fill-standard')
576
+ }
577
+ el.innerHTML = html
578
+ }
579
+
580
+ function donut(segments, totalLabel) {
581
+ const total = segments.reduce((s, x) => s + x.n, 0)
582
+ const r = 70
583
+ const c = 2 * Math.PI * r
584
+ let offset = 0
585
+ const arcs = segments.map((s) => {
586
+ const len = (s.n / total) * c
587
+ const arc = `<circle cx="90" cy="90" r="${r}" fill="none" class="${s.fill}" style="stroke:var(${s.color})" stroke-width="18" stroke-dasharray="${len.toFixed(2)} ${(c - len).toFixed(2)}" stroke-dashoffset="${(-offset).toFixed(2)}" transform="rotate(-90 90 90)"><title>${esc(`${s.label}: ${s.n}`)}</title></circle>`
588
+ offset += len
589
+ return arc
590
+ })
591
+ return `<div class="donut-wrap"><svg viewBox="0 0 180 180" class="donut-svg" role="img" aria-label="${esc(segments.map((s) => `${s.label} ${s.n}`).join(', '))}">
592
+ <circle cx="90" cy="90" r="${r}" fill="none" class="donut-track" stroke-width="18"/>${arcs.join('')}</svg>
593
+ <div class="donut-center"><span class="donut-total">${total}</span><span class="donut-total-label">${esc(totalLabel)}</span></div></div>`
594
+ }
595
+
596
+ function legendRows(segments, total) {
597
+ return segments.map((s) => `<div class="legend-item"><i class="swatch ${s.fill}" style="background:var(${s.color})"></i><span class="legend-name">${s.labelHtml || esc(s.label)}</span><span class="legend-count">${s.n} (${Math.round((s.n / total) * 100)}%)</span></div>`).join('')
598
+ }
599
+
600
+ const TIER_COLOR = { premium: '--tier-premium', standard: '--tier-standard', utility: '--tier-utility', economy: '--tier-economy' }
601
+
602
+ function renderTierChart(el, tiers, notRecorded, eventsRecorded) {
603
+ if (eventsRecorded === false) {
604
+ el.innerHTML = eventsMissing()
605
+ return
606
+ }
607
+ const segs = [...tiers]
608
+ .sort((a, b) => (TIER_ORDER.indexOf(a.tier) + 1 || 99) - (TIER_ORDER.indexOf(b.tier) + 1 || 99))
609
+ .map((t) => ({ label: t.tier, n: t.tasks, color: TIER_COLOR[t.tier] || '--color-muted', fill: '' }))
610
+ if (notRecorded > 0) segs.push({ label: 'not recorded', labelHtml: `${nr('not recorded')} ${info('Tasks with no delegation event: not finished yet, never run, or from an engine that wrote none.')}`, n: notRecorded, color: '--color-muted', fill: '' })
611
+ if (!segs.length) {
612
+ el.innerHTML = empty('tiers', 'No tiers recorded', 'Each task records its tier in a delegation event when it finishes.')
613
+ return
614
+ }
615
+ const total = segs.reduce((s, x) => s + x.n, 0)
616
+ el.innerHTML = `<div class="donut-container">${donut(segs, 'tasks')}<div class="donut-legend">${legendRows(segs, total)}</div></div>`
617
+ }
618
+
619
+ function renderMechanismChart(el, mechanisms, runtimes, eventsRecorded) {
620
+ if (eventsRecorded === false) {
621
+ el.innerHTML = eventsMissing()
622
+ return
623
+ }
624
+ if (!mechanisms.length) {
625
+ el.innerHTML = empty('mechanism', 'No attempts recorded', 'Each attempt records how it ran in its task_started event.')
626
+ return
627
+ }
628
+ const colors = ['--accent-blue', '--accent-purple', '--color-partial', '--cat-merge', '--color-muted']
629
+ const segs = mechanisms.map((m, i) => ({ label: m.mechanism === 'worktree' ? 'worktree (its own git worktree)' : m.mechanism, n: m.attempts, color: colors[i % colors.length], fill: '' }))
630
+ const total = segs.reduce((s, x) => s + x.n, 0)
631
+ const rt = runtimes.length
632
+ ? `<div class="legend-group">Runtime</div>${runtimes.map((r) => `<div class="legend-item"><span class="legend-name">${esc(r.runtime)}</span><span class="legend-count">${r.attempts}</span></div>`).join('')}`
633
+ : ''
634
+ el.innerHTML = `<div class="donut-container">${donut(segs, 'attempts')}<div class="donut-legend">${legendRows(segs, total)}${rt}</div></div>`
635
+ }
636
+
637
+ // ── home ───────────────────────────────────────────────────────────────────
638
+
639
+ function renderHome() {
640
+ renderHeader()
641
+ renderOverall()
642
+ renderActivity()
643
+ renderConvoyList()
644
+ const o = state.overview
645
+ if (o) {
646
+ renderAgentChart($('home-agent-chart'), o.agents)
647
+ renderModelChart($('home-model-chart'), o.models, o.models_not_reported, o.reviews ? o.reviews.models : null)
648
+ renderTierChart($('home-tier-chart'), o.tiers, o.tiers_not_recorded, o.reviews !== null)
649
+ renderMechanismChart($('home-mechanism-chart'), o.mechanisms, o.runtimes, o.reviews !== null)
650
+ renderHomeQuality(o)
651
+ }
652
+ renderSessions()
653
+ }
654
+
655
+ function kpi(label, value, sub, tip) {
656
+ return `<div class="overall-kpi">
657
+ <span class="overall-kpi__label">${esc(label)}${tip ? ` ${info(tip)}` : ''}</span>
658
+ <span class="overall-kpi__value">${value == null ? nr() : value}</span>
659
+ ${sub ? `<span class="overall-kpi__sub">${sub}</span>` : ''}
660
+ </div>`
661
+ }
662
+
663
+ function statusLine(byStatus) {
664
+ return Object.entries(byStatus || {}).sort((a, b) => b[1] - a[1]).map(([s, n]) => `${n} ${esc(s)}`).join(' · ')
665
+ }
666
+
667
+ function renderOverall() {
668
+ const o = state.overview
669
+ const grid = $('overall-grid')
670
+ if (!o) {
671
+ grid.innerHTML = state.listError ? '' : kpi('Total Runs', '…')
672
+ return
673
+ }
674
+ const cost = o.cost
675
+ const costSub = [
676
+ cost.estimated === true ? 'includes estimates' : cost.estimated === false ? 'as the runtime reported' : '',
677
+ cost.runs_not_reported ? `${plural(cost.runs_not_reported, 'run')} not reported` : '',
678
+ ].filter(Boolean).join(' · ')
679
+ $('overall-desc').innerHTML = state.projects > 1
680
+ ? `Every convoy run recorded in these ${state.projects} projects' <code>.opencastle/convoy.db</code>.`
681
+ : "Every convoy run recorded in this project's <code>.opencastle/convoy.db</code>."
682
+ grid.innerHTML = [
683
+ kpi('Total Runs', String(o.runs.total), statusLine(o.runs.by_status), 'Convoy runs recorded in this project'),
684
+ kpi('Running Now', String(o.runs.alive), LIVE ? (o.runs.alive ? 'a process is working on it' : 'nothing running') : 'a snapshot is never live', 'Runs a live process is working on: a recent engine heartbeat and, on this machine, a live pid'),
685
+ kpi('Total Tasks', String(o.tasks.total), statusLine(o.tasks.by_status)),
686
+ kpi('Total Retries', String(o.tasks.retries), 'attempts after a task’s first'),
687
+ kpi('Success Rate', fmtPct(o.runs.success_rate), o.runs.ended ? `${o.runs.done} done of ${plural(o.runs.ended, 'ended run')}` : 'no run has ended', 'Runs that ended done, out of every run that ended (done, failed, gate-failed, hook-failed or interrupted)'),
688
+ kpi('Avg Duration', fmtDuration(o.duration.avg_ms), o.duration.measured ? `p95 ${esc(fmtDuration(o.duration.p95_ms))} · over ${plural(o.duration.measured, 'finished run')}` : 'no run has finished', 'Finished minus started, over runs that finished. A run resumed after an interrupt counts the time between.'),
689
+ kpi('Total Tokens', o.tokens.total == null ? null : fmtTokens(o.tokens.total), o.tokens.runs_not_reported ? `${plural(o.tokens.runs_not_reported, 'run')} not reported` : 'every run reported', 'Tokens as each run recorded them: input, output and cache, plus reviews'),
690
+ kpi('Total Cost', fmtCost(cost.total_usd, cost.estimated), costSub, 'Cost as the runtime reported it. Marked est. where any part had to be estimated.'),
691
+ ].join('')
692
+ }
693
+
694
+ function renderActivity() {
695
+ const el = $('activity-timeline-chart')
696
+ const days = state.overview ? state.overview.activity : []
697
+ if (!days.length) {
698
+ el.innerHTML = empty('timeline', 'No runs yet', 'Runs per day appear here once the project has run a convoy.')
699
+ return
700
+ }
701
+ const max = Math.max(1, ...days.map((d) => d.total))
702
+ const segs = [
703
+ { key: 'done', label: 'done', fill: 'fill-done' },
704
+ { key: 'failed', label: 'failed', fill: 'fill-failed' },
705
+ { key: 'interrupted', label: 'interrupted', fill: 'fill-interrupted' },
706
+ { key: 'other', label: 'running or pending', fill: 'fill-running' },
707
+ ]
708
+ el.innerHTML = `<div class="activity-timeline--vertical">${days.map((d) => {
709
+ const date = new Date(`${d.date}T00:00:00Z`)
710
+ const label = `${MONTHS[date.getUTCMonth()]} ${date.getUTCDate()}`
711
+ return `<div class="vbar-col" title="${esc(`${d.date}: ${segs.filter((s) => d[s.key]).map((s) => `${d[s.key]} ${s.label}`).join(', ')}`)}">
712
+ <span class="vbar-value">${d.total}</span>
713
+ <div class="vbar-track">${segs.filter((s) => d[s.key] > 0).map((s) => `<div class="vbar-fill ${s.fill}" style="height:${((d[s.key] / max) * 100).toFixed(2)}%"></div>`).join('')}</div>
714
+ <span class="vbar-label">${label}</span>
715
+ </div>`
716
+ }).join('')}</div>${legend(segs)}`
717
+ }
718
+
719
+ function filteredRuns() {
720
+ const q = $('cl-filter-search').value.trim().toLowerCase()
721
+ const status = $('cl-filter-status').value
722
+ const from = $('cl-filter-from').value
723
+ const to = $('cl-filter-to').value
724
+ return state.runs.filter((r) => {
725
+ if (q && !`${r.name} ${r.id}`.toLowerCase().includes(q)) return false
726
+ if (status && (r.alive ? 'live' : r.display_status) !== status) return false
727
+ const day = String(r.created_at).slice(0, 10)
728
+ if (from && day < from) return false
729
+ if (to && day > to) return false
730
+ return true
731
+ })
732
+ }
733
+
734
+ function renderStatusFilter() {
735
+ const sel = $('cl-filter-status')
736
+ const current = sel.value
737
+ const present = [...new Set(state.runs.map((r) => (r.alive ? 'live' : r.display_status)))].sort()
738
+ if (current && !present.includes(current)) present.push(current)
739
+ sel.innerHTML = '<option value="">All</option>' + present.map((s) => `<option value="${esc(s)}">${esc(s)}</option>`).join('')
740
+ sel.value = current
741
+ }
742
+
743
+ function runRow(r, cls) {
744
+ const dur = r.duration_ms != null ? fmtDuration(r.duration_ms) : r.alive ? `${fmtDuration(since(r.started_at || r.created_at)) || '—'} so far` : null
745
+ const tasks = `${r.tasks_done}/${r.tasks_total} done${r.tasks_failed ? ` · <span class="td-reason" style="display:inline">${r.tasks_failed} failed</span>` : ''}`
746
+ const status = r.alive ? `${badge(r.status, 'A process is working on it now')}` : badge(r.display_status, r.display_status !== r.status ? `Recorded as ${r.status}; no process is working on it` : RUN_EXPLANATIONS[r.display_status])
747
+ return `<tr data-run-id="${esc(r.id)}"${cls ? ` class="${cls}"` : ''}>
748
+ <td class="card-key"><a class="run-link" href="#run=${encodeURIComponent(r.id)}">${esc(r.name)}</a><span class="td-sub">${esc(r.id)}</span></td>
749
+ <td data-label="Status">${status}</td>
750
+ <td data-label="Tasks">${tasks}</td>
751
+ <td data-label="Started">${timeTag(r.started_at || r.created_at, fmtWhen(r.started_at || r.created_at))}</td>
752
+ <td data-label="Duration" class="td-num">${dur == null ? '—' : esc(dur)}</td>
753
+ <td data-label="Tokens" class="td-num">${r.tokens == null ? nr() : fmtTokens(r.tokens)}</td>
754
+ <td data-label="Cost" class="td-num">${r.cost_usd == null ? nr() : fmtCost(r.cost_usd, r.cost_estimated)}</td>
755
+ </tr>`
756
+ }
757
+
758
+ function renderConvoyList() {
759
+ renderStatusFilter()
760
+ const wrap = $('convoy-list-table-wrap')
761
+ const pag = $('convoy-list-pagination')
762
+ if (!state.runs.length) {
763
+ wrap.innerHTML = `<div class="convoy-list-empty">${LIVE ? 'No convoy runs in this project yet. Start one with <code>opencastle convoy "&lt;task&gt;"</code>; it appears here within 10 seconds.' : 'This snapshot has no runs.'}</div>`
764
+ pag.innerHTML = ''
765
+ return
766
+ }
767
+ const runs = filteredRuns()
768
+ if (!runs.length) {
769
+ wrap.innerHTML = '<div class="convoy-list-empty">No runs match these filters.</div>'
770
+ pag.innerHTML = ''
771
+ return
772
+ }
773
+ // Runs of one pipeline are listed together, under the pipeline.
774
+ const items = []
775
+ const groups = new Map()
776
+ for (const r of runs) {
777
+ if (!r.pipeline_id) {
778
+ items.push(r)
779
+ continue
780
+ }
781
+ let g = groups.get(r.pipeline_id)
782
+ if (!g) {
783
+ groups.set(r.pipeline_id, (g = { pipeline_id: r.pipeline_id, runs: [] }))
784
+ items.push(g)
785
+ }
786
+ g.runs.push(r)
787
+ }
788
+ const pages = Math.max(1, Math.ceil(items.length / LIST_PAGE))
789
+ if (state.ui.listPage > pages) state.ui.listPage = pages
790
+ const shown = items.slice((state.ui.listPage - 1) * LIST_PAGE, state.ui.listPage * LIST_PAGE)
791
+ const rows = []
792
+ for (const item of shown) {
793
+ if (!item.runs) {
794
+ rows.push(runRow(item))
795
+ continue
796
+ }
797
+ const open = state.ui.chainOpen.has(item.pipeline_id)
798
+ const done = item.runs.filter((r) => r.display_status === 'done').length
799
+ const live = item.runs.some((r) => r.alive)
800
+ rows.push(`<tr class="convoy-chain-row" data-pipeline-group-id="${esc(item.pipeline_id)}" aria-expanded="${open}">
801
+ <td class="card-key"><span class="convoy-chain-toggle" aria-hidden="true">${open ? '▼' : '▶'}</span>Pipeline <code>${esc(item.pipeline_id)}</code></td>
802
+ <td data-label="Status">${live ? badge('running', 'A run in this pipeline is working now') : `${done}/${item.runs.length} runs done`}</td>
803
+ <td data-label="Tasks">${sum(item.runs, (r) => r.tasks_done)}/${sum(item.runs, (r) => r.tasks_total)} done</td>
804
+ <td data-label="Runs">${plural(item.runs.length, 'run')}</td>
805
+ <td class="td-num" data-label="Duration">—</td>
806
+ <td class="td-num" data-label="Tokens">${item.runs.some((r) => r.tokens != null) ? fmtTokens(sum(item.runs, (r) => r.tokens)) : nr()}</td>
807
+ <td class="td-num" data-label="Cost">${item.runs.some((r) => r.cost_usd != null) ? fmtCost(sum(item.runs, (r) => r.cost_usd), item.runs.some((r) => r.cost_estimated)) : nr()}</td>
808
+ </tr>`)
809
+ if (open) for (const r of item.runs) rows.push(runRow(r, 'convoy-chain-child'))
810
+ }
811
+ wrap.innerHTML = `<table class="convoy-list-table cards">
812
+ <thead><tr><th scope="col">Name</th><th scope="col">Status</th><th scope="col">Tasks</th><th scope="col">Started</th><th scope="col" class="td-num">Duration</th><th scope="col" class="td-num">Tokens</th><th scope="col" class="td-num">Cost</th></tr></thead>
813
+ <tbody>${rows.join('')}</tbody></table>`
814
+ pag.innerHTML = pages > 1
815
+ ? `<div class="convoy-list-pagination">
816
+ <button class="dash-btn dash-btn--ghost" type="button" data-page="${state.ui.listPage - 1}"${state.ui.listPage === 1 ? ' disabled' : ''}>Previous</button>
817
+ <span class="convoy-list-pagination__info">Page ${state.ui.listPage} of ${pages} · ${plural(runs.length, 'run')}</span>
818
+ <button class="dash-btn dash-btn--ghost" type="button" data-page="${state.ui.listPage + 1}"${state.ui.listPage === pages ? ' disabled' : ''}>Next</button>
819
+ </div>`
820
+ : ''
821
+ }
822
+
823
+ function renderHomeQuality(o) {
824
+ const el = $('home-quality-body')
825
+ const rv = o.reviews
826
+ const ck = o.checks
827
+ const cards = [
828
+ card('Reviews run', rv ? String(rv.ran) : null, { mod: 'review', missing: 'not recorded', sub: rv ? `${rv.passed} passed · ${rv.blocked} blocked` : '', tip: 'Fast and panel reviews that reached a reviewer. Auto-passes are not counted here.' }),
829
+ card('Blocked by review', rv ? String(rv.blocked) : null, { mod: 'errors', missing: 'not recorded', tip: 'Verdicts that sent a change back. The task retries with the reviewer’s issues if it has a retry left.' }),
830
+ card('No verdict', rv ? String(rv.skipped) : null, { mod: 'input', missing: 'not recorded', tip: 'A review was due and reached no verdict: the work went unreviewed. Never counted as a pass.' }),
831
+ card('Auto-passed', rv ? String(rv.auto_pass) : null, { mod: 'waiting', missing: 'not recorded', tip: 'Passed without a reviewer: a writer’s change, or a small one. No reviewer read it.' }),
832
+ card('Review tokens', rv ? fmtTokens(rv.tokens) : null, { mod: 'review', missing: 'not recorded' }),
833
+ card('Checks run', ck ? String(ck.ran) : null, { mod: 'done', missing: 'not recorded', sub: ck ? `${ck.passed} passed · ${ck.failed} failed` : '', tip: 'Spec gates and built-in gates, per task and on the merged result' }),
834
+ card('Warnings', ck ? String(ck.warnings) : null, { mod: 'input', missing: 'not recorded', tip: 'Contract and file-partition violations: recorded, and the work kept' }),
835
+ card('Retry queue', o.dlq ? String(o.dlq.entries) : null, { mod: o.dlq && o.dlq.unresolved ? 'errors' : 'done', missing: 'not recorded', sub: o.dlq ? `${o.dlq.unresolved} unresolved` : '', tip: 'Dead-letter queue: tasks that failed for good' }),
836
+ card('Artifacts', o.artifacts == null ? null : String(o.artifacts), { mod: 'waiting', missing: 'not recorded' }),
837
+ ]
838
+ el.innerHTML = `<div class="task-summary-cards">${cards.join('')}</div>`
839
+ }
840
+
841
+ function sessionsTable(rows, withSource) {
842
+ return `<div class="table-wrap"><table class="sessions-table cards">
843
+ <thead><tr>${withSource ? '<th scope="col">Source</th>' : ''}<th scope="col">When</th><th scope="col">Task</th><th scope="col">Agent</th><th scope="col">Outcome</th><th scope="col" class="td-num">Minutes</th><th scope="col" class="td-num">Files</th><th scope="col" class="td-num">Retries</th><th scope="col">Model</th></tr></thead>
844
+ <tbody>${rows.map((s) => {
845
+ const src = s.source === 'convoy'
846
+ ? `<span class="kind-badge" title="The engine's session event for a finished task">convoy run</span>${s.convoy_id ? `<span class="td-sub"><a href="#run=${encodeURIComponent(s.convoy_id)}" title="${esc(s.convoy_id)}">${esc(runName(s.convoy_id))}</a></span>` : ''}`
847
+ : '<span class="kind-badge" title="Appended with opencastle log">opencastle log</span>'
848
+ const num = (v) => (v == null ? nr() : esc(v))
849
+ return `<tr>
850
+ ${withSource ? `<td data-label="Source">${src}</td>` : ''}
851
+ <td data-label="When" class="td-nowrap">${timeTag(s.timestamp, fmtWhen(s.timestamp))}</td>
852
+ <td class="card-key td-task">${s.task ? esc(s.task) : nr()}${s.tracker_issue ? `<span class="td-sub">${esc(s.tracker_issue)}</span>` : ''}</td>
853
+ <td data-label="Agent">${s.agent ? esc(s.agent) : nr()}</td>
854
+ <td data-label="Outcome">${s.outcome ? `<span class="outcome-badge ${tone(s.outcome)}">${esc(s.outcome)}</span>` : nr()}</td>
855
+ <td data-label="Minutes" class="td-num">${num(s.duration_min)}</td>
856
+ <td data-label="Files" class="td-num">${num(s.files_changed)}</td>
857
+ <td data-label="Retries" class="td-num">${num(s.retries)}</td>
858
+ <td data-label="Model">${s.model ? esc(s.model) : nr()}</td>
859
+ </tr>`
860
+ }).join('')}</tbody></table></div>`
861
+ }
862
+
863
+ function runName(id) {
864
+ const run = state.runs.find((r) => r.id === id)
865
+ return run ? run.name : id
866
+ }
867
+
868
+ function renderSessions() {
869
+ const el = $('sessions-table')
870
+ if (state.sessionsError) {
871
+ el.innerHTML = `<p class="notice notice--error" style="margin:16px 24px">Could not read sessions: ${esc(state.sessionsError)}</p>`
872
+ return
873
+ }
874
+ if (!state.sessions.length) {
875
+ el.innerHTML = `<div style="padding:16px 24px">${empty('table', 'No sessions recorded yet', 'Agents append sessions with <code>opencastle log --type session</code>, and a convoy run records one per task it finishes.')}</div>`
876
+ return
877
+ }
878
+ el.innerHTML = sessionsTable(state.sessions.slice(0, 20), true)
879
+ }
880
+
881
+ // ── detail ─────────────────────────────────────────────────────────────────
882
+
883
+ function renderDetail() {
884
+ renderNotices()
885
+ renderFooter()
886
+ const run = state.run
887
+ const hero = $('convoy-detail-hero')
888
+ $('breadcrumbs-run').textContent = run ? run.name : state.selected || ''
889
+ if (!run) {
890
+ hero.innerHTML = state.detailError
891
+ ? `<p class="notice notice--error">Could not read run <code>${esc(state.selected)}</code>: ${esc(state.detailError)}</p>`
892
+ : '<p class="muted">Loading…</p>'
893
+ for (const id of ['task-summary-cards', 'task-table-wrap', 'deps-view', 'agent-chart', 'model-chart', 'tier-chart', 'mechanism-chart', 'quality-body', 'reviews-table', 'reliability-body', 'checks-body', 'outputs-body', 'event-timeline-filters', 'event-timeline-list', 'event-timeline-more', 'execution-log', 'detail-sessions-table']) $(id).innerHTML = ''
894
+ return
895
+ }
896
+ const ins = state.insights
897
+ renderHero(run, ins)
898
+ renderTasks(run, ins)
899
+ renderDeps(run)
900
+ renderAgentChart($('agent-chart'), agentsOf(run.tasks))
901
+ renderModelChart($('model-chart'), modelsOf(run.tasks), run.tasks.filter((t) => !t.model).length, ins ? ins.review_stats.models : null)
902
+ if (ins) {
903
+ renderTierChart($('tier-chart'), ins.tiers, ins.tiers_not_recorded, ins.events_recorded)
904
+ renderMechanismChart($('mechanism-chart'), ins.mechanisms, ins.runtimes, ins.events_recorded)
905
+ }
906
+ renderQuality(run, ins)
907
+ renderFastReviews(run, ins)
908
+ renderPanels(ins)
909
+ renderReliability(run, ins)
910
+ renderChecks(ins)
911
+ renderOutputs(run, ins)
912
+ renderTimeline()
913
+ renderExecLog(run, ins)
914
+ renderDetailSessions(ins)
915
+ setViewVisibility('detail')
916
+ }
917
+
918
+ function modelsOf(tasks) {
919
+ const map = new Map()
920
+ for (const t of tasks) if (t.model) map.set(t.model, (map.get(t.model) || 0) + 1)
921
+ return [...map.entries()].sort((a, b) => b[1] - a[1]).map(([model, tasks]) => ({ model, tasks }))
922
+ }
923
+
924
+ function metaItem(label, value) {
925
+ return `<div class="convoy-detail-hero__meta-item"><span class="convoy-detail-hero__meta-label">${esc(label)}</span><span class="convoy-detail-hero__meta-value">${value}</span></div>`
926
+ }
927
+
928
+ function renderHero(run, ins) {
929
+ const shown = run.display_status
930
+ const live = LIVE && run.alive
931
+ ? '<span class="status-badge tone-running" title="A process is working on this run now"><span class="live-dot" aria-hidden="true" style="margin-right:6px"></span>live</span>'
932
+ : ''
933
+ const explanation = shown !== run.status
934
+ ? `Recorded as <b>${esc(run.status)}</b>, but no process is working on it: it was interrupted. <code>opencastle convoy resume</code> continues it.`
935
+ : esc(RUN_EXPLANATIONS[shown] || '').replace(/`([^`]+)`/g, '<code>$1</code>')
936
+ const interrupts = ins ? ins.interruptions.filter((i) => i.type === 'convoy_interrupted').length : 0
937
+ const resumes = ins ? ins.interruptions.filter((i) => i.type === 'convoy_resumed').length : 0
938
+ const history = interrupts || resumes
939
+ ? `<p class="convoy-status-explanation">Interrupted ${plural(interrupts, 'time')} and resumed ${plural(resumes, 'time')}; the duration includes the time between.</p>`
940
+ : ''
941
+ const elapsed = run.duration_ms != null
942
+ ? esc(fmtDuration(run.duration_ms))
943
+ : run.alive ? `<span data-elapsed-since="${esc(run.started_at || run.created_at)}">${esc(fmtDuration(since(run.started_at || run.created_at)) || '—')}</span> so far` : nr('not finished')
944
+ const failed = run.tasks_failed ? ` · <span class="td-reason" style="display:inline">${run.tasks_failed} failed</span>` : ''
945
+ const running = run.tasks_running && run.alive ? ` · ${run.tasks_running} running` : ''
946
+ const chain = run.pipeline_id ? state.runs.filter((r) => r.pipeline_id === run.pipeline_id).sort((a, b) => String(a.created_at).localeCompare(String(b.created_at))) : []
947
+ const chainHtml = chain.length > 1
948
+ ? `<div class="pipeline-chain-nav"><span class="pipeline-chain__label">Pipeline</span>${chain.map((r) => `<a class="pipeline-chain__item${r.id === run.id ? ' pipeline-chain__item--active' : ''}" href="#run=${encodeURIComponent(r.id)}"><i class="swatch ${fillOf(r.display_status)}"></i>${esc(r.name)}</a>`).join('')}</div>`
949
+ : ''
950
+ $('convoy-detail-hero').innerHTML = `
951
+ <div class="convoy-detail-hero__top">
952
+ <div style="min-width:0">
953
+ <h2 class="convoy-detail-hero__title">${esc(run.name)}</h2>
954
+ <div class="convoy-detail-hero__id"><code>${esc(run.id)}</code>${run.pipeline_id ? ` · pipeline <code>${esc(run.pipeline_id)}</code>` : ''}</div>
955
+ </div>
956
+ <div class="convoy-detail-hero__badges">${badge(shown, RUN_EXPLANATIONS[shown])}${live}</div>
957
+ </div>
958
+ <p class="convoy-status-explanation">${explanation}</p>${history}
959
+ ${state.follow && LIVE ? `<p class="convoy-status-explanation muted">${run.alive ? 'Following this run while it works.' : 'This run has ended.'} A run that starts next opens here; pick another run, or the overview, to stop that.</p>` : ''}
960
+ ${chainHtml}
961
+ <div class="convoy-detail-hero__meta">
962
+ ${metaItem('Branch', run.branch ? `<code>${esc(run.branch)}</code>` : '<span class="muted">current checkout</span>')}
963
+ ${metaItem('Runtime', run.adapters.length ? esc(run.adapters.join(', ')) : nr('not recorded'))}
964
+ ${metaItem('Models', run.models.length ? esc(run.models.join(', ')) : nr())}
965
+ ${metaItem('Started', timeTag(run.started_at || run.created_at, fmtWhenSec(run.started_at || run.created_at)))}
966
+ ${metaItem('Finished', run.finished_at ? timeTag(run.finished_at, fmtWhenSec(run.finished_at)) : nr('not finished'))}
967
+ ${metaItem(run.alive ? 'Elapsed' : 'Duration', elapsed)}
968
+ ${metaItem('Tasks', `${run.tasks_done}/${run.tasks_total} done${failed}${running}`)}
969
+ ${metaItem('Tokens', run.tokens == null ? nr() : `${fmtTokens(run.tokens)}${run.alive ? ' <span class="muted">so far</span>' : ''}`)}
970
+ ${metaItem('Cost', run.cost_usd == null ? nr() : fmtCost(run.cost_usd, run.cost_estimated))}
971
+ </div>`
972
+ }
973
+
974
+ function taskDuration(t, run) {
975
+ if (t.duration_ms != null) return fmtDuration(t.duration_ms)
976
+ if (run.alive && RUNNING.includes(t.status) && t.started_at) return `<span data-elapsed-since="${esc(t.started_at)}">${esc(fmtDuration(since(t.started_at)) || '—')}</span> so far`
977
+ return null
978
+ }
979
+
980
+ function tokensTip(t) {
981
+ return [['prompt', t.prompt_tokens], ['completion', t.completion_tokens], ['cache read', t.cache_read_tokens], ['cache write', t.cache_write_tokens]]
982
+ .filter(([, n]) => n != null).map(([k, n]) => `${k} ${Number(n).toLocaleString('en-US')}`).join(', ')
983
+ }
984
+
985
+ const TASK_COLS = [
986
+ { key: 'id', label: 'Task', value: (t) => t.id },
987
+ { key: 'agent', label: 'Agent', value: (t) => t.agent },
988
+ { key: 'status', label: 'Status', value: (t) => t.display_status },
989
+ { key: 'deps', label: 'Waits for', value: (t) => t.depends_on.length },
990
+ { key: 'started', label: 'Started', value: (t) => t.started_at || '' },
991
+ { key: 'duration', label: 'Duration', value: (t) => t.duration_ms ?? -1, num: true },
992
+ { key: 'retries', label: 'Retries', value: (t) => t.retries, num: true },
993
+ { key: 'changed', label: 'Files', title: 'Files the task changed, as its task_merged event recorded', value: (t) => (state.insights && t.id in state.insights.merges ? state.insights.merges[t.id] : -1), num: true },
994
+ { key: 'tokens', label: 'Tokens', value: (t) => t.total_tokens ?? -1, num: true },
995
+ { key: 'cost', label: 'Cost', value: (t) => t.cost_usd ?? -1, num: true },
996
+ ]
997
+
998
+ function renderTasks(run, ins) {
999
+ const tasks = run.tasks
1000
+ const count = (pick) => tasks.filter((t) => pick(t.display_status)).length
1001
+ const cards = [
1002
+ card('Tasks Completed', String(count((s) => s === 'done')), { mod: 'done', tip: 'Finished, and their work merged' }),
1003
+ card('Tasks Running', String(count((s) => RUNNING.includes(s))), { mod: 'running', tip: 'An agent is working on them now' }),
1004
+ card('Tasks Waiting', String(count((s) => s === 'pending')), { mod: 'waiting', tip: 'Waiting for what they depend on, or for a free slot' }),
1005
+ card('Tasks With Errors', String(count((s) => FAILED.includes(s))), { mod: 'errors', tip: 'Failed for good: out of retries' }),
1006
+ ]
1007
+ const skipped = count((s) => s === 'skipped')
1008
+ const interrupted = count((s) => s === 'interrupted')
1009
+ const input = count((s) => s === 'wait-for-input')
1010
+ if (skipped) cards.push(card('Skipped', String(skipped), { mod: 'input', tip: 'Never ran: something they depend on did not finish' }))
1011
+ if (interrupted) cards.push(card('Interrupted', String(interrupted), { mod: 'input', tip: 'Recorded as running, but no process is working on them' }))
1012
+ if (input) cards.push(card('Waiting For Input', String(input), { mod: 'input' }))
1013
+ $('task-summary-cards').innerHTML = cards.join('')
1014
+
1015
+ const wrap = $('task-table-wrap')
1016
+ if (!tasks.length) {
1017
+ wrap.innerHTML = empty('table', 'No tasks', 'This run has no tasks recorded.')
1018
+ return
1019
+ }
1020
+ const col = TASK_COLS.find((c) => c.key === state.ui.sortCol) || TASK_COLS[4]
1021
+ const dir = state.ui.sortAsc ? 1 : -1
1022
+ const sorted = tasks.map((t, i) => ({ t, i })).sort((a, b) => {
1023
+ const av = col.value(a.t)
1024
+ const bv = col.value(b.t)
1025
+ if (col.key === 'started') {
1026
+ // Not started yet sorts last either way.
1027
+ if (!av !== !bv) return av ? -1 : 1
1028
+ }
1029
+ return (av < bv ? -1 : av > bv ? 1 : 0) * dir || a.i - b.i
1030
+ }).map((x) => x.t)
1031
+ const head = TASK_COLS.map((c) => {
1032
+ const active = c.key === col.key
1033
+ return `<th scope="col" class="sortable-th${active ? ' sortable-th--active' : ''}${c.num ? ' td-num' : ''}" aria-sort="${active ? (state.ui.sortAsc ? 'ascending' : 'descending') : 'none'}"${c.title ? ` title="${esc(c.title)}"` : ''}><button type="button" data-sort="${c.key}">${esc(c.label)}<span class="sort-indicator">${active ? (state.ui.sortAsc ? '▲' : '▼') : '↕'}</span></button></th>`
1034
+ }).join('')
1035
+ const body = sorted.map((t) => {
1036
+ const reason = FAILED.includes(t.display_status) && t.failure_reason ? `<span class="td-reason">${esc(t.failure_reason)}</span>` : ''
1037
+ const review = t.review_verdict === 'skipped' ? '<span class="td-sub">review: no verdict</span>' : ''
1038
+ const changed = ins && t.id in ins.merges ? String(ins.merges[t.id]) : null
1039
+ const dur = taskDuration(t, run)
1040
+ const tip = tokensTip(t)
1041
+ return `<tr>
1042
+ <td class="card-key td-task"><code>${esc(t.id)}</code></td>
1043
+ <td data-label="Agent">${esc(t.agent)}</td>
1044
+ <td data-label="Status">${badge(t.display_status)}${reason}${review}</td>
1045
+ <td data-label="Waits for">${t.depends_on.length ? t.depends_on.map((d) => `<code>${esc(d)}</code>`).join(', ') : '<span class="muted">nothing</span>'}</td>
1046
+ <td data-label="Started">${t.started_at ? timeTag(t.started_at, fmtClock(t.started_at)) : '<span class="muted">not started</span>'}</td>
1047
+ <td data-label="Duration" class="td-num">${dur ?? '—'}</td>
1048
+ <td data-label="Retries" class="td-num">${t.retries}</td>
1049
+ <td data-label="Files changed" class="td-num">${changed ?? '<span class="muted">not merged</span>'}</td>
1050
+ <td data-label="Tokens" class="td-num">${t.total_tokens == null ? nr() : `<span${tip ? ` title="${esc(tip)}"` : ''}>${fmtTokens(t.total_tokens)}</span>`}</td>
1051
+ <td data-label="Cost" class="td-num">${t.cost_usd == null ? nr() : fmtCost(t.cost_usd, t.cost_estimated)}</td>
1052
+ </tr>`
1053
+ }).join('')
1054
+ wrap.innerHTML = `<table class="sessions-table cards task-table"><thead><tr>${head}</tr></thead><tbody>${body}</tbody></table>`
1055
+ }
1056
+
1057
+ // ── dependency view ────────────────────────────────────────────────────────
1058
+
1059
+ /** Depth from `depends_on`: 0 for a task that waits for nothing, else one more than the deepest task it waits for. */
1060
+ function depths(tasks) {
1061
+ const byId = new Map(tasks.map((t) => [t.id, t]))
1062
+ const memo = new Map()
1063
+ const visiting = new Set()
1064
+ const depth = (id) => {
1065
+ if (memo.has(id)) return memo.get(id)
1066
+ if (visiting.has(id)) return 0
1067
+ visiting.add(id)
1068
+ const deps = (byId.get(id)?.depends_on || []).filter((d) => byId.has(d) && d !== id)
1069
+ const d = deps.length ? 1 + Math.max(...deps.map(depth)) : 0
1070
+ visiting.delete(id)
1071
+ memo.set(id, d)
1072
+ return d
1073
+ }
1074
+ for (const t of tasks) depth(t.id)
1075
+ return memo
1076
+ }
1077
+
1078
+ const BLOCKING = new Set([...FAILED, 'skipped', 'interrupted'])
1079
+
1080
+ function renderDeps(run) {
1081
+ const el = $('deps-view')
1082
+ const tasks = run.tasks
1083
+ if (!tasks.length) {
1084
+ el.innerHTML = empty('deps', 'No tasks', 'Tasks and what they wait for appear here.')
1085
+ return
1086
+ }
1087
+ const d = depths(tasks)
1088
+ const cols = []
1089
+ for (const t of tasks) (cols[d.get(t.id)] ||= []).push(t)
1090
+ const known = new Set(tasks.map((t) => t.id))
1091
+ const html = cols.map((list, depth) => {
1092
+ const rows = Math.min(list.length, 8)
1093
+ return `<div class="deps-col">
1094
+ <div class="deps-col__head">${depth === 0 ? 'Waits for nothing' : `Depth ${depth}`}</div>
1095
+ <div class="deps-col__nodes" style="grid-template-rows:repeat(${rows}, auto)">
1096
+ ${list.map((t) => {
1097
+ const missing = t.depends_on.filter((x) => !known.has(x))
1098
+ const tip = [`${t.id} — ${t.display_status}`, `agent: ${t.agent}`, t.depends_on.length ? `waits for: ${t.depends_on.join(', ')}` : 'waits for nothing', missing.length ? `not in this run: ${missing.join(', ')}` : ''].filter(Boolean).join('\n')
1099
+ const dur = taskDuration(t, run)
1100
+ return `<div class="dep-node ${tone(t.display_status)}" data-task="${esc(t.id)}" title="${esc(tip)}" tabindex="0">
1101
+ <span class="dep-node__id">${esc(t.id)}</span>
1102
+ <span class="dep-node__meta"><span>${esc(t.agent)}</span><span>${dur || esc(t.display_status)}</span></span>
1103
+ </div>`
1104
+ }).join('')}
1105
+ </div>
1106
+ </div>`
1107
+ }).join('')
1108
+ el.innerHTML = `<div class="deps-scroll"><div class="deps-canvas"><svg class="deps-edges" aria-hidden="true"></svg>${html}</div></div>
1109
+ ${legend([{ fill: 'fill-done', label: 'done' }, { fill: 'fill-running', label: 'running' }, { fill: 'fill-other', label: 'waiting' }, { fill: 'fill-failed', label: 'failed' }, { fill: 'fill-interrupted', label: 'skipped or interrupted' }])}`
1110
+ requestAnimationFrame(drawEdges)
1111
+ }
1112
+
1113
+ function drawEdges() {
1114
+ const canvas = document.querySelector('.deps-canvas')
1115
+ const svg = canvas && canvas.querySelector('.deps-edges')
1116
+ if (!svg || !state.run) return
1117
+ const base = canvas.getBoundingClientRect()
1118
+ const vertical = getComputedStyle(canvas).flexDirection === 'column'
1119
+ const boxes = new Map([...canvas.querySelectorAll('.dep-node')].map((n) => [n.dataset.task, n.getBoundingClientRect()]))
1120
+ const status = new Map(state.run.tasks.map((t) => [t.id, t.display_status]))
1121
+ const paths = []
1122
+ for (const t of state.run.tasks) {
1123
+ for (const dep of t.depends_on) {
1124
+ const a = boxes.get(dep)
1125
+ const b = boxes.get(t.id)
1126
+ if (!a || !b) continue
1127
+ let p
1128
+ if (vertical) {
1129
+ const x1 = a.left + a.width / 2 - base.left
1130
+ const y1 = a.bottom - base.top
1131
+ const x2 = b.left + b.width / 2 - base.left
1132
+ const y2 = b.top - base.top
1133
+ const my = (y1 + y2) / 2
1134
+ p = `M${x1},${y1} C${x1},${my} ${x2},${my} ${x2},${y2}`
1135
+ } else {
1136
+ const x1 = a.right - base.left
1137
+ const y1 = a.top + a.height / 2 - base.top
1138
+ const x2 = b.left - base.left
1139
+ const y2 = b.top + b.height / 2 - base.top
1140
+ const mx = (x1 + x2) / 2
1141
+ p = `M${x1},${y1} C${mx},${y1} ${mx},${y2} ${x2},${y2}`
1142
+ }
1143
+ paths.push(`<path d="${p}" class="${BLOCKING.has(status.get(dep)) ? 'edge-blocked' : ''}"><title>${esc(`${t.id} waits for ${dep}`)}</title></path>`)
1144
+ }
1145
+ }
1146
+ svg.innerHTML = paths.join('')
1147
+ }
1148
+
1149
+ // ── quality ────────────────────────────────────────────────────────────────
1150
+
1151
+ function renderQuality(run, ins) {
1152
+ const el = $('quality-body')
1153
+ if (!ins || !ins.events_recorded) {
1154
+ el.innerHTML = eventsMissing()
1155
+ return
1156
+ }
1157
+ const s = ins.review_stats
1158
+ const cards = [
1159
+ card('Reviews run', String(s.ran), { mod: 'review', tip: 'Fast and panel reviews that reached a reviewer, every attempt counted' }),
1160
+ card('Passed', String(s.passed), { mod: 'done' }),
1161
+ card('Blocked', String(s.blocked), { mod: 'errors', tip: 'Sent back with the reviewer’s issues' }),
1162
+ card('No verdict', String(s.skipped), { mod: 'input', tip: 'A review was due and reached no verdict. The work went unreviewed; never a pass.' }),
1163
+ card('Auto-passed', String(s.auto_pass), { mod: 'waiting', tip: 'No reviewer read these: a writer’s change, or a small one' }),
1164
+ card('Review tokens', fmtTokens(s.tokens), { mod: 'review' }),
1165
+ ]
1166
+ if (s.disputes) cards.push(card('Disputes', String(s.disputes), { mod: 'errors', tip: 'A panel blocked the task three times' }))
1167
+ const parts = [`<div class="task-summary-cards">${cards.join('')}</div>`]
1168
+ const auto = ins.reviews.filter((r) => r.level === 'auto-pass')
1169
+ if (auto.length) {
1170
+ parts.push(`<h3 class="section-subtitle">Passed without a reviewer (auto-pass)</h3><ul class="plain-list">${auto.map((r) => `<li><code>${esc(r.task_id)}</code> — no reviewer read this change</li>`).join('')}</ul>`)
1171
+ }
1172
+ if (ins.reviews_skipped.length) {
1173
+ parts.push(`<h3 class="section-subtitle">Reviews that reached no verdict</h3><ul class="plain-list">${ins.reviews_skipped.map((r) => `<li><code>${esc(r.task_id)}</code> ${esc(r.level || '')} review${r.attempt ? `, attempt ${r.attempt}` : ''}: ${r.reason ? esc(r.reason) : nr('no reason recorded')}</li>`).join('')}</ul>`)
1174
+ }
1175
+ if (ins.disputes.length) {
1176
+ parts.push(`<h3 class="section-subtitle">Disputes</h3><ul class="plain-list">${ins.disputes.map((d) => `<li><code>${esc(d.task_id)}</code> ${esc(d.dispute_id || '')}: ${esc(d.reason || '')}</li>`).join('')}</ul>`)
1177
+ }
1178
+ if (!s.ran && !s.skipped && !auto.length) parts.push('<p class="reliability-empty">No review recorded in this run.</p>')
1179
+ el.innerHTML = parts.join('')
1180
+ }
1181
+
1182
+ function renderFastReviews(run, ins) {
1183
+ const el = $('reviews-table')
1184
+ if (!ins || !ins.events_recorded) {
1185
+ el.innerHTML = `<div style="padding:0 24px 16px">${eventsMissing()}</div>`
1186
+ return
1187
+ }
1188
+ const rows = ins.reviews.filter((r) => r.level === 'fast')
1189
+ if (!rows.length) {
1190
+ el.innerHTML = `<div style="padding:0 24px 16px">${empty('review', 'No fast reviews', 'No single-reviewer review ran in this run.')}</div>`
1191
+ return
1192
+ }
1193
+ el.innerHTML = `<div class="table-wrap"><table class="sessions-table cards">
1194
+ <thead><tr><th scope="col">Task</th><th scope="col">Attempt</th><th scope="col">Verdict</th><th scope="col">Reviewer model</th><th scope="col" class="td-num">Tokens</th><th scope="col" class="td-num">Feedback</th><th scope="col">When</th></tr></thead>
1195
+ <tbody>${rows.map((r) => `<tr>
1196
+ <td class="card-key td-task"><code>${esc(r.task_id)}</code></td>
1197
+ <td data-label="Attempt">${r.attempt ?? nr('not recorded')}</td>
1198
+ <td data-label="Verdict">${r.verdict ? badge(r.verdict, r.verdict === 'block' ? 'Sent back with the reviewer’s issues' : '') : nr()}</td>
1199
+ <td data-label="Reviewer model">${r.model ? esc(r.model) : nr()}</td>
1200
+ <td data-label="Tokens" class="td-num">${r.tokens == null ? nr() : fmtTokens(r.tokens)}</td>
1201
+ <td data-label="Feedback" class="td-num">${r.feedback_length == null ? nr() : `${r.feedback_length} chars`}</td>
1202
+ <td data-label="When">${timeTag(r.created_at, fmtClock(r.created_at))}</td>
1203
+ </tr>`).join('')}</tbody></table></div>`
1204
+ }
1205
+
1206
+ function renderPanels(ins) {
1207
+ const section = $('panel-section')
1208
+ const rows = ins ? ins.reviews.filter((r) => r.level === 'panel') : []
1209
+ section.hidden = rows.length === 0
1210
+ if (!rows.length) {
1211
+ $('panel-chart').innerHTML = ''
1212
+ return
1213
+ }
1214
+ $('panel-chart').innerHTML = `<div class="panel-grid">${rows.map((r) => {
1215
+ const votes = r.passes == null && r.blocks == null
1216
+ ? nr('votes not recorded')
1217
+ : `${'<span class="panel-item__vote" title="pass">✓</span>'.repeat(r.passes || 0)}${'<span class="panel-item__vote panel-item__vote--block" title="block">✗</span>'.repeat(r.blocks || 0)}`
1218
+ return `<div class="panel-item">
1219
+ <div class="panel-item__header"><span class="panel-item__key" title="${esc(r.task_id)}">${esc(r.task_id)}</span>${badge(r.verdict || 'unknown')}</div>
1220
+ <div class="panel-item__votes">${votes}</div>
1221
+ <div class="panel-item__meta">
1222
+ <span>${r.model ? esc(r.model) : 'model not reported'}</span>
1223
+ <span>${r.tokens == null ? 'tokens not reported' : `${fmtTokens(r.tokens)} tokens`}</span>
1224
+ ${r.attempt ? `<span>attempt ${r.attempt}</span>` : ''}
1225
+ </div>
1226
+ </div>`
1227
+ }).join('')}</div>`
1228
+ }
1229
+
1230
+ // ── reliability, checks, outputs ───────────────────────────────────────────
1231
+
1232
+ function renderReliability(run, ins) {
1233
+ const tasks = run.tasks
1234
+ const done = tasks.filter((t) => t.display_status === 'done').length
1235
+ const dlq = ins ? ins.dlq : null
1236
+ const cards = [
1237
+ card('Retry Queue', dlq == null ? null : String(dlq.length), { mod: dlq && dlq.length ? 'errors' : 'done', missing: 'not recorded', tip: 'Dead-letter queue: tasks that failed for good, with their output' }),
1238
+ card('Total Retries', String(sum(tasks, (t) => t.retries)), { mod: 'running', tip: 'Attempts after a task’s first' }),
1239
+ card('Task Success Rate', tasks.length ? `${Math.round((done / tasks.length) * 100)}%` : null, { mod: 'done', missing: 'no tasks', sub: `${done} of ${plural(tasks.length, 'task')} done` }),
1240
+ ]
1241
+ const parts = [`<div class="task-summary-cards">${cards.join('')}</div>`]
1242
+
1243
+ if (dlq && dlq.length) {
1244
+ parts.push(`<h3 class="section-subtitle">Retry queue</h3><div class="table-wrap"><table class="sessions-table cards">
1245
+ <thead><tr><th scope="col">Task</th><th scope="col">Agent</th><th scope="col">Failure</th><th scope="col" class="td-num">Attempts</th><th scope="col" class="td-num">Tokens spent</th><th scope="col">Resolved</th></tr></thead>
1246
+ <tbody>${dlq.map((d) => {
1247
+ const key = `dlq:${d.id}`
1248
+ const open = state.ui.open.has(key)
1249
+ return `<tr>
1250
+ <td class="card-key td-task"><code>${esc(d.task_id)}</code>${d.error_tail ? toggle(key, 'Output tail') : ''}${open && d.error_tail ? `<pre class="output-tail">${esc(d.error_tail)}</pre>` : ''}</td>
1251
+ <td data-label="Agent">${d.agent ? esc(d.agent) : nr()}</td>
1252
+ <td data-label="Failure">${d.failure_type ? esc(d.failure_type) : nr()}</td>
1253
+ <td data-label="Attempts" class="td-num">${d.attempts ?? nr()}</td>
1254
+ <td data-label="Tokens spent" class="td-num">${d.tokens_spent == null ? nr() : fmtTokens(d.tokens_spent)}</td>
1255
+ <td data-label="Resolved">${d.resolved ? `yes${d.resolution ? ` — ${esc(d.resolution)}` : ''}` : 'no'}</td>
1256
+ </tr>`
1257
+ }).join('')}</tbody></table></div>`)
1258
+ } else if (dlq) {
1259
+ parts.push('<p class="reliability-empty">The retry queue is empty: no task in this run failed for good.</p>')
1260
+ }
1261
+
1262
+ if (ins && ins.retries.length) {
1263
+ parts.push(`<h3 class="section-subtitle">Retries</h3><div class="table-wrap"><table class="sessions-table cards">
1264
+ <thead><tr><th scope="col">When</th><th scope="col">Task</th><th scope="col">Next attempt</th><th scope="col">After</th><th scope="col">Why</th></tr></thead>
1265
+ <tbody>${ins.retries.map((r) => `<tr>
1266
+ <td data-label="When">${timeTag(r.created_at, fmtClock(r.created_at))}</td>
1267
+ <td class="card-key td-task"><code>${esc(r.task_id)}</code></td>
1268
+ <td data-label="Next attempt">${r.attempt ?? nr('not recorded')}</td>
1269
+ <td data-label="After">${r.previous_status ? badge(r.previous_status) : nr()}</td>
1270
+ <td data-label="Why" class="card-wide">${r.reason ? esc(r.reason) : '<span class="muted">reset by convoy resume</span>'}</td>
1271
+ </tr>`).join('')}</tbody></table></div>`)
1272
+ }
1273
+
1274
+ const kinds = [
1275
+ ['failed', 'Failed'], ['gate-failed', 'Gate failed'], ['timed-out', 'Timed out'], ['review-blocked', 'Blocked by review'],
1276
+ ['hook-failed', 'Lifecycle script failed'], ['disputed', 'Disputed'], ['skipped', 'Skipped'], ['interrupted', 'Interrupted'],
1277
+ ].map(([key, label]) => ({ label, n: tasks.filter((t) => t.display_status === key).length, fill: key === 'skipped' || key === 'interrupted' ? 'fill-interrupted' : 'fill-failed' })).filter((k) => k.n > 0)
1278
+ parts.push('<h3 class="section-subtitle">Error overview</h3>')
1279
+ if (!kinds.length) {
1280
+ parts.push('<p class="reliability-empty">✓ No task in this run failed, was skipped or was left interrupted.</p>')
1281
+ } else {
1282
+ parts.push(simpleBars(kinds, 'fill-failed'))
1283
+ const reasons = tasks.filter((t) => t.failure_reason)
1284
+ if (reasons.length) parts.push(`<ul class="plain-list" style="margin-top:12px">${reasons.map((t) => `<li><code>${esc(t.id)}</code>: ${esc(t.failure_reason)}</li>`).join('')}</ul>`)
1285
+ }
1286
+ $('reliability-body').innerHTML = parts.join('')
1287
+ }
1288
+
1289
+ function checkWhen(c) {
1290
+ if (c.scope === 'task') return c.attempt ? `attempt ${c.attempt}` : nr('not recorded')
1291
+ if (c.round == null) return nr('not recorded')
1292
+ return c.round === 1 ? 'round 1' : `round ${c.round} · after fix ${c.round - 1}`
1293
+ }
1294
+
1295
+ function renderChecks(ins) {
1296
+ const el = $('checks-body')
1297
+ if (!ins || !ins.events_recorded) {
1298
+ el.innerHTML = eventsMissing()
1299
+ return
1300
+ }
1301
+ const s = ins.check_stats
1302
+ const parts = [`<div class="task-summary-cards">${[
1303
+ card('Checks run', String(s.ran), { mod: 'done', sub: `${s.gates.passed + s.gates.failed} spec gates · ${s.built_in.passed + s.built_in.failed} built-in` }),
1304
+ card('Passed', String(s.passed), { mod: 'done' }),
1305
+ card('Failed', String(s.failed), { mod: s.failed ? 'errors' : 'done' }),
1306
+ card('Warnings', String(s.warnings), { mod: 'input', tip: 'Contract and file-partition violations: recorded, and the work kept' }),
1307
+ ].join('')}</div>`]
1308
+ if (ins.checks.length) {
1309
+ parts.push(`<div class="table-wrap"><table class="sessions-table cards">
1310
+ <thead><tr><th scope="col">When</th><th scope="col">Check</th><th scope="col">Where</th><th scope="col">Attempt</th><th scope="col">Result</th><th scope="col" class="td-num">Exit code</th></tr></thead>
1311
+ <tbody>${ins.checks.map((c) => {
1312
+ const key = `check:${c.event_id}`
1313
+ const open = state.ui.open.has(key)
1314
+ const result = c.passed == null ? nr() : badge(c.passed ? 'passed' : 'failed', '')
1315
+ return `<tr>
1316
+ <td data-label="When">${timeTag(c.created_at, fmtClock(c.created_at))}</td>
1317
+ <td class="card-key td-task"><code>${esc(c.name)}</code> <span class="kind-badge">${c.kind === 'built-in' ? 'built-in' : 'spec gate'}</span>${c.level ? `<span class="td-sub">level ${esc(c.level)}</span>` : ''}${c.output ? toggle(key, 'Output') : ''}${open && c.output ? `<pre class="output-tail">${esc(c.output)}</pre>` : ''}</td>
1318
+ <td data-label="Where">${c.scope === 'task' ? `task <code>${esc(c.task_id)}</code>` : 'merged result'}</td>
1319
+ <td data-label="Attempt">${checkWhen(c)}</td>
1320
+ <td data-label="Result">${result}</td>
1321
+ <td data-label="Exit code" class="td-num">${c.exit_code == null ? '<span class="muted">—</span>' : c.exit_code}</td>
1322
+ </tr>`
1323
+ }).join('')}</tbody></table></div>`)
1324
+ } else {
1325
+ parts.push('<p class="reliability-empty">No check ran in this run. Checks are the spec’s <code>gates</code>, a task’s own <code>gates</code>, and the built-in gates a spec turns on.</p>')
1326
+ }
1327
+ if (ins.warnings.length) {
1328
+ parts.push(`<h3 class="section-subtitle">Warnings (the work was kept)</h3><ul class="plain-list">${ins.warnings.map((w) => `<li>${timeTag(w.created_at, fmtClock(w.created_at))} <code>${esc(w.task_id)}</code> <span class="kind-badge">${esc(w.type.replace(/_/g, ' '))}</span> ${w.items.length ? esc(w.items.join(', ')) : ''}</li>`).join('')}</ul>`)
1329
+ }
1330
+ if (ins.secrets_prevented.length) {
1331
+ parts.push(`<div class="secret-leak-banner"><span aria-hidden="true">⚠</span><div><strong>${plural(ins.secrets_prevented.length, 'secret')} masked or withheld.</strong> ${ins.secrets_prevented.map((x) => `${esc(x.context || 'unknown context')}${x.task_id ? ` (<code>${esc(x.task_id)}</code>)` : ''}`).join(', ')}</div></div>`)
1332
+ }
1333
+ el.innerHTML = parts.join('')
1334
+ }
1335
+
1336
+ function renderOutputs(run, ins) {
1337
+ const el = $('outputs-body')
1338
+ const merges = ins ? ins.merges : {}
1339
+ const merged = Object.keys(merges).length
1340
+ const files = Object.values(merges).reduce((s, n) => s + n, 0)
1341
+ const artifacts = ins ? ins.artifacts : null
1342
+ const cards = [
1343
+ card('Tasks merged', ins && ins.events_recorded ? String(merged) : null, { mod: 'done', missing: 'not recorded', tip: 'Tasks whose commit merged into the run’s branch (task_merged)' }),
1344
+ card('Files changed', ins && ins.events_recorded ? String(files) : null, { mod: 'running', missing: 'not recorded', tip: 'Summed over merged tasks, as each task_merged recorded it' }),
1345
+ card('Artifacts', artifacts == null ? null : String(artifacts.length), { mod: 'waiting', missing: 'not recorded' }),
1346
+ ]
1347
+ const parts = [`<div class="task-summary-cards">${cards.join('')}</div>`]
1348
+ if (artifacts && artifacts.length) {
1349
+ parts.push(`<div class="table-wrap"><table class="sessions-table cards">
1350
+ <thead><tr><th scope="col">Artifact</th><th scope="col">Type</th><th scope="col">Task</th><th scope="col">Recorded</th></tr></thead>
1351
+ <tbody>${artifacts.map((a) => `<tr>
1352
+ <td class="card-key td-task"><code>${esc(a.name)}</code>${a.type !== 'file' && a.size_bytes != null ? `<span class="td-sub">${a.size_bytes.toLocaleString('en-US')} bytes</span>` : ''}</td>
1353
+ <td data-label="Type"><span class="kind-badge" title="${esc(a.type === 'file' ? 'A path from the task’s files' : 'What the agent answered')}">${esc(a.type)}</span></td>
1354
+ <td data-label="Task">${a.task_id ? `<code>${esc(a.task_id)}</code>` : nr()}</td>
1355
+ <td data-label="Recorded">${timeTag(a.created_at, fmtClock(a.created_at))}</td>
1356
+ </tr>`).join('')}</tbody></table></div>`)
1357
+ } else if (artifacts) {
1358
+ parts.push('<p class="reliability-empty">No artifacts recorded in this run.</p>')
1359
+ }
1360
+ el.innerHTML = parts.join('')
1361
+ }
1362
+
1363
+ // ── event timeline ─────────────────────────────────────────────────────────
1364
+
1365
+ function eventSummary(e) {
1366
+ const d = e.data
1367
+ if (d == null) return ''
1368
+ if (typeof d !== 'object') return esc(String(d).slice(0, 200))
1369
+ return Object.entries(d)
1370
+ .filter(([k, v]) => !(k === 'convoy_id' && v === state.selected) && !(k === 'task_id' && v === e.task_id) && v !== null && v !== '')
1371
+ .slice(0, 6)
1372
+ .map(([k, v]) => {
1373
+ let text = typeof v === 'object' ? (Array.isArray(v) && v.every((x) => typeof x !== 'object') ? v.join(', ') : JSON.stringify(v)) : String(v)
1374
+ if (text.length > 90) text = `${text.slice(0, 87)}…`
1375
+ return `${esc(k)}=<b>${esc(text)}</b>`
1376
+ })
1377
+ .join(' ')
1378
+ }
1379
+
1380
+ function eventMatches(e) {
1381
+ if (state.ui.filter === 'all') return true
1382
+ if (state.ui.filter === 'problem') return e.problem
1383
+ return e.category === state.ui.filter
1384
+ }
1385
+
1386
+ function renderTimeline() {
1387
+ const filtersEl = $('event-timeline-filters')
1388
+ const listEl = $('event-timeline-list')
1389
+ const moreEl = $('event-timeline-more')
1390
+ if (!state.run) return
1391
+ if (state.insights && !state.insights.events_recorded) {
1392
+ filtersEl.innerHTML = ''
1393
+ listEl.innerHTML = eventsMissing()
1394
+ moreEl.innerHTML = ''
1395
+ return
1396
+ }
1397
+ const counts = { all: state.events.length, problem: 0 }
1398
+ for (const e of state.events) {
1399
+ counts[e.category] = (counts[e.category] || 0) + 1
1400
+ if (e.problem) counts.problem++
1401
+ }
1402
+ const chip = (key, label, title) => `<button type="button" class="timeline-filter-chip" data-filter="${esc(key)}" aria-pressed="${state.ui.filter === key}" title="${esc(title)}">${esc(label)} <span class="timeline-filter-chip__count">${counts[key] || 0}</span></button>`
1403
+ const chips = [chip('all', 'All', 'Every event loaded'), chip('problem', 'Problems', 'Failures, violations, conflicts, retries, interrupts, failed checks, blocked or unfinished reviews')]
1404
+ for (const [key, types] of Object.entries(state.categories)) {
1405
+ if ((types && types.length) || counts[key]) chips.push(chip(key, CATEGORY_LABELS[key] || key, (types || []).join(', ')))
1406
+ }
1407
+ filtersEl.innerHTML = chips.join('')
1408
+
1409
+ const old = listEl.querySelector('.event-timeline-list')
1410
+ const scrollTop = old ? old.scrollTop : 0
1411
+ const atBottom = old ? old.scrollHeight - old.scrollTop - old.clientHeight < 40 : false
1412
+ const shown = state.events.filter(eventMatches)
1413
+ if (!shown.length) {
1414
+ listEl.innerHTML = empty('timeline', state.events.length ? 'No events in this group' : 'No events yet', state.events.length ? 'Pick another filter.' : 'Events appear here as the run writes them.')
1415
+ } else {
1416
+ listEl.innerHTML = `<div class="event-timeline-list">${shown.map((e) => {
1417
+ const open = state.ui.eventOpen.has(e.id)
1418
+ return `<div class="event-timeline-row${e.problem ? ' event-timeline-row--problem' : ''}">
1419
+ <button type="button" class="event-timeline-row__main" data-event="${e.id}" aria-expanded="${open}">
1420
+ <span class="event-timeline-ts" title="${esc(e.created_at)}">${esc(fmtWhenSec(e.created_at))}</span>
1421
+ <span class="event-type-badge cat-${esc(e.category)}">${esc(e.type)}</span>
1422
+ ${e.task_id ? `<span class="event-timeline-context">${esc(e.task_id)}</span>` : ''}
1423
+ ${e.problem ? '<span class="status-badge tone-failed">problem</span>' : ''}
1424
+ <span class="event-timeline-summary">${eventSummary(e)}</span>
1425
+ </button>
1426
+ ${open ? `<div class="event-timeline-detail"><pre class="event-timeline-json">${esc(JSON.stringify(e.data, null, 2))}</pre></div>` : ''}
1427
+ </div>`
1428
+ }).join('')}</div>`
1429
+ const list = listEl.querySelector('.event-timeline-list')
1430
+ list.scrollTop = atBottom && state.run.alive ? list.scrollHeight : scrollTop
1431
+ }
1432
+ const parts = [`${plural(state.events.length, 'event')} loaded`]
1433
+ if (state.more) parts.push(`<button type="button" class="dash-btn dash-btn--ghost" id="event-more-btn"${state.eventsLoading ? ' disabled' : ''}>${state.eventsLoading ? 'Loading…' : `Load ${EVENT_PAGE} more`}</button>`)
1434
+ else if (LIVE && state.run.alive) parts.push('new events appear as they are written')
1435
+ else parts.push('that is every event this run recorded')
1436
+ moreEl.innerHTML = parts.join(' · ')
1437
+ }
1438
+
1439
+ // ── execution log ──────────────────────────────────────────────────────────
1440
+
1441
+ const EXEC_ICON = { 'tone-done': '✓', 'tone-failed': '✗', 'tone-running': '▶', 'tone-warn': '‖', 'tone-muted': '○', 'tone-review': '○' }
1442
+
1443
+ function renderExecLog(run, ins) {
1444
+ const el = $('execution-log')
1445
+ if (!run.tasks.length) {
1446
+ el.innerHTML = empty('log', 'No tasks', 'Each task appears here as it starts.')
1447
+ return
1448
+ }
1449
+ const started = run.tasks.filter((t) => t.started_at).sort((a, b) => String(a.started_at).localeCompare(String(b.started_at)))
1450
+ const waiting = run.tasks.filter((t) => !t.started_at)
1451
+ const all = started.concat(waiting)
1452
+ const shown = all.slice(0, state.ui.execLimit)
1453
+ const tiers = ins ? ins.task_tiers : {}
1454
+ el.innerHTML = `<div class="exec-log">${shown.map((t) => {
1455
+ const tn = tone(t.display_status)
1456
+ const dur = taskDuration(t, run)
1457
+ const starts = ins && ins.starts[t.id] ? ins.starts[t.id] : 0
1458
+ const retries = ins ? ins.retries.filter((r) => r.task_id === t.id) : []
1459
+ const kills = ins ? ins.interruptions.filter((i) => i.type === 'worker_killed' && i.task_id === t.id) : []
1460
+ const key = `tail:${t.id}`
1461
+ const open = state.ui.open.has(key)
1462
+ const meta = [
1463
+ t.started_at ? `Started <b>${timeTag(t.started_at, fmtClock(t.started_at))}</b>` : 'Not started',
1464
+ t.finished_at ? `Finished <b>${timeTag(t.finished_at, fmtClock(t.finished_at))}</b>` : '',
1465
+ dur ? `Duration <b>${dur}</b>` : '',
1466
+ `Model <b>${t.model ? esc(t.model) : nr()}</b>`,
1467
+ starts > 1 ? `<b>${starts}</b> starts` : '',
1468
+ t.retries ? `<b>${t.retries}</b> ${t.retries === 1 ? 'retry' : 'retries'}` : '',
1469
+ t.total_tokens != null ? `Tokens <b>${fmtTokens(t.total_tokens)}</b>` : '',
1470
+ t.cost_usd != null ? `Cost <b>${fmtCost(t.cost_usd, t.cost_estimated)}</b>` : '',
1471
+ ].filter(Boolean)
1472
+ const notes = [
1473
+ ...kills.map((k) => `<div class="exec-step__note">Stopped by an interrupt at ${timeTag(k.created_at, fmtClock(k.created_at))}; started again on resume.</div>`),
1474
+ ...retries.map((r) => `<div class="exec-step__note">Retried${r.attempt ? ` as attempt ${r.attempt}` : ''} at ${timeTag(r.created_at, fmtClock(r.created_at))} after <b>${esc(r.previous_status || 'a failure')}</b>${r.reason ? `: ${esc(r.reason)}` : ''}</div>`),
1475
+ ]
1476
+ const failure = FAILED.includes(t.display_status)
1477
+ ? `<div class="td-reason">${t.failure_reason ? esc(t.failure_reason) : 'No reason recorded'}</div>${t.error_tail ? toggle(key, 'Output tail') : ''}${open && t.error_tail ? `<pre class="output-tail">${esc(t.error_tail)}</pre>` : ''}`
1478
+ : ''
1479
+ return `<div class="exec-step" id="exec-${esc(t.id)}">
1480
+ <div class="exec-step__indicator"><div class="exec-step__dot ${tn}">${EXEC_ICON[tn] || '○'}</div></div>
1481
+ <div class="exec-step__content">
1482
+ <div class="exec-step__header"><span class="exec-step__agent">${esc(t.agent)}</span>${badge(t.display_status)}${tiers[t.id] ? `<span class="kind-badge" title="Tier from the task's delegation event">${esc(tiers[t.id])}</span>` : ''}</div>
1483
+ <div class="exec-step__task"><code>${esc(t.id)}</code>${t.depends_on.length ? ` <span class="muted">waits for ${t.depends_on.map(esc).join(', ')}</span>` : ''}</div>
1484
+ <div class="exec-step__meta">${meta.map((m) => `<span>${m}</span>`).join('')}</div>
1485
+ ${notes.join('')}${failure}
1486
+ </div>
1487
+ </div>`
1488
+ }).join('')}</div>${all.length > shown.length ? `<div style="text-align:center;padding-top:12px"><button class="dash-btn dash-btn--ghost" type="button" id="exec-more-btn">Show all ${all.length} tasks</button></div>` : ''}`
1489
+ }
1490
+
1491
+ function renderDetailSessions(ins) {
1492
+ const el = $('detail-sessions-table')
1493
+ if (!ins || !ins.events_recorded) {
1494
+ el.innerHTML = `<div style="padding:0 24px 16px">${eventsMissing()}</div>`
1495
+ return
1496
+ }
1497
+ if (!ins.sessions.length) {
1498
+ el.innerHTML = `<div style="padding:0 24px 16px">${empty('table', 'No sessions yet', 'The engine writes one when each task finishes.')}</div>`
1499
+ return
1500
+ }
1501
+ el.innerHTML = sessionsTable(ins.sessions, false)
1502
+ }
1503
+
1504
+ // ── export ─────────────────────────────────────────────────────────────────
1505
+
1506
+ function exportJson() {
1507
+ const exportedAt = new Date().toISOString()
1508
+ const data = state.view === 'detail' && state.run
1509
+ ? { exported_at: exportedAt, source: LIVE ? 'live' : 'snapshot', project: state.project, run: state.run, insights: state.insights, events: state.events, events_complete: !state.more }
1510
+ : { exported_at: exportedAt, source: LIVE ? 'live' : 'snapshot', project: state.project, overview: state.overview, runs: state.runs, sessions: state.sessions }
1511
+ const name = state.view === 'detail' && state.run ? `opencastle-${fileId(state.run.id)}.json` : `opencastle-${fileId(state.project || 'dashboard')}-overview.json`
1512
+ const url = URL.createObjectURL(new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' }))
1513
+ const a = document.createElement('a')
1514
+ a.href = url
1515
+ a.download = name
1516
+ document.body.appendChild(a)
1517
+ a.click()
1518
+ a.remove()
1519
+ setTimeout(() => URL.revokeObjectURL(url), 1000)
1520
+ }
1521
+
1522
+ // ── wiring ─────────────────────────────────────────────────────────────────
1523
+
1524
+ function onListFilter() {
1525
+ state.ui.listPage = 1
1526
+ renderConvoyList()
1527
+ }
1528
+
1529
+ function wire() {
1530
+ $('export-btn').addEventListener('click', exportJson)
1531
+ $('run-picker').addEventListener('change', (e) => {
1532
+ state.follow = false
1533
+ const id = e.target.value
1534
+ if (id) location.hash = `run=${encodeURIComponent(id)}`
1535
+ else goHome()
1536
+ })
1537
+ $('breadcrumbs-home').addEventListener('click', (e) => {
1538
+ e.preventDefault()
1539
+ goHome()
1540
+ })
1541
+ for (const id of ['cl-filter-search', 'cl-filter-status', 'cl-filter-from', 'cl-filter-to']) {
1542
+ $(id).addEventListener(id === 'cl-filter-search' ? 'input' : 'change', onListFilter)
1543
+ }
1544
+ $('cl-filter-reset').addEventListener('click', () => {
1545
+ for (const id of ['cl-filter-search', 'cl-filter-status', 'cl-filter-from', 'cl-filter-to']) $(id).value = ''
1546
+ onListFilter()
1547
+ })
1548
+ $('convoy-list-table-wrap').addEventListener('click', (e) => {
1549
+ const group = e.target.closest('tr[data-pipeline-group-id]')
1550
+ if (group) {
1551
+ const id = group.dataset.pipelineGroupId
1552
+ if (state.ui.chainOpen.has(id)) state.ui.chainOpen.delete(id)
1553
+ else state.ui.chainOpen.add(id)
1554
+ renderConvoyList()
1555
+ return
1556
+ }
1557
+ const row = e.target.closest('tr[data-run-id]')
1558
+ if (!row) return
1559
+ state.follow = false
1560
+ if (e.target.closest('a')) return
1561
+ location.hash = `run=${encodeURIComponent(row.dataset.runId)}`
1562
+ })
1563
+ $('convoy-list-pagination').addEventListener('click', (e) => {
1564
+ const btn = e.target.closest('button[data-page]')
1565
+ if (!btn || btn.disabled) return
1566
+ state.ui.listPage = Number(btn.dataset.page)
1567
+ renderConvoyList()
1568
+ })
1569
+ document.addEventListener('click', (e) => {
1570
+ if (e.target.closest('a[href^="#run="]')) state.follow = false
1571
+ })
1572
+ $('view-convoy-detail').addEventListener('click', (e) => {
1573
+ const sortBtn = e.target.closest('button[data-sort]')
1574
+ if (sortBtn) {
1575
+ const key = sortBtn.dataset.sort
1576
+ if (state.ui.sortCol === key) state.ui.sortAsc = !state.ui.sortAsc
1577
+ else Object.assign(state.ui, { sortCol: key, sortAsc: true })
1578
+ renderTasks(state.run, state.insights)
1579
+ return
1580
+ }
1581
+ const tog = e.target.closest('button[data-toggle]')
1582
+ if (tog) {
1583
+ const key = tog.dataset.toggle
1584
+ if (state.ui.open.has(key)) state.ui.open.delete(key)
1585
+ else state.ui.open.add(key)
1586
+ renderDetail()
1587
+ return
1588
+ }
1589
+ const chip = e.target.closest('button[data-filter]')
1590
+ if (chip) {
1591
+ state.ui.filter = chip.dataset.filter
1592
+ renderTimeline()
1593
+ return
1594
+ }
1595
+ const ev = e.target.closest('button[data-event]')
1596
+ if (ev) {
1597
+ const id = Number(ev.dataset.event)
1598
+ if (state.ui.eventOpen.has(id)) state.ui.eventOpen.delete(id)
1599
+ else state.ui.eventOpen.add(id)
1600
+ renderTimeline()
1601
+ return
1602
+ }
1603
+ if (e.target.closest('#event-more-btn')) return void loadMoreEvents()
1604
+ if (e.target.closest('#exec-more-btn')) {
1605
+ state.ui.execLimit = Infinity
1606
+ renderExecLog(state.run, state.insights)
1607
+ }
1608
+ })
1609
+ window.addEventListener('hashchange', route)
1610
+ window.addEventListener('popstate', route)
1611
+ let resizeTimer = null
1612
+ window.addEventListener('resize', () => {
1613
+ clearTimeout(resizeTimer)
1614
+ resizeTimer = setTimeout(drawEdges, 100)
1615
+ })
1616
+ // Elapsed times of live runs and tasks tick every second between reads.
1617
+ setInterval(() => {
1618
+ document.querySelectorAll('[data-elapsed-since]').forEach((el) => {
1619
+ el.textContent = fmtDuration(since(el.dataset.elapsedSince)) || '—'
1620
+ })
1621
+ }, 1000)
1622
+ initSidebarNav()
1623
+ }
1624
+
1625
+ function activate(id) {
1626
+ for (const link of document.querySelectorAll('.dash-sidebar__link')) link.classList.toggle('dash-sidebar__link--active', link.dataset.section === id)
1627
+ }
1628
+
1629
+ /** At the top of the page the first section is the current one, whatever crosses the band below it. */
1630
+ function activateFirstSection() {
1631
+ const first = [...document.querySelectorAll('.dash-sidebar__link')].find((l) => !l.closest('li').hidden)
1632
+ if (first) activate(first.dataset.section)
1633
+ }
1634
+
1635
+ function initSidebarNav() {
1636
+ const links = [...document.querySelectorAll('.dash-sidebar__link')]
1637
+ const observer = new IntersectionObserver((entries) => {
1638
+ if (window.scrollY < 40) return
1639
+ for (const entry of entries) if (entry.isIntersecting) activate(entry.target.id)
1640
+ }, { rootMargin: '-20% 0px -70% 0px', threshold: 0 })
1641
+ window.addEventListener('scroll', () => {
1642
+ if (window.scrollY < 40) activateFirstSection()
1643
+ }, { passive: true })
1644
+ document.querySelectorAll('[data-nav-section]').forEach((s) => observer.observe(s))
1645
+ for (const link of links) {
1646
+ link.addEventListener('click', (e) => {
1647
+ e.preventDefault()
1648
+ const target = $(link.dataset.section)
1649
+ if (target) target.scrollIntoView({ behavior: 'smooth', block: 'start' })
1650
+ })
1651
+ }
1652
+ }
1653
+
1654
+ async function boot() {
1655
+ renderFooter()
1656
+ try {
1657
+ await loadRuns()
1658
+ } catch (err) {
1659
+ state.listError = `Could not read runs: ${err.message}`
1660
+ renderNotices()
1661
+ renderHeader()
1662
+ if (LIVE) setTimeout(boot, SLOW_MS)
1663
+ return
1664
+ }
1665
+ renderHeader()
1666
+ renderPicker()
1667
+ loadSessions()
1668
+ // An old link with ?convoy=<id> opens that run.
1669
+ const legacy = new URLSearchParams(location.search).get('convoy')
1670
+ if (!hashRun() && legacy && legacy !== 'active') history.replaceState(null, '', `${location.pathname}#run=${encodeURIComponent(legacy)}`)
1671
+ const picked = hashRun()
1672
+ const working = LIVE ? state.runs.find((r) => r.alive) : null
1673
+ if (picked) {
1674
+ state.follow = false
1675
+ await openRun(picked, false)
1676
+ } else if (working) {
1677
+ followRun(working.id)
1678
+ } else {
1679
+ showHome()
1680
+ }
1681
+ if (LIVE) setInterval(slowTick, SLOW_MS)
1682
+ }
1683
+
1684
+ wire()
1685
+ setViewVisibility('home')
1686
+ boot()
1687
+ })()