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
@@ -1,15 +1,28 @@
1
- import { readFile, writeFile, mkdir, unlink } from 'node:fs/promises'
1
+ import { readFile, writeFile, mkdir } from 'node:fs/promises'
2
2
  import { existsSync } from 'node:fs'
3
- import { resolve } from 'node:path'
4
- import { stringify } from 'yaml'
3
+ import { createHash } from 'node:crypto'
4
+ import { resolve, relative, basename } from 'node:path'
5
5
  import { c, confirm, closePrompts } from './prompt.js'
6
- import { runPromptStep, readProjectMcpServers } from './plan.js'
7
- import type { PromptStepOptions } from './plan.js'
8
- import { cleanupAdapters } from './run/adapters/index.js'
6
+ import { runPromptStep, freePath } from './plan.js'
7
+ import type { PromptStepOptions, PromptStepResult } from './plan.js'
8
+ import { resolveAdapter, cleanupAdapters, type ResolvedAdapter } from './run/adapters/index.js'
9
+ import { findProjectRoot } from './convoy/read-model.js'
10
+ import type { AgentAdapter } from './convoy/spec-types.js'
9
11
  import type { CliContext } from './types.js'
10
- import { parseYaml, validateSpec } from './run/schema.js'
11
- import { buildConvoyYaml, parseTaskPlanWithReason, parsePatches, applyPatches, deriveSpecEnrichment } from './convoy/spec-builder.js'
12
- import type { TaskPlan, SpecEnrichment } from './convoy/spec-builder.js'
12
+ import { foldTestOnlyTasks,
13
+ applyPatches,
14
+ buildConvoyYaml,
15
+ checkPlan,
16
+ detectGates,
17
+ mergeGroupPlans,
18
+ normalizePlanFiles,
19
+ parsePatches,
20
+ parseTaskPlanWithReason,
21
+ planConcurrency,
22
+ sequenceConflicts,
23
+ slugify,
24
+ } from './convoy/spec-builder.js'
25
+ import type { SpecSettings, TaskPlan } from './convoy/spec-builder.js'
13
26
 
14
27
  export interface ConvoyGroup {
15
28
  name: string
@@ -290,834 +303,606 @@ export function topologicalSortGroups(groups: ConvoyGroup[]): ConvoyGroup[] {
290
303
  return sorted
291
304
  }
292
305
 
293
- const HELP = `
294
- opencastle convoy plan [options]
295
-
296
- Run the full convoy generation pipeline from a feature prompt:
297
-
298
- Step 1 — Generate PRD (generate-prd)
299
- Step 2 — Validate PRD (validate-prd)
300
- Step 3 — Fix PRD (fix-prd, up to 2 retries if invalid)
301
- Step 4 — Assess complexity (assess-complexity, determines single vs chain)
302
- Step 5 — Generate task plan (generate-convoy outputs JSON, code builds YAML)
303
- Step 6 — Validate convoy spec (programmatic + semantic validation)
304
- Step 7 — Fix convoy spec (patch-based fixing, up to 2 retries)
305
-
306
- Options:
307
- --text, -t <text> Feature prompt text (required, unless --prd is set)
308
- --prd <path> Skip step 1 — use an existing PRD file
309
- --output-prd <path> Override path for the generated PRD
310
- --output-spec <path> Override path for the generated convoy spec
311
- --adapter, -a <name> Override agent runtime adapter
312
- --verbose Show full agent output for each step
313
- --dry-run Generate and print the PRD prompt only, then stop
314
- --complexity <path> Skip complexity assessment — use an existing complexity file
315
- --skip-validation Skip PRD and convoy validation (steps 2, 3, 6, 7)
316
- --help, -h Show this help
317
- `
318
-
319
- interface PipelineOptions {
320
- text: string | null
321
- prd: string | null
322
- complexity: string | null
323
- outputPrd: string | null
324
- outputSpec: string | null
325
- adapter: string | null
326
- verbose: boolean
327
- dryRun: boolean
328
- skipValidation: boolean
329
- help: boolean
306
+ /** The SHA-256 of a PRD's text: the complexity cache's key. */
307
+ export function hashPrd(content: string): string {
308
+ return createHash('sha256').update(content).digest('hex')
330
309
  }
331
310
 
332
- function parseArgs(args: string[]): PipelineOptions {
333
- const opts: PipelineOptions = {
334
- text: null,
335
- prd: null,
336
- complexity: null,
337
- outputPrd: null,
338
- outputSpec: null,
339
- adapter: null,
340
- verbose: false,
341
- dryRun: false,
342
- skipValidation: false,
343
- help: false,
344
- }
345
-
346
- for (let i = 0; i < args.length; i++) {
347
- const arg = args[i]
348
- switch (arg) {
349
- case '--help':
350
- case '-h':
351
- opts.help = true
352
- break
353
- case '--text':
354
- case '-t':
355
- if (i + 1 >= args.length) { console.error(' ✗ --text requires a value'); process.exit(1) }
356
- opts.text = args[++i]
357
- if (!opts.text.trim()) { console.error(' ✗ --text cannot be empty'); process.exit(1) }
358
- break
359
- case '--prd':
360
- if (i + 1 >= args.length) { console.error(' ✗ --prd requires a path'); process.exit(1) }
361
- opts.prd = args[++i]
362
- break
363
- case '--complexity':
364
- if (i + 1 >= args.length) { console.error(' ✗ --complexity requires a path'); process.exit(1) }
365
- opts.complexity = args[++i]
366
- break
367
- case '--output-prd':
368
- if (i + 1 >= args.length) { console.error(' ✗ --output-prd requires a path'); process.exit(1) }
369
- opts.outputPrd = args[++i]
370
- break
371
- case '--output-spec':
372
- if (i + 1 >= args.length) { console.error(' ✗ --output-spec requires a path'); process.exit(1) }
373
- opts.outputSpec = args[++i]
374
- break
375
- case '--adapter':
376
- case '-a':
377
- if (i + 1 >= args.length) { console.error(' ✗ --adapter requires a name'); process.exit(1) }
378
- opts.adapter = args[++i]
379
- break
380
- case '--verbose':
381
- opts.verbose = true
382
- break
383
- case '--dry-run':
384
- case '--dryRun':
385
- opts.dryRun = true
386
- break
387
- case '--skip-validation':
388
- opts.skipValidation = true
389
- break
390
- default:
391
- console.error(` ✗ Unknown option: ${arg}. Run with --help to see available options.`)
392
- process.exit(1)
393
- }
311
+ /**
312
+ * The cached assessment of exactly this PRD, or null.
313
+ *
314
+ * The cache sits next to the PRD and records the hash of the text it assessed;
315
+ * it is used only when that hash matches. It used to be trusted by path alone,
316
+ * and PRDs were overwritten by title, so a different request that produced the
317
+ * same title was planned with the previous request's assessment.
318
+ */
319
+ export async function readCachedComplexity(prdPath: string, prdContent: string): Promise<ComplexityAssessment | null> {
320
+ const path = deriveComplexityPath(prdPath)
321
+ if (!existsSync(path)) return null
322
+ try {
323
+ const raw = JSON.parse(await readFile(path, 'utf8')) as { prd_sha256?: unknown }
324
+ if (raw.prd_sha256 !== hashPrd(prdContent)) return null
325
+ return parseComplexityAssessment(JSON.stringify(raw))
326
+ } catch {
327
+ return null
394
328
  }
395
-
396
- return opts
397
329
  }
398
330
 
399
- const MAX_FIX_RETRIES = 2
400
-
401
- function relPath(abs: string): string {
402
- return abs.startsWith(process.cwd()) ? abs.slice(process.cwd().length + 1) : abs
331
+ async function writeCachedComplexity(prdPath: string, prdContent: string, assessment: ComplexityAssessment): Promise<void> {
332
+ const record = { prd_sha256: hashPrd(prdContent), ...assessment }
333
+ await writeFile(deriveComplexityPath(prdPath), JSON.stringify(record, null, 2) + '\n', 'utf8')
403
334
  }
404
335
 
405
- function stepLabel(n: number, total: number, name: string): string {
406
- return c.bold(c.cyan(` [${n}/${total}] ${name}`))
336
+ // ── Planning ────────────────────────────────────────────────────────────────
337
+
338
+ /** Rounds of fix-prd, and of fix-convoy, before the planner stops asking. */
339
+ const MAX_FIX_ROUNDS = 2
340
+
341
+ export interface PlanRequest {
342
+ /** What the user asked for. Absent when re-planning from a PRD. */
343
+ task?: string
344
+ /** An existing PRD to plan from instead of writing one. */
345
+ prdPath?: string
346
+ /** The runtime every step runs on, resolved once by the caller. */
347
+ adapter: AgentAdapter
348
+ /** Its name, recorded in the spec so run and resume stay on it. */
349
+ adapterName: string
350
+ pkgRoot: string
351
+ /** Defaults to the current directory. */
352
+ projectRoot?: string
353
+ verbose?: boolean
354
+ /**
355
+ * Have validate-convoy review the plan. Only when nobody will read it before
356
+ * it runs (`--yes`): a person looking at the plan is the better reviewer,
357
+ * and the session is skipped for them.
358
+ */
359
+ critic?: boolean
407
360
  }
408
361
 
409
- async function fixPrd(
410
- sharedOpts: Omit<PromptStepOptions, 'template' | 'goalText'>,
411
- prdPath: string,
412
- prdContent: string,
413
- initialErrors: string,
414
- totalSteps: number,
415
- adapterFlag: string | null,
416
- ): Promise<void> {
417
- const MAX_PRD_FIX_RETRIES = 2
418
- let fixedPrdContent = prdContent
419
- let prdValidationErrors = initialErrors
420
- let prdFixed = false
421
-
422
- for (let attempt = 1; attempt <= MAX_PRD_FIX_RETRIES; attempt++) {
423
- const label = `Fix PRD attempt ${attempt}/${MAX_PRD_FIX_RETRIES}…`
424
- console.log(stepLabel(3, totalSteps, label))
425
-
426
- try {
427
- await runPromptStep({
428
- ...sharedOpts,
429
- template: 'fix-prd',
430
- goalText: fixedPrdContent,
431
- contextText: prdValidationErrors,
432
- outputPath: prdPath,
433
- })
434
- } catch (err) {
435
- console.error(`\n ✗ Step 3 (attempt ${attempt}) failed: ${err instanceof Error ? err.message : String(err)}`)
436
- process.exit(1)
437
- }
438
-
439
- console.log(c.dim(` Re-validating after fix…`))
362
+ export interface PlanOutcome {
363
+ /** Null for a small change, planned straight from the request. */
364
+ prdPath: string | null
365
+ specPath: string
366
+ plan: TaskPlan
367
+ settings: SpecSettings
368
+ /** What still fails the checks after every fix. A spec with any is written, not runnable. */
369
+ problems: string[]
370
+ /** What planning took: sessions run, time, and spend as the runtime reported it. */
371
+ planning?: PlanningSpend
372
+ }
440
373
 
441
- fixedPrdContent = await readFile(prdPath, 'utf8')
374
+ export interface PlanningSpend {
375
+ sessions: number
376
+ ms: number
377
+ tokens: number
378
+ costUsd: number
379
+ /** False when some session reported no cost, so `costUsd` is a lower bound. */
380
+ costComplete: boolean
381
+ }
442
382
 
443
- let revalidation
444
- try {
445
- revalidation = await runPromptStep({
446
- ...sharedOpts,
447
- template: 'validate-prd',
448
- goalText: `<!-- validation-pass: ${attempt + 1} -->\n${fixedPrdContent}`,
449
- })
450
- } catch (err) {
451
- console.error(`\n ✗ Re-validation failed: ${err instanceof Error ? err.message : String(err)}`)
452
- process.exit(1)
453
- }
383
+ type StepRunner = (template: string, inputs: Omit<PromptStepOptions, 'template' | 'adapter' | 'pkgRoot'>) => Promise<PromptStepResult>
454
384
 
455
- if (revalidation.isValid) {
456
- console.log(c.green(` ✓ PRD fixed and validated\n`))
457
- prdFixed = true
458
- break
459
- }
385
+ function done(text: string, detail = ''): void {
386
+ console.log(` ${c.green('✓')} ${text}${detail ? ` ${c.dim(detail)}` : ''}`)
387
+ }
460
388
 
461
- prdValidationErrors = revalidation.errors ?? revalidation.rawOutput
389
+ function warn(text: string): void {
390
+ console.log(` ${c.yellow('⚠')} ${text}`)
391
+ }
462
392
 
463
- if (attempt < MAX_PRD_FIX_RETRIES) {
464
- console.log(c.yellow(` ⚠ Still has issues after fix attempt ${attempt} — retrying…\n`))
465
- console.log(c.dim(prdValidationErrors))
466
- console.log()
467
- }
468
- }
393
+ /** Agent-written text, indented under the line that introduced it. */
394
+ function indented(text: string): string {
395
+ return c.dim(text.trim().split('\n').map((line) => ` ${line}`).join('\n'))
396
+ }
469
397
 
470
- if (!prdFixed) {
471
- console.log(c.yellow(`\n ⚠ Could not fully auto-fix the PRD after ${MAX_PRD_FIX_RETRIES} attempts — continuing with best-effort PRD.\n`))
472
- console.log(c.dim(` Remaining issues:\n`))
473
- console.log(c.dim(prdValidationErrors))
474
- console.log(
475
- c.dim(`\n PRD saved to ${relPath(prdPath)} with best available fixes.`) +
476
- c.dim(`\n You can re-validate later with:\n`) +
477
- ` opencastle convoy plan --prd ${relPath(prdPath)}${adapterFlag ? ` --adapter ${adapterFlag}` : ''}\n`
478
- )
479
- }
398
+ function relPath(abs: string): string {
399
+ const rel = relative(process.cwd(), abs)
400
+ return rel && !rel.startsWith('..') ? rel : abs
480
401
  }
481
402
 
482
- export default async function pipeline({ args, pkgRoot }: CliContext): Promise<void> {
483
- const opts = parseArgs(args)
403
+ function message(err: unknown): string {
404
+ return err instanceof Error ? err.message : String(err)
405
+ }
484
406
 
485
- if (opts.help) {
486
- console.log(HELP)
487
- return
488
- }
407
+ /**
408
+ * Like Promise.all, but waits for every step before reporting the first failure,
409
+ * so a failed step never leaves its siblings' sessions running unwatched.
410
+ */
411
+ async function settleAll<T>(work: Array<Promise<T>>): Promise<T[]> {
412
+ const settled = await Promise.allSettled(work)
413
+ const failed = settled.find((s): s is PromiseRejectedResult => s.status === 'rejected')
414
+ if (failed) throw failed.reason
415
+ return settled.map((s) => (s as PromiseFulfilledResult<T>).value)
416
+ }
489
417
 
490
- if (!opts.text && !opts.prd) {
491
- console.error(` ✗ Either --text or --prd is required.`)
492
- console.log(HELP)
493
- process.exit(1)
418
+ /** generate-convoy, with the one retry an unreadable answer gets. */
419
+ async function generatePlan(step: StepRunner, goal: string, context: string, label: string, convoyDir: string): Promise<TaskPlan> {
420
+ let raw = ''
421
+ let reason = ''
422
+ for (let attempt = 1; attempt <= 2; attempt++) {
423
+ raw = (await step('generate-convoy', { goalText: goal, contextText: context })).rawOutput
424
+ const parsed = parseTaskPlanWithReason(raw)
425
+ if (parsed.plan) return parsed.plan
426
+ reason = parsed.reason ?? 'unreadable'
427
+ if (attempt === 1) warn(`The ${label} plan could not be read (${reason}) — asking once more`)
494
428
  }
429
+ await mkdir(convoyDir, { recursive: true })
430
+ const kept = freePath(convoyDir, `${slugify(label) || 'plan'}.task-plan`, '.json')
431
+ await writeFile(kept, raw + '\n', 'utf8')
432
+ throw new Error(`The ${label} plan could not be read after a retry: ${reason}. The answer is in ${relPath(kept)}.`)
433
+ }
495
434
 
496
- if (opts.text && opts.prd) {
497
- console.error(` ✗ --text and --prd are mutually exclusive.`)
498
- process.exit(1)
435
+ /** One fix-convoy round: patches applied to the plan, globs reduced again. */
436
+ async function fixPlan(step: StepRunner, plan: TaskPlan, problems: string): Promise<TaskPlan> {
437
+ const answer = await step('fix-convoy', { goalText: JSON.stringify(plan, null, 2), contextText: problems })
438
+ const patches = parsePatches(answer.rawOutput)
439
+ if (!patches?.length) {
440
+ warn('No usable patches came back')
441
+ return plan
499
442
  }
443
+ return normalizePlanFiles(applyPatches(plan, patches)).plan
444
+ }
500
445
 
501
- if (opts.prd) {
502
- const resolvedPrd = resolve(process.cwd(), opts.prd)
503
- if (!existsSync(resolvedPrd)) {
504
- console.error(` ✗ PRD file not found: ${opts.prd}`)
505
- process.exit(1)
446
+ /**
447
+ * From a request (or an edited PRD) to a checked spec on disk.
448
+ *
449
+ * Sessions, all read-only, on the one adapter the caller resolved:
450
+ * - generate-prd, unless a PRD was given;
451
+ * - validate-prd beside assess-complexity, which is skipped when this exact
452
+ * PRD was assessed before; up to two fix-prd + validate-prd rounds;
453
+ * - generate-convoy, once, or once per group at the same time for a large
454
+ * feature; one retry when an answer cannot be read;
455
+ * - fix-convoy only when the code's checks fail, at most twice;
456
+ * - validate-convoy only as the reviewer for `--yes`.
457
+ *
458
+ * The semantic validate-convoy pass that followed every plan is gone: the
459
+ * checks it was there for are done in code, and a person reads the plan
460
+ * before it runs.
461
+ */
462
+ /** Where a PRD would go, for a change small enough to plan from the request alone. */
463
+ const NO_PRD = 'There is no PRD: this is a small change, planned straight from the request. Read the code it touches before you plan.'
464
+
465
+ export async function planConvoy(req: PlanRequest): Promise<PlanOutcome> {
466
+ const root = req.projectRoot ?? process.cwd()
467
+ const convoyDir = resolve(root, '.opencastle', 'convoys')
468
+ // Planning is agent sessions too, and the run's own total never counted them.
469
+ const started = Date.now()
470
+ const spend: PlanningSpend = { sessions: 0, ms: 0, tokens: 0, costUsd: 0, costComplete: true }
471
+ const step: StepRunner = async (template, inputs) => {
472
+ const r = await runPromptStep({ template, adapter: req.adapter, pkgRoot: req.pkgRoot, cwd: root, verbose: req.verbose, ...inputs })
473
+ spend.sessions++
474
+ spend.tokens += r.tokens ?? 0
475
+ if (r.costUsd === undefined) spend.costComplete = false
476
+ else spend.costUsd += r.costUsd
477
+ spend.ms = Date.now() - started
478
+ return r
479
+ }
480
+
481
+ // ── A small change: no PRD ────────────────────────────────────────────────
482
+ // Sizing the request first is one short economy session. When it is small,
483
+ // the plan is written straight from it: a PRD, its review and its fixes were
484
+ // four or five sessions and most of the planning time — 7m 25s in a real
485
+ // run — for a change the request already described.
486
+ let prdPath: string | null = null
487
+ let plan: TaskPlan | null = null
488
+ let quick: ComplexityAssessment | null = null
489
+ if (!req.prdPath && req.task) {
490
+ quick = await step('assess-complexity', { goalText: req.task, contextText: req.task })
491
+ .then((r) => parseComplexityAssessment(r.rawOutput))
492
+ .catch(() => null)
493
+ if (quick?.complexity === 'low' && quick.recommended_strategy !== 'chain') {
494
+ done('Sized', 'low — planned straight from the request, without a PRD')
495
+ plan = await generatePlan(step, req.task, appendTaskComplexity(NO_PRD, quick.task_complexity), 'task', convoyDir)
496
+ done(`${plan.tasks.length} tasks planned`)
497
+ }
498
+ }
499
+
500
+ if (!plan) {
501
+ // ── The PRD ───────────────────────────────────────────────────────────────
502
+ if (req.prdPath) {
503
+ prdPath = resolve(root, req.prdPath)
504
+ done('PRD', relPath(prdPath))
505
+ } else {
506
+ const written = await step('generate-prd', { goalText: req.task ?? '' })
507
+ prdPath = written.outputPath!
508
+ done('PRD written', relPath(prdPath))
509
+ }
510
+ let prd = await readFile(prdPath!, 'utf8')
511
+
512
+ // Both only read the PRD, so they run side by side. fix-prd is told to keep
513
+ // the PRD's phases, so the assessment of this draft still fits a fixed one;
514
+ // it is cached under this draft's text, which is the text it describes.
515
+ const cached = await readCachedComplexity(prdPath, prd)
516
+ const assessedFrom = prd
517
+ const [verdict, complexity] = await settleAll<PromptStepResult | ComplexityAssessment | null>([
518
+ step('validate-prd', { goalText: `<!-- validation-pass: 1 -->\n${prd}` }),
519
+ // The request was sized already. Only groups need sizing against the
520
+ // PRD, whose phases they name.
521
+ cached || (quick && quick.recommended_strategy !== 'chain')
522
+ ? Promise.resolve(cached ?? quick)
523
+ : step('assess-complexity', { goalText: prd, contextText: req.task ?? '' })
524
+ .then((r) => parseComplexityAssessment(r.rawOutput))
525
+ .catch((err: unknown) => {
526
+ warn(`Could not size the work (${message(err)}) — planning it as one`)
527
+ return null
528
+ }),
529
+ ]) as [PromptStepResult, ComplexityAssessment | null]
530
+
531
+ if (complexity && !cached && complexity !== quick) await writeCachedComplexity(prdPath, assessedFrom, complexity)
532
+
533
+ if (verdict.isValid) {
534
+ done('PRD checked')
535
+ } else {
536
+ let issues = verdict.errors || verdict.rawOutput
537
+ let fixed = false
538
+ for (let round = 1; round <= MAX_FIX_ROUNDS && !fixed; round++) {
539
+ warn(`The PRD has issues — fixing (${round}/${MAX_FIX_ROUNDS})`)
540
+ console.log(indented(issues))
541
+ await step('fix-prd', { goalText: prd, contextText: issues, outputPath: prdPath })
542
+ prd = await readFile(prdPath, 'utf8')
543
+ const again = await step('validate-prd', { goalText: `<!-- validation-pass: ${round + 1} -->\n${prd}` })
544
+ fixed = again.isValid === true
545
+ if (!fixed) issues = again.errors || again.rawOutput
546
+ }
547
+ if (fixed) done('PRD fixed and checked')
548
+ else warn(`The PRD still has issues after ${MAX_FIX_ROUNDS} fixes — planning from it anyway:\n${indented(issues)}`)
506
549
  }
507
- }
508
550
 
509
- const totalSteps = opts.skipValidation ? 4 : 7
510
- const mcpServers = await readProjectMcpServers(process.cwd())
511
- const sharedOpts = {
512
- adapterName: opts.adapter ?? undefined,
513
- verbose: opts.verbose,
514
- pkgRoot,
515
- ...(mcpServers.length ? { mcpServers } : {}),
516
- }
517
-
518
- console.log(c.bold('\n opencastle convoy\n'))
519
-
520
- // ── Step 1: Generate PRD ──────────────────────────────────────────────────
521
- let prdPath: string
522
-
523
- if (opts.prd) {
524
- prdPath = resolve(process.cwd(), opts.prd)
525
- console.log(c.dim(` [−] Skipping PRD generation — using: ${relPath(prdPath)}`))
526
- } else {
527
- console.log(stepLabel(1, totalSteps, 'Generating PRD…'))
528
-
529
- let result
530
- try {
531
- result = await runPromptStep({
532
- ...sharedOpts,
533
- template: 'generate-prd',
534
- goalText: opts.text!,
535
- outputPath: opts.outputPrd ? resolve(process.cwd(), opts.outputPrd) : undefined,
536
- dryRun: opts.dryRun,
537
- })
538
- } catch (err) {
539
- console.error(`\n ✗ Step 1 failed: ${err instanceof Error ? err.message : String(err)}`)
540
- process.exit(1)
551
+ if (complexity) {
552
+ done(cached ? 'Sized (cached for this PRD)' : 'Sized', `${complexity.complexity}, ${complexity.total_tasks} workstreams`)
541
553
  }
542
554
 
543
- if (opts.dryRun) {
544
- console.log(c.dim('\n [dry-run] Stopping after step 1. Remove --dry-run to run the full pipeline.'))
545
- return
555
+ // ── The tasks ─────────────────────────────────────────────────────────────
556
+ let groups: ConvoyGroup[] | null = null
557
+ if (complexity?.recommended_strategy === 'chain' && complexity.convoy_groups.length > 1) {
558
+ const check = validateComplexityGroups(complexity)
559
+ if (check.valid) groups = topologicalSortGroups(complexity.convoy_groups)
560
+ else warn(`Ignoring the suggested groups (${check.reason}) — planning it as one`)
546
561
  }
547
562
 
548
- prdPath = result.outputPath!
549
- console.log(c.green(` ✓ PRD written to ${relPath(prdPath)}\n`))
550
- }
551
-
552
- // Handle --dry-run when PRD was provided externally (not generated)
553
- if (opts.dryRun && opts.prd) {
554
- console.log(c.dim('\n [dry-run] Nothing to preview — PRD already provided via --prd. Remove --dry-run to continue.'))
555
- return
563
+ if (groups) {
564
+ const featureName =
565
+ prd.match(/^# (.+?)\s*(?:—|-)?\s*PRD/m)?.[1].trim() ?? complexity?.original_prompt ?? 'Feature'
566
+ const request = req.task ?? complexity?.original_prompt ?? ''
567
+ const all = groups
568
+ const plans = await settleAll(
569
+ all.map((group) => {
570
+ const goal = [
571
+ request,
572
+ '',
573
+ '## Convoy Group Scope',
574
+ '',
575
+ `This is one of ${all.length} groups, all planned at the same time. Plan ONLY the phases listed here.`,
576
+ 'The planner joins the group plans into one spec: tasks of the groups this one depends on are',
577
+ 'finished before this group\'s first tasks start.',
578
+ '',
579
+ `- **Group name:** ${group.name}`,
580
+ `- **Description:** ${group.description}`,
581
+ `- **Phases to include:** ${group.phases.join(', ')}`,
582
+ group.depends_on.length ? `- **Depends on groups:** ${group.depends_on.join(', ')}` : '',
583
+ ].filter((line, i, lines) => line !== '' || lines[i - 1] !== '').join('\n')
584
+ const context = appendTaskComplexity(
585
+ extractRelevantPrdSections(prd, group.phases),
586
+ filterTaskComplexityByPhases(complexity?.task_complexity, group.phases),
587
+ )
588
+ return generatePlan(step, goal, context, group.name, convoyDir)
589
+ }),
590
+ )
591
+ plan = mergeGroupPlans(
592
+ featureName,
593
+ all.map((g, i) => ({ name: g.name, depends_on: g.depends_on, plan: plans[i] })),
594
+ )
595
+ done(`${plan.tasks.length} tasks planned`, `${all.length} groups, planned side by side`)
596
+ } else {
597
+ const goal = req.task ?? complexity?.original_prompt ?? 'Implement the PRD.'
598
+ plan = await generatePlan(step, goal, appendTaskComplexity(prd, complexity?.task_complexity), 'task', convoyDir)
599
+ done(`${plan.tasks.length} tasks planned`)
600
+ }
556
601
  }
557
602
 
558
- // ── Steps 2 + 4: Validate PRD & Assess complexity (in parallel) ────────
559
- // Both only read the PRD — run them concurrently to save one LLM round-trip.
560
- // If validation fails we still use the complexity result (fix-prd patches
561
- // issues without changing the overall structure/phases).
562
-
563
- const complexityStep = opts.skipValidation ? 2 : 4
603
+ const normalized = normalizePlanFiles(plan)
604
+ plan = normalized.plan
605
+ for (const note of normalized.notes) console.log(c.dim(` files: ${note}`))
606
+ const tests = foldTestOnlyTasks(plan)
607
+ plan = tests.plan
608
+ for (const [from, into] of tests.folded) console.log(c.dim(` ${from} folded into ${into}: the agent that writes the code writes its tests`))
564
609
 
565
- let complexity: ComplexityAssessment | null = null
566
- const complexityFilePath = opts.complexity
567
- ? resolve(process.cwd(), opts.complexity)
568
- : deriveComplexityPath(prdPath)
569
-
570
- // Check for cached / provided complexity before launching LLM calls
571
- if (opts.complexity) {
572
- if (!existsSync(complexityFilePath)) {
573
- console.error(` ✗ Complexity file not found: ${opts.complexity}`)
574
- process.exit(1)
575
- }
576
- try {
577
- const raw = await readFile(complexityFilePath, 'utf8')
578
- complexity = parseComplexityAssessment(raw)
579
- if (complexity) {
580
- console.log(c.dim(` [−] Using existing complexity assessment: ${relPath(complexityFilePath)}`))
581
- } else {
582
- console.error(` ✗ Invalid complexity file: ${opts.complexity}`)
583
- process.exit(1)
584
- }
585
- } catch (err) {
586
- console.error(` ✗ Failed to read complexity file: ${err instanceof Error ? err.message : String(err)}`)
587
- process.exit(1)
588
- }
589
- } else if (existsSync(complexityFilePath)) {
590
- try {
591
- const raw = await readFile(complexityFilePath, 'utf8')
592
- const cached = parseComplexityAssessment(raw)
593
- if (cached) {
594
- complexity = cached
595
- console.log(c.dim(` [−] Using existing complexity assessment: ${relPath(complexityFilePath)}`))
610
+ // ── The spec ──────────────────────────────────────────────────────────────
611
+ await mkdir(convoyDir, { recursive: true })
612
+ const specPath = freePath(convoyDir, slugify(plan.name) || 'convoy', '.convoy.yml')
613
+ const settings: SpecSettings = {
614
+ adapter: req.adapterName,
615
+ branch: `convoy/${basename(specPath, '.convoy.yml')}`,
616
+ gates: detectGates(root),
617
+ }
618
+
619
+ let problems = checkPlan(plan, settings)
620
+ for (let round = 1; round <= MAX_FIX_ROUNDS && problems.length > 0; round++) {
621
+ warn(`The plan fails ${problems.length} check${problems.length === 1 ? '' : 's'} — fixing (${round}/${MAX_FIX_ROUNDS})`)
622
+ console.log(indented(problems.join('\n')))
623
+ plan = await fixPlan(step, plan, problems.map((p) => `- ${p}`).join('\n'))
624
+ problems = checkPlan(plan, settings)
625
+ }
626
+ if (problems.length > 0) {
627
+ const sequenced = sequenceConflicts(plan)
628
+ if (sequenced.added.length > 0) {
629
+ plan = sequenced.plan
630
+ problems = checkPlan(plan, settings)
631
+ for (const [later, earlier] of sequenced.added) {
632
+ console.log(c.dim(` ${later} now waits for ${earlier}: they claim the same files`))
596
633
  }
597
- } catch {
598
- // ignore — fall through to LLM assessment
599
634
  }
600
635
  }
636
+ if (problems.length === 0) done('Plan checked')
601
637
 
602
- const needsValidation = !opts.skipValidation
603
- const needsComplexity = !complexity
604
-
605
- if (needsValidation || needsComplexity) {
606
- const prdContent = await readFile(prdPath, 'utf8')
607
-
608
- // Launch validation and complexity in parallel when both are needed
609
- if (needsValidation && needsComplexity) {
610
- console.log(stepLabel(2, totalSteps, 'Validating PRD…'))
611
- console.log(stepLabel(complexityStep, totalSteps, 'Assessing complexity…'))
612
- console.log(c.dim(` (running in parallel)\n`))
613
-
614
- const [validationResult, complexityResult] = await Promise.all([
615
- runPromptStep({
616
- ...sharedOpts,
617
- template: 'validate-prd',
618
- goalText: `<!-- validation-pass: 1 -->\n${prdContent}`,
619
- }).catch((err) => {
620
- console.error(`\n ✗ Validation failed: ${err instanceof Error ? err.message : String(err)}`)
621
- return null
622
- }),
623
- runPromptStep({
624
- ...sharedOpts,
625
- template: 'assess-complexity',
626
- filePath: prdPath,
627
- contextText: opts.text ?? undefined,
628
- }).catch((err) => {
629
- console.warn(c.yellow(` ⚠ Complexity assessment failed: ${err instanceof Error ? err.message : String(err)}`))
630
- return null
631
- }),
632
- ])
633
-
634
- // Process complexity result
635
- if (complexityResult) {
636
- complexity = parseComplexityAssessment(complexityResult.rawOutput)
637
- if (complexity) {
638
- await writeFile(complexityFilePath, JSON.stringify(complexity, null, 2), 'utf8')
639
- console.log(c.green(` ✓ Complexity assessment saved to ${relPath(complexityFilePath)}`))
640
- }
641
- }
642
-
643
- // Process validation result
644
- if (!validationResult) {
645
- process.exit(1)
646
- }
647
-
648
- if (!validationResult.isValid) {
649
- let prdValidationErrors = validationResult.errors ?? validationResult.rawOutput
650
- console.log(c.yellow(` ⚠ PRD has validation issues — attempting auto-fix…\n`))
651
- console.log(c.dim(prdValidationErrors))
652
- console.log()
653
-
654
- await fixPrd(sharedOpts, prdPath, prdContent, prdValidationErrors, totalSteps, opts.adapter)
655
- } else {
656
- console.log(c.green(` ✓ PRD is valid\n`))
657
- }
658
- } else if (needsValidation) {
659
- // Only validation needed (complexity was cached)
660
- console.log(stepLabel(2, totalSteps, 'Validating PRD…'))
661
-
662
- let result
663
- try {
664
- result = await runPromptStep({
665
- ...sharedOpts,
666
- template: 'validate-prd',
667
- goalText: `<!-- validation-pass: 1 -->\n${prdContent}`,
668
- })
669
- } catch (err) {
670
- console.error(`\n ✗ Step 2 failed: ${err instanceof Error ? err.message : String(err)}`)
671
- process.exit(1)
672
- }
673
-
674
- if (!result.isValid) {
675
- let prdValidationErrors = result.errors ?? result.rawOutput
676
- console.log(c.yellow(` ⚠ PRD has validation issues — attempting auto-fix…\n`))
677
- console.log(c.dim(prdValidationErrors))
678
- console.log()
679
-
680
- await fixPrd(sharedOpts, prdPath, prdContent, prdValidationErrors, totalSteps, opts.adapter)
681
- } else {
682
- console.log(c.green(` ✓ PRD is valid\n`))
683
- }
638
+ if (req.critic && problems.length === 0) {
639
+ const review = await step('validate-convoy', { goalText: buildConvoyYaml(plan, settings) })
640
+ if (review.isValid) {
641
+ done('Plan reviewed')
684
642
  } else {
685
- // Only complexity needed (validation skipped)
686
- console.log(stepLabel(complexityStep, totalSteps, 'Assessing complexity…'))
687
- try {
688
- const complexityResult = await runPromptStep({
689
- ...sharedOpts,
690
- template: 'assess-complexity',
691
- filePath: prdPath,
692
- contextText: opts.text ?? undefined,
693
- })
694
- complexity = parseComplexityAssessment(complexityResult.rawOutput)
695
- if (complexity) {
696
- await writeFile(complexityFilePath, JSON.stringify(complexity, null, 2), 'utf8')
697
- console.log(c.green(` ✓ Complexity assessment saved to ${relPath(complexityFilePath)}\n`))
698
- }
699
- } catch (err) {
700
- console.warn(c.yellow(` ⚠ Complexity assessment failed: ${err instanceof Error ? err.message : String(err)}`))
701
- console.warn(c.dim(` Falling back to single convoy strategy.\n`))
643
+ const issues = review.errors || review.rawOutput
644
+ warn('The review found issues — fixing once')
645
+ console.log(indented(issues))
646
+ const revised = await fixPlan(step, plan, issues)
647
+ if (checkPlan(revised, settings).length === 0) {
648
+ plan = revised
649
+ done('Plan revised after review')
650
+ } else {
651
+ warn('The revision fails the checks — keeping the plan as it was')
702
652
  }
703
653
  }
704
654
  }
705
655
 
706
- if (!complexity) {
707
- console.log(c.dim(` Could not determine complexity — using single convoy strategy.\n`))
708
- }
709
-
710
- if (complexity) {
711
- if (complexity.recommended_strategy === 'chain' && complexity.convoy_groups.length > 1) {
712
- // Validate complexity groups before chain generation
713
- const groupValidation = validateComplexityGroups(complexity)
714
- if (!groupValidation.valid) {
715
- console.log(c.yellow(` ⚠ Complexity groups failed validation: ${groupValidation.reason}`))
716
- console.log(c.yellow(` Falling back to single convoy strategy.\n`))
717
- // Fall through to single-spec generation below
718
- } else {
719
- // Sort groups in dependency order
720
- complexity.convoy_groups = topologicalSortGroups(complexity.convoy_groups)
721
- console.log(
722
- c.cyan(` ℹ`) +
723
- ` Complexity: ${complexity.complexity} | Strategy: chain | ${complexity.convoy_groups.length} convoy groups\n`
724
- )
725
- console.log(` Chain plan:`)
726
- for (let i = 0; i < complexity.convoy_groups.length; i++) {
727
- const g = complexity.convoy_groups[i]
728
- const depStr =
729
- g.depends_on.length > 0 ? ` → depends on: ${g.depends_on.join(', ')}` : ''
730
- console.log(
731
- ` ${i + 1}. ${g.name.padEnd(20)} (phases: ${g.phases.join(', ')})${depStr}`
732
- )
733
- }
734
- console.log()
735
-
736
- const convoyDir = resolve(process.cwd(), '.opencastle', 'convoys')
737
- await mkdir(convoyDir, { recursive: true })
656
+ await writeFile(specPath, buildConvoyYaml(plan, settings), 'utf8')
657
+ return { prdPath, specPath, plan, settings, problems, planning: spend }
658
+ }
738
659
 
739
- // Extract feature name early for convoy naming
740
- const chainPrdContent = await readFile(prdPath, 'utf8')
741
- const featureNameMatch = chainPrdContent.match(/^# (.+?)\s*(?:—|-)?\s*PRD/m)
742
- const featureName = featureNameMatch
743
- ? featureNameMatch[1].trim().toLowerCase().replace(/[^a-z0-9]+/g, '-')
744
- : 'feature'
660
+ // ── Showing the plan ────────────────────────────────────────────────────────
745
661
 
746
- const groupSpecPaths: string[] = []
662
+ function fit(text: string, width: number): string {
663
+ if (text.length <= width) return text.padEnd(width)
664
+ return text.slice(0, Math.max(0, width - 1)) + '…'
665
+ }
747
666
 
748
- for (let i = 0; i < complexity.convoy_groups.length; i++) {
749
- const group = complexity.convoy_groups[i]
750
- console.log(c.cyan(` [${i + 1}/${complexity.convoy_groups.length}] Generating convoy: ${group.name}`) + c.dim(` (phases: ${group.phases.join(', ')})`))
667
+ /**
668
+ * The plan as a few lines a person can check before saying yes: who does what,
669
+ * after what, touching which files.
670
+ */
671
+ export function renderPlan(outcome: Pick<PlanOutcome, 'plan' | 'settings' | 'specPath' | 'planning'>, columns = 100): string[] {
672
+ const { plan, settings } = outcome
673
+ const rows = plan.tasks.map((t) => ({
674
+ id: t.id,
675
+ agent: t.agent ?? 'developer',
676
+ deps: t.depends_on?.length ? t.depends_on.join(', ') : '–',
677
+ files: t.files?.length ? t.files.join(', ') : '(any)',
678
+ }))
679
+ const width = (pick: (r: (typeof rows)[number]) => string, header: string, cap: number): number =>
680
+ Math.min(cap, Math.max(header.length, ...rows.map((r) => pick(r).length)))
681
+ const idW = width((r) => r.id, 'TASK', 32)
682
+ const agentW = width((r) => r.agent, 'AGENT', 18)
683
+ const depsW = width((r) => r.deps, 'DEPENDS ON', 30)
684
+ const filesW = Math.max(20, columns - 4 - idW - agentW - depsW - 6)
685
+ const line = (a: string, b: string, d: string, f: string): string =>
686
+ ` ${fit(a, idW)} ${fit(b, agentW)} ${fit(d, depsW)} ${fit(f, filesW).trimEnd()}`
687
+
688
+ const at = planConcurrency(plan)
689
+ const out = [
690
+ '',
691
+ ` ${c.bold(`Plan: ${plan.name}`)} ${c.dim(`— ${plan.tasks.length} task${plan.tasks.length === 1 ? '' : 's'}, up to ${at} at a time`)}`,
692
+ '',
693
+ c.dim(line('TASK', 'AGENT', 'DEPENDS ON', 'FILES')),
694
+ ...rows.map((r) => line(r.id, r.agent, r.deps, r.files)),
695
+ '',
696
+ ` ${c.dim('Branch')} ${settings.branch} ${c.dim('· runtime')} ${settings.adapter}` +
697
+ (settings.gates.length ? ` ${c.dim('· then once:')} ${settings.gates.join(', ')}` : ''),
698
+ ` ${c.dim('Spec')} ${relPath(outcome.specPath)}`,
699
+ ...(outcome.planning ? [` ${c.dim('Planned')} ${describeSpend(outcome.planning)}`] : []),
700
+ '',
701
+ ]
702
+ return out
703
+ }
751
704
 
752
- const chainGoal = [
753
- complexity.original_prompt,
754
- '',
755
- '## Convoy Group Scope',
756
- '',
757
- `This is group **${i + 1} of ${complexity.convoy_groups.length}** in a convoy chain.`,
758
- `Generate a convoy spec covering ONLY the phases listed below.`,
759
- '',
760
- `- **Group name:** ${group.name}`,
761
- `- **Description:** ${group.description}`,
762
- `- **Phases to include:** ${group.phases.join(', ')}`,
763
- group.depends_on.length ? `- **Depends on groups:** ${group.depends_on.join(', ')}` : '',
764
- ].filter(Boolean).join('\n')
765
-
766
- const prdContent = await readFile(prdPath, 'utf8')
767
- const relevantPrd = extractRelevantPrdSections(prdContent, group.phases)
768
- const relevantComplexity = filterTaskComplexityByPhases(complexity?.task_complexity, group.phases)
769
- const contextForSpec = appendTaskComplexity(relevantPrd, relevantComplexity)
770
- const groupSpecPath = resolve(convoyDir, `${featureName}-${group.name}.convoy.yml`)
771
-
772
- const { specPath: resolvedGroupSpecPath } = await generateAndValidateSpec({
773
- sharedOpts,
774
- goalText: chainGoal,
775
- contextText: contextForSpec,
776
- specPath: groupSpecPath,
777
- skipValidation: opts.skipValidation,
778
- groupName: group.name,
779
- featureName,
780
- enrichment: complexity ? deriveSpecEnrichment(complexity) : undefined,
781
- })
782
- groupSpecPaths.push(resolvedGroupSpecPath)
783
- }
705
+ function describeSpend(s: PlanningSpend): string {
706
+ const secs = Math.round(s.ms / 1000)
707
+ const time = secs >= 60 ? `${Math.floor(secs / 60)}m ${secs % 60}s` : `${secs}s`
708
+ const tokens = s.tokens >= 1_000_000 ? `${(s.tokens / 1_000_000).toFixed(1)}M` : s.tokens >= 1000 ? `${Math.round(s.tokens / 1000)}K` : String(s.tokens)
709
+ const cost = s.costUsd > 0 || s.costComplete ? ` · $${s.costUsd.toFixed(2)}${s.costComplete ? '' : '+ (not every session reported a cost)'}` : ''
710
+ return `in ${time} · ${s.sessions} session${s.sessions === 1 ? '' : 's'} · ${tokens} tokens${cost}`
711
+ }
784
712
 
785
- // Build master pipeline spec (version 2)
786
- const branchMatch = chainPrdContent.match(/`feat\/([^`]+)`/)
787
- const branch = branchMatch ? `feat/${branchMatch[1]}` : `feat/${featureName}`
713
+ // ── The command ─────────────────────────────────────────────────────────────
788
714
 
789
- const masterSpec = {
790
- name: featureNameMatch ? featureNameMatch[1].trim() : 'Feature Pipeline',
791
- version: 2,
792
- branch,
793
- on_failure: 'stop',
794
- depends_on_convoy: groupSpecPaths.map(p => relPath(p)),
795
- }
715
+ const HELP = `
716
+ opencastle convoy plan --prd <file> [options]
796
717
 
797
- const masterSpecPath = resolve(convoyDir, `${featureName}-pipeline.convoy.yml`)
798
- await writeFile(masterSpecPath, stringify(masterSpec), 'utf8')
718
+ Plan again from a PRD you edited. The PRD is checked, broken into tasks and
719
+ written as a spec; you see the plan and are asked before it runs.
799
720
 
800
- console.log(c.green(` ✓ Generated convoy chain:\n`))
801
- for (const p of groupSpecPaths) {
802
- console.log(` ${relPath(p)}`)
803
- }
804
- console.log(` ${relPath(masterSpecPath)} ${c.dim('(master)')}`)
805
- console.log()
806
- console.log(
807
- ` ${c.dim('Preview:')} npx opencastle convoy run -f ${relPath(masterSpecPath)} --dry-run\n` +
808
- ` ${c.dim('Execute:')} npx opencastle convoy run -f ${relPath(masterSpecPath)}\n`
809
- )
810
-
811
- try {
812
- const shouldRun = await confirm('Run the convoy chain now?', true)
813
- if (shouldRun) {
814
- closePrompts()
815
- const runModule = await import('./run.js')
816
- const runArgs = ['-f', masterSpecPath]
817
- if (opts.adapter) runArgs.push('-a', opts.adapter)
818
- if (opts.verbose) runArgs.push('--verbose')
819
- await runModule.default({ args: runArgs, pkgRoot })
820
- }
821
- } finally {
822
- closePrompts()
823
- await cleanupAdapters()
824
- }
825
- return
826
- }
827
- } else {
828
- console.log(
829
- c.cyan(` ℹ`) + ` Complexity: ${complexity.complexity} | Strategy: single\n`
830
- )
831
- }
832
- }
721
+ Options:
722
+ --prd <file> The PRD to plan from (opencastle convoy "<task>" writes
723
+ them to .opencastle/prds/)
724
+ --yes, -y Run the plan without asking
725
+ --dry-run Plan and write the spec, but do not run it
726
+ --adapter, -a <name> Agent runtime to plan and run with
727
+ --concurrency, -c <n> Tasks at once when it runs
728
+ --verbose Show each planning session's output
729
+ --help, -h Show this help
730
+ `
833
731
 
834
- // ── Generate convoy spec ──────────────────────────────────────────────────
835
- const singlePrdContent = await readFile(prdPath, 'utf8')
836
- const singleContextForSpec = appendTaskComplexity(singlePrdContent, complexity?.task_complexity)
837
- const singleGoal = complexity?.original_prompt ?? opts.text ?? ''
838
-
839
- const specResult = await generateAndValidateSpec({
840
- sharedOpts,
841
- goalText: singleGoal,
842
- contextText: singleContextForSpec,
843
- specPath: opts.outputSpec ? resolve(process.cwd(), opts.outputSpec) : undefined,
844
- skipValidation: opts.skipValidation,
845
- enrichment: complexity ? deriveSpecEnrichment(complexity) : undefined,
846
- })
847
-
848
- await printFinalSummary(prdPath, specResult.specPath, opts, pkgRoot)
732
+ interface CliOptions {
733
+ prd: string | null
734
+ yes: boolean
735
+ dryRun: boolean
736
+ adapter: string | null
737
+ concurrency: number | null
738
+ verbose: boolean
739
+ help: boolean
849
740
  }
850
741
 
851
- async function fixViaPatch(
852
- taskPlan: TaskPlan,
853
- errors: string,
854
- sharedOpts: Omit<PromptStepOptions, 'template' | 'goalText' | 'contextText'>,
855
- specPath: string,
856
- enrichment?: SpecEnrichment,
857
- ): Promise<TaskPlan> {
858
- let currentPlan = taskPlan
859
- let currentErrors = errors
860
-
861
- for (let attempt = 1; attempt <= MAX_FIX_RETRIES; attempt++) {
862
- console.log(c.dim(` Fix attempt ${attempt}/${MAX_FIX_RETRIES}…`))
863
-
864
- let fixResult
865
- try {
866
- fixResult = await runPromptStep({
867
- ...sharedOpts,
868
- template: 'fix-convoy',
869
- goalText: JSON.stringify(currentPlan, null, 2),
870
- contextText: currentErrors,
871
- })
872
- } catch (err) {
873
- console.error(`\n ✗ Fix attempt ${attempt} failed: ${err instanceof Error ? err.message : String(err)}`)
742
+ /** Flags `convoy "<task>"` and `convoy plan` share; `--prd` is plan's alone. */
743
+ function parseArgs(args: string[], allowPrd: boolean): CliOptions {
744
+ const opts: CliOptions = { prd: null, yes: false, dryRun: false, adapter: null, concurrency: null, verbose: false, help: false }
745
+ const value = (i: number, flag: string): string => {
746
+ const v = args[i + 1]
747
+ if (v === undefined || !v.trim() || v.startsWith('-')) {
748
+ console.error(` ✗ ${flag} needs a value`)
874
749
  process.exit(1)
875
750
  }
876
-
877
- const patches = parsePatches(fixResult.rawOutput)
878
- if (!patches || patches.length === 0) {
879
- console.warn(c.yellow(` ⚠ No valid patches returned`))
880
- if (attempt >= MAX_FIX_RETRIES) break
881
- continue
882
- }
883
-
884
- console.log(c.dim(` Applied ${patches.length} patches`))
885
- currentPlan = applyPatches(currentPlan, patches)
886
-
887
- // Rebuild YAML and re-validate
888
- const yaml = buildConvoyYaml(currentPlan, enrichment)
889
- try {
890
- const parsed = parseYaml(yaml)
891
- const { valid, errors: schemaErrors } = validateSpec(parsed)
892
- if (!valid) {
893
- currentErrors = schemaErrors.map(e => `- Schema: ${e}`).join('\n')
894
- if (attempt < MAX_FIX_RETRIES) {
895
- console.log(c.yellow(` ⚠ Still has schema issues — retrying…\n`))
896
- console.log(c.dim(currentErrors))
751
+ return v
752
+ }
753
+ for (let i = 0; i < args.length; i++) {
754
+ const arg = args[i]
755
+ switch (arg) {
756
+ case '--help':
757
+ case '-h':
758
+ opts.help = true
759
+ break
760
+ case '--prd':
761
+ if (!allowPrd) {
762
+ console.error(` ✗ --prd belongs to \`opencastle convoy plan\`: plan from a task or from a PRD, not both.`)
763
+ process.exit(1)
897
764
  }
898
- continue
765
+ opts.prd = value(i++, arg)
766
+ break
767
+ case '--yes':
768
+ case '-y':
769
+ opts.yes = true
770
+ break
771
+ case '--dry-run':
772
+ opts.dryRun = true
773
+ break
774
+ case '--adapter':
775
+ case '-a':
776
+ opts.adapter = value(i++, arg)
777
+ break
778
+ case '--concurrency':
779
+ case '-c': {
780
+ const raw = value(i++, arg)
781
+ const n = Number(raw)
782
+ if (!/^\d+$/.test(raw) || n < 1 || n > 50) {
783
+ console.error(` ✗ --concurrency must be a whole number from 1 to 50, not "${raw}"`)
784
+ process.exit(1)
785
+ }
786
+ opts.concurrency = n
787
+ break
899
788
  }
900
- } catch (err) {
901
- currentErrors = `YAML error: ${err instanceof Error ? err.message : String(err)}`
902
- continue
903
- }
904
-
905
- await writeFile(specPath, yaml, 'utf8')
906
- console.log(c.dim(` Re-validating after fix…`))
907
-
908
- let revalidation
909
- try {
910
- revalidation = await runPromptStep({
911
- ...sharedOpts,
912
- template: 'validate-convoy',
913
- goalText: `<!-- validation-pass: ${attempt + 1} -->\n${yaml}`,
914
- })
915
- } catch (err) {
916
- console.error(`\n ✗ Re-validation failed: ${err instanceof Error ? err.message : String(err)}`)
917
- process.exit(1)
918
- }
919
-
920
- if (revalidation.isValid) {
921
- console.log(c.green(` ✓ Fixed and validated\n`))
922
- return currentPlan
923
- }
924
-
925
- currentErrors = revalidation.errors ?? revalidation.rawOutput
926
- if (attempt < MAX_FIX_RETRIES) {
927
- console.log(c.yellow(` ⚠ Still has issues — retrying…\n`))
928
- console.log(c.dim(currentErrors))
789
+ case '--verbose':
790
+ opts.verbose = true
791
+ break
792
+ default:
793
+ console.error(` ✗ Unknown option: ${arg}`)
794
+ console.error(` ${c.dim('Accepts:')} --yes --dry-run --adapter --concurrency --verbose --help${allowPrd ? ' --prd' : ''}`)
795
+ process.exit(1)
929
796
  }
930
797
  }
798
+ return opts
799
+ }
931
800
 
932
- // Exhausted retries — save best effort and continue with warning
933
- await writeFile(specPath, buildConvoyYaml(currentPlan, enrichment), 'utf8')
934
- console.log(c.yellow(`\n ⚠ Could not fully auto-fix after ${MAX_FIX_RETRIES} attempts — continuing with best-effort spec.\n`))
935
- console.log(c.dim(` Remaining issues:\n`))
936
- console.log(c.dim(currentErrors))
937
- console.log(
938
- c.dim(`\n Spec saved to ${relPath(specPath)} with best available fixes.`) +
939
- c.dim(`\n You can re-validate later with:\n`) +
940
- ` opencastle convoy run --file ${relPath(specPath)} --dry-run\n`
941
- )
942
- return currentPlan
801
+ /**
802
+ * The runtime for the whole plan, and the run after it, chosen once by the
803
+ * rule `resolveAdapter` owns: `--adapter`, else what `opencastle init` set up,
804
+ * else what is on PATH.
805
+ */
806
+ async function chooseRuntime(projectRoot: string, explicit: string | null): Promise<ResolvedAdapter> {
807
+ try {
808
+ return await resolveAdapter({ projectRoot, explicit })
809
+ } catch (err) {
810
+ console.error(` ${c.red('✗')} ${message(err)}`)
811
+ process.exit(1)
812
+ }
943
813
  }
944
814
 
945
- async function generateAndValidateSpec(params: {
946
- sharedOpts: Omit<PromptStepOptions, 'template' | 'goalText' | 'contextText'>
947
- goalText: string
948
- contextText: string
949
- specPath?: string
950
- skipValidation: boolean
951
- groupName?: string
952
- featureName?: string
953
- enrichment?: SpecEnrichment
954
- }): Promise<{ specPath: string; taskPlan: TaskPlan }> {
955
- const label = params.groupName
956
- ? `Generating task plan: ${params.groupName}…`
957
- : 'Generating task plan…'
958
- console.log(c.cyan(` ${label}`))
959
-
960
- // Temp file for debugging — kept on failure, deleted on success
961
- const convoyDir = resolve(process.cwd(), '.opencastle', 'convoys')
962
- await mkdir(convoyDir, { recursive: true })
963
- const tempJsonName = params.groupName
964
- ? `${params.featureName ? `${params.featureName}-` : ''}${params.groupName}.task-plan.json`
965
- : `${params.featureName ?? 'task-plan'}.task-plan.json`
966
- const tempJsonPath = resolve(convoyDir, tempJsonName)
815
+ /**
816
+ * Plan, show the plan once, ask once, run.
817
+ *
818
+ * Nothing runs without a yes. A closed stdin is not one: piped into a script,
819
+ * the old prompt's default-yes started a full convoy nobody had agreed to.
820
+ */
821
+ async function planThenRun(source: { task: string } | { prd: string }, opts: CliOptions, pkgRoot: string): Promise<void> {
822
+ const projectRoot = process.cwd()
823
+ const runtime = await chooseRuntime(findProjectRoot(projectRoot) ?? projectRoot, opts.adapter)
824
+ console.log(`\n ${c.bold('opencastle convoy')} ${c.dim('— planning, read-only')}`)
825
+ console.log(` ${c.dim('Runtime:')} ${runtime.detail}\n`)
967
826
 
968
- let taskPlanResult
827
+ let outcome: PlanOutcome
969
828
  try {
970
- taskPlanResult = await runPromptStep({
971
- ...params.sharedOpts,
972
- template: 'generate-convoy',
973
- goalText: params.goalText,
974
- contextText: params.contextText,
829
+ outcome = await planConvoy({
830
+ task: 'task' in source ? source.task : undefined,
831
+ prdPath: 'prd' in source ? source.prd : undefined,
832
+ adapter: runtime.adapter,
833
+ adapterName: runtime.name,
834
+ pkgRoot,
835
+ verbose: opts.verbose,
836
+ critic: opts.yes && !opts.dryRun,
975
837
  })
976
838
  } catch (err) {
977
- console.error(`\n ✗ Task plan generation failed: ${err instanceof Error ? err.message : String(err)}`)
839
+ console.error(`\n ${c.red('✗')} Planning stopped: ${message(err)}`)
840
+ await cleanupAdapters()
978
841
  process.exit(1)
979
842
  }
980
843
 
981
- // Write raw JSON to temp file for debugging
982
- await writeFile(tempJsonPath, taskPlanResult.rawOutput + '\n', 'utf8')
983
-
984
- let result = parseTaskPlanWithReason(taskPlanResult.rawOutput)
985
- if (!result.plan) {
986
- console.log(c.yellow(` ⚠ Failed to parse task plan JSON: ${result.reason}`))
987
- console.log(c.dim(` Output length: ${taskPlanResult.rawOutput.length} chars`))
988
- console.log(c.dim(` Temp file: ${relPath(tempJsonPath)}`))
989
- console.log(c.yellow(` Retrying generation…\n`))
990
-
991
- let retryResult
992
- try {
993
- retryResult = await runPromptStep({
994
- ...params.sharedOpts,
995
- template: 'generate-convoy',
996
- goalText: params.goalText,
997
- contextText: params.contextText,
998
- })
999
- } catch (err) {
1000
- console.error(`\n ✗ Retry failed: ${err instanceof Error ? err.message : String(err)}`)
1001
- process.exit(1)
1002
- }
1003
-
1004
- // Overwrite temp file with retry output
1005
- await writeFile(tempJsonPath, retryResult.rawOutput + '\n', 'utf8')
844
+ for (const row of renderPlan(outcome, process.stdout.columns ?? 100)) console.log(row)
845
+ const later = `opencastle convoy run ${relPath(outcome.specPath)}`
1006
846
 
1007
- result = parseTaskPlanWithReason(retryResult.rawOutput)
1008
- if (!result.plan) {
1009
- console.error(` ✗ Failed to parse task plan JSON after retry: ${result.reason}`)
1010
- console.error(c.dim(` Output length: ${retryResult.rawOutput.length} chars`))
1011
- console.error(c.dim(` Raw JSON saved to ${relPath(tempJsonPath)} for inspection.`))
1012
- console.error(c.dim(`\n${retryResult.rawOutput}`))
1013
- process.exit(1)
1014
- }
847
+ if (outcome.problems.length > 0) {
848
+ console.error(` ${c.red('✗')} The plan still fails these checks, so it was not started:`)
849
+ for (const p of outcome.problems) console.error(` • ${p}`)
850
+ console.error(`\n Edit the spec, then: ${later}\n`)
851
+ await cleanupAdapters()
852
+ process.exit(1)
1015
853
  }
1016
854
 
1017
- let taskPlan = result.plan
1018
-
1019
- // Success — clean up temp file
1020
- await unlink(tempJsonPath).catch(() => {})
1021
-
1022
- console.log(c.green(` ✓ Task plan generated (${taskPlan.tasks.length} tasks)`))
1023
-
1024
- // Derive spec path from plan name if not provided
1025
- let resolvedSpecPath = params.specPath
1026
- if (!resolvedSpecPath) {
1027
- const convoyDir = resolve(process.cwd(), '.opencastle', 'convoys')
1028
- await mkdir(convoyDir, { recursive: true })
1029
- const kebab = taskPlan.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')
1030
- resolvedSpecPath = resolve(convoyDir, `${kebab}.convoy.yml`)
855
+ if (opts.dryRun) {
856
+ console.log(` ${c.dim('Dry run — not started. To run it:')} ${later}\n`)
857
+ await cleanupAdapters()
858
+ return
1031
859
  }
1032
860
 
1033
- // Build YAML from JSON task plan
1034
- let yamlContent = buildConvoyYaml(taskPlan, params.enrichment)
1035
- await mkdir(resolve(resolvedSpecPath, '..'), { recursive: true })
1036
- await writeFile(resolvedSpecPath, yamlContent, 'utf8')
1037
- console.log(c.green(` ✓ Convoy spec written to ${relPath(resolvedSpecPath)}\n`))
1038
-
1039
- if (!params.skipValidation) {
1040
- // Programmatic validation first
1041
- try {
1042
- const parsed = parseYaml(yamlContent)
1043
- const { valid, errors: schemaErrors } = validateSpec(parsed)
1044
- if (!valid) {
1045
- console.log(c.yellow(` ⚠ Schema validation issues — auto-fixing…\n`))
1046
- const errorText = schemaErrors.map(e => `- Schema: ${e}`).join('\n')
1047
- console.log(c.dim(errorText))
1048
- console.log()
1049
- taskPlan = await fixViaPatch(taskPlan, errorText, params.sharedOpts, resolvedSpecPath, params.enrichment)
1050
- yamlContent = buildConvoyYaml(taskPlan, params.enrichment)
1051
- await writeFile(resolvedSpecPath, yamlContent, 'utf8')
1052
- } else {
1053
- console.log(c.dim(` ✓ Schema validation passed`))
1054
- }
1055
- } catch (err) {
1056
- console.warn(c.yellow(` ⚠ YAML warning: ${err instanceof Error ? err.message : String(err)}`))
1057
- }
1058
-
1059
- // Semantic validation (LLM)
1060
- const valLabel = params.groupName
1061
- ? `Validating spec: ${params.groupName}…`
1062
- : 'Validating convoy spec…'
1063
- console.log(c.cyan(` ${valLabel}`))
1064
-
1065
- let semanticResult
1066
- try {
1067
- semanticResult = await runPromptStep({
1068
- ...params.sharedOpts,
1069
- template: 'validate-convoy',
1070
- goalText: `<!-- validation-pass: 1 -->\n${await readFile(resolvedSpecPath, 'utf8')}`,
1071
- })
1072
- } catch (err) {
1073
- console.error(`\n ✗ Semantic validation failed: ${err instanceof Error ? err.message : String(err)}`)
1074
- process.exit(1)
1075
- }
1076
-
1077
- if (semanticResult.isValid) {
1078
- console.log(c.green(` ✓ Spec is valid\n`))
1079
- } else {
1080
- const semanticErrors = semanticResult.errors ?? semanticResult.rawOutput
1081
- console.log(c.yellow(` ⚠ Semantic issues — auto-fixing…\n`))
1082
- console.log(c.dim(semanticErrors))
1083
- console.log()
1084
- taskPlan = await fixViaPatch(taskPlan, semanticErrors, params.sharedOpts, resolvedSpecPath, params.enrichment)
1085
- yamlContent = buildConvoyYaml(taskPlan, params.enrichment)
1086
- await writeFile(resolvedSpecPath, yamlContent, 'utf8')
1087
- }
861
+ const go = opts.yes || (await confirm('Run it?', true, 'refuse'))
862
+ closePrompts()
863
+ if (!go) {
864
+ console.log(`\n ${c.dim('Not started. To run it later:')} ${later}\n`)
865
+ await cleanupAdapters()
866
+ return
1088
867
  }
1089
868
 
1090
- return { specPath: resolvedSpecPath, taskPlan }
1091
- }
1092
-
1093
- async function printFinalSummary(
1094
- prdPath: string,
1095
- specPath: string,
1096
- opts: PipelineOptions,
1097
- pkgRoot: string,
1098
- ): Promise<void> {
1099
- const prd = relPath(prdPath)
1100
- const spec = relPath(specPath)
1101
- console.log(c.bold(c.green(' Pipeline complete!\n')))
1102
- console.log(` PRD: ${prd}`)
1103
- console.log(` Convoy spec: ${spec}\n`)
1104
- console.log(
1105
- ` ${c.dim('Preview:')} npx opencastle convoy run -f ${spec} --dry-run\n` +
1106
- ` ${c.dim('Execute:')} npx opencastle convoy run -f ${spec}\n`
1107
- )
1108
-
869
+ // The run takes the spec by its path, as `convoy run <spec>` does, on the
870
+ // runtime already chosen and printed above.
871
+ const { runSpec, exitWith } = await import('./run.js')
872
+ let code = 1
1109
873
  try {
1110
- const shouldRun = await confirm('Run the convoy now?', true)
1111
- if (shouldRun) {
1112
- closePrompts()
1113
- const runModule = await import('./run.js')
1114
- const runArgs = ['-f', specPath]
1115
- if (opts.adapter) runArgs.push('-a', opts.adapter)
1116
- if (opts.verbose) runArgs.push('--verbose')
1117
- await runModule.default({ args: runArgs, pkgRoot })
1118
- }
874
+ code = await runSpec(
875
+ { spec: outcome.specPath, dryRun: false, adapter: opts.adapter, concurrency: opts.concurrency, verbose: opts.verbose, help: false },
876
+ { runtime },
877
+ )
1119
878
  } finally {
1120
879
  closePrompts()
1121
880
  await cleanupAdapters()
1122
881
  }
882
+ exitWith(code)
883
+ }
884
+
885
+ /** `opencastle convoy "<task>"`: the task comes from the words typed, the flags from `args`. */
886
+ export async function planTask({ args, pkgRoot }: CliContext, task: string): Promise<void> {
887
+ const opts = parseArgs(args, false)
888
+ await planThenRun({ task }, opts, pkgRoot)
889
+ }
890
+
891
+ /** `opencastle convoy plan --prd <file>`. */
892
+ export default async function pipeline({ args, pkgRoot }: CliContext): Promise<void> {
893
+ const opts = parseArgs(args, true)
894
+ if (opts.help) {
895
+ console.log(HELP)
896
+ return
897
+ }
898
+ if (opts.prd === null) {
899
+ console.error(' ✗ Name the PRD to plan from: opencastle convoy plan --prd <file>')
900
+ console.log(HELP)
901
+ process.exit(1)
902
+ }
903
+ if (!existsSync(resolve(process.cwd(), opts.prd))) {
904
+ console.error(` ✗ PRD not found: ${opts.prd}`)
905
+ process.exit(1)
906
+ }
907
+ await planThenRun({ prd: opts.prd }, opts, pkgRoot)
1123
908
  }