opencastle 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (577) hide show
  1. package/README.md +102 -131
  2. package/bin/cli.mjs +20 -10
  3. package/dist/cli/adapters/claude-code.d.ts +5 -3
  4. package/dist/cli/adapters/claude-code.d.ts.map +1 -1
  5. package/dist/cli/adapters/claude-code.js +7 -3
  6. package/dist/cli/adapters/claude-code.js.map +1 -1
  7. package/dist/cli/adapters/single-file-base.d.ts +18 -0
  8. package/dist/cli/adapters/single-file-base.d.ts.map +1 -1
  9. package/dist/cli/adapters/single-file-base.js +29 -4
  10. package/dist/cli/adapters/single-file-base.js.map +1 -1
  11. package/dist/cli/agent-plugin.test.js +12 -0
  12. package/dist/cli/agent-plugin.test.js.map +1 -1
  13. package/dist/cli/agent-roster.test.js +0 -48
  14. package/dist/cli/agent-roster.test.js.map +1 -1
  15. package/dist/cli/bootstrap.d.ts.map +1 -1
  16. package/dist/cli/bootstrap.js +20 -0
  17. package/dist/cli/bootstrap.js.map +1 -1
  18. package/dist/cli/boundary.test.js +9 -7
  19. package/dist/cli/boundary.test.js.map +1 -1
  20. package/dist/cli/ci.d.ts.map +1 -1
  21. package/dist/cli/ci.js +6 -4
  22. package/dist/cli/ci.js.map +1 -1
  23. package/dist/cli/command-namespace.test.js +33 -0
  24. package/dist/cli/command-namespace.test.js.map +1 -1
  25. package/dist/cli/convoy/artifacts.d.ts +9 -2
  26. package/dist/cli/convoy/artifacts.d.ts.map +1 -1
  27. package/dist/cli/convoy/artifacts.js +13 -10
  28. package/dist/cli/convoy/artifacts.js.map +1 -1
  29. package/dist/cli/convoy/artifacts.test.js +4 -2
  30. package/dist/cli/convoy/artifacts.test.js.map +1 -1
  31. package/dist/cli/convoy/engine.d.ts +53 -23
  32. package/dist/cli/convoy/engine.d.ts.map +1 -1
  33. package/dist/cli/convoy/engine.git.test.d.ts +2 -0
  34. package/dist/cli/convoy/engine.git.test.d.ts.map +1 -0
  35. package/dist/cli/convoy/engine.git.test.js +435 -0
  36. package/dist/cli/convoy/engine.git.test.js.map +1 -0
  37. package/dist/cli/convoy/engine.js +1746 -2305
  38. package/dist/cli/convoy/engine.js.map +1 -1
  39. package/dist/cli/convoy/engine.test.js +698 -678
  40. package/dist/cli/convoy/engine.test.js.map +1 -1
  41. package/dist/cli/convoy/event-schemas.d.ts +2 -0
  42. package/dist/cli/convoy/event-schemas.d.ts.map +1 -1
  43. package/dist/cli/convoy/event-schemas.js +59 -57
  44. package/dist/cli/convoy/event-schemas.js.map +1 -1
  45. package/dist/cli/convoy/events.d.ts +4 -1
  46. package/dist/cli/convoy/events.d.ts.map +1 -1
  47. package/dist/cli/convoy/events.js +69 -84
  48. package/dist/cli/convoy/events.js.map +1 -1
  49. package/dist/cli/convoy/events.test.js +50 -9
  50. package/dist/cli/convoy/events.test.js.map +1 -1
  51. package/dist/cli/convoy/gates.d.ts +9 -4
  52. package/dist/cli/convoy/gates.d.ts.map +1 -1
  53. package/dist/cli/convoy/gates.js +29 -14
  54. package/dist/cli/convoy/gates.js.map +1 -1
  55. package/dist/cli/convoy/isolation.d.ts +32 -6
  56. package/dist/cli/convoy/isolation.d.ts.map +1 -1
  57. package/dist/cli/convoy/isolation.js +72 -34
  58. package/dist/cli/convoy/isolation.js.map +1 -1
  59. package/dist/cli/convoy/isolation.test.js +66 -42
  60. package/dist/cli/convoy/isolation.test.js.map +1 -1
  61. package/dist/cli/convoy/lock.d.ts.map +1 -1
  62. package/dist/cli/convoy/lock.js +25 -10
  63. package/dist/cli/convoy/lock.js.map +1 -1
  64. package/dist/cli/convoy/lock.test.js +12 -0
  65. package/dist/cli/convoy/lock.test.js.map +1 -1
  66. package/dist/cli/convoy/merge.d.ts +21 -4
  67. package/dist/cli/convoy/merge.d.ts.map +1 -1
  68. package/dist/cli/convoy/merge.js +69 -53
  69. package/dist/cli/convoy/merge.js.map +1 -1
  70. package/dist/cli/convoy/merge.test.js +23 -1
  71. package/dist/cli/convoy/merge.test.js.map +1 -1
  72. package/dist/cli/convoy/progress.d.ts +35 -0
  73. package/dist/cli/convoy/progress.d.ts.map +1 -0
  74. package/dist/cli/convoy/progress.js +103 -0
  75. package/dist/cli/convoy/progress.js.map +1 -0
  76. package/dist/cli/convoy/progress.test.d.ts +2 -0
  77. package/dist/cli/convoy/progress.test.d.ts.map +1 -0
  78. package/dist/cli/convoy/progress.test.js +53 -0
  79. package/dist/cli/convoy/progress.test.js.map +1 -0
  80. package/dist/cli/convoy/read-model.d.ts +468 -0
  81. package/dist/cli/convoy/read-model.d.ts.map +1 -0
  82. package/dist/cli/convoy/read-model.js +1132 -0
  83. package/dist/cli/convoy/read-model.js.map +1 -0
  84. package/dist/cli/convoy/read-model.test.d.ts +2 -0
  85. package/dist/cli/convoy/read-model.test.d.ts.map +1 -0
  86. package/dist/cli/convoy/read-model.test.js +609 -0
  87. package/dist/cli/convoy/read-model.test.js.map +1 -0
  88. package/dist/cli/convoy/redact.d.ts +34 -0
  89. package/dist/cli/convoy/redact.d.ts.map +1 -0
  90. package/dist/cli/convoy/redact.js +66 -0
  91. package/dist/cli/convoy/redact.js.map +1 -0
  92. package/dist/cli/convoy/redact.test.d.ts +2 -0
  93. package/dist/cli/convoy/redact.test.d.ts.map +1 -0
  94. package/dist/cli/convoy/redact.test.js +43 -0
  95. package/dist/cli/convoy/redact.test.js.map +1 -0
  96. package/dist/cli/convoy/reviewer.d.ts +65 -0
  97. package/dist/cli/convoy/reviewer.d.ts.map +1 -0
  98. package/dist/cli/convoy/reviewer.js +141 -0
  99. package/dist/cli/convoy/reviewer.js.map +1 -0
  100. package/dist/cli/convoy/reviewer.test.d.ts +2 -0
  101. package/dist/cli/convoy/reviewer.test.d.ts.map +1 -0
  102. package/dist/cli/convoy/reviewer.test.js +96 -0
  103. package/dist/cli/convoy/reviewer.test.js.map +1 -0
  104. package/dist/cli/convoy/schedule.d.ts +30 -0
  105. package/dist/cli/convoy/schedule.d.ts.map +1 -0
  106. package/dist/cli/convoy/schedule.js +111 -0
  107. package/dist/cli/convoy/schedule.js.map +1 -0
  108. package/dist/cli/convoy/schedule.test.d.ts +2 -0
  109. package/dist/cli/convoy/schedule.test.d.ts.map +1 -0
  110. package/dist/cli/convoy/schedule.test.js +45 -0
  111. package/dist/cli/convoy/schedule.test.js.map +1 -0
  112. package/dist/cli/convoy/spec-builder.d.ts +120 -30
  113. package/dist/cli/convoy/spec-builder.d.ts.map +1 -1
  114. package/dist/cli/convoy/spec-builder.js +438 -114
  115. package/dist/cli/convoy/spec-builder.js.map +1 -1
  116. package/dist/cli/convoy/spec-builder.test.js +419 -435
  117. package/dist/cli/convoy/spec-builder.test.js.map +1 -1
  118. package/dist/cli/convoy/spec-types.d.ts +46 -92
  119. package/dist/cli/convoy/spec-types.d.ts.map +1 -1
  120. package/dist/cli/convoy/store.d.ts +6 -1
  121. package/dist/cli/convoy/store.d.ts.map +1 -1
  122. package/dist/cli/convoy/store.js +111 -15
  123. package/dist/cli/convoy/store.js.map +1 -1
  124. package/dist/cli/convoy/store.test.js +59 -13
  125. package/dist/cli/convoy/store.test.js.map +1 -1
  126. package/dist/cli/convoy/types.d.ts +76 -113
  127. package/dist/cli/convoy/types.d.ts.map +1 -1
  128. package/dist/cli/convoy/types.js +6 -13
  129. package/dist/cli/convoy/types.js.map +1 -1
  130. package/dist/cli/convoy/worktree.d.ts +88 -3
  131. package/dist/cli/convoy/worktree.d.ts.map +1 -1
  132. package/dist/cli/convoy/worktree.js +282 -56
  133. package/dist/cli/convoy/worktree.js.map +1 -1
  134. package/dist/cli/convoy/worktree.test.js +132 -1
  135. package/dist/cli/convoy/worktree.test.js.map +1 -1
  136. package/dist/cli/convoy-args.test.js +9 -27
  137. package/dist/cli/convoy-args.test.js.map +1 -1
  138. package/dist/cli/convoy-cmd.d.ts +31 -6
  139. package/dist/cli/convoy-cmd.d.ts.map +1 -1
  140. package/dist/cli/convoy-cmd.js +150 -200
  141. package/dist/cli/convoy-cmd.js.map +1 -1
  142. package/dist/cli/convoy-cmd.test.d.ts +2 -0
  143. package/dist/cli/convoy-cmd.test.d.ts.map +1 -0
  144. package/dist/cli/convoy-cmd.test.js +144 -0
  145. package/dist/cli/convoy-cmd.test.js.map +1 -0
  146. package/dist/cli/dashboard.d.ts +24 -11
  147. package/dist/cli/dashboard.d.ts.map +1 -1
  148. package/dist/cli/dashboard.js +241 -303
  149. package/dist/cli/dashboard.js.map +1 -1
  150. package/dist/cli/dashboard.test.d.ts +2 -0
  151. package/dist/cli/dashboard.test.d.ts.map +1 -0
  152. package/dist/cli/dashboard.test.js +340 -0
  153. package/dist/cli/dashboard.test.js.map +1 -0
  154. package/dist/cli/dispatcher.test.js +41 -2
  155. package/dist/cli/dispatcher.test.js.map +1 -1
  156. package/dist/cli/docs-accuracy.test.js +36 -11
  157. package/dist/cli/docs-accuracy.test.js.map +1 -1
  158. package/dist/cli/doctor.d.ts.map +1 -1
  159. package/dist/cli/doctor.js +9 -6
  160. package/dist/cli/doctor.js.map +1 -1
  161. package/dist/cli/init-own-files.test.d.ts +2 -0
  162. package/dist/cli/init-own-files.test.d.ts.map +1 -0
  163. package/dist/cli/init-own-files.test.js +133 -0
  164. package/dist/cli/init-own-files.test.js.map +1 -0
  165. package/dist/cli/init.d.ts.map +1 -1
  166. package/dist/cli/init.js +106 -7
  167. package/dist/cli/init.js.map +1 -1
  168. package/dist/cli/init.test.js +5 -4
  169. package/dist/cli/init.test.js.map +1 -1
  170. package/dist/cli/layers.d.ts.map +1 -1
  171. package/dist/cli/layers.js +13 -4
  172. package/dist/cli/layers.js.map +1 -1
  173. package/dist/cli/lesson.d.ts.map +1 -1
  174. package/dist/cli/lesson.js +6 -5
  175. package/dist/cli/lesson.js.map +1 -1
  176. package/dist/cli/log.d.ts +39 -0
  177. package/dist/cli/log.d.ts.map +1 -1
  178. package/dist/cli/log.js +267 -93
  179. package/dist/cli/log.js.map +1 -1
  180. package/dist/cli/log.test.d.ts +2 -0
  181. package/dist/cli/log.test.d.ts.map +1 -0
  182. package/dist/cli/log.test.js +208 -0
  183. package/dist/cli/log.test.js.map +1 -0
  184. package/dist/cli/nearest.d.ts +18 -0
  185. package/dist/cli/nearest.d.ts.map +1 -0
  186. package/dist/cli/nearest.js +38 -0
  187. package/dist/cli/nearest.js.map +1 -0
  188. package/dist/cli/nearest.test.d.ts +2 -0
  189. package/dist/cli/nearest.test.d.ts.map +1 -0
  190. package/dist/cli/nearest.test.js +24 -0
  191. package/dist/cli/nearest.test.js.map +1 -0
  192. package/dist/cli/pipeline.d.ts +61 -0
  193. package/dist/cli/pipeline.d.ts.map +1 -1
  194. package/dist/cli/pipeline.flow.test.d.ts +2 -0
  195. package/dist/cli/pipeline.flow.test.d.ts.map +1 -0
  196. package/dist/cli/pipeline.flow.test.js +524 -0
  197. package/dist/cli/pipeline.flow.test.js.map +1 -0
  198. package/dist/cli/pipeline.js +471 -690
  199. package/dist/cli/pipeline.js.map +1 -1
  200. package/dist/cli/plan.d.ts +82 -31
  201. package/dist/cli/plan.d.ts.map +1 -1
  202. package/dist/cli/plan.js +167 -507
  203. package/dist/cli/plan.js.map +1 -1
  204. package/dist/cli/plan.test.d.ts +2 -0
  205. package/dist/cli/plan.test.d.ts.map +1 -0
  206. package/dist/cli/plan.test.js +158 -0
  207. package/dist/cli/plan.test.js.map +1 -0
  208. package/dist/cli/prompt.d.ts.map +1 -1
  209. package/dist/cli/prompt.js +9 -7
  210. package/dist/cli/prompt.js.map +1 -1
  211. package/dist/cli/prompt.test.js +20 -2
  212. package/dist/cli/prompt.test.js.map +1 -1
  213. package/dist/cli/remove.d.ts.map +1 -1
  214. package/dist/cli/remove.js +3 -1
  215. package/dist/cli/remove.js.map +1 -1
  216. package/dist/cli/review.d.ts.map +1 -1
  217. package/dist/cli/review.js +7 -1
  218. package/dist/cli/review.js.map +1 -1
  219. package/dist/cli/run/adapters/agent-process.d.ts +82 -0
  220. package/dist/cli/run/adapters/agent-process.d.ts.map +1 -0
  221. package/dist/cli/run/adapters/agent-process.js +224 -0
  222. package/dist/cli/run/adapters/agent-process.js.map +1 -0
  223. package/dist/cli/run/adapters/agent-process.test.d.ts +2 -0
  224. package/dist/cli/run/adapters/agent-process.test.d.ts.map +1 -0
  225. package/dist/cli/run/adapters/agent-process.test.js +159 -0
  226. package/dist/cli/run/adapters/agent-process.test.js.map +1 -0
  227. package/dist/cli/run/adapters/claude.d.ts +53 -2
  228. package/dist/cli/run/adapters/claude.d.ts.map +1 -1
  229. package/dist/cli/run/adapters/claude.js +147 -171
  230. package/dist/cli/run/adapters/claude.js.map +1 -1
  231. package/dist/cli/run/adapters/claude.test.js +197 -254
  232. package/dist/cli/run/adapters/claude.test.js.map +1 -1
  233. package/dist/cli/run/adapters/codex.d.ts +25 -2
  234. package/dist/cli/run/adapters/codex.d.ts.map +1 -1
  235. package/dist/cli/run/adapters/codex.js +113 -81
  236. package/dist/cli/run/adapters/codex.js.map +1 -1
  237. package/dist/cli/run/adapters/codex.test.js +116 -95
  238. package/dist/cli/run/adapters/codex.test.js.map +1 -1
  239. package/dist/cli/run/adapters/copilot.d.ts +35 -1
  240. package/dist/cli/run/adapters/copilot.d.ts.map +1 -1
  241. package/dist/cli/run/adapters/copilot.js +104 -287
  242. package/dist/cli/run/adapters/copilot.js.map +1 -1
  243. package/dist/cli/run/adapters/copilot.test.js +122 -282
  244. package/dist/cli/run/adapters/copilot.test.js.map +1 -1
  245. package/dist/cli/run/adapters/cursor.d.ts +25 -7
  246. package/dist/cli/run/adapters/cursor.d.ts.map +1 -1
  247. package/dist/cli/run/adapters/cursor.js +103 -156
  248. package/dist/cli/run/adapters/cursor.js.map +1 -1
  249. package/dist/cli/run/adapters/cursor.test.js +106 -218
  250. package/dist/cli/run/adapters/cursor.test.js.map +1 -1
  251. package/dist/cli/run/adapters/index.d.ts +34 -5
  252. package/dist/cli/run/adapters/index.d.ts.map +1 -1
  253. package/dist/cli/run/adapters/index.js +147 -21
  254. package/dist/cli/run/adapters/index.js.map +1 -1
  255. package/dist/cli/run/adapters/index.test.d.ts +2 -0
  256. package/dist/cli/run/adapters/index.test.d.ts.map +1 -0
  257. package/dist/cli/run/adapters/index.test.js +129 -0
  258. package/dist/cli/run/adapters/index.test.js.map +1 -0
  259. package/dist/cli/run/adapters/opencode.d.ts +25 -9
  260. package/dist/cli/run/adapters/opencode.d.ts.map +1 -1
  261. package/dist/cli/run/adapters/opencode.js +136 -152
  262. package/dist/cli/run/adapters/opencode.js.map +1 -1
  263. package/dist/cli/run/adapters/opencode.test.js +99 -218
  264. package/dist/cli/run/adapters/opencode.test.js.map +1 -1
  265. package/dist/cli/run/adapters/permission-modes.d.ts +47 -4
  266. package/dist/cli/run/adapters/permission-modes.d.ts.map +1 -1
  267. package/dist/cli/run/adapters/permission-modes.js +113 -37
  268. package/dist/cli/run/adapters/permission-modes.js.map +1 -1
  269. package/dist/cli/run/adapters/permission-modes.test.js +55 -40
  270. package/dist/cli/run/adapters/permission-modes.test.js.map +1 -1
  271. package/dist/cli/run/adapters/stub-cli.test-helper.d.ts +22 -0
  272. package/dist/cli/run/adapters/stub-cli.test-helper.d.ts.map +1 -0
  273. package/dist/cli/run/adapters/stub-cli.test-helper.js +73 -0
  274. package/dist/cli/run/adapters/stub-cli.test-helper.js.map +1 -0
  275. package/dist/cli/run/platform.d.ts +52 -0
  276. package/dist/cli/run/platform.d.ts.map +1 -0
  277. package/dist/cli/run/platform.js +207 -0
  278. package/dist/cli/run/platform.js.map +1 -0
  279. package/dist/cli/run/platform.test.d.ts +2 -0
  280. package/dist/cli/run/platform.test.d.ts.map +1 -0
  281. package/dist/cli/run/platform.test.js +119 -0
  282. package/dist/cli/run/platform.test.js.map +1 -0
  283. package/dist/cli/run/schema.d.ts +6 -8
  284. package/dist/cli/run/schema.d.ts.map +1 -1
  285. package/dist/cli/run/schema.js +44 -68
  286. package/dist/cli/run/schema.js.map +1 -1
  287. package/dist/cli/run/schema.test.js +59 -279
  288. package/dist/cli/run/schema.test.js.map +1 -1
  289. package/dist/cli/run.d.ts +34 -56
  290. package/dist/cli/run.d.ts.map +1 -1
  291. package/dist/cli/run.js +379 -1132
  292. package/dist/cli/run.js.map +1 -1
  293. package/dist/cli/run.test.d.ts +2 -0
  294. package/dist/cli/run.test.d.ts.map +1 -0
  295. package/dist/cli/run.test.js +318 -0
  296. package/dist/cli/run.test.js.map +1 -0
  297. package/dist/cli/sync-check.d.ts.map +1 -1
  298. package/dist/cli/sync-check.js +12 -3
  299. package/dist/cli/sync-check.js.map +1 -1
  300. package/dist/cli/sync.d.ts.map +1 -1
  301. package/dist/cli/sync.js +3 -2
  302. package/dist/cli/sync.js.map +1 -1
  303. package/dist/cli/team-config.d.ts.map +1 -1
  304. package/dist/cli/team-config.js +2 -21
  305. package/dist/cli/team-config.js.map +1 -1
  306. package/dist/cli/tiers.test.js +4 -13
  307. package/dist/cli/tiers.test.js.map +1 -1
  308. package/dist/cli/update.d.ts.map +1 -1
  309. package/dist/cli/update.js +4 -3
  310. package/dist/cli/update.js.map +1 -1
  311. package/dist/cli/website-plugins.test.js +51 -2
  312. package/dist/cli/website-plugins.test.js.map +1 -1
  313. package/dist/orchestrator/plugins/coolify/config.d.ts.map +1 -1
  314. package/dist/orchestrator/plugins/coolify/config.js +13 -0
  315. package/dist/orchestrator/plugins/coolify/config.js.map +1 -1
  316. package/dist/orchestrator/plugins/sentry/config.d.ts.map +1 -1
  317. package/dist/orchestrator/plugins/sentry/config.js +13 -0
  318. package/dist/orchestrator/plugins/sentry/config.js.map +1 -1
  319. package/package.json +3 -10
  320. package/src/cli/adapters/claude-code.ts +7 -3
  321. package/src/cli/adapters/single-file-base.ts +47 -4
  322. package/src/cli/agent-plugin.test.ts +14 -0
  323. package/src/cli/agent-roster.test.ts +0 -55
  324. package/src/cli/bootstrap.ts +23 -0
  325. package/src/cli/boundary.test.ts +9 -7
  326. package/src/cli/ci.ts +6 -4
  327. package/src/cli/command-namespace.test.ts +35 -0
  328. package/src/cli/convoy/TELEMETRY.md +138 -130
  329. package/src/cli/convoy/artifacts.test.ts +4 -2
  330. package/src/cli/convoy/artifacts.ts +13 -12
  331. package/src/cli/convoy/engine.git.test.ts +462 -0
  332. package/src/cli/convoy/engine.test.ts +817 -850
  333. package/src/cli/convoy/engine.ts +1864 -2596
  334. package/src/cli/convoy/event-schemas.ts +63 -59
  335. package/src/cli/convoy/events.test.ts +58 -9
  336. package/src/cli/convoy/events.ts +69 -91
  337. package/src/cli/convoy/gates.ts +31 -12
  338. package/src/cli/convoy/isolation.test.ts +76 -43
  339. package/src/cli/convoy/isolation.ts +100 -38
  340. package/src/cli/convoy/lock.test.ts +16 -0
  341. package/src/cli/convoy/lock.ts +25 -8
  342. package/src/cli/convoy/merge.test.ts +25 -1
  343. package/src/cli/convoy/merge.ts +74 -61
  344. package/src/cli/convoy/progress.test.ts +59 -0
  345. package/src/cli/convoy/progress.ts +121 -0
  346. package/src/cli/convoy/read-model.test.ts +685 -0
  347. package/src/cli/convoy/read-model.ts +1469 -0
  348. package/src/cli/convoy/redact.test.ts +49 -0
  349. package/src/cli/convoy/redact.ts +73 -0
  350. package/src/cli/convoy/reviewer.test.ts +112 -0
  351. package/src/cli/convoy/reviewer.ts +196 -0
  352. package/src/cli/convoy/schedule.test.ts +56 -0
  353. package/src/cli/convoy/schedule.ts +109 -0
  354. package/src/cli/convoy/spec-builder.test.ts +460 -464
  355. package/src/cli/convoy/spec-builder.ts +460 -129
  356. package/src/cli/convoy/spec-types.ts +46 -108
  357. package/src/cli/convoy/store.test.ts +64 -13
  358. package/src/cli/convoy/store.ts +143 -33
  359. package/src/cli/convoy/types.ts +59 -71
  360. package/src/cli/convoy/worktree.test.ts +140 -1
  361. package/src/cli/convoy/worktree.ts +311 -61
  362. package/src/cli/convoy-args.test.ts +10 -30
  363. package/src/cli/convoy-cmd.test.ts +163 -0
  364. package/src/cli/convoy-cmd.ts +173 -215
  365. package/src/cli/dashboard/dashboard.css +2086 -0
  366. package/src/cli/dashboard/dashboard.js +1687 -0
  367. package/src/cli/dashboard/index.html +307 -0
  368. package/src/cli/dashboard.test.ts +382 -0
  369. package/src/cli/dashboard.ts +243 -339
  370. package/src/cli/dispatcher.test.ts +43 -2
  371. package/src/cli/docs-accuracy.test.ts +37 -10
  372. package/src/cli/doctor.ts +9 -6
  373. package/src/cli/init-own-files.test.ts +156 -0
  374. package/src/cli/init.test.ts +5 -4
  375. package/src/cli/init.ts +104 -7
  376. package/src/cli/layers.ts +13 -4
  377. package/src/cli/lesson.ts +6 -5
  378. package/src/cli/log.test.ts +228 -0
  379. package/src/cli/log.ts +302 -83
  380. package/src/cli/nearest.test.ts +27 -0
  381. package/src/cli/nearest.ts +38 -0
  382. package/src/cli/pipeline.flow.test.ts +607 -0
  383. package/src/cli/pipeline.ts +544 -759
  384. package/src/cli/plan.test.ts +193 -0
  385. package/src/cli/plan.ts +209 -545
  386. package/src/cli/prompt.test.ts +21 -2
  387. package/src/cli/prompt.ts +11 -7
  388. package/src/cli/remove.ts +3 -0
  389. package/src/cli/review.ts +7 -1
  390. package/src/cli/run/adapters/agent-process.test.ts +175 -0
  391. package/src/cli/run/adapters/agent-process.ts +252 -0
  392. package/src/cli/run/adapters/claude.test.ts +205 -260
  393. package/src/cli/run/adapters/claude.ts +151 -162
  394. package/src/cli/run/adapters/codex.test.ts +120 -100
  395. package/src/cli/run/adapters/codex.ts +115 -91
  396. package/src/cli/run/adapters/copilot.test.ts +135 -306
  397. package/src/cli/run/adapters/copilot.ts +105 -274
  398. package/src/cli/run/adapters/cursor.test.ts +111 -220
  399. package/src/cli/run/adapters/cursor.ts +105 -156
  400. package/src/cli/run/adapters/index.test.ts +148 -0
  401. package/src/cli/run/adapters/index.ts +168 -20
  402. package/src/cli/run/adapters/opencode.test.ts +106 -227
  403. package/src/cli/run/adapters/opencode.ts +139 -151
  404. package/src/cli/run/adapters/permission-modes.test.ts +63 -41
  405. package/src/cli/run/adapters/permission-modes.ts +118 -37
  406. package/src/cli/run/adapters/stub-cli.test-helper.ts +88 -0
  407. package/src/cli/run/platform.test.ts +128 -0
  408. package/src/cli/run/platform.ts +213 -0
  409. package/src/cli/run/schema.test.ts +62 -344
  410. package/src/cli/run/schema.ts +48 -78
  411. package/src/cli/run.test.ts +351 -0
  412. package/src/cli/run.ts +366 -1151
  413. package/src/cli/sync-check.ts +12 -3
  414. package/src/cli/sync.ts +3 -2
  415. package/src/cli/team-config.ts +2 -21
  416. package/src/cli/tiers.test.ts +4 -17
  417. package/src/cli/update.ts +4 -3
  418. package/src/cli/website-plugins.test.ts +55 -5
  419. package/src/orchestrator/agents/team-lead.agent.md +2 -2
  420. package/src/orchestrator/customizations/README.md +58 -13
  421. package/src/orchestrator/customizations/logs/README.md +23 -18
  422. package/src/orchestrator/instructions/general.instructions.md +1 -1
  423. package/src/orchestrator/plugins/coolify/config.ts +13 -0
  424. package/src/orchestrator/plugins/sentry/config.ts +13 -0
  425. package/src/orchestrator/prompts/assess-complexity.prompt.md +43 -26
  426. package/src/orchestrator/prompts/bootstrap-customizations.prompt.md +44 -49
  427. package/src/orchestrator/prompts/brainstorm.prompt.md +2 -2
  428. package/src/orchestrator/prompts/bug-fix.prompt.md +5 -4
  429. package/src/orchestrator/prompts/create-skill.prompt.md +29 -39
  430. package/src/orchestrator/prompts/fix-convoy.prompt.md +43 -29
  431. package/src/orchestrator/prompts/fix-prd.prompt.md +26 -22
  432. package/src/orchestrator/prompts/generate-convoy.prompt.md +139 -147
  433. package/src/orchestrator/prompts/generate-prd.prompt.md +75 -68
  434. package/src/orchestrator/prompts/implement-feature.prompt.md +7 -6
  435. package/src/orchestrator/prompts/validate-convoy.prompt.md +29 -28
  436. package/src/orchestrator/prompts/validate-prd.prompt.md +28 -21
  437. package/src/orchestrator/skills/agent-hooks/HOOKS-REFERENCE.md +3 -3
  438. package/src/orchestrator/skills/agent-hooks/SKILL.md +1 -1
  439. package/src/orchestrator/skills/fast-review/SKILL.md +3 -1
  440. package/src/orchestrator/skills/orchestration-protocols/SKILL.md +7 -8
  441. package/dist/cli/convoy/dag-analysis.d.ts +0 -39
  442. package/dist/cli/convoy/dag-analysis.d.ts.map +0 -1
  443. package/dist/cli/convoy/dag-analysis.js +0 -279
  444. package/dist/cli/convoy/dag-analysis.js.map +0 -1
  445. package/dist/cli/convoy/dag-analysis.test.d.ts +0 -2
  446. package/dist/cli/convoy/dag-analysis.test.d.ts.map +0 -1
  447. package/dist/cli/convoy/dag-analysis.test.js +0 -289
  448. package/dist/cli/convoy/dag-analysis.test.js.map +0 -1
  449. package/dist/cli/convoy/formula.d.ts +0 -19
  450. package/dist/cli/convoy/formula.d.ts.map +0 -1
  451. package/dist/cli/convoy/formula.js +0 -142
  452. package/dist/cli/convoy/formula.js.map +0 -1
  453. package/dist/cli/convoy/formula.test.d.ts +0 -2
  454. package/dist/cli/convoy/formula.test.d.ts.map +0 -1
  455. package/dist/cli/convoy/formula.test.js +0 -342
  456. package/dist/cli/convoy/formula.test.js.map +0 -1
  457. package/dist/cli/convoy/health.d.ts +0 -34
  458. package/dist/cli/convoy/health.d.ts.map +0 -1
  459. package/dist/cli/convoy/health.js +0 -123
  460. package/dist/cli/convoy/health.js.map +0 -1
  461. package/dist/cli/convoy/health.test.d.ts +0 -2
  462. package/dist/cli/convoy/health.test.d.ts.map +0 -1
  463. package/dist/cli/convoy/health.test.js +0 -448
  464. package/dist/cli/convoy/health.test.js.map +0 -1
  465. package/dist/cli/convoy/last-run.d.ts +0 -53
  466. package/dist/cli/convoy/last-run.d.ts.map +0 -1
  467. package/dist/cli/convoy/last-run.js +0 -54
  468. package/dist/cli/convoy/last-run.js.map +0 -1
  469. package/dist/cli/convoy/last-run.test.d.ts +0 -2
  470. package/dist/cli/convoy/last-run.test.d.ts.map +0 -1
  471. package/dist/cli/convoy/last-run.test.js +0 -110
  472. package/dist/cli/convoy/last-run.test.js.map +0 -1
  473. package/dist/cli/convoy/pipeline.d.ts +0 -41
  474. package/dist/cli/convoy/pipeline.d.ts.map +0 -1
  475. package/dist/cli/convoy/pipeline.js +0 -414
  476. package/dist/cli/convoy/pipeline.js.map +0 -1
  477. package/dist/cli/convoy/pipeline.test.d.ts +0 -2
  478. package/dist/cli/convoy/pipeline.test.d.ts.map +0 -1
  479. package/dist/cli/convoy/pipeline.test.js +0 -837
  480. package/dist/cli/convoy/pipeline.test.js.map +0 -1
  481. package/dist/cli/convoy/review-stages.d.ts +0 -9
  482. package/dist/cli/convoy/review-stages.d.ts.map +0 -1
  483. package/dist/cli/convoy/review-stages.js +0 -134
  484. package/dist/cli/convoy/review-stages.js.map +0 -1
  485. package/dist/cli/convoy/review-stages.test.d.ts +0 -2
  486. package/dist/cli/convoy/review-stages.test.d.ts.map +0 -1
  487. package/dist/cli/convoy/review-stages.test.js +0 -197
  488. package/dist/cli/convoy/review-stages.test.js.map +0 -1
  489. package/dist/cli/run/executor.d.ts +0 -15
  490. package/dist/cli/run/executor.d.ts.map +0 -1
  491. package/dist/cli/run/executor.js +0 -249
  492. package/dist/cli/run/executor.js.map +0 -1
  493. package/dist/cli/run/executor.test.d.ts +0 -2
  494. package/dist/cli/run/executor.test.d.ts.map +0 -1
  495. package/dist/cli/run/executor.test.js +0 -297
  496. package/dist/cli/run/executor.test.js.map +0 -1
  497. package/dist/cli/run/reporter.d.ts +0 -10
  498. package/dist/cli/run/reporter.d.ts.map +0 -1
  499. package/dist/cli/run/reporter.js +0 -142
  500. package/dist/cli/run/reporter.js.map +0 -1
  501. package/dist/cli/run-dry-run.test.d.ts +0 -2
  502. package/dist/cli/run-dry-run.test.d.ts.map +0 -1
  503. package/dist/cli/run-dry-run.test.js +0 -83
  504. package/dist/cli/run-dry-run.test.js.map +0 -1
  505. package/dist/cli/run-executor-flags.test.d.ts +0 -2
  506. package/dist/cli/run-executor-flags.test.d.ts.map +0 -1
  507. package/dist/cli/run-executor-flags.test.js +0 -31
  508. package/dist/cli/run-executor-flags.test.js.map +0 -1
  509. package/dist/cli/run-finish.test.d.ts +0 -2
  510. package/dist/cli/run-finish.test.d.ts.map +0 -1
  511. package/dist/cli/run-finish.test.js +0 -77
  512. package/dist/cli/run-finish.test.js.map +0 -1
  513. package/dist/cli/watch.d.ts +0 -15
  514. package/dist/cli/watch.d.ts.map +0 -1
  515. package/dist/cli/watch.js +0 -277
  516. package/dist/cli/watch.js.map +0 -1
  517. package/dist/dashboard/scripts/etl.d.ts +0 -10
  518. package/dist/dashboard/scripts/etl.d.ts.map +0 -1
  519. package/dist/dashboard/scripts/etl.js +0 -141
  520. package/dist/dashboard/scripts/etl.js.map +0 -1
  521. package/src/cli/convoy/dag-analysis.test.ts +0 -349
  522. package/src/cli/convoy/dag-analysis.ts +0 -367
  523. package/src/cli/convoy/formula.test.ts +0 -404
  524. package/src/cli/convoy/formula.ts +0 -174
  525. package/src/cli/convoy/health.test.ts +0 -519
  526. package/src/cli/convoy/health.ts +0 -189
  527. package/src/cli/convoy/last-run.test.ts +0 -130
  528. package/src/cli/convoy/last-run.ts +0 -87
  529. package/src/cli/convoy/pipeline.test.ts +0 -999
  530. package/src/cli/convoy/pipeline.ts +0 -492
  531. package/src/cli/convoy/review-stages.test.ts +0 -235
  532. package/src/cli/convoy/review-stages.ts +0 -166
  533. package/src/cli/run/executor.test.ts +0 -338
  534. package/src/cli/run/executor.ts +0 -292
  535. package/src/cli/run/reporter.ts +0 -160
  536. package/src/cli/run-dry-run.test.ts +0 -97
  537. package/src/cli/run-executor-flags.test.ts +0 -38
  538. package/src/cli/run-finish.test.ts +0 -91
  539. package/src/cli/watch.ts +0 -295
  540. package/src/dashboard/astro.config.mjs +0 -6
  541. package/src/dashboard/dist/_astro/index.CADNhRPS.css +0 -1
  542. package/src/dashboard/dist/data/.gitkeep +0 -0
  543. package/src/dashboard/dist/data/convoy-list.json +0 -1
  544. package/src/dashboard/dist/data/overall-stats.json +0 -29
  545. package/src/dashboard/dist/index.html +0 -1963
  546. package/src/dashboard/node_modules/.vite/deps/_metadata.json +0 -31
  547. package/src/dashboard/node_modules/.vite/deps/astro___aria-query.js +0 -6776
  548. package/src/dashboard/node_modules/.vite/deps/astro___aria-query.js.map +0 -7
  549. package/src/dashboard/node_modules/.vite/deps/astro___axobject-query.js +0 -3754
  550. package/src/dashboard/node_modules/.vite/deps/astro___axobject-query.js.map +0 -7
  551. package/src/dashboard/node_modules/.vite/deps/astro___cssesc.js +0 -99
  552. package/src/dashboard/node_modules/.vite/deps/astro___cssesc.js.map +0 -7
  553. package/src/dashboard/node_modules/.vite/deps/chunk-BUSYA2B4.js +0 -8
  554. package/src/dashboard/node_modules/.vite/deps/chunk-BUSYA2B4.js.map +0 -7
  555. package/src/dashboard/node_modules/.vite/deps/package.json +0 -3
  556. package/src/dashboard/package-lock.json +0 -6
  557. package/src/dashboard/public/data/.gitkeep +0 -0
  558. package/src/dashboard/public/data/convoy-list.json +0 -1
  559. package/src/dashboard/public/data/overall-stats.json +0 -29
  560. package/src/dashboard/public/icon-192.png +0 -0
  561. package/src/dashboard/scripts/etl.test.ts +0 -166
  562. package/src/dashboard/scripts/etl.ts +0 -170
  563. package/src/dashboard/scripts/generate-demo-db.test.ts +0 -30
  564. package/src/dashboard/scripts/generate-demo-db.ts +0 -529
  565. package/src/dashboard/scripts/integration-test.ts +0 -504
  566. package/src/dashboard/scripts/verify-demo-data.sh +0 -51
  567. package/src/dashboard/seed-data/delegations.ndjson +0 -35
  568. package/src/dashboard/seed-data/events.ndjson +0 -104
  569. package/src/dashboard/seed-data/panels.ndjson +0 -13
  570. package/src/dashboard/seed-data/reviews.ndjson +0 -6
  571. package/src/dashboard/seed-data/sessions.ndjson +0 -50
  572. package/src/dashboard/src/env.d.ts +0 -1
  573. package/src/dashboard/src/layouts/Layout.astro +0 -25
  574. package/src/dashboard/src/pages/index.astro +0 -2313
  575. package/src/dashboard/src/styles/dashboard.css +0 -2943
  576. package/src/dashboard/tsconfig.json +0 -6
  577. /package/src/{dashboard/dist → cli/dashboard}/icon-192.png +0 -0
package/src/cli/run.ts CHANGED
@@ -1,1258 +1,473 @@
1
+ /**
2
+ * `opencastle convoy run <spec.yml>` and `opencastle convoy resume`.
3
+ *
4
+ * Two things, and only two: start a spec, or continue the newest run that is
5
+ * not done. This file used to be a 1,250-line parser in front of three
6
+ * executors — the convoy engine, a legacy executor and a pipeline orchestrator —
7
+ * with watch mode, formulas, a dead-letter queue and a status report bolted on.
8
+ * Each path finished a run in its own way, so the summary printed twice and a
9
+ * finished run could sit waiting for Ctrl+C. The engine now does the work and
10
+ * prints its own summary; this file picks the runtime, shows the live view,
11
+ * and exits with the engine's code.
12
+ */
1
13
  import { readFile } from 'node:fs/promises'
2
- import { existsSync } from 'node:fs'
3
14
  import { resolve } from 'node:path'
4
- import { stringify as yamlStringify } from 'yaml'
5
- import { parseTaskSpecText, isConvoySpec, isPipelineSpec } from './run/schema.js'
6
- import { createExecutor, buildPhases } from './run/executor.js'
7
- import { getAdapter, detectAdapter } from './run/adapters/index.js'
15
+ import { parseTaskSpecText } from './run/schema.js'
16
+ import { resolveAdapter, cleanupAdapters, type ResolvedAdapter } from './run/adapters/index.js'
8
17
  import { permissionModeError } from './run/adapters/permission-modes.js'
9
- import { createReporter, printExecutionPlan } from './run/reporter.js'
18
+ import { findProjectRoot, isRunAlive, readRun, readRunSpec, readRuns, type RunSummary } from './convoy/read-model.js'
19
+ import { checkConvoyPlan, createConvoyEngine, RESUME_RESET_STATUSES, type ConvoyResult } from './convoy/engine.js'
20
+ import { EngineAlreadyRunningError } from './convoy/lock.js'
21
+ import { startDashboard, type DashboardHandle } from './dashboard.js'
22
+ import { nearest } from './nearest.js'
10
23
  import { c } from './prompt.js'
24
+ import type { TaskSpec } from './convoy/spec-types.js'
11
25
  import type { CliContext } from './types.js'
12
- import { PERMISSION_MODES } from './convoy/spec-types.js'
13
- import type { RunOptions, PermissionMode, TaskSpec } from './convoy/spec-types.js'
14
- import type { ConvoyResult } from './convoy/engine.js'
15
- import type { PipelineResult } from './convoy/pipeline.js'
16
- import { EngineAlreadyRunningError } from './convoy/lock.js'
17
-
18
- function formatTokens(n: number): string {
19
- if (n >= 1_000_000) return (n / 1_000_000).toFixed(1) + 'M'
20
- if (n >= 1_000) return (n / 1_000).toFixed(1) + 'K'
21
- return String(n)
22
- }
23
26
 
24
- const HELP = `
25
- opencastle convoy run [options]
27
+ const RUN_HELP = `
28
+ opencastle convoy run <spec.yml> [options]
26
29
 
27
- Process a task queue from a spec file, delegating to AI agents autonomously.
28
- Version 1 specs use the Convoy Engine; legacy specs use the standard executor.
30
+ Run a convoy spec: one you wrote, or one opencastle convoy "<task>" wrote to
31
+ .opencastle/convoys/. The work lands on a branch of its own (the spec's
32
+ branch, or convoy/<name>-<id>); your checkout is never touched.
29
33
 
30
34
  Options:
31
- --file, -f <path> Task spec file
32
- --formula <path> Use a formula template (alternative to --file)
33
- --set key=value Set a formula variable (repeatable)
34
- --dry-run Show execution plan without running; with --resume
35
- or --retry-failed, list the tasks that would run
36
- --concurrency, -c <n> Override max parallel tasks
37
- --adapter, -a <name> Override agent runtime adapter
38
- --report-dir <path> Where to write run reports, for legacy specs only
39
- (default: .opencastle/runs). Convoy specs record to
40
- .opencastle/convoy.db and .opencastle/logs instead
41
- --permission-mode <m> How much a worker may do unattended: default,
42
- acceptEdits (the default), auto, dontAsk,
43
- bypassPermissions, plan
44
- --verbose Show full agent output
45
- --resume Resume the last interrupted convoy from .opencastle/convoy.db
46
- --retry-failed [task-id] Retry failed/gate-failed/timed-out tasks from the last convoy
47
- --status Print the current convoy state from .opencastle/convoy.db
48
- --dlq-list List dead letter queue entries
49
- --dlq-resolve <id> Resolve a DLQ entry (requires --resolution)
50
- --dlq-retry <id> Reset a DLQ task to pending for retry
51
- --convoy <id> Filter by convoy ID (used with --dlq-list)
52
- --resolution <text> Resolution text (used with --dlq-resolve)
53
- --watch Keep running, re-triggering on file changes, cron,
54
- or git push (convoy specs only)
55
- --watch-config <p> Path to watch configuration file (overrides spec
56
- watch config)
57
- --clear-scratchpad Clear scratchpad data at watch start
35
+ --dry-run Check the spec and show what would run; start nothing
36
+ --adapter, -a <name> Agent runtime: claude, codex, cursor, opencode or copilot
37
+ (default: the spec's, else the one opencastle init set up)
38
+ --concurrency, -c <n> Tasks at once (default: the spec's, else 4)
39
+ --verbose Stream agent output
58
40
  --help, -h Show this help
59
41
  `
60
42
 
61
- /**
62
- * CLI flags win over whatever the spec says.
63
- *
64
- * Four entry points build a spec — a fresh run, a retry, a convoy resume and a
65
- * pipeline resume — and each used to repeat this by hand, which is how a flag
66
- * comes to work on one of them and not the others.
67
- */
68
- function applyCliOverrides(spec: TaskSpec, opts: RunOptions): void {
69
- if (opts.concurrency !== null) spec.concurrency = opts.concurrency
70
- if (opts.adapter !== null) spec.adapter = opts.adapter
71
- if (opts.permissionMode !== null) {
72
- spec.defaults = { ...spec.defaults, permission_mode: opts.permissionMode }
73
- }
74
- if (opts.verbose) spec._verbose = true
75
- }
43
+ const RESUME_HELP = `
44
+ opencastle convoy resume [options]
76
45
 
77
- export interface DashboardHandle {
78
- server: { close(): void }
79
- url: string
80
- }
46
+ Continue the newest run that is not done. Failed, timed-out and interrupted
47
+ tasks run again, and so do the tasks a failure skipped; finished tasks are
48
+ kept. It runs on the branch and runtime the run started with.
81
49
 
82
- /**
83
- * End the run: say where the results went, keep the dashboard up if there is
84
- * one, and stop.
85
- *
86
- * Five paths finish a run — a fresh convoy, a fresh pipeline, a retry, a convoy
87
- * resume and a pipeline resume — and each wrote this out by hand. The no-dashboard
88
- * half ended in `process.exit`, so it stopped whether or not anyone remembered to
89
- * say so; the dashboard half only registered a SIGINT handler, and four of the
90
- * five then carried straight on into the next block. With the dashboard running,
91
- * `convoy run` executed the whole spec on the engine and then ran it a second time
92
- * on the legacy executor, and `--retry-failed` followed its retry with a full fresh
93
- * run — every task done twice, and paid for twice, visible only when a dashboard
94
- * was up.
95
- *
96
- * One copy, and it either exits or hands control back for the caller to `return`.
97
- */
98
- export function finishRun(
99
- dashboard: DashboardHandle | null,
100
- failed: boolean,
101
- retryHint?: string,
102
- ): void {
103
- const exitCode = failed ? 1 : 0
104
- const printRetryHint = (): void => {
105
- if (failed && retryHint) console.log(`\n ${c.dim('Retry failed:')} ${retryHint}`)
106
- }
50
+ Options:
51
+ --dry-run List the tasks that would run; start nothing
52
+ --adapter, -a <name> Run on another agent runtime instead
53
+ --concurrency, -c <n> Tasks at once
54
+ --verbose Stream agent output
55
+ --help, -h Show this help
56
+ `
107
57
 
108
- if (dashboard) {
109
- console.log(`\n ${c.dim('Results saved to .opencastle/convoy.db')}`)
110
- console.log(` ${c.dim('Dashboard:')} ${dashboard.url}`)
111
- console.log(`\n Press Ctrl+C to stop`)
112
- printRetryHint()
113
- process.on('SIGINT', () => {
114
- console.log('\n Dashboard stopped.\n')
115
- dashboard.server.close()
116
- process.exit(exitCode)
117
- })
118
- return
119
- }
58
+ // ── Arguments ─────────────────────────────────────────────────────────────────
120
59
 
121
- printRetryHint()
122
- process.exit(exitCode)
60
+ export interface RunArgs {
61
+ /** The spec path, as typed. Null for resume, or when it is missing. */
62
+ spec: string | null
63
+ dryRun: boolean
64
+ adapter: string | null
65
+ concurrency: number | null
66
+ verbose: boolean
67
+ help: boolean
123
68
  }
124
69
 
125
- /**
126
- * The statuses `engine.retryFailed` reopens, and the ones `engine.resume` picks
127
- * up. Named here so the `--dry-run` preview and the engine cannot drift about
128
- * which tasks a run would touch.
129
- */
130
- export const RETRYABLE_TASK_STATUSES = [
131
- 'failed',
132
- 'gate-failed',
133
- 'timed-out',
134
- 'review-blocked',
135
- 'disputed',
136
- ] as const
137
- export const RESUMABLE_TASK_STATUSES = ['pending', 'assigned', 'running'] as const
70
+ const KNOWN_FLAGS = ['--dry-run', '--adapter', '-a', '--concurrency', '-c', '--verbose', '--help', '-h']
138
71
 
139
72
  /**
140
- * What `--resume` or `--retry-failed` would do, without doing it.
141
- *
142
- * `--dry-run` was read only on the fresh-run path, so combining it with either
143
- * of those flags spawned agents against the user's repository for real. The flag
144
- * a person reaches for to find out what will happen was the one flag that did
145
- * not change what happened.
73
+ * Flags this command used to take, and what to do instead. Named one by one,
74
+ * because "unknown option" is the wrong answer to a flag our own docs taught.
146
75
  */
147
- export function printRunDryRun(
148
- verb: 'resume' | 'retry',
149
- runLabel: string,
150
- runName: string,
151
- tasks: Array<{ id: string; agent: string; status: string }>,
152
- statuses: readonly string[],
153
- ): void {
154
- const selected = tasks.filter((t) => statuses.includes(t.status))
155
-
156
- console.log(`\n 🏰 ${runLabel}: ${runName}`)
157
- console.log(c.dim(` [dry-run] Nothing will be executed.\n`))
158
-
159
- if (selected.length === 0) {
160
- console.log(
161
- verb === 'retry'
162
- ? ' No failed tasks to retry.'
163
- : ' No unfinished tasks — nothing to resume.',
164
- )
165
- console.log(c.dim(` (matching: ${statuses.join(', ')})\n`))
166
- return
167
- }
168
-
169
- console.log(
170
- ` Would ${verb === 'retry' ? 're-run' : 'run'} ${selected.length} of ${tasks.length} task(s):`,
171
- )
172
- for (const t of selected) {
173
- console.log(` ${t.id} ${c.dim(`— ${t.agent} [${t.status}]`)}`)
174
- }
175
- console.log()
76
+ export const REMOVED_FLAGS: Record<string, string> = {
77
+ '--resume': 'Use: opencastle convoy resume',
78
+ '--retry-failed': 'Use: opencastle convoy resume — it re-runs failed tasks too',
79
+ '--status': 'Use: opencastle convoy — it shows the last run and what to do next',
80
+ '--dlq-list': 'Failed tasks are listed by opencastle convoy, and re-run by opencastle convoy resume',
81
+ '--dlq-resolve': 'Failed tasks are listed by opencastle convoy, and re-run by opencastle convoy resume',
82
+ '--dlq-retry': 'Use: opencastle convoy resume',
83
+ '--formula': 'Formulas are gone: write the spec out, or plan it with opencastle convoy "<task>"',
84
+ '--set': 'Formulas are gone: write the spec out, or plan it with opencastle convoy "<task>"',
85
+ '--watch': 'Watch mode is gone: run the spec again when you want it run',
86
+ '--watch-config': 'Watch mode is gone: run the spec again when you want it run',
87
+ '--clear-scratchpad': 'Watch mode is gone: run the spec again when you want it run',
88
+ '--report-dir': 'Runs are recorded in .opencastle/convoy.db. See them with opencastle convoy dashboard',
89
+ '--permission-mode': 'Set defaults.permission_mode in the spec instead',
176
90
  }
177
91
 
178
92
  /**
179
- * Parse CLI arguments for the run command.
93
+ * Read `convoy run` or `convoy resume` arguments.
94
+ *
95
+ * The spec is positional; `-f`/`--file` still names it, quietly, because
96
+ * every spec written before this change says `convoy run -f <spec>`.
180
97
  */
181
- function parseArgs(args: string[]): RunOptions {
182
- const opts: RunOptions = {
183
- file: 'convoy.yml',
184
- dryRun: false,
185
- concurrency: null,
186
- adapter: null,
187
- reportDir: null,
188
- permissionMode: null,
189
- verbose: false,
190
- help: false,
191
- resume: false,
192
- status: false,
193
- retryFailed: false,
194
- retryFailedTaskIds: undefined,
195
- dlqList: false,
196
- dlqResolve: false,
197
- dlqResolveId: undefined,
198
- dlqResolveText: undefined,
199
- dlqRetry: false,
200
- dlqRetryId: undefined,
201
- dlqConvoyFilter: undefined,
202
- formula: null,
203
- setVars: {},
204
- watch: false,
205
- watchConfig: null,
206
- clearScratchpad: false,
98
+ export function parseRunArgs(args: string[], command: 'run' | 'resume'): RunArgs | { error: string } {
99
+ const out: RunArgs = { spec: null, dryRun: false, adapter: null, concurrency: null, verbose: false, help: false }
100
+ const value = (i: number, flag: string): string | { error: string } => {
101
+ const v = args[i + 1]
102
+ if (v === undefined || v.startsWith('-') || !v.trim()) return { error: `${flag} needs a value` }
103
+ return v
207
104
  }
208
-
209
105
  for (let i = 0; i < args.length; i++) {
210
106
  const arg = args[i]
211
107
  switch (arg) {
212
108
  case '--help':
213
109
  case '-h':
214
- opts.help = true
110
+ out.help = true
215
111
  break
216
- case '--file':
217
- case '-f':
218
- if (i + 1 >= args.length) { console.error(' \u2717 --file requires a path'); process.exit(1) }
219
- opts.file = args[++i]
220
- if (!opts.file.trim()) { console.error(' ✗ --file cannot be empty'); process.exit(1) }
221
- break
222
- case '--dryRun':
223
112
  case '--dry-run':
224
- opts.dryRun = true
113
+ out.dryRun = true
225
114
  break
226
- case '--concurrency':
227
- case '-c': {
228
- if (i + 1 >= args.length) { console.error(' \u2717 --concurrency requires a number'); process.exit(1) }
229
- const val = parseInt(args[++i], 10)
230
- if (!Number.isFinite(val) || val < 1) {
231
- console.error(` ✗ --concurrency must be an integer >= 1`)
232
- process.exit(1)
233
- }
234
- opts.concurrency = val
115
+ case '--verbose':
116
+ out.verbose = true
235
117
  break
236
- }
237
118
  case '--adapter':
238
- case '-a':
239
- if (i + 1 >= args.length) { console.error(' \u2717 --adapter requires a name'); process.exit(1) }
240
- opts.adapter = args[++i]
241
- if (!opts.adapter.trim()) { console.error(' ✗ --adapter cannot be empty'); process.exit(1) }
242
- break
243
- case '--report-dir':
244
- if (i + 1 >= args.length) { console.error(' \u2717 --report-dir requires a path'); process.exit(1) }
245
- opts.reportDir = args[++i]
246
- if (!opts.reportDir.trim()) { console.error(' ✗ --report-dir cannot be empty'); process.exit(1) }
247
- break
248
- case '--permission-mode': {
249
- if (i + 1 >= args.length) { console.error(' ✗ --permission-mode requires a mode'); process.exit(1) }
250
- const mode = args[++i]
251
- if (!PERMISSION_MODES.includes(mode as PermissionMode)) {
252
- console.error(` ✗ --permission-mode must be one of: ${PERMISSION_MODES.join(', ')}`)
253
- process.exit(1)
254
- }
255
- opts.permissionMode = mode as PermissionMode
119
+ case '-a': {
120
+ const v = value(i++, arg)
121
+ if (typeof v !== 'string') return v
122
+ out.adapter = v
256
123
  break
257
124
  }
258
- case '--verbose':
259
- opts.verbose = true
125
+ case '--concurrency':
126
+ case '-c': {
127
+ const v = value(i++, arg)
128
+ if (typeof v !== 'string') return v
129
+ const n = Number(v)
130
+ if (!/^\d+$/.test(v) || n < 1 || n > 50) return { error: `--concurrency must be a whole number from 1 to 50, not "${v}"` }
131
+ out.concurrency = n
260
132
  break
261
- case '--resume':
262
- opts.resume = true
133
+ }
134
+ case '--file':
135
+ case '-f': {
136
+ if (command !== 'run') return { error: `${arg} belongs to opencastle convoy run` }
137
+ const v = value(i++, arg)
138
+ if (typeof v !== 'string') return v
139
+ if (out.spec !== null) return { error: `Two specs given: ${out.spec} and ${v}. Run one at a time.` }
140
+ out.spec = v
263
141
  break
264
- case '--retry-failed':
265
- opts.retryFailed = true
266
- if (i + 1 < args.length && !args[i + 1].startsWith('--')) {
267
- opts.retryFailedTaskIds = [args[++i]]
142
+ }
143
+ default: {
144
+ if (arg in REMOVED_FLAGS) return { error: `${arg} was removed. ${REMOVED_FLAGS[arg]}.` }
145
+ if (arg.startsWith('-')) {
146
+ const near = nearest(arg, KNOWN_FLAGS)
147
+ return { error: `Unknown option ${arg}. ${near ? `Did you mean ${near}?` : `It accepts ${KNOWN_FLAGS.join(', ')}.`}` }
268
148
  }
269
- break
270
- case '--status':
271
- opts.status = true
272
- break
273
- case '--dlq-list':
274
- opts.dlqList = true
275
- break
276
- case '--dlq-resolve':
277
- opts.dlqResolve = true
278
- if (i + 1 < args.length && !args[i + 1].startsWith('--')) opts.dlqResolveId = args[++i]
279
- break
280
- case '--dlq-retry':
281
- opts.dlqRetry = true
282
- if (i + 1 < args.length && !args[i + 1].startsWith('--')) opts.dlqRetryId = args[++i]
283
- break
284
- case '--resolution':
285
- if (i + 1 >= args.length) { console.error(' ✗ --resolution requires text'); process.exit(1) }
286
- opts.dlqResolveText = args[++i]
287
- if (!opts.dlqResolveText.trim()) { console.error(' ✗ --resolution cannot be empty'); process.exit(1) }
288
- break
289
- case '--convoy':
290
- if (i + 1 >= args.length) { console.error(' ✗ --convoy requires an ID'); process.exit(1) }
291
- opts.dlqConvoyFilter = args[++i]
292
- if (!opts.dlqConvoyFilter.trim()) { console.error(' ✗ --convoy cannot be empty'); process.exit(1) }
293
- break
294
- case '--formula':
295
- if (i + 1 >= args.length) { console.error(' ✗ --formula requires a path'); process.exit(1) }
296
- opts.formula = args[++i]
297
- if (!opts.formula.trim()) { console.error(' ✗ --formula cannot be empty'); process.exit(1) }
298
- break
299
- case '--set': {
300
- if (i + 1 >= args.length) { console.error(' ✗ --set requires key=value'); process.exit(1) }
301
- const pair = args[++i]
302
- const eqIdx = pair.indexOf('=')
303
- if (eqIdx < 1) {
304
- console.error(` ✗ --set value must be in key=value format, got: ${pair}`)
305
- process.exit(1)
149
+ if (command === 'resume') {
150
+ return { error: `Unexpected argument "${arg}". resume continues the newest run that is not done, and takes no name.` }
306
151
  }
307
- opts.setVars[pair.slice(0, eqIdx)] = pair.slice(eqIdx + 1)
308
- break
152
+ if (out.spec !== null) return { error: `Two specs given: ${out.spec} and ${arg}. Run one at a time.` }
153
+ out.spec = arg
309
154
  }
310
- case '--watch':
311
- opts.watch = true
312
- break
313
- case '--watch-config':
314
- if (i + 1 >= args.length) { console.error(' ✗ --watch-config requires a path'); process.exit(1) }
315
- opts.watchConfig = args[++i]
316
- if (!opts.watchConfig.trim()) { console.error(' ✗ --watch-config cannot be empty'); process.exit(1) }
317
- break
318
- case '--clear-scratchpad':
319
- opts.clearScratchpad = true
320
- break
321
- default:
322
- console.error(` ✗ Unknown option: ${arg}. Run with --help to see available options.`)
323
- console.log(HELP)
324
- process.exit(1)
325
155
  }
326
156
  }
327
-
328
- return opts
157
+ return out
329
158
  }
330
159
 
331
- /**
332
- * Which executor a spec will run on, and therefore which flags mean anything.
333
- *
334
- * Three exist — the pipeline orchestrator for `version: 2`, the convoy engine
335
- * for `version: 1`, and the legacy executor for everything else — and several
336
- * flags are wired into exactly one of them:
337
- *
338
- * `--report-dir` is read where `createReporter` is called, which is the legacy
339
- * path alone. For a `version: 1` spec, which is what every generated spec is,
340
- * it was parsed, resolved against cwd, and never passed to the engine; the
341
- * engine writes to SQLite and NDJSON and has no report directory at all. The
342
- * flag was accepted, documented as "where to write run reports", and did
343
- * nothing on the path nearly every user is on.
344
- *
345
- * `--watch` and its two companions are the mirror image: they live inside the
346
- * convoy-engine branch, so a legacy or pipeline spec accepted them and ran
347
- * once.
348
- */
349
- export function specExecutor(spec: TaskSpec): 'pipeline' | 'engine' | 'legacy' {
350
- if (isPipelineSpec(spec)) return 'pipeline'
351
- if (isConvoySpec(spec)) return 'engine'
352
- return 'legacy'
160
+ // ── Shared pieces ─────────────────────────────────────────────────────────────
161
+
162
+ /** Where `.opencastle/` is: the nearest one at or above the current directory, else here. */
163
+ function projectRootHere(): string {
164
+ return findProjectRoot(process.cwd()) ?? process.cwd()
353
165
  }
354
166
 
355
- /** Flags that only one executor reads, and the one that reads each. */
356
- const EXECUTOR_ONLY_FLAGS: Array<{
357
- flag: string
358
- executor: 'pipeline' | 'engine' | 'legacy'
359
- set: (_o: RunOptions) => boolean
360
- why: string
361
- }> = [
362
- {
363
- flag: '--report-dir',
364
- executor: 'legacy',
365
- set: (o) => o.reportDir !== null,
366
- why: 'the convoy engine records runs in .opencastle/convoy.db and .opencastle/logs, not as report files',
367
- },
368
- {
369
- flag: '--watch',
370
- executor: 'engine',
371
- set: (o) => o.watch,
372
- why: 'only the convoy engine has a watch loop',
373
- },
374
- {
375
- flag: '--watch-config',
376
- executor: 'engine',
377
- set: (o) => o.watchConfig !== null,
378
- why: 'only the convoy engine has a watch loop',
379
- },
380
- {
381
- flag: '--clear-scratchpad',
382
- executor: 'engine',
383
- set: (o) => o.clearScratchpad,
384
- why: 'only the convoy engine has a watch loop',
385
- },
386
- ]
167
+ function fail(message: string): number {
168
+ console.error(` ${c.red('✗')} ${message}`)
169
+ return 1
170
+ }
387
171
 
388
172
  /**
389
- * Refuse a flag the spec's executor will never read.
390
- *
391
- * Same rule as everywhere else on this command: a flag is honoured or refused,
392
- * never accepted and dropped. Silence here meant `--report-dir ./out` on an
393
- * ordinary convoy spec exited 0 with `./out` empty.
173
+ * Pick the runtime, once, with the rule `resolveAdapter` owns. On resume the
174
+ * runtime the run recorded comes before the spec's own `adapter:`, so a run
175
+ * that started on the configured runtime continues on it.
394
176
  */
395
- function assertFlagsApplyToSpec(spec: TaskSpec, opts: RunOptions): void {
396
- const executor = specExecutor(spec)
397
- for (const entry of EXECUTOR_ONLY_FLAGS) {
398
- if (!entry.set(opts) || entry.executor === executor) continue
399
- const kind =
400
- executor === 'pipeline'
401
- ? 'a pipeline spec (version: 2)'
402
- : executor === 'engine'
403
- ? 'a convoy spec (version: 1)'
404
- : 'a legacy spec (no version)'
405
- console.error(` ✗ ${entry.flag} does nothing for ${kind}.`)
406
- console.error(` ${entry.why}.`)
407
- process.exit(1)
177
+ async function chooseRuntime(projectRoot: string, explicit: string | null, spec: TaskSpec, recorded?: string | null): Promise<ResolvedAdapter> {
178
+ const fromRecord = !explicit && Boolean(recorded)
179
+ const why = (text: string): string =>
180
+ fromRecord ? text.replace(/adapter: \S+ in the spec/, 'the runtime this run started on') : text
181
+ try {
182
+ const resolved = await resolveAdapter({ projectRoot, explicit, specAdapter: recorded || spec.adapter || null })
183
+ return { ...resolved, detail: why(resolved.detail) }
184
+ } catch (err) {
185
+ throw new Error(why((err as Error).message))
408
186
  }
409
187
  }
410
188
 
411
- /**
412
- * Refuse a permission mode the chosen adapter cannot honour, before it runs.
413
- *
414
- * Every entry point resolves its own adapter, so every one of them calls this.
415
- * Until now the mode simply evaporated on four of the five adapters: a run told
416
- * to hold its workers to `plan` went ahead and wrote files, and said nothing
417
- * about it. Refusing is the only honest answer left once a mode cannot be
418
- * carried out, and it has to happen here — before a worker starts, while the
419
- * user can still change the flag.
420
- */
421
- function assertPermissionModeSupported(adapterName: string, spec: TaskSpec): void {
422
- const mode = spec.defaults?.permission_mode
423
- if (!mode) return
424
- const problem = permissionModeError(adapterName, mode)
425
- if (problem) {
426
- console.error(` ✗ ${problem}`)
427
- process.exit(1)
428
- }
189
+ /** The run's own settings, after the command line has had its say. */
190
+ function applyArgs(spec: TaskSpec, args: RunArgs, runtime: string): void {
191
+ // Written into the spec the engine gets, so the run, its resume and its
192
+ // record all name the same runtime.
193
+ spec.adapter = runtime
194
+ if (args.concurrency !== null) spec.concurrency = args.concurrency
195
+ if (args.verbose) spec._verbose = true
429
196
  }
430
197
 
431
- /**
432
- * Print a user-friendly adapter unavailable error.
433
- */
434
- function printAdapterError(detectionFailed: boolean, adapterName: string): void {
435
- if (detectionFailed) {
436
- console.error(
437
- ` ✗ No agent CLI found on your PATH.\n` +
438
- ` Install one of the following adapters:\n` +
439
- ` • copilot — https://docs.github.com/en/copilot/how-tos/set-up/install-copilot-cli\n` +
440
- ` • claude — npm install -g @anthropic-ai/claude-code\n` +
441
- ` • cursor — https://cursor.com (Cursor > Install CLI)\n` +
442
- ` • opencode — https://opencode.ai\n` +
443
- ` • codex — npm install -g @openai/codex\n` +
444
- `\n` +
445
- ` Or specify an adapter explicitly: opencastle convoy run --adapter <name>`
446
- )
447
- } else {
448
- const hints: Record<string, string> = {
449
- 'claude':
450
- ' Install: npm install -g @anthropic-ai/claude-code\n' +
451
- ' Docs: https://docs.anthropic.com/en/docs/claude-code',
452
- copilot:
453
- ' Requires the Copilot CLI installed and authenticated:\n' +
454
- ' https://docs.github.com/en/copilot/how-tos/set-up/install-copilot-cli\n' +
455
- ' Docs: https://docs.github.com/en/copilot',
456
- cursor:
457
- ' The Cursor agent CLI ships with the Cursor editor.\n' +
458
- ' Install Cursor from https://cursor.com and ensure the\n' +
459
- ' "agent" command is on your PATH (Cursor > Install CLI).',
460
- opencode:
461
- ' Install OpenCode from https://opencode.ai\n' +
462
- ' Ensure the "opencode" command is on your PATH.',
463
- codex:
464
- ' Install: npm install -g @openai/codex\n' +
465
- ' Docs: https://developers.openai.com/codex',
466
- }
467
- const cliName = adapterName === 'cursor' ? 'agent' : adapterName
468
- const hint = hints[adapterName] ?? ''
469
- console.error(
470
- ` ✗ Adapter "${adapterName}" is not available.\n` +
471
- ` Make sure the "${cliName}" CLI is installed and on your PATH.\n` +
472
- hint
473
- )
474
- }
198
+ function concurrencyOf(spec: TaskSpec): number {
199
+ return typeof spec.concurrency === 'number' ? spec.concurrency : (spec.defaults?.max_swarm_concurrency ?? 4)
475
200
  }
476
201
 
477
202
  /**
478
- * Print a convoy result summary.
203
+ * The live dashboard, on a terminal and outside CI. A run in a pipeline has
204
+ * nobody to look at it, and a port held open there is a port held for nothing.
479
205
  */
480
- function printConvoyResult(result: ConvoyResult): void {
481
- console.log(`\n ──────────────────────────────────────`)
482
- console.log(` Convoy ${result.status}: ${result.duration}`)
483
- console.log(
484
- ` Tasks: ${result.summary.done}/${result.summary.total} done` +
485
- (result.summary.failed > 0 ? ` | ${result.summary.failed} failed` : '') +
486
- (result.summary.skipped > 0 ? ` | ${result.summary.skipped} skipped` : '') +
487
- (result.summary.timedOut > 0 ? ` | ${result.summary.timedOut} timed out` : '')
488
- )
489
- if (result.gateResults) {
490
- const gatesPassed = result.gateResults.filter(g => g.passed).length
491
- const gatesFailed = result.gateResults.filter(g => !g.passed).length
492
- console.log(` Gates: ${gatesPassed}/${result.gateResults.length} passed${gatesFailed > 0 ? ` | ${gatesFailed} failed` : ''}`)
493
- for (const g of result.gateResults) {
494
- console.log(` ${g.passed ? '✓' : '✗'} ${g.command}`)
495
- }
496
- }
497
- if (result.cost) {
498
- const parts = [`Tokens: ${formatTokens(result.cost.total_tokens)}`]
499
- if (result.cost.total_cost_usd != null) {
500
- parts.push(`Cost: $${result.cost.total_cost_usd.toFixed(2)}`)
501
- }
502
- console.log(` ${parts.join(' | ')}`)
206
+ async function maybeStartDashboard(projectRoot: string): Promise<DashboardHandle | null> {
207
+ if (!process.stdout.isTTY || process.env.CI) return null
208
+ try {
209
+ return await startDashboard({ projectRoot, port: 4300, open: false })
210
+ } catch {
211
+ // A busy port or a missing page must not stop the run itself.
212
+ return null
503
213
  }
504
214
  }
505
215
 
506
216
  /**
507
- * Print a pipeline result summary.
217
+ * Run the engine, then let go of everything: the dashboard's server, any agent
218
+ * an adapter still holds. Whatever happens, the caller gets an exit code back and
219
+ * nothing is left keeping the process alive.
508
220
  */
509
- function printPipelineResult(result: PipelineResult): void {
510
- console.log(`\n ──────────────────────────────────────`)
511
- console.log(` Pipeline ${result.status}: ${result.duration}`)
512
- console.log(
513
- ` Convoys: ${result.summary.completed}/${result.summary.totalConvoys} completed` +
514
- (result.summary.failed > 0 ? ` | ${result.summary.failed} failed` : '') +
515
- (result.summary.skipped > 0 ? ` | ${result.summary.skipped} skipped` : '')
516
- )
517
- for (const cr of result.convoyResults) {
518
- const icon = cr.status === 'done' ? '✓' : cr.status === 'failed' ? '✗' : '⊘'
519
- console.log(` ${icon} ${cr.convoyId}: ${cr.status} (${cr.duration})`)
520
- }
521
- if (result.cost) {
522
- const parts = [`Tokens: ${formatTokens(result.cost.total_tokens)}`]
523
- if (result.cost.total_cost_usd != null) {
524
- parts.push(`Cost: $${result.cost.total_cost_usd.toFixed(2)}`)
525
- }
526
- console.log(` ${parts.join(' | ')}`)
221
+ async function drive(work: () => Promise<ConvoyResult>, projectRoot: string): Promise<number> {
222
+ const dashboard = await maybeStartDashboard(projectRoot)
223
+ if (dashboard) console.log(` ${c.dim('Live view:')} ${dashboard.url}`)
224
+ console.log('')
225
+ try {
226
+ const result = await work()
227
+ return result.exitCode ?? (result.status === 'done' ? 0 : 1)
228
+ } catch (err) {
229
+ if (err instanceof EngineAlreadyRunningError) {
230
+ return fail(`${err.message}\n Watch it with: opencastle convoy dashboard`)
231
+ }
232
+ return fail((err as Error).message)
233
+ } finally {
234
+ await dashboard?.close()
235
+ await cleanupAdapters()
527
236
  }
528
237
  }
529
238
 
530
- /**
531
- * CLI entry point for the `run` command.
532
- */
533
- export default async function run({ args, pkgRoot }: CliContext): Promise<void> {
534
- const opts = parseArgs(args)
239
+ // ── convoy run <spec.yml> ─────────────────────────────────────────────────────
535
240
 
536
- if (opts.help) {
537
- console.log(HELP)
538
- return
539
- }
241
+ function fit(text: string, width: number): string {
242
+ return text.length <= width ? text.padEnd(width) : text.slice(0, Math.max(0, width - 1)) + '…'
243
+ }
540
244
 
541
- const dbPath = resolve(process.cwd(), '.opencastle', 'convoy.db')
245
+ /** What a run would do: the tasks and their order, where the work lands, and on what. */
246
+ function describePlan(spec: TaskSpec, runtime: string): string[] {
247
+ const tasks = spec.tasks ?? []
248
+ const rows = tasks.map((t) => ({
249
+ id: t.id,
250
+ agent: t.agent,
251
+ deps: t.depends_on.length ? t.depends_on.join(', ') : '–',
252
+ files: t.files.length ? t.files.join(', ') : '(any)',
253
+ }))
254
+ const width = (pick: (r: (typeof rows)[number]) => string, header: string, cap: number): number =>
255
+ Math.min(cap, Math.max(header.length, ...rows.map((r) => pick(r).length)))
256
+ const idW = width((r) => r.id, 'TASK', 32)
257
+ const agentW = width((r) => r.agent, 'AGENT', 18)
258
+ const depsW = width((r) => r.deps, 'WAITS FOR', 30)
259
+ const line = (a: string, b: string, d: string, f: string): string =>
260
+ ` ${fit(a, idW)} ${fit(b, agentW)} ${fit(d, depsW)} ${f}`
261
+ return [
262
+ ` ${c.bold(`Convoy: ${spec.name}`)} ${c.dim(`— ${tasks.length} task${tasks.length === 1 ? '' : 's'}, up to ${concurrencyOf(spec)} at once`)}`,
263
+ '',
264
+ c.dim(line('TASK', 'AGENT', 'WAITS FOR', 'FILES')),
265
+ ...rows.map((r) => line(r.id, r.agent, r.deps, r.files)),
266
+ '',
267
+ ` ${c.dim('Runtime')} ${runtime}`,
268
+ ` ${c.dim('Branch')} ${spec.branch ?? 'convoy/<name>-<id>, created when it runs'}`,
269
+ ...(spec.gates?.length ? [` ${c.dim('Gates')} ${spec.gates.join(', ')} ${c.dim('(once, after the tasks)')}`] : []),
270
+ ]
271
+ }
542
272
 
543
- // ── --dlq-list flag ───────────────────────────────────────────
544
- if (opts.dlqList) {
545
- if (!existsSync(dbPath)) {
546
- console.log(' No convoy database found at .opencastle/convoy.db')
547
- return
548
- }
549
- const { createConvoyStore } = await import('./convoy/store.js')
550
- const store = createConvoyStore(dbPath)
551
- try {
552
- const entries = store.listDlqEntries(opts.dlqConvoyFilter)
553
- if (entries.length === 0) {
554
- console.log(' No DLQ entries found.')
555
- return
556
- }
557
- console.log(`\n Dead Letter Queue (${entries.length} entries):\n`)
558
- for (const e of entries) {
559
- const status = e.resolved ? c.green('resolved') : c.red('unresolved')
560
- console.log(` ${e.id} ${status}`)
561
- console.log(` Task: ${e.task_id} | Agent: ${e.agent} | Type: ${e.failure_type}`)
562
- console.log(` Attempts: ${e.attempts} | Created: ${e.created_at}`)
563
- if (e.resolution) console.log(` Resolution: ${e.resolution}`)
564
- console.log()
565
- }
566
- } finally {
567
- store.close()
568
- }
569
- return
273
+ /**
274
+ * `convoy run <spec>`: the exit code it should end with.
275
+ *
276
+ * `runtime` is for the planner, which has already chosen the runtime and said
277
+ * which; the run uses it rather than choosing, and saying, a second time.
278
+ */
279
+ export async function runSpec(args: RunArgs, opts: { runtime?: ResolvedAdapter } = {}): Promise<number> {
280
+ if (!args.spec) {
281
+ console.error(` ${c.red('✗')} Name the spec to run: opencastle convoy run <spec.yml>`)
282
+ console.error(` ${c.dim('Specs the planner wrote are in .opencastle/convoys/.')}`)
283
+ return 1
570
284
  }
571
285
 
572
- // ── --dlq-resolve flag ────────────────────────────────────────
573
- if (opts.dlqResolve) {
574
- if (!opts.dlqResolveId) {
575
- console.error(' \u2717 --dlq-resolve requires a DLQ entry ID')
576
- process.exit(1)
577
- }
578
- if (!opts.dlqResolveText) {
579
- console.error(' \u2717 --dlq-resolve requires --resolution "text"')
580
- process.exit(1)
581
- }
582
- if (!existsSync(dbPath)) {
583
- console.error(' \u2717 No convoy database found at .opencastle/convoy.db')
584
- process.exit(1)
585
- }
586
- const { createConvoyStore } = await import('./convoy/store.js')
587
- const store = createConvoyStore(dbPath)
588
- try {
589
- store.resolveDlqEntry(opts.dlqResolveId, opts.dlqResolveText)
590
- console.log(` \u2713 DLQ entry ${opts.dlqResolveId} resolved.`)
591
- } finally {
592
- store.close()
593
- }
594
- return
286
+ let specText: string
287
+ try {
288
+ specText = await readFile(resolve(process.cwd(), args.spec), 'utf8')
289
+ } catch (err) {
290
+ const e = err as NodeJS.ErrnoException
291
+ return fail(e.code === 'ENOENT' ? `Spec not found: ${args.spec}` : `Cannot read ${args.spec}: ${e.message}`)
595
292
  }
596
-
597
- // ── --dlq-retry flag ──────────────────────────────────────────
598
- if (opts.dlqRetry) {
599
- if (!opts.dlqRetryId) {
600
- console.error(' \u2717 --dlq-retry requires a DLQ entry ID')
601
- process.exit(1)
602
- }
603
- if (!existsSync(dbPath)) {
604
- console.error(' \u2717 No convoy database found at .opencastle/convoy.db')
605
- process.exit(1)
606
- }
607
- const { createConvoyStore } = await import('./convoy/store.js')
608
- const store = createConvoyStore(dbPath)
609
- try {
610
- const entries = store.listDlqEntries()
611
- const entry = entries.find(e => e.id === opts.dlqRetryId)
612
- if (!entry) {
613
- console.error(` \u2717 DLQ entry "${opts.dlqRetryId}" not found`)
614
- process.exit(1)
615
- }
616
- // Reset the task to pending
617
- store.updateTaskStatus(entry.task_id, entry.convoy_id, 'pending', {
618
- worker_id: null,
619
- worktree: null,
620
- started_at: null,
621
- finished_at: null,
622
- })
623
- store.resolveDlqEntry(entry.id, 'Retried via CLI')
624
- // Reset convoy status to running if needed
625
- const convoy = store.getConvoy(entry.convoy_id)
626
- if (convoy && (convoy.status === 'failed' || convoy.status === 'done')) {
627
- store.updateConvoyStatus(entry.convoy_id, 'running', {})
628
- }
629
- console.log(` \u2713 Task ${entry.task_id} reset to pending. Run 'opencastle convoy run --resume' to execute.`)
630
- } finally {
631
- store.close()
632
- }
633
- return
293
+ let spec: TaskSpec
294
+ try {
295
+ spec = parseTaskSpecText(specText)
296
+ } catch (err) {
297
+ return fail(`${args.spec}: ${(err as Error).message}`)
634
298
  }
635
299
 
636
- // ── --status flag ─────────────────────────────────────────────
637
- if (opts.status) {
638
- if (!existsSync(dbPath)) {
639
- console.log(' No convoy database found at .opencastle/convoy.db')
640
- return
641
- }
642
- const { createConvoyStore } = await import('./convoy/store.js')
643
- const store = createConvoyStore(dbPath)
300
+ const projectRoot = projectRootHere()
301
+ let runtime: ResolvedAdapter | null = opts.runtime ?? null
302
+ let runtimeProblem: string | null = null
303
+ if (!runtime) {
644
304
  try {
645
- const pipeline = store.getLatestPipeline()
646
- if (pipeline) {
647
- const pipelineConvoys = store.getConvoysByPipeline(pipeline.id)
648
- console.log(`\n Pipeline: ${pipeline.name}`)
649
- console.log(` ID: ${pipeline.id}`)
650
- console.log(` Status: ${pipeline.status}`)
651
- console.log(` Branch: ${pipeline.branch ?? '(none)'}`)
652
- console.log(` Created: ${pipeline.created_at}`)
653
- if (pipeline.started_at) console.log(` Started: ${pipeline.started_at}`)
654
- if (pipeline.finished_at) console.log(` Finished: ${pipeline.finished_at}`)
655
- if (pipelineConvoys.length > 0) {
656
- console.log(`\n Convoys:`)
657
- let totalTasks = 0
658
- let totalDone = 0
659
- let totalFailed = 0
660
- let totalTokens = 0
661
- for (const c of pipelineConvoys) {
662
- const tasks = store.getTasksByConvoy(c.id)
663
- const done = tasks.filter(t => t.status === 'done').length
664
- const failed = tasks.filter(t => t.status === 'failed').length
665
- totalTasks += tasks.length
666
- totalDone += done
667
- totalFailed += failed
668
- totalTokens += tasks.reduce((sum, t) => sum + (t.total_tokens ?? 0), 0)
669
- console.log(` ${c.name} [${c.status}] — ${done}/${tasks.length} tasks done`)
670
- }
671
- console.log(`\n Tasks: ${totalDone} done | ${totalFailed} failed | ${totalTasks} total`)
672
- if (totalTokens > 0) console.log(` Tokens: ${formatTokens(totalTokens)}`)
673
- }
674
- return
675
- }
676
-
677
- const convoy = store.getLatestConvoy()
678
- if (!convoy) {
679
- console.log(' No convoy records found.')
680
- return
681
- }
682
- const tasks = store.getTasksByConvoy(convoy.id)
683
- const byStatus = tasks.reduce((acc, t) => {
684
- acc[t.status] = (acc[t.status] ?? 0) + 1
685
- return acc
686
- }, {} as Record<string, number>)
687
- console.log(`\n Convoy: ${convoy.name}`)
688
- console.log(` ID: ${convoy.id}`)
689
- console.log(` Status: ${convoy.status}`)
690
- console.log(` Branch: ${convoy.branch ?? '(none)'}`)
691
- console.log(` Created: ${convoy.created_at}`)
692
- if (convoy.started_at) console.log(` Started: ${convoy.started_at}`)
693
- if (convoy.finished_at) console.log(` Finished: ${convoy.finished_at}`)
694
- console.log(`\n Tasks:`)
695
- for (const [status, count] of Object.entries(byStatus)) {
696
- console.log(` ${status}: ${count}`)
697
- }
698
- console.log(` total: ${tasks.length}`)
699
- const totalTokens = tasks.reduce((sum, t) => sum + (t.total_tokens ?? 0), 0)
700
- if (tasks.some(t => t.total_tokens != null)) {
701
- console.log(`\n Tokens: ${formatTokens(totalTokens)}`)
702
- const tasksWithTokens = tasks.filter(t => t.total_tokens != null)
703
- if (tasksWithTokens.length > 0) {
704
- console.log(`\n Token usage by task:`)
705
- for (const t of tasksWithTokens) {
706
- const parts = [formatTokens(t.total_tokens!)]
707
- if (t.prompt_tokens != null) parts.push(`in: ${formatTokens(t.prompt_tokens)}`)
708
- if (t.completion_tokens != null) parts.push(`out: ${formatTokens(t.completion_tokens)}`)
709
- console.log(` ${t.id}: ${parts.join(' | ')}`)
710
- }
711
- }
712
- }
713
- } finally {
714
- store.close()
715
- }
716
- return
717
- }
718
-
719
- // ── --retry-failed flag ───────────────────────────────────────
720
- if (opts.retryFailed) {
721
- if (!existsSync(dbPath)) {
722
- console.error(' ✗ No convoy database found at .opencastle/convoy.db')
723
- console.error(' Run a convoy spec first: opencastle convoy run -f convoy.yml')
724
- process.exit(1)
725
- }
726
- const { createConvoyStore } = await import('./convoy/store.js')
727
- const store = createConvoyStore(dbPath)
728
- const convoy = store.getLatestConvoy()
729
- const retryTasks = convoy ? store.getTasksByConvoy(convoy.id) : []
730
- store.close()
731
- if (!convoy) {
732
- console.error(' ✗ No convoy records found in .opencastle/convoy.db')
733
- process.exit(1)
734
- }
735
-
736
- // Before adapter detection: a preview should not require an agent CLI to be
737
- // installed, and it must return before anything is executed.
738
- if (opts.dryRun) {
739
- printRunDryRun(
740
- 'retry',
741
- 'OpenCastle Convoy (Retry Failed)',
742
- convoy.name,
743
- opts.retryFailedTaskIds?.length
744
- ? retryTasks.filter((t) => opts.retryFailedTaskIds!.includes(t.id))
745
- : retryTasks,
746
- RETRYABLE_TASK_STATUSES,
747
- )
748
- return
749
- }
750
-
751
- const retrySpec = parseTaskSpecText(convoy.spec_yaml)
752
- applyCliOverrides(retrySpec, opts)
753
-
754
- let retryDetectionFailed = false
755
- if (!retrySpec.adapter) {
756
- const detected = await detectAdapter()
757
- if (detected) {
758
- retrySpec.adapter = detected
759
- console.log(` ℹ Auto-detected adapter: ${detected}`)
760
- } else {
761
- retryDetectionFailed = true
762
- retrySpec.adapter = 'claude'
763
- }
764
- }
765
-
766
- const retryAdapter = await getAdapter(retrySpec.adapter)
767
- const retryAvailable = await retryAdapter.isAvailable()
768
- if (!retryAvailable) {
769
- printAdapterError(retryDetectionFailed, retrySpec.adapter)
770
- process.exit(1)
771
- }
772
- assertPermissionModeSupported(retrySpec.adapter, retrySpec)
773
-
774
- console.log(`\n 🏰 OpenCastle Convoy (Retry Failed): ${convoy.name}`)
775
- console.log(` Convoy ID: ${convoy.id}`)
776
-
777
- const { startDashboardServer } = await import('./dashboard.js')
778
- let retryDashboardResult: { server: import('node:http').Server; port: number; url: string } | null = null
779
- try {
780
- retryDashboardResult = await startDashboardServer({
781
- pkgRoot,
782
- openBrowser: true,
783
- convoyId: 'active',
784
- })
785
- } catch {
786
- // Dashboard failure must not block convoy
787
- }
788
- if (retryDashboardResult) {
789
- console.log(` ${c.dim('Dashboard:')} ${retryDashboardResult.url}`)
790
- }
791
-
792
- const { createConvoyEngine } = await import('./convoy/engine.js')
793
- const retryEngine = createConvoyEngine({
794
- spec: retrySpec,
795
- specYaml: convoy.spec_yaml,
796
- adapter: retryAdapter,
797
- verbose: opts.verbose,
798
- })
799
- await retryEngine.retryFailed(convoy.id, opts.retryFailedTaskIds)
800
- let retryResult: ConvoyResult
801
- try {
802
- retryResult = await retryEngine.resume(convoy.id)
305
+ runtime = await chooseRuntime(projectRoot, args.adapter, spec)
803
306
  } catch (err) {
804
- if (err instanceof EngineAlreadyRunningError) {
805
- console.error(` ✗ ${err.message}`)
806
- process.exit(1)
807
- }
808
- throw err
307
+ runtimeProblem = (err as Error).message
809
308
  }
810
- printConvoyResult(retryResult)
811
- return finishRun(retryDashboardResult, retryResult.status !== 'done')
812
309
  }
813
310
 
814
- // ── --resume flag ─────────────────────────────────────────────
815
- if (opts.resume) {
816
- if (!existsSync(dbPath)) {
817
- console.error(' ✗ No convoy database found at .opencastle/convoy.db')
818
- console.error(' Run a convoy spec first: opencastle convoy run -f convoy.yml')
819
- process.exit(1)
820
- }
821
- const { createConvoyStore } = await import('./convoy/store.js')
822
- const store = createConvoyStore(dbPath)
823
- const { selectResumableRun } = await import('./convoy/last-run.js')
824
- const selected = selectResumableRun(store)
825
-
826
- if (!selected) {
827
- store.close()
828
- console.error(' ✗ No convoy records found in .opencastle/convoy.db')
829
- process.exit(1)
830
- }
831
-
832
- // Whichever run was started most recently, and only if it can be continued.
833
- // Preferring pipelines unconditionally meant a standalone convoy could never
834
- // be resumed once the project had run one, and the status screen — which
835
- // reads the same selector — named a different run than this command resumed.
836
- if (!selected.resumable) {
837
- store.close()
838
- const { kind, record } = selected.run
839
- console.error(
840
- ` ✗ Last ${kind} "${record.name}" already finished with status: ${record.status}`,
841
- )
842
- console.error(
843
- kind === 'pipeline'
844
- ? ' Only interrupted (running/pending/failed) pipelines can be resumed.'
845
- : ' Only interrupted (running/pending) convoys can be resumed.',
846
- )
847
- if (kind === 'convoy' && record.status === 'failed') {
848
- console.error(`\n To re-run its failed tasks: opencastle convoy retry`)
849
- }
850
- process.exit(1)
851
- }
852
-
853
- // Before adapter detection, and before either orchestrator is constructed.
854
- if (opts.dryRun) {
855
- const previewIds =
856
- selected.run.kind === 'pipeline'
857
- ? store.getConvoysByPipeline(selected.run.record.id).map((c) => c.id)
858
- : [selected.run.record.id]
859
- const previewTasks = previewIds.flatMap((id) => store.getTasksByConvoy(id))
860
- store.close()
861
- printRunDryRun(
862
- 'resume',
863
- selected.run.kind === 'pipeline'
864
- ? 'OpenCastle Pipeline (Resume)'
865
- : 'OpenCastle Convoy (Resume)',
866
- selected.run.record.name,
867
- previewTasks,
868
- RESUMABLE_TASK_STATUSES,
869
- )
870
- return
871
- }
872
-
873
- const latestPipeline = selected.run.kind === 'pipeline' ? selected.run.record : null
874
-
875
- // ── Pipeline resume (pending / running / failed) ────────────
876
- if (latestPipeline) {
877
- store.close()
878
- const resumePipelineSpec = parseTaskSpecText(latestPipeline.spec_yaml)
879
- applyCliOverrides(resumePipelineSpec, opts)
880
-
881
- let resumePipelineDetectionFailed = false
882
- if (!resumePipelineSpec.adapter) {
883
- const detected = await detectAdapter()
884
- if (detected) {
885
- resumePipelineSpec.adapter = detected
886
- console.log(` ℹ Auto-detected adapter: ${detected}`)
887
- } else {
888
- resumePipelineDetectionFailed = true
889
- resumePipelineSpec.adapter = 'claude'
890
- }
891
- }
892
-
893
- const resumePipelineAdapter = await getAdapter(resumePipelineSpec.adapter)
894
- const resumePipelineAvailable = await resumePipelineAdapter.isAvailable()
895
- if (!resumePipelineAvailable) {
896
- printAdapterError(resumePipelineDetectionFailed, resumePipelineSpec.adapter)
897
- process.exit(1)
898
- }
899
- assertPermissionModeSupported(resumePipelineSpec.adapter, resumePipelineSpec)
900
-
901
- console.log(`\n 🏰 OpenCastle Pipeline (Resume): ${latestPipeline.name}`)
902
- console.log(` Pipeline ID: ${latestPipeline.id}`)
903
-
904
- const { startDashboardServer } = await import('./dashboard.js')
905
- let resumePipelineDashResult: { server: import('node:http').Server; port: number; url: string } | null = null
906
- try {
907
- resumePipelineDashResult = await startDashboardServer({
908
- pkgRoot,
909
- openBrowser: true,
910
- convoyId: 'active',
911
- })
912
- } catch {
913
- // Dashboard failure must not block pipeline
914
- }
915
- if (resumePipelineDashResult) {
916
- console.log(` ${c.dim('Dashboard:')} ${resumePipelineDashResult.url}`)
917
- }
918
-
919
- const { createPipelineOrchestrator } = await import('./convoy/pipeline.js')
920
- const resumePipelineOrchestrator = createPipelineOrchestrator({
921
- spec: resumePipelineSpec,
922
- specYaml: latestPipeline.spec_yaml,
923
- adapter: resumePipelineAdapter,
924
- verbose: opts.verbose,
925
- })
926
- const resumePipelineResult = await resumePipelineOrchestrator.resume(latestPipeline.id)
927
- printPipelineResult(resumePipelineResult)
928
- return finishRun(resumePipelineDashResult, resumePipelineResult.status !== 'done')
929
- }
930
-
931
- // ── Standalone convoy resume ────────────────────────────────
932
- // Selection and the finished-run refusal both happened above, against the
933
- // one selector. This branch only executes what was chosen.
934
- const convoy = selected.run.record as import('./convoy/types.js').ConvoyRecord
935
- store.close()
936
-
937
- const resumeSpec = parseTaskSpecText(convoy.spec_yaml)
938
- applyCliOverrides(resumeSpec, opts)
939
-
940
- let resumeDetectionFailed = false
941
- if (!resumeSpec.adapter) {
942
- const detected = await detectAdapter()
943
- if (detected) {
944
- resumeSpec.adapter = detected
945
- console.log(` ℹ Auto-detected adapter: ${detected}`)
946
- } else {
947
- resumeDetectionFailed = true
948
- resumeSpec.adapter = 'claude'
949
- }
950
- }
951
-
952
- const resumeAdapter = await getAdapter(resumeSpec.adapter)
953
- const resumeAvailable = await resumeAdapter.isAvailable()
954
- if (!resumeAvailable) {
955
- printAdapterError(resumeDetectionFailed, resumeSpec.adapter)
956
- process.exit(1)
957
- }
958
- assertPermissionModeSupported(resumeSpec.adapter, resumeSpec)
959
-
960
- console.log(`\n \uD83C\uDFF0 OpenCastle Convoy (Resume): ${convoy.name}`)
961
- console.log(` Convoy ID: ${convoy.id}`)
962
-
963
- const { startDashboardServer } = await import('./dashboard.js')
964
- let resumeDashResult: { server: import('node:http').Server; port: number; url: string } | null = null
311
+ if (args.dryRun) {
312
+ // The engine's own check, so a dry run refuses exactly what a run refuses.
313
+ // Nothing is started and nothing is written to the database.
965
314
  try {
966
- resumeDashResult = await startDashboardServer({
967
- pkgRoot,
968
- openBrowser: true,
969
- convoyId: 'active',
970
- })
971
- } catch {
972
- // Dashboard failure must not block convoy
973
- }
974
- if (resumeDashResult) {
975
- console.log(` ${c.dim('Dashboard:')} ${resumeDashResult.url}`)
976
- }
977
-
978
- const { createConvoyEngine } = await import('./convoy/engine.js')
979
- const resumeEngine = createConvoyEngine({
980
- spec: resumeSpec,
981
- specYaml: convoy.spec_yaml,
982
- adapter: resumeAdapter,
983
- verbose: opts.verbose,
984
- })
985
- let resumeResult: ConvoyResult
986
- try {
987
- resumeResult = await resumeEngine.resume(convoy.id)
315
+ await checkConvoyPlan(spec, runtime?.name ?? (spec.adapter || 'auto'))
988
316
  } catch (err) {
989
- if (err instanceof EngineAlreadyRunningError) {
990
- console.error(` ✗ ${err.message}`)
991
- process.exit(1)
992
- }
993
- throw err
994
- }
995
- printConvoyResult(resumeResult)
996
- return finishRun(resumeDashResult, resumeResult.status !== 'done')
317
+ return fail((err as Error).message)
318
+ }
319
+ if (runtime) applyArgs(spec, args, runtime.name)
320
+ else if (args.concurrency !== null) spec.concurrency = args.concurrency
321
+ console.log('')
322
+ for (const l of describePlan(spec, runtime?.detail ?? c.red('none usable — see below'))) console.log(l)
323
+ console.log('')
324
+ if (runtimeProblem) return fail(runtimeProblem)
325
+ const problem = spec.defaults?.permission_mode ? permissionModeError(runtime!.name, spec.defaults.permission_mode) : null
326
+ if (problem) return fail(problem)
327
+ console.log(` ${c.dim('Dry run — nothing started, nothing recorded. To run it:')} opencastle convoy run ${args.spec}`)
328
+ console.log('')
329
+ return 0
997
330
  }
998
331
 
999
- // ── Formula template resolution / Read and validate spec ─────
1000
- let specText = ''
1001
- let spec: ReturnType<typeof parseTaskSpecText>
1002
-
1003
- if (opts.formula) {
1004
- const { parseFormula, substituteVariables, validateTemplate } = await import('./convoy/formula.js')
1005
- const formulaPath = resolve(process.cwd(), opts.formula)
1006
- let template
1007
- try {
1008
- template = parseFormula(formulaPath)
1009
- } catch (err: unknown) {
1010
- console.error(` ✗ ${(err as Error).message}`)
1011
- console.log(`\n ${c.dim('Resume:')} npx opencastle convoy run --formula ${opts.formula}`)
1012
- process.exit(1)
1013
- }
332
+ if (!runtime) return fail(runtimeProblem!)
333
+ const problem = spec.defaults?.permission_mode ? permissionModeError(runtime.name, spec.defaults.permission_mode) : null
334
+ if (problem) return fail(problem)
335
+ applyArgs(spec, args, runtime.name)
336
+
337
+ console.log('')
338
+ console.log(` ${c.bold(`Convoy: ${spec.name}`)} ${c.dim(`— ${spec.tasks?.length ?? 0} tasks`)}`)
339
+ if (!opts.runtime) console.log(` ${c.dim('Runtime:')} ${runtime.detail}`)
340
+ const models = describeModels(spec, runtime)
341
+ if (models) console.log(` ${c.dim('Models:')} ${models}`)
342
+ const engine = createConvoyEngine({ spec, specYaml: specText, adapter: runtime.adapter, verbose: args.verbose, basePath: projectRoot })
343
+ return drive(() => engine.run(), projectRoot)
344
+ }
1014
345
 
1015
- const validation = validateTemplate(template)
1016
- if (!validation.valid) {
1017
- console.error(` ✗ Invalid formula template:\n • ${validation.errors.join('\n • ')}`)
1018
- console.log(`\n ${c.dim('Resume:')} npx opencastle convoy run --formula ${opts.formula}`)
1019
- process.exit(1)
1020
- }
346
+ /**
347
+ * Which model the tasks run on, said once before they start: a run that picks
348
+ * models by tier spends far less than one on the runtime's default, and a
349
+ * person should be able to see which happened.
350
+ */
351
+ function describeModels(spec: TaskSpec, runtime: ResolvedAdapter): string | null {
352
+ if (spec.defaults?.model) return `${spec.defaults.model} for every task (defaults.model)`
353
+ const t = runtime.adapter.tierModels
354
+ if (!t) return null
355
+ return `by agent tier — ${[t.premium && `premium ${t.premium}`, t.standard && `standard ${t.standard}`, t.economy && `economy ${t.economy} (and reviews)`].filter(Boolean).join(', ')}`
356
+ }
1021
357
 
1022
- if (opts.dryRun) {
1023
- console.log(`\n 📋 Formula: ${template.name}`)
1024
- if (template.description) console.log(` ${template.description}`)
1025
- console.log(` Variables:`)
1026
- for (const [key, val] of Object.entries(opts.setVars)) {
1027
- console.log(` ${key} = ${val}`)
1028
- }
1029
- for (const [key, def] of Object.entries(template.variables)) {
1030
- if (!(key in opts.setVars) && !def.required && def.default) {
1031
- console.log(` ${key} = ${def.default} (default)`)
1032
- }
1033
- }
1034
- }
358
+ // ── convoy resume ─────────────────────────────────────────────────────────────
1035
359
 
1036
- try {
1037
- spec = substituteVariables(template, opts.setVars)
1038
- } catch (err: unknown) {
1039
- console.error(` ✗ ${(err as Error).message}`)
1040
- console.log(`\n ${c.dim('Resume:')} npx opencastle convoy run --formula ${opts.formula}`)
1041
- process.exit(1)
1042
- }
1043
- specText = yamlStringify(spec)
1044
- } else {
1045
- // ── Read and validate spec ──────────────────────────────────
1046
- const specPath = resolve(process.cwd(), opts.file)
1047
- try {
1048
- specText = await readFile(specPath, 'utf8')
1049
- } catch (err: unknown) {
1050
- const e = err as Error & { code?: string }
1051
- if (e.code === 'ENOENT') {
1052
- console.error(` ✗ Task spec file not found: ${opts.file}`)
1053
- } else {
1054
- console.error(` ✗ Cannot read task spec file: ${e.message}`)
1055
- }
1056
- console.log(`\n ${c.dim('Resume:')} npx opencastle convoy run -f ${opts.file}`)
1057
- process.exit(1)
1058
- }
360
+ /** Not done: a status other than done, or a task that did not finish (older runs ended "done" with tasks skipped). */
361
+ function unfinished(run: RunSummary): boolean {
362
+ return run.status !== 'done' || run.tasks_done < run.tasks_total
363
+ }
1059
364
 
1060
- try {
1061
- spec = parseTaskSpecText(specText)
1062
- } catch (err: unknown) {
1063
- console.error(` ✗ ${(err as Error).message}`)
1064
- console.log(`\n ${c.dim('Resume:')} npx opencastle convoy run -f ${opts.file}`)
1065
- process.exit(1)
1066
- }
365
+ /** `convoy resume`: the exit code it should end with. */
366
+ export async function resumeLast(args: RunArgs): Promise<number> {
367
+ const projectRoot = projectRootHere()
368
+ const runs = readRuns(projectRoot, 200)
369
+ if (runs.length === 0) {
370
+ console.error(` ${c.red('✗')} No convoy runs in this project yet.`)
371
+ console.error(` ${c.dim('Start one:')} opencastle convoy "<task>"`)
372
+ return 1
1067
373
  }
1068
-
1069
- // Apply CLI overrides
1070
- applyCliOverrides(spec, opts)
1071
-
1072
- // Refuse the flags this spec's executor cannot act on, before anything runs.
1073
- assertFlagsApplyToSpec(spec, opts)
1074
-
1075
- // ── Auto-detect adapter if not specified ─────────────────────
1076
- let detectionFailed = false
1077
- if (!spec.adapter) {
1078
- const detected = await detectAdapter()
1079
- if (detected) {
1080
- spec.adapter = detected
1081
- console.log(` ℹ Auto-detected adapter: ${detected}`)
1082
- } else {
1083
- detectionFailed = true
1084
- spec.adapter = 'claude' // fallback for availability check below
1085
- }
374
+ const target = runs.find(unfinished)
375
+ if (!target) {
376
+ const last = runs[0]
377
+ console.log(` Nothing to resume: the last run, ${c.bold(last.name)}, finished with all ${last.tasks_total} tasks done.`)
378
+ console.log(` ${c.dim('Start another:')} opencastle convoy "<task>"`)
379
+ return 0
1086
380
  }
1087
-
1088
- // ── Dry run ──────────────────────────────────────────────────
1089
- if (opts.dryRun) {
1090
- if (isPipelineSpec(spec)) {
1091
- console.log(`\n 🏰 Pipeline Plan: ${spec.name}`)
1092
- console.log(` Convoy chain: ${(spec.depends_on_convoy as string[]).join(' → ')}`)
1093
- if (spec.tasks?.length) {
1094
- console.log(` Plus ${spec.tasks.length} local tasks after chain completes`)
1095
- }
1096
- if (spec.branch) console.log(` Branch: ${spec.branch}`)
1097
- if (spec.gates?.length) console.log(` Gates: ${spec.gates.length} validation commands`)
1098
- if (!spec.tasks?.length) return
1099
- } else if (isConvoySpec(spec)) {
1100
- console.log(`\n \uD83C\uDFF0 Convoy Plan: ${spec.name}`)
1101
- console.log(
1102
- ` Adapter: ${spec.adapter} | Concurrency: ${spec.concurrency} | Tasks: ${spec.tasks!.length}`
1103
- )
1104
- if (spec.branch) console.log(` Branch: ${spec.branch}`)
1105
- if (spec.gates?.length) console.log(` Gates: ${spec.gates.length} validation commands`)
1106
- }
1107
- const phases = buildPhases(spec.tasks!)
1108
- printExecutionPlan(spec, phases)
1109
- return
381
+ if (isRunAlive(projectRoot, target.id)) {
382
+ console.error(` ${c.red('✗')} ${target.name} (${target.id}) is still running in another process.`)
383
+ console.error(` ${c.dim('Watch it:')} opencastle convoy dashboard`)
384
+ return 1
1110
385
  }
1111
386
 
1112
- // ── Check adapter ────────────────────────────────────────────
1113
- const adapter = await getAdapter(spec.adapter)
1114
- const available = await adapter.isAvailable()
1115
- if (!available) {
1116
- printAdapterError(detectionFailed, spec.adapter)
1117
- console.log(`\n ${c.dim('Resume:')} npx opencastle convoy run -f ${opts.file}`)
1118
- process.exit(1)
387
+ const recorded = readRunSpec(projectRoot, target.id)
388
+ if (!recorded) return fail(`The spec ${target.id} was started with is not in .opencastle/convoy.db.`)
389
+ let spec: TaskSpec
390
+ try {
391
+ spec = parseTaskSpecText(recorded.specYaml)
392
+ } catch (err) {
393
+ return fail(`The spec ${target.name} was recorded with no longer reads: ${(err as Error).message}`)
1119
394
  }
1120
- assertPermissionModeSupported(spec.adapter, spec)
1121
-
1122
- // ── Pipeline orchestrator path (version: 2 specs with depends_on_convoy) ──
1123
- if (isPipelineSpec(spec)) {
1124
- const { createPipelineOrchestrator } = await import('./convoy/pipeline.js')
1125
- console.log(`\n 🏰 OpenCastle Pipeline: ${spec.name}`)
1126
- console.log(` Convoy chain: ${(spec.depends_on_convoy as string[]).join(' → ')}`)
1127
- if (spec.branch) console.log(` Branch: ${spec.branch}`)
1128
- if (spec.gates?.length) console.log(` Gates: ${spec.gates.length} validation commands`)
1129
395
 
1130
- const { startDashboardServer } = await import('./dashboard.js')
1131
- let pipelineDashboardResult: { server: import('node:http').Server; port: number; url: string } | null = null
1132
- try {
1133
- pipelineDashboardResult = await startDashboardServer({
1134
- pkgRoot,
1135
- openBrowser: true,
1136
- convoyId: 'active',
1137
- })
1138
- } catch {
1139
- // Dashboard failure must not block pipeline
1140
- }
1141
- if (pipelineDashboardResult) {
1142
- console.log(` ${c.dim('Dashboard:')} ${pipelineDashboardResult.url}`)
1143
- }
1144
-
1145
- const pipelineOrchestrator = createPipelineOrchestrator({
1146
- spec,
1147
- specYaml: specText,
1148
- adapter,
1149
- verbose: opts.verbose,
1150
- })
396
+ const done = `${target.tasks_done}/${target.tasks_total} tasks done`
397
+ console.log('')
398
+ console.log(` ${c.bold(`Resuming ${target.name}`)} ${c.dim(`(${target.id}) — ${target.status}, ${done}`)}`)
399
+ if (target !== runs[0]) {
400
+ console.log(` ${c.dim(`The newest run, ${runs[0].name}, finished; this is the newest one that did not.`)}`)
401
+ }
1151
402
 
1152
- let pipelineResult: PipelineResult
1153
- try {
1154
- pipelineResult = await pipelineOrchestrator.run()
1155
- } catch (err) {
1156
- if (err instanceof EngineAlreadyRunningError) {
1157
- console.error(` ✗ ${err.message}`)
1158
- console.log(`\n ${c.dim('Resume:')} npx opencastle convoy run -f ${opts.file} --resume`)
1159
- process.exit(1)
1160
- }
1161
- throw err
403
+ if (args.dryRun) {
404
+ // Read from the read model: a preview opens nothing that could migrate or write.
405
+ const tasks = readRun(projectRoot, target.id)?.tasks ?? []
406
+ const again = new Set<string>(['pending', ...RESUME_RESET_STATUSES])
407
+ const selected = tasks.filter((t) => again.has(t.status))
408
+ console.log('')
409
+ if (selected.length === 0) {
410
+ console.log(' No task would run: every task is done.')
411
+ } else {
412
+ console.log(` Would run ${selected.length} of ${tasks.length} task(s):`)
413
+ for (const t of selected) console.log(` ${t.id} ${c.dim(`— ${t.agent} [${t.status}]`)}`)
1162
414
  }
1163
- printPipelineResult(pipelineResult)
1164
- return finishRun(
1165
- pipelineDashboardResult,
1166
- pipelineResult.status !== 'done',
1167
- `npx opencastle convoy run -f ${opts.file} --retry-failed`,
1168
- )
415
+ console.log('')
416
+ console.log(` ${c.dim('Dry run — nothing started, nothing recorded.')}`)
417
+ console.log('')
418
+ return 0
1169
419
  }
1170
420
 
1171
- // ── Convoy engine path (version: 1 specs) ────────────────────
1172
- if (isConvoySpec(spec)) {
1173
- const { createConvoyEngine } = await import('./convoy/engine.js')
1174
- console.log(`\n \uD83C\uDFF0 OpenCastle Convoy: ${spec.name}`)
1175
- console.log(
1176
- ` Adapter: ${adapter.name} | Concurrency: ${spec.concurrency} | Tasks: ${spec.tasks!.length}`
1177
- )
1178
- if (spec.branch) console.log(` Branch: ${spec.branch}`)
1179
- if (spec.gates?.length) console.log(` Gates: ${spec.gates.length} validation commands`)
1180
-
1181
- const { startDashboardServer } = await import('./dashboard.js')
1182
- let dashboardResult: { server: import('node:http').Server; port: number; url: string } | null = null
1183
- try {
1184
- dashboardResult = await startDashboardServer({
1185
- pkgRoot,
1186
- openBrowser: true,
1187
- convoyId: 'active',
1188
- })
1189
- } catch {
1190
- // Dashboard failure must not block convoy
1191
- }
1192
- if (dashboardResult) {
1193
- console.log(` ${c.dim('Dashboard:')} ${dashboardResult.url}`)
1194
- }
421
+ let runtime: ResolvedAdapter
422
+ try {
423
+ runtime = await chooseRuntime(projectRoot, args.adapter, spec, recorded.adapter)
424
+ } catch (err) {
425
+ return fail((err as Error).message)
426
+ }
427
+ const problem = spec.defaults?.permission_mode ? permissionModeError(runtime.name, spec.defaults.permission_mode) : null
428
+ if (problem) return fail(problem)
429
+ applyArgs(spec, args, runtime.name)
430
+ console.log(` ${c.dim('Runtime:')} ${runtime.detail}`)
431
+ const models = describeModels(spec, runtime)
432
+ if (models) console.log(` ${c.dim('Models:')} ${models}`)
433
+
434
+ const engine = createConvoyEngine({ spec, specYaml: recorded.specYaml, adapter: runtime.adapter, verbose: args.verbose, basePath: projectRoot })
435
+ return drive(() => engine.resume(target.id), projectRoot)
436
+ }
1195
437
 
1196
- const engine = createConvoyEngine({
1197
- spec,
1198
- specYaml: specText,
1199
- adapter,
1200
- verbose: opts.verbose,
1201
- })
438
+ // ── Entry points ──────────────────────────────────────────────────────────────
1202
439
 
1203
- if (opts.watch) {
1204
- const pidPath = resolve(process.cwd(), '.opencastle', 'watch.pid')
1205
- const { watchLoop } = await import('./watch.js')
1206
- await watchLoop({
1207
- spec,
1208
- specText,
1209
- specPath: resolve(process.cwd(), opts.file),
1210
- adapter,
1211
- verbose: opts.verbose,
1212
- pidPath,
1213
- clearScratchpad: opts.clearScratchpad,
1214
- watchConfigPath: opts.watchConfig ? resolve(process.cwd(), opts.watchConfig) : null,
1215
- printResult: printConvoyResult,
1216
- })
1217
- return
1218
- }
440
+ /**
441
+ * Exit once what was written has reached the terminal or the pipe. Exiting is
442
+ * deliberate: a finished run must never sit waiting for Ctrl+C because some
443
+ * handle — a socket, a timer, an agent's pipe — was left open.
444
+ */
445
+ export function exitWith(code: number): void {
446
+ process.exitCode = code
447
+ process.stdout.write('', () => process.stderr.write('', () => process.exit(code)))
448
+ }
1219
449
 
1220
- let result: ConvoyResult
1221
- try {
1222
- result = await engine.run()
1223
- } catch (err) {
1224
- if (err instanceof EngineAlreadyRunningError) {
1225
- console.error(` ✗ ${err.message}`)
1226
- console.log(`\n ${c.dim('Resume:')} npx opencastle convoy run -f ${opts.file} --resume`)
1227
- process.exit(1)
1228
- }
1229
- throw err
1230
- }
1231
- printConvoyResult(result)
1232
- return finishRun(
1233
- dashboardResult,
1234
- result.status !== 'done',
1235
- `npx opencastle convoy run -f ${opts.file} --retry-failed`,
1236
- )
450
+ async function main(args: string[], command: 'run' | 'resume'): Promise<void> {
451
+ const parsed = parseRunArgs(args, command)
452
+ if ('error' in parsed) {
453
+ console.error(` ${c.red('✗')} ${parsed.error}`)
454
+ console.error(` Run "opencastle convoy ${command} --help" for usage.`)
455
+ exitWith(1)
456
+ return
1237
457
  }
458
+ if (parsed.help) {
459
+ console.log(command === 'run' ? RUN_HELP : RESUME_HELP)
460
+ return
461
+ }
462
+ exitWith(command === 'run' ? await runSpec(parsed) : await resumeLast(parsed))
463
+ }
1238
464
 
1239
- // ── Legacy executor path ──────────────────────────────────────
1240
- console.log(`\n \uD83C\uDFF0 OpenCastle Run: ${spec.name}`)
1241
- console.log(
1242
- ` Adapter: ${adapter.name} | Concurrency: ${spec.concurrency} | Tasks: ${spec.tasks!.length}`
1243
- )
1244
-
1245
- const reporter = createReporter(spec, {
1246
- reportDir: opts.reportDir
1247
- ? resolve(process.cwd(), opts.reportDir)
1248
- : undefined,
1249
- verbose: opts.verbose,
1250
- })
1251
-
1252
- const executor = createExecutor(spec, adapter, reporter)
1253
- const report = await executor.run()
465
+ /** `opencastle convoy run <spec.yml>`. */
466
+ export default async function run({ args }: CliContext): Promise<void> {
467
+ await main(args, 'run')
468
+ }
1254
469
 
1255
- // ── Exit code ────────────────────────────────────────────────
1256
- const hasFailures = report.summary.failed > 0 || report.summary['timed-out'] > 0
1257
- process.exit(hasFailures ? 1 : 0)
470
+ /** `opencastle convoy resume`, and its hidden alias `retry`. */
471
+ export async function resume({ args }: CliContext): Promise<void> {
472
+ await main(args, 'resume')
1258
473
  }