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,28 +1,30 @@
1
- import { execFile as execFileCb } from 'node:child_process';
2
1
  import { createHash } from 'node:crypto';
3
- import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, } from 'node:fs';
4
- import { dirname, join, resolve } from 'node:path';
2
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, realpathSync } from 'node:fs';
3
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
5
4
  import { DatabaseSync } from 'node:sqlite';
6
- import { promisify } from 'node:util';
7
5
  import { createConvoyStore, ConvoyArtifactLimitError } from './store.js';
8
6
  import { acquireEngineLock } from './lock.js';
9
7
  import { createEventEmitter, ndjsonPathForConvoy, recoverNdjson } from './events.js';
10
- import { createWorktreeManager } from './worktree.js';
8
+ import { createWorktreeManager, ensureRootWorktree, removeRootWorktree, mainRepoRoot, currentRef, listAllWorktrees, worktreesDirFor, workerBranchName, commitAllIn, git, BranchInUseError, } from './worktree.js';
11
9
  import { createMergeQueue, MergeConflictError } from './merge.js';
12
- import { createHealthMonitor, detectDrift } from './health.js';
13
- import { buildPhases, formatDuration } from '../run/executor.js';
14
- import { parseTimeout, parseYaml } from '../run/schema.js';
15
- import { getAdapter, detectAdapter } from '../run/adapters/index.js';
10
+ import { parseTimeout } from '../run/schema.js';
11
+ import { getAdapter } from '../run/adapters/index.js';
12
+ import { supportsPermissionMode } from '../run/adapters/permission-modes.js';
13
+ import { runShell } from '../run/platform.js';
16
14
  import { c } from '../prompt.js';
15
+ import { tierForAgent } from '../tiers.js';
17
16
  import { validateFilePartitions, scanSymlinks, scanNewSymlinks, normalizePath, pathsOverlap } from './partition.js';
18
- import { scanForSecrets, runSecretScanGate, runBlastRadiusGate, runDependencyAuditGate, runRegressionTestGate, browserTestGate, noOpGate, collectWorktreeChanges, } from './gates.js';
19
- import { validateOutput, buildContractInstruction, buildContractRetryPrompt } from './contracts.js';
20
- import { runTwoStageReview } from './review-stages.js';
21
- import { buildIsolationPreamble, resolveDependencyResults, detectPartitionViolations } from './isolation.js';
17
+ import { scanForSecrets, runSecretScanGate, runBlastRadiusGate, runDependencyAuditGate, runRegressionTestGate, browserTestGate, noOpGate, } from './gates.js';
18
+ import { validateOutput, buildContractInstruction } from './contracts.js';
19
+ import { defaultReviewer, evaluateReviewLevel, countChangedLines, } from './reviewer.js';
20
+ import { buildSharedContext, buildTaskSection, composePrompt, resolveDependencyResults, detectPartitionViolations, summarizeTask, } from './isolation.js';
22
21
  import { checkTDD, formatTDDFailure, DEFAULT_TDD_CONFIG } from './tdd-gate.js';
23
- import { getArtifactDir, extractArtifactRefs } from './artifacts.js';
22
+ import { extractArtifactRefs } from './artifacts.js';
24
23
  import { calculateCost } from './pricing.js';
25
- const execFile = promisify(execFileCb);
24
+ import { buildPhases, formatDuration, pickStartable, taskFiles } from './schedule.js';
25
+ import { createProgress, firstLine, formatCost, formatTokens } from './progress.js';
26
+ import { redactSecrets } from './redact.js';
27
+ export { evaluateReviewLevel };
26
28
  export class CircuitBreakerManager {
27
29
  states = new Map();
28
30
  threshold;
@@ -101,25 +103,23 @@ export class CircuitBreakerManager {
101
103
  return JSON.stringify(Object.fromEntries(this.states));
102
104
  }
103
105
  }
106
+ const TERMINAL_TASK_STATUSES = new Set([
107
+ 'done', 'failed', 'skipped', 'timed-out', 'gate-failed', 'review-blocked', 'hook-failed', 'disputed',
108
+ ]);
104
109
  export function runConvoyGuard(store, convoyId, _wtManager, ndjsonPath, guardConfig) {
105
- // If guard is explicitly disabled, skip all checks
106
110
  if (guardConfig?.enabled === false) {
107
111
  return { passed: true, warnings: [] };
108
112
  }
109
113
  const warnings = [];
110
114
  const tasks = store.getTasksByConvoy(convoyId);
111
- // Check 1: All task statuses are terminal
112
- const terminalStatuses = new Set(['done', 'failed', 'skipped', 'timed-out', 'gate-failed', 'review-blocked', 'hook-failed', 'disputed']);
113
- const nonTerminal = tasks.filter(t => !terminalStatuses.has(t.status));
115
+ const nonTerminal = tasks.filter(t => !TERMINAL_TASK_STATUSES.has(t.status));
114
116
  if (nonTerminal.length > 0) {
115
117
  warnings.push(`Non-terminal tasks: ${nonTerminal.map(t => `${t.id}(${t.status})`).join(', ')}`);
116
118
  }
117
- // Check 2: NDJSON file exists and record count >= completed task count
118
119
  const completedTasks = tasks.filter(t => t.status === 'done');
119
120
  try {
120
121
  const content = readFileSync(ndjsonPath, 'utf8');
121
122
  const lines = content.split('\n').filter(l => l.trim());
122
- // Per-convoy file — all records belong to this convoy, no need to filter by convoy_id
123
123
  if (lines.length < completedTasks.length) {
124
124
  warnings.push(`NDJSON record count (${lines.length}) < completed tasks (${completedTasks.length})`);
125
125
  }
@@ -129,7 +129,6 @@ export function runConvoyGuard(store, convoyId, _wtManager, ndjsonPath, guardCon
129
129
  warnings.push(`NDJSON file not found at ${ndjsonPath} but ${completedTasks.length} tasks completed`);
130
130
  }
131
131
  }
132
- // Check 3: Every retried task has events for each attempt
133
132
  const retriedTasks = tasks.filter(t => t.retries > 0);
134
133
  const events = store.getEvents(convoyId);
135
134
  for (const task of retriedTasks) {
@@ -138,25 +137,6 @@ export function runConvoyGuard(store, convoyId, _wtManager, ndjsonPath, guardCon
138
137
  warnings.push(`Task ${task.id} has ${task.retries} retries but only ${taskEvents.length} task_started events`);
139
138
  }
140
139
  }
141
- // Check 4: Gate results recorded for all gates that ran
142
- const gateEvents = events.filter(e => {
143
- if (e.type === 'built_in_gate_result')
144
- return true;
145
- if (e.data == null)
146
- return false;
147
- try {
148
- const parsed = JSON.parse(e.data);
149
- return 'gate' in parsed;
150
- }
151
- catch {
152
- return false;
153
- }
154
- });
155
- const tasksWithGates = tasks.filter(t => t.gates);
156
- if (tasksWithGates.length > 0 && gateEvents.length === 0) {
157
- warnings.push('Tasks have gates configured but no gate result events found');
158
- }
159
- // Check 5: Token/cost totals computed
160
140
  const convoy = store.getConvoy(convoyId);
161
141
  if (convoy && convoy.total_tokens == null) {
162
142
  const totalTokens = tasks.reduce((sum, t) => sum + (t.total_tokens ?? 0), 0);
@@ -164,54 +144,27 @@ export function runConvoyGuard(store, convoyId, _wtManager, ndjsonPath, guardCon
164
144
  warnings.push('Convoy total_tokens not persisted despite tasks having token data');
165
145
  }
166
146
  }
167
- // Check 6: No orphaned worktrees — engine already calls removeAll() during cleanup.
168
- // Synchronous check is not possible; the engine handles this.
169
147
  return { passed: warnings.length === 0, warnings };
170
148
  }
171
- export function evaluateReviewLevel(task, diff, heuristics, allGatesPassed) {
172
- const panelPaths = heuristics?.panel_paths ?? ['auth/', 'security/', 'migrations/', 'rls/'];
173
- const panelAgents = heuristics?.panel_agents ?? ['security-expert', 'data-engineer'];
174
- const autoPassAgents = heuristics?.auto_pass_agents ?? ['writer'];
175
- const autoPassMaxLines = heuristics?.auto_pass_max_lines ?? 10;
176
- const autoPassMaxFiles = heuristics?.auto_pass_max_files ?? 2;
177
- // Panel: sensitive paths or agents
178
- if (panelPaths.some(p => diff.filePaths.some(fp => fp.startsWith(p) || fp.includes('/' + p))))
179
- return 'panel';
180
- if (panelAgents.includes(task.agent))
181
- return 'panel';
182
- // Auto-pass: documentation/copy agents
183
- if (autoPassAgents.includes(task.agent))
184
- return 'auto-pass';
185
- // Auto-pass: small diffs with all gates passing
186
- if (diff.linesChanged <= autoPassMaxLines && diff.filesChanged <= autoPassMaxFiles && allGatesPassed !== false)
187
- return 'auto-pass';
188
- // Large diffs → fast review
189
- if (diff.linesChanged > 200 || diff.filesChanged > 5)
190
- return 'fast';
191
- // Default → fast review
192
- return 'fast';
193
- }
194
- class ReviewSemaphore {
149
+ // ── Small helpers ─────────────────────────────────────────────────────────────
150
+ class Semaphore {
195
151
  max;
196
152
  current = 0;
197
153
  queue = [];
198
154
  constructor(max) {
199
155
  this.max = max;
200
156
  }
201
- async acquire() {
202
- if (this.current < this.max) {
203
- this.current++;
204
- return;
157
+ async use(fn) {
158
+ if (this.current >= this.max) {
159
+ await new Promise(res => this.queue.push(res));
205
160
  }
206
- return new Promise(resolve => {
207
- this.queue.push(() => { this.current++; resolve(); });
208
- });
209
- }
210
- release() {
211
- this.current--;
212
- if (this.queue.length > 0) {
213
- const next = this.queue.shift();
214
- next();
161
+ this.current++;
162
+ try {
163
+ return await fn();
164
+ }
165
+ finally {
166
+ this.current--;
167
+ this.queue.shift()?.();
215
168
  }
216
169
  }
217
170
  }
@@ -220,22 +173,47 @@ function msToTimeout(ms) {
220
173
  return `${ms / 3_600_000}h`;
221
174
  if (ms >= 60_000 && ms % 60_000 === 0)
222
175
  return `${ms / 60_000}m`;
223
- return `${ms / 1_000}s`;
176
+ return `${Math.max(1, Math.round(ms / 1_000))}s`;
224
177
  }
225
- // ── DLQ markdown dual-write ───────────────────────────────────────────────────
226
- // Builds the DLQ markdown entry text (no I/O, no scanning).
178
+ function parseJsonList(raw) {
179
+ if (!raw)
180
+ return [];
181
+ try {
182
+ const v = JSON.parse(raw);
183
+ return Array.isArray(v) ? v.filter((x) => typeof x === 'string') : [];
184
+ }
185
+ catch {
186
+ return [];
187
+ }
188
+ }
189
+ function slugify(text, max) {
190
+ return text.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, max).replace(/-+$/, '');
191
+ }
192
+ /** Six characters that name a convoy's worktrees, derived from its id so resume finds them. */
193
+ export function shortConvoyId(convoyId) {
194
+ return createHash('sha1').update(convoyId).digest('hex').slice(0, 6);
195
+ }
196
+ /** `convoy/<name>-<short id>`: the branch a run works on when its spec names none. */
197
+ export function defaultBranchName(specName, convoyId) {
198
+ return `convoy/${slugify(specName, 40) || 'run'}-${shortConvoyId(convoyId)}`;
199
+ }
200
+ /** Every task status `resume` turns back into pending. Skipped counts: it was skipped because something failed. */
201
+ export const RESUME_RESET_STATUSES = [
202
+ 'failed', 'timed-out', 'gate-failed', 'review-blocked', 'disputed', 'hook-failed',
203
+ 'running', 'assigned', 'skipped', 'wait-for-input',
204
+ ];
205
+ /** Statuses whose reset gives the task its retry budget back. Interrupted tasks keep theirs. */
206
+ const FAILED_STATUSES = new Set(['failed', 'timed-out', 'gate-failed', 'review-blocked', 'disputed', 'hook-failed']);
207
+ // ── DLQ and dispute ledgers ───────────────────────────────────────────────────
227
208
  function buildDlqMarkdownEntry(dlqId, task, failureType, errorOutput) {
228
209
  const marker = `<!-- dlq:${dlqId} -->`;
229
210
  const entry = `\n${marker}\n### ${dlqId}\n\n| Field | Value |\n|-------|-------|\n| Task | ${task.id} |\n| Agent | ${task.agent} |\n| Type | ${failureType} |\n| Attempts | ${task.retries + 1} |\n| Date | ${new Date().toISOString()} |\n\n**Error:**\n\`\`\`\n${(errorOutput ?? '(no output)').slice(0, 2000)}\n\`\`\`\n`;
230
211
  return { marker, entry };
231
212
  }
232
- // Appends a pre-scanned DLQ entry to AGENT-FAILURES.md. The caller must have
233
- // already verified the entry is clean via scanForSecrets — no re-scan here.
234
- function appendDlqMarkdownClean(marker, entry, basePath) {
235
- const mdPath = join(resolve(basePath), '.opencastle', 'AGENT-FAILURES.md');
213
+ function appendLedger(repoRoot, file, marker, entry) {
214
+ const mdPath = join(resolve(repoRoot), '.opencastle', file);
236
215
  try {
237
- const existing = readFileSync(mdPath, 'utf8');
238
- if (existing.includes(marker))
216
+ if (readFileSync(mdPath, 'utf8').includes(marker))
239
217
  return;
240
218
  }
241
219
  catch {
@@ -245,12 +223,8 @@ function appendDlqMarkdownClean(marker, entry, basePath) {
245
223
  appendFileSync(mdPath, entry);
246
224
  }
247
225
  /**
248
- * Marks a convoy 'failed' after an unexpected throw escapes runConvoy.
249
- *
250
- * Both run() and resume() previously wrapped runConvoy in try/finally with no
251
- * catch, so a crash left the row reading 'running' — which resume() then treats
252
- * as owned by a live engine and refuses to pick up (KI-003). Best-effort: if the
253
- * store is already closed or the DB is gone, the original error still wins.
226
+ * Marks a convoy 'failed' after an unexpected throw escapes runConvoy, so a
227
+ * crash does not leave the row reading 'running'. Best-effort.
254
228
  */
255
229
  function markConvoyCrashed(store, events, convoyId, err) {
256
230
  const reason = err instanceof Error ? err.message : String(err);
@@ -263,62 +237,22 @@ function markConvoyCrashed(store, events, convoyId, err) {
263
237
  }
264
238
  catch { /* ditto */ }
265
239
  }
266
- function writeDisputeToMarkdown(disputeId, convoyId, task, panelResults, basePath, events) {
267
- const mdPath = join(resolve(basePath), '.opencastle', 'DISPUTES.md');
268
- const marker = `<!-- dispute:${disputeId} -->`;
269
- try {
270
- const existing = readFileSync(mdPath, 'utf8');
271
- if (existing.includes(marker))
272
- return;
273
- }
274
- catch {
275
- // File doesn't exist yet
276
- }
277
- const blockingReasons = panelResults
278
- .filter(r => r.verdict === 'block')
279
- .map(r => r.feedback)
280
- .join('\n\n');
281
- const entry = `\n${marker}\n## Dispute: ${task.id}\n\n| Field | Value |\n|-------|-------|\n| Convoy | ${convoyId} |\n| Task | ${task.id} |\n| Date | ${new Date().toISOString()} |\n| Panel attempts | ${task.panel_attempts + 1} |\n| Agent | ${task.agent} |\n| Status | Open |\n\n**Blocking reasons:**\n\n${blockingReasons}\n`;
282
- const scanResult = scanForSecrets(entry, '.opencastle/DISPUTES.md');
283
- if (!scanResult.clean) {
284
- if (events) {
285
- events.emit('secret_leak_prevented', {
286
- task_id: task.id,
287
- findings_count: scanResult.findings.length,
288
- patterns: scanResult.findings.map((f) => f.pattern),
289
- context: 'dispute_markdown_write',
290
- }, { convoy_id: convoyId, task_id: task.id });
291
- }
292
- return;
293
- }
294
- mkdirSync(dirname(mdPath), { recursive: true });
295
- appendFileSync(mdPath, entry);
296
- }
297
240
  function taskRecordToTask(record) {
298
241
  return {
299
242
  id: record.id,
300
243
  prompt: record.prompt,
301
244
  agent: record.agent,
302
245
  timeout: msToTimeout(record.timeout_ms),
303
- depends_on: record.depends_on ? JSON.parse(record.depends_on) : [],
304
- files: record.files ? JSON.parse(record.files) : [],
246
+ depends_on: parseJsonList(record.depends_on),
247
+ files: parseJsonList(record.files),
305
248
  description: '',
306
249
  model: record.model ?? undefined,
307
250
  max_retries: record.max_retries,
308
251
  adapter: record.adapter ?? undefined,
309
- gates: record.gates ? JSON.parse(record.gates) : undefined,
252
+ gates: record.gates ? parseJsonList(record.gates) : undefined,
310
253
  };
311
254
  }
312
- function makeTimeoutPromise(ms) {
313
- let timerId;
314
- const promise = new Promise((res) => {
315
- timerId = setTimeout(() => res({ _timedOut: true, success: false, output: 'Task timed out', exitCode: -1 }), ms);
316
- });
317
- return { promise, clear: () => { if (timerId !== undefined)
318
- clearTimeout(timerId); } };
319
- }
320
- // ── Step condition evaluation ─────────────────────────────────────────────────
321
- function evaluateStepCondition(condition, stepResults, worktreePath, basePath) {
255
+ function evaluateStepCondition(condition, stepResults, worktreePath) {
322
256
  if (!condition)
323
257
  return true;
324
258
  if (condition.exitCode) {
@@ -337,329 +271,210 @@ function evaluateStepCondition(condition, stepResults, worktreePath, basePath) {
337
271
  return false;
338
272
  }
339
273
  if (condition.fileExists) {
340
- const base = worktreePath ?? basePath;
341
- if (condition.fileExists.path.startsWith('/')) {
342
- return false; // Absolute paths not allowed in step conditions
274
+ // Absolute paths and `..` are refused on either separator; the check used
275
+ // to test for a leading '/' only, which never matched on Windows.
276
+ const raw = condition.fileExists.path;
277
+ if (isAbsolute(raw) || /^[a-zA-Z]:/.test(raw) || raw.startsWith('\\'))
278
+ return false;
279
+ let rel;
280
+ try {
281
+ rel = normalizePath(raw);
343
282
  }
344
- const filePath = join(base, condition.fileExists.path);
345
- const resolved = resolve(filePath);
346
- const resolvedBase = resolve(base);
347
- if (!resolved.startsWith(resolvedBase + '/') && resolved !== resolvedBase) {
348
- return false; // path escapes the worktree — treat as "file doesn't exist"
283
+ catch {
284
+ return false;
349
285
  }
350
- if (!existsSync(filePath))
286
+ if (!existsSync(join(worktreePath, rel)))
351
287
  return false;
352
288
  }
353
289
  return true;
354
290
  }
355
- async function executeSteps(taskRecord, steps, adapter, worktreePath, basePath, store, convoyId, verbose, permissionMode) {
356
- const now = () => new Date().toISOString();
357
- const stepResults = new Map();
358
- let combinedOutput = '';
359
- let lastExitCode = 0;
360
- // Track total_steps in DB
361
- store.updateTaskStatus(taskRecord.id, convoyId, 'running', {});
362
- for (let i = 0; i < steps.length; i++) {
363
- const step = steps[i];
364
- // Evaluate condition — skip step if condition is not met
365
- if (step.if) {
366
- const condMet = evaluateStepCondition(step.if, stepResults, worktreePath, basePath);
367
- if (!condMet) {
368
- store.insertTaskStep({
369
- task_id: taskRecord.id,
370
- step_index: i,
371
- prompt: step.prompt,
372
- gates: step.gates ? JSON.stringify(step.gates) : null,
373
- status: 'skipped',
374
- exit_code: null,
375
- output: 'Skipped: condition not met',
376
- started_at: now(),
377
- finished_at: now(),
378
- });
379
- if (step.id) {
380
- stepResults.set(step.id, { exitCode: 0 });
381
- }
382
- combinedOutput += `\n[Step ${i + 1} skipped: condition not met]`;
383
- continue;
384
- }
385
- }
386
- // Insert step record as running
387
- const stepDbId = store.insertTaskStep({
388
- task_id: taskRecord.id,
389
- step_index: i,
390
- prompt: step.prompt,
391
- gates: step.gates ? JSON.stringify(step.gates) : null,
392
- status: 'running',
393
- exit_code: null,
394
- output: null,
395
- started_at: now(),
396
- finished_at: null,
397
- });
398
- // Update current_step on the task record
399
- store.updateTaskStatus(taskRecord.id, convoyId, 'running', {});
400
- const stepMaxRetries = step.max_retries ?? taskRecord.max_retries;
401
- let stepResult = { success: false, output: '', exitCode: -1 };
402
- let stepAttempt = 0;
403
- while (stepAttempt <= stepMaxRetries) {
404
- // Prepend prior failure context on retries
405
- let stepPrompt = step.prompt;
406
- if (stepAttempt > 0 && stepResult) {
407
- const failedOutput = stepResult.output || '(no output)';
408
- stepPrompt = `Previous attempt failed.\nExit code: ${stepResult.exitCode}\nError output:\n${failedOutput}\n\nFix the issues and try again.\n\n` + step.prompt;
409
- }
410
- const stepTask = {
411
- id: taskRecord.id,
412
- prompt: stepPrompt,
413
- agent: taskRecord.agent,
414
- timeout: `${taskRecord.timeout_ms}ms`,
415
- depends_on: [],
416
- files: taskRecord.files ? JSON.parse(taskRecord.files) : [],
417
- description: `step ${i + 1}`,
418
- max_retries: stepMaxRetries,
419
- };
420
- try {
421
- stepResult = await adapter.execute(stepTask, { verbose, cwd: worktreePath ?? basePath, permissionMode });
422
- }
423
- catch (err) {
424
- stepResult = { success: false, output: err.message, exitCode: -1 };
425
- }
426
- if (stepResult.success)
427
- break;
428
- stepAttempt++;
429
- if (stepAttempt <= stepMaxRetries) {
430
- process.stdout.write(` ↺ step ${i + 1}/${steps.length} failed, retry ${stepAttempt}/${stepMaxRetries}\n`);
431
- }
432
- }
433
- lastExitCode = stepResult.exitCode;
434
- combinedOutput += `\n[Step ${i + 1}]\n${stepResult.output}`;
435
- if (step.id) {
436
- stepResults.set(step.id, { exitCode: stepResult.exitCode });
437
- }
438
- // Run step-level gates if present
439
- if (step.gates && step.gates.length > 0 && stepResult.success) {
440
- let gateFailure = null;
441
- const execFileCb = (await import('node:child_process')).execFile;
442
- const execFileP = (await import('node:util')).promisify(execFileCb);
443
- for (const command of step.gates) {
444
- try {
445
- // SECURITY: Gate/hook commands come from the .convoy.yml spec file, which is operator-controlled.
446
- // They are NOT user-supplied and are part of the trusted build configuration.
447
- await execFileP('sh', ['-c', command], { cwd: worktreePath ?? basePath });
448
- }
449
- catch (gateErr) {
450
- const ge = gateErr;
451
- const code = typeof ge.code === 'number' ? ge.code : 1;
452
- const output = ge.stderr || ge.stdout || ge.message || '';
453
- gateFailure = { command, exitCode: code, output };
454
- break;
455
- }
456
- }
457
- if (gateFailure !== null) {
458
- stepResult = { success: false, output: `Gate failed: ${gateFailure.command}\nExit code: ${gateFailure.exitCode}\n${gateFailure.output}`, exitCode: gateFailure.exitCode };
459
- lastExitCode = gateFailure.exitCode;
460
- combinedOutput += `\n[Step ${i + 1} gate failed: ${gateFailure.command}]`;
461
- }
462
- }
463
- // Update step record
464
- store.updateTaskStep(stepDbId, {
465
- status: stepResult.success ? 'done' : 'failed',
466
- exit_code: stepResult.exitCode,
467
- output: stepResult.output,
468
- finished_at: now(),
469
- });
470
- if (!stepResult.success) {
471
- return {
472
- success: false,
473
- output: combinedOutput.trim(),
474
- exitCode: lastExitCode,
475
- };
476
- }
291
+ /** Add `b` to `a`, keeping null when neither side knows. */
292
+ function addNullable(a, b) {
293
+ if (b == null)
294
+ return a ?? null;
295
+ return (a ?? 0) + b;
296
+ }
297
+ /**
298
+ * What one agent session spent, as the runtime reported it.
299
+ *
300
+ * When it reported nothing the tokens are estimated from the text (4 characters
301
+ * a token) and flagged. Cost is the runtime's own figure; failing that, a price
302
+ * for the *model* it says it used, flagged as an estimate. It is never priced
303
+ * by the adapter's name — "claude" is not a model, and pricing it as Sonnet
304
+ * produced figures that looked measured and were not.
305
+ */
306
+ function usageOf(result, promptText, fallbackModel) {
307
+ const u = result.usage;
308
+ const reported = u != null && (u.prompt_tokens != null || u.completion_tokens != null || u.total_tokens != null);
309
+ const prompt = reported ? (u.prompt_tokens ?? null) : Math.ceil(promptText.length / 4);
310
+ const completion = reported ? (u.completion_tokens ?? null) : Math.ceil((result.output ?? '').length / 4);
311
+ const total = reported ? (u.total_tokens ?? (prompt ?? 0) + (completion ?? 0)) : (prompt ?? 0) + (completion ?? 0);
312
+ const model = result.model ?? fallbackModel ?? null;
313
+ let cost = null;
314
+ let costEstimated = false;
315
+ if (result.costUsd != null) {
316
+ cost = result.costUsd;
317
+ }
318
+ else {
319
+ cost = calculateCost(model, prompt, completion);
320
+ costEstimated = true;
477
321
  }
478
322
  return {
479
- success: true,
480
- output: combinedOutput.trim(),
481
- exitCode: lastExitCode,
323
+ prompt,
324
+ completion,
325
+ total,
326
+ cacheRead: reported ? (u.cache_read_tokens ?? null) : null,
327
+ cacheWrite: reported ? (u.cache_write_tokens ?? null) : null,
328
+ cost,
329
+ estimated: !reported || costEstimated,
330
+ model,
482
331
  };
483
332
  }
484
- // ── File-based injection ──────────────────────────────────────────────────────
485
- const INJECT_DIR = '.opencastle/convoy-inject';
486
- const CONVOY_ID_RE = /^[a-zA-Z0-9-]+$/;
487
- const MAX_FILE_INJECTED_TASKS = 10;
488
- function pollInjectFile(convoyId, store, events, basePath) {
489
- // Path traversal guard: convoy_id must be alphanumeric + hyphens only
490
- if (!CONVOY_ID_RE.test(convoyId))
491
- return 0;
492
- const injectDir = join(basePath, INJECT_DIR, convoyId);
493
- const injectPath = join(injectDir, 'inject.yml');
494
- if (!existsSync(injectPath))
495
- return 0;
496
- // Atomic rename to prevent double-read
497
- const processingPath = injectPath + '.processing';
498
- try {
499
- renameSync(injectPath, processingPath);
500
- }
501
- catch {
502
- return 0; // Another process may have grabbed it
503
- }
504
- let raw;
505
- try {
506
- raw = readFileSync(processingPath, 'utf8');
507
- }
508
- catch {
509
- return 0;
510
- }
511
- finally {
512
- try {
513
- unlinkSync(processingPath);
514
- }
515
- catch { /* ignore */ }
516
- }
517
- let parsed;
518
- try {
519
- parsed = parseYaml(raw);
520
- if (!parsed || typeof parsed !== 'object' || !Array.isArray(parsed.tasks)) {
521
- process.stderr.write(`Warning: inject file has invalid format (expected { tasks: [...] })\n`);
522
- return 0;
523
- }
524
- }
525
- catch (err) {
526
- process.stderr.write(`Warning: failed to parse inject file: ${err.message}\n`);
527
- return 0;
528
- }
529
- const tasks = parsed.tasks;
530
- const allExisting = store.getTasksByConvoy(convoyId);
531
- const existingFileInjected = allExisting.filter(t => t.provenance === 'file-injection').length;
532
- const remaining = MAX_FILE_INJECTED_TASKS - existingFileInjected;
533
- let injectedCount = 0;
534
- for (const rawTask of tasks) {
535
- if (injectedCount >= remaining) {
536
- process.stderr.write(`Warning: file injection limit reached (${MAX_FILE_INJECTED_TASKS}), skipping remaining tasks\n`);
537
- break;
538
- }
539
- // Validate required fields
540
- if (!rawTask.id || typeof rawTask.id !== 'string') {
541
- process.stderr.write(`Warning: skipping injected task with missing/invalid id\n`);
542
- continue;
543
- }
544
- if (!rawTask.prompt || typeof rawTask.prompt !== 'string') {
545
- process.stderr.write(`Warning: skipping injected task "${rawTask.id}": missing prompt\n`);
546
- continue;
547
- }
548
- if (!rawTask.agent || typeof rawTask.agent !== 'string') {
549
- process.stderr.write(`Warning: skipping injected task "${rawTask.id}": missing agent\n`);
550
- continue;
551
- }
552
- // Check ID uniqueness
553
- if (allExisting.some(t => t.id === rawTask.id)) {
554
- process.stderr.write(`Warning: skipping injected task "${rawTask.id}": ID already exists\n`);
555
- continue;
556
- }
557
- // Determine phase — inject into last scheduled phase
558
- const maxPhase = allExisting.reduce((max, t) => Math.max(max, t.phase), 0);
559
- // Validate file paths before building the record
560
- let validatedFiles = null;
561
- if (rawTask.files && Array.isArray(rawTask.files)) {
562
- try {
563
- validatedFiles = JSON.stringify(rawTask.files.map(f => normalizePath(f)));
564
- }
565
- catch (err) {
566
- process.stderr.write(`Warning: skipping injected task "${rawTask.id}": invalid file path: ${err.message}\n`);
567
- continue;
333
+ function createRunControl() {
334
+ let resolveInterrupt = () => { };
335
+ const abort = new AbortController();
336
+ const ctl = {
337
+ stopDispatch: false,
338
+ interrupted: null,
339
+ interruptedPromise: new Promise(r => { resolveInterrupt = r; }),
340
+ signal: abort.signal,
341
+ onInterrupt: [],
342
+ interrupt(reason) {
343
+ if (ctl.interrupted)
344
+ return;
345
+ ctl.interrupted = reason;
346
+ ctl.stopDispatch = true;
347
+ for (const fn of ctl.onInterrupt) {
348
+ try {
349
+ fn();
350
+ }
351
+ catch { /* best effort */ }
568
352
  }
569
- }
570
- const record = {
571
- id: rawTask.id,
572
- convoy_id: convoyId,
573
- phase: maxPhase,
574
- prompt: rawTask.prompt,
575
- agent: rawTask.agent,
576
- adapter: null,
577
- model: null,
578
- timeout_ms: typeof rawTask.timeout_ms === 'number' ? rawTask.timeout_ms : 1_800_000,
579
- status: 'pending',
580
- worker_id: null,
581
- worktree: null,
582
- output: null,
583
- exit_code: null,
584
- started_at: null,
585
- finished_at: null,
586
- retries: 0,
587
- max_retries: typeof rawTask.max_retries === 'number' ? rawTask.max_retries : 1,
588
- files: validatedFiles,
589
- depends_on: null,
590
- prompt_tokens: null,
591
- completion_tokens: null,
592
- total_tokens: null,
593
- cost_usd: null,
594
- gates: null,
595
- on_exhausted: 'dlq',
596
- injected: 1,
597
- provenance: 'file-injection',
598
- idempotency_key: null,
599
- current_step: null,
600
- total_steps: null,
601
- review_level: null,
602
- review_verdict: null,
603
- review_tokens: null,
604
- review_model: null,
605
- panel_attempts: 0,
606
- dispute_id: null,
607
- drift_score: null,
608
- drift_retried: 0,
609
- outputs: null,
610
- inputs: null,
611
- };
612
- try {
613
- store.insertInjectedTask(record);
614
- injectedCount++;
615
- }
616
- catch (err) {
617
- process.stderr.write(`Warning: failed to inject task "${rawTask.id}": ${err.message}\n`);
618
- }
619
- }
620
- if (injectedCount > 0) {
621
- events.emit('file_injection_received', {
622
- task_count: injectedCount,
623
- source: injectPath,
624
- }, { convoy_id: convoyId });
625
- }
626
- return injectedCount;
353
+ abort.abort();
354
+ resolveInterrupt();
355
+ },
356
+ };
357
+ return ctl;
627
358
  }
359
+ /** How long an interrupted run waits for its tasks to wind down before it lets go of them. */
360
+ const INTERRUPT_GRACE_MS = 10_000;
628
361
  // ── Core convoy execution ─────────────────────────────────────────────────────
629
- async function runConvoy(convoyId, spec, adapter, store, events, wtManager, mergeQueue, basePath, baseBranch, verbose, startTime, ndjsonPath, reviewRunner) {
630
- const totalTasks = spec.tasks?.length ?? 0;
631
- let completedCount = 0;
632
- const activeTaskMap = new Map();
633
- const reviewSemaphore = new ReviewSemaphore(spec.defaults?.max_concurrent_reviews ?? 3);
634
- let reviewTokensTotal = 0;
635
- const taskAdapterMap = new Map();
636
- const healthMonitor = createHealthMonitor({
637
- store,
638
- events,
639
- convoyId,
640
- onKill: (_workerId, taskId) => {
641
- const task = activeTaskMap.get(taskId);
642
- const taskAdpt = taskAdapterMap.get(taskId) ?? adapter;
643
- if (task && typeof taskAdpt.kill === 'function') {
644
- taskAdpt.kill(task);
645
- }
646
- activeTaskMap.delete(taskId);
647
- taskAdapterMap.delete(taskId);
648
- },
649
- });
650
- healthMonitor.start();
362
+ async function runConvoy(ctx) {
363
+ const { convoyId, spec, adapter, store, events, wtManager, mergeQueue, repoRoot, workRoot, branch, verbose, ndjsonPath, reviewRunner, progress, ctl, } = ctx;
364
+ const startTime = ctx.startTime;
365
+ const short = shortConvoyId(convoyId);
366
+ const specTasks = new Map((spec.tasks ?? []).map(t => [t.id, t]));
367
+ const reviewSemaphore = new Semaphore(spec.defaults?.max_concurrent_reviews ?? 3);
368
+ const adapterCache = new Map();
369
+ const conflictReruns = new Set();
370
+ const running = new Map();
371
+ // Worker ids must be unique even when a retry starts in the same millisecond.
372
+ let workerSeq = Date.now();
373
+ const permissionMode = spec.defaults?.permission_mode;
374
+ let reviewTokensTotal = store.getConvoy(convoyId)?.review_tokens_total ?? 0;
375
+ let extraTokens = 0;
376
+ let extraCost = 0;
377
+ let extraEstimated = false;
651
378
  // ── Circuit breaker ────────────────────────────────────────────────────────
652
379
  const circuitBreakerConfig = spec.defaults?.circuit_breaker;
653
380
  const convoyRecord = store.getConvoy(convoyId);
654
381
  const initialCircuitState = convoyRecord?.circuit_state ? JSON.parse(convoyRecord.circuit_state) : undefined;
655
382
  const circuitBreaker = new CircuitBreakerManager(circuitBreakerConfig, initialCircuitState);
656
383
  // ── Trust model ────────────────────────────────────────────────────────────
657
- // Gate commands, hook commands, and step commands in .convoy.yml are treated
658
- // as operator-controlled build configuration (analogous to Makefiles, CI
659
- // configs, or package.json scripts). They are executed via sh -c and must
660
- // NOT contain user-supplied input. The spec file itself is the trust boundary.
661
- // ──────────────────────────────────────────────────────────────────────────
662
- // ── Task skipping ─────────────────────────────────────────────────────────
384
+ // Gate, hook and step commands in a spec are operator-controlled build
385
+ // configuration, like a Makefile or package.json scripts. They run through
386
+ // the platform shell and must not carry user-supplied input; the spec file is
387
+ // the trust boundary.
388
+ // ── Shared prompt context, built once so it is identical for every task ───
389
+ const sharedContext = buildSharedContext({
390
+ convoyName: spec.name,
391
+ plan: (spec.tasks ?? []).map(t => ({
392
+ id: t.id,
393
+ agent: t.agent,
394
+ summary: summarizeTask(t),
395
+ files: t.files ?? [],
396
+ depends_on: t.depends_on ?? [],
397
+ })),
398
+ artifactsDir: join(repoRoot, '.opencastle', 'artifacts', convoyId) + '/',
399
+ });
400
+ // ── Agent sessions, tracked so Ctrl+C can stop them ───────────────────────
401
+ const live = new Map();
402
+ ctl.onInterrupt.push(() => {
403
+ for (const [task, { adapter: a, taskId }] of live) {
404
+ try {
405
+ a.kill?.(task);
406
+ }
407
+ catch { /* already gone */ }
408
+ events.emit('worker_killed', { reason: 'interrupted', task_id: taskId }, { convoy_id: convoyId, task_id: taskId });
409
+ }
410
+ });
411
+ /**
412
+ * One agent session with a deadline. On timeout the session is killed
413
+ * through the adapter and the result says so; nothing waits on a process
414
+ * that will not end.
415
+ */
416
+ async function runAgent(taskId, agentAdapter, task, options, timeoutMs) {
417
+ if (ctl.interrupted)
418
+ return { success: false, output: 'Interrupted before it started', exitCode: 130 };
419
+ live.set(task, { adapter: agentAdapter, taskId });
420
+ let timer;
421
+ const timedOut = new Promise(res => {
422
+ timer = setTimeout(() => {
423
+ try {
424
+ agentAdapter.kill?.(task);
425
+ }
426
+ catch { /* already gone */ }
427
+ res({ _timedOut: true, success: false, output: `Timed out after ${formatDuration(timeoutMs)}`, exitCode: -1 });
428
+ }, Math.max(1, timeoutMs));
429
+ });
430
+ const interrupted = ctl.interruptedPromise.then(() => ({ success: false, output: 'Interrupted', exitCode: 130 }));
431
+ try {
432
+ const execution = agentAdapter.execute(task, { verbose, ...options }).catch((err) => ({ success: false, output: err.message, exitCode: -1 }));
433
+ return await Promise.race([execution, timedOut, interrupted]);
434
+ }
435
+ finally {
436
+ if (timer)
437
+ clearTimeout(timer);
438
+ live.delete(task);
439
+ }
440
+ }
441
+ // ── Usage bookkeeping ──────────────────────────────────────────────────────
442
+ /** Add one session's spend to the task row; attempts and steps accumulate. */
443
+ function addTaskUsage(taskId, usage) {
444
+ const row = store.getTask(taskId, convoyId);
445
+ if (!row)
446
+ return;
447
+ const cost = usage.cost == null && row.cost_usd == null
448
+ ? null
449
+ : (row.cost_usd ?? 0) + (usage.cost ?? 0);
450
+ store.updateTaskStatus(taskId, convoyId, row.status, {
451
+ prompt_tokens: addNullable(row.prompt_tokens, usage.prompt),
452
+ completion_tokens: addNullable(row.completion_tokens, usage.completion),
453
+ total_tokens: (row.total_tokens ?? 0) + usage.total,
454
+ cache_read_tokens: addNullable(row.cache_read_tokens, usage.cacheRead),
455
+ cache_write_tokens: addNullable(row.cache_write_tokens, usage.cacheWrite),
456
+ cost_usd: cost,
457
+ cost_estimated: (row.cost_estimated ?? 0) || usage.estimated || usage.cost == null ? 1 : 0,
458
+ model: usage.model ?? row.model,
459
+ });
460
+ }
461
+ // ── Adapters ───────────────────────────────────────────────────────────────
462
+ /**
463
+ * A task's runtime. No `adapter:`, `auto`, or the run's own name means the
464
+ * run's adapter; `auto` used to re-run detection for every task and could
465
+ * land on a different runtime than the one the user chose.
466
+ */
467
+ function adapterFor(name) {
468
+ if (!name || name === 'auto' || name === adapter.name)
469
+ return Promise.resolve(adapter);
470
+ let pending = adapterCache.get(name);
471
+ if (!pending) {
472
+ pending = getAdapter(name);
473
+ adapterCache.set(name, pending);
474
+ }
475
+ return pending;
476
+ }
477
+ // ── Task skipping and failure cascade ──────────────────────────────────────
663
478
  function skipTask(taskId, reason, visited = new Set()) {
664
479
  if (visited.has(taskId))
665
480
  return;
@@ -669,59 +484,64 @@ async function runConvoy(convoyId, spec, adapter, store, events, wtManager, merg
669
484
  if (!task || task.status !== 'pending')
670
485
  return;
671
486
  store.updateTaskStatus(taskId, convoyId, 'skipped', { output: reason });
672
- process.stdout.write(` ${c.dim('⊘')} ${c.bold(`[${taskId}]`)} skipped\n`);
487
+ progress.line(` ${c.dim('⊘')} ${c.bold(`[${taskId}]`)} skipped: ${reason}`);
673
488
  events.emit('task_skipped', { reason }, { convoy_id: convoyId, task_id: taskId });
674
489
  for (const t of allTasks) {
675
- const deps = t.depends_on ? JSON.parse(t.depends_on) : [];
676
- if (deps.includes(taskId)) {
677
- skipTask(t.id, `dependency "${taskId}" was skipped/failed`, visited);
490
+ if (parseJsonList(t.depends_on).includes(taskId)) {
491
+ skipTask(t.id, `dependency "${taskId}" did not finish`, visited);
678
492
  }
679
493
  }
680
494
  }
681
495
  function cascadeFailure(failedTaskId) {
682
- if (spec.on_failure === 'stop') {
683
- const allPending = store.getTasksByConvoy(convoyId).filter(t => t.status === 'pending');
684
- for (const t of allPending) {
685
- skipTask(t.id, 'execution halted due to on_failure: stop');
686
- }
687
- }
688
- else {
689
- const allTasks = store.getTasksByConvoy(convoyId);
690
- for (const t of allTasks) {
691
- const deps = t.depends_on ? JSON.parse(t.depends_on) : [];
692
- if (deps.includes(failedTaskId)) {
693
- skipTask(t.id, `dependency "${failedTaskId}" failed`);
694
- }
496
+ for (const t of store.getTasksByConvoy(convoyId)) {
497
+ if (parseJsonList(t.depends_on).includes(failedTaskId)) {
498
+ skipTask(t.id, `dependency "${failedTaskId}" failed`);
695
499
  }
696
500
  }
697
501
  }
502
+ /** Dispatch nothing new; tasks already running finish. */
503
+ function stopDispatching(reason) {
504
+ if (ctl.stopDispatch)
505
+ return;
506
+ ctl.stopDispatch = true;
507
+ progress.line(` ${c.yellow('■')} ${reason} — no new tasks will start; running tasks finish`);
508
+ }
698
509
  function handleExhaustion(taskRecord, failureType, errorOutput) {
699
510
  const exhausted = taskRecord.on_exhausted ?? 'dlq';
700
511
  if (exhausted === 'dlq' || exhausted === 'stop') {
701
512
  const dlqId = `dlq-${taskRecord.id}-${Date.now()}`;
702
- // Pre-scan: build the markdown entry and check for secrets BEFORE any
703
- // writes. This keeps the SQLite DLQ row and the Markdown file in sync —
704
- // either both are written or neither is (MF-2 dual-write atomicity).
705
- const { marker: dlqMarker, entry: dlqMdEntry } = buildDlqMarkdownEntry(dlqId, taskRecord, failureType, errorOutput);
706
- const dlqScanResult = scanForSecrets(dlqMdEntry, 'AGENT-FAILURES.md');
707
- if (!dlqScanResult.clean) {
708
- // Block BOTH writes to maintain consistent state
513
+ // Masked, then written to both the table and the ledger. Holding back
514
+ // both on any finding used to lose the failure record altogether; now
515
+ // only an entry that still flags after masking is held back — both
516
+ // halves, so the table and the ledger never disagree.
517
+ const masked = errorOutput == null ? null : redactSecrets(errorOutput);
518
+ const clean = masked?.text ?? null;
519
+ if (masked && masked.patterns.length > 0) {
520
+ events.emit('secret_leak_prevented', {
521
+ task_id: taskRecord.id,
522
+ findings_count: masked.patterns.length,
523
+ patterns: [...new Set(masked.patterns)],
524
+ context: 'dlq_redacted',
525
+ }, { convoy_id: convoyId, task_id: taskRecord.id });
526
+ }
527
+ const { marker, entry } = buildDlqMarkdownEntry(dlqId, taskRecord, failureType, clean);
528
+ const leak = scanForSecrets(entry, 'AGENT-FAILURES.md');
529
+ if (!leak.clean) {
709
530
  events.emit('secret_leak_prevented', {
710
531
  task_id: taskRecord.id,
711
- findings_count: dlqScanResult.findings.length,
712
- patterns: dlqScanResult.findings.map((f) => f.pattern),
532
+ findings_count: leak.findings.length,
533
+ patterns: leak.findings.map(f => f.pattern),
713
534
  context: 'dlq_dual_write',
714
535
  }, { convoy_id: convoyId, task_id: taskRecord.id });
715
536
  }
716
537
  else {
717
- // Clean — proceed with both writes atomically
718
538
  store.insertDlqEntry({
719
539
  id: dlqId,
720
540
  convoy_id: convoyId,
721
541
  task_id: taskRecord.id,
722
542
  agent: taskRecord.agent,
723
543
  failure_type: failureType,
724
- error_output: errorOutput,
544
+ error_output: clean,
725
545
  attempts: taskRecord.retries + 1,
726
546
  tokens_spent: taskRecord.total_tokens,
727
547
  escalation_task_id: null,
@@ -730,29 +550,19 @@ async function runConvoy(convoyId, spec, adapter, store, events, wtManager, merg
730
550
  created_at: new Date().toISOString(),
731
551
  resolved_at: null,
732
552
  });
733
- appendDlqMarkdownClean(dlqMarker, dlqMdEntry, basePath);
553
+ appendLedger(repoRoot, 'AGENT-FAILURES.md', marker, entry);
734
554
  events.emit('dlq_entry_created', {
735
555
  dlq_id: dlqId,
736
556
  task_id: taskRecord.id,
737
557
  agent: taskRecord.agent,
738
- failure_type: failureType,
558
+ attempts: taskRecord.retries + 1,
739
559
  }, { convoy_id: convoyId, task_id: taskRecord.id });
740
560
  }
741
561
  }
742
562
  if (exhausted === 'stop') {
743
- // Skip all remaining pending tasks + set convoy to failed
744
- const allPending = store.getTasksByConvoy(convoyId).filter(t => t.status === 'pending');
745
- for (const t of allPending) {
746
- skipTask(t.id, `on_exhausted: stop — task "${taskRecord.id}" exhausted retries`);
747
- }
748
- store.updateConvoyStatus(convoyId, 'failed');
749
- events.emit('convoy_failed', { status: 'failed', reason: `on_exhausted: stop — task "${taskRecord.id}" exhausted retries` }, { convoy_id: convoyId });
563
+ stopDispatching(`on_exhausted: stop — task "${taskRecord.id}" exhausted retries`);
750
564
  }
751
- else if (exhausted === 'dlq' || exhausted === 'skip') {
752
- // Default behavior: cascade failure to dependents only
753
- cascadeFailure(taskRecord.id);
754
- }
755
- // ── Circuit breaker: record exhaustion failure ──────────────────────────
565
+ cascadeFailure(taskRecord.id);
756
566
  if (circuitBreakerConfig) {
757
567
  const { tripped } = circuitBreaker.recordFailure(taskRecord.agent);
758
568
  try {
@@ -762,35 +572,28 @@ async function runConvoy(convoyId, spec, adapter, store, events, wtManager, merg
762
572
  if (tripped) {
763
573
  events.emit('circuit_breaker_tripped', {
764
574
  agent: taskRecord.agent,
765
- state: circuitBreaker.getState(taskRecord.agent),
575
+ failure_count: circuitBreaker.getState(taskRecord.agent).failures,
766
576
  }, { convoy_id: convoyId, task_id: taskRecord.id });
767
577
  }
768
578
  }
769
579
  }
770
- // ── Hook execution ────────────────────────────────────────────────────────
580
+ // ── Hooks ──────────────────────────────────────────────────────────────────
771
581
  async function runHooks(hooks, lifecycle, context) {
772
582
  const filtered = hooks.filter(h => (h.on ?? 'post_task') === lifecycle);
773
583
  for (const hook of filtered) {
774
584
  if (hook.type === 'command' || hook.type === 'guard' || hook.type === 'validate') {
775
- const cmd = hook.command;
776
- if (!cmd)
585
+ if (!hook.command)
777
586
  continue;
778
- try {
779
- // SECURITY: Gate/hook commands come from the .convoy.yml spec file, which is operator-controlled.
780
- // They are NOT user-supplied and are part of the trusted build configuration.
781
- await execFile('sh', ['-c', cmd], { cwd: context.cwd });
782
- }
783
- catch (err) {
784
- const execErr = err;
785
- const errorMsg = execErr.stderr || execErr.stdout || execErr.message || '';
786
- return { passed: false, failedHook: hook, error: errorMsg };
587
+ const r = await runShell(hook.command, { cwd: context.cwd, timeoutMs: 600_000, signal: ctl.signal });
588
+ if (r.code !== 0) {
589
+ return { passed: false, failedHook: hook, error: (r.stderr || r.stdout).trim() || `exit ${r.code}` };
787
590
  }
788
591
  }
789
592
  else if (hook.type === 'agent') {
790
593
  if (!hook.prompt)
791
594
  continue;
792
595
  const hookTask = {
793
- id: `hook-${lifecycle}-${context.taskId ?? 'convoy'}-${Date.now()}`,
596
+ id: `hook-${lifecycle}-${context.taskId ?? 'convoy'}`,
794
597
  prompt: hook.prompt,
795
598
  agent: hook.name ?? 'developer',
796
599
  timeout: '10m',
@@ -799,1781 +602,1330 @@ async function runConvoy(convoyId, spec, adapter, store, events, wtManager, merg
799
602
  description: `Hook: ${hook.name ?? hook.type}`,
800
603
  max_retries: 0,
801
604
  };
802
- try {
803
- const hookResult = await adapter.execute(hookTask, { verbose, cwd: context.cwd, permissionMode: spec.defaults?.permission_mode });
804
- if (!hookResult.success) {
805
- return { passed: false, failedHook: hook, error: hookResult.output };
806
- }
807
- }
808
- catch (err) {
809
- return { passed: false, failedHook: hook, error: err.message };
605
+ const hookResult = await runAgent(context.taskId ?? convoyId, context.taskAdapter ?? adapter, hookTask, {
606
+ cwd: context.cwd,
607
+ permissionMode,
608
+ }, 600_000);
609
+ if (!hookResult.success) {
610
+ return { passed: false, failedHook: hook, error: hookResult.output };
810
611
  }
811
612
  }
812
613
  else if (hook.type === 'review') {
813
- if (!context.taskId || !reviewRunner)
614
+ if (!context.taskId)
814
615
  continue;
815
- const reviewTaskRecord = store.getTask(context.taskId, context.convoyId);
816
- if (reviewTaskRecord) {
817
- const reviewResult = await reviewRunner(reviewTaskRecord, 'fast', spec.defaults?.reviewer_model ?? 'default');
818
- if (reviewResult.verdict !== 'pass') {
819
- return { passed: false, failedHook: hook, error: reviewResult.feedback };
616
+ const rec = store.getTask(context.taskId, convoyId);
617
+ if (rec) {
618
+ const r = await reviewRunner(rec, 'fast', spec.defaults?.reviewer_model ?? 'default');
619
+ if (r.verdict === 'block') {
620
+ return { passed: false, failedHook: hook, error: r.feedback };
820
621
  }
821
622
  }
822
623
  }
823
624
  }
824
625
  return { passed: true };
825
626
  }
826
- // ── Single-task executor ──────────────────────────────────────────────────
827
- async function executeOneTask(taskRecord) {
828
- const workerId = `worker-${taskRecord.id}-${Date.now()}`;
627
+ // ── Multi-step tasks ───────────────────────────────────────────────────────
628
+ async function executeSteps(rec, steps, taskAdapter, worktreePath, deadline, baseOptions,
629
+ /** Wraps a step's text in the shared context and the task's role and files. */
630
+ wrap) {
829
631
  const now = () => new Date().toISOString();
830
- // Resolve per-task adapter (fallback to convoy-level adapter)
831
- let taskAdapter = adapter;
832
- if (taskRecord.adapter && taskRecord.adapter !== adapter.name) {
833
- if (taskRecord.adapter === 'auto') {
834
- const detected = await detectAdapter();
835
- if (detected) {
836
- taskAdapter = await getAdapter(detected);
837
- }
632
+ const stepResults = new Map();
633
+ let combinedOutput = '';
634
+ let lastExitCode = 0;
635
+ for (let i = 0; i < steps.length; i++) {
636
+ const step = steps[i];
637
+ if (step.if && !evaluateStepCondition(step.if, stepResults, worktreePath)) {
638
+ store.insertTaskStep({
639
+ task_id: rec.id,
640
+ step_index: i,
641
+ prompt: step.prompt,
642
+ gates: step.gates ? JSON.stringify(step.gates) : null,
643
+ status: 'skipped',
644
+ exit_code: null,
645
+ output: 'Skipped: condition not met',
646
+ started_at: now(),
647
+ finished_at: now(),
648
+ });
649
+ if (step.id)
650
+ stepResults.set(step.id, { exitCode: 0 });
651
+ combinedOutput += `\n[Step ${i + 1} skipped: condition not met]`;
652
+ continue;
838
653
  }
839
- else {
840
- taskAdapter = await getAdapter(taskRecord.adapter);
841
- }
842
- }
843
- taskAdapterMap.set(taskRecord.id, taskAdapter);
844
- // ── Check inputs availability ────────────────────────────────────────────
845
- if (taskRecord.inputs) {
846
- const inputs = JSON.parse(taskRecord.inputs);
847
- for (const input of inputs) {
848
- const artifact = store.getArtifact(convoyId, input.name);
849
- if (!artifact) {
850
- store.updateTaskStatus(taskRecord.id, convoyId, 'wait-for-input');
851
- events.emit('task_waiting_input', {
852
- task_id: taskRecord.id,
853
- missing_artifact: input.name,
854
- from_task: input.from,
855
- }, { convoy_id: convoyId, task_id: taskRecord.id });
856
- taskAdapterMap.delete(taskRecord.id);
857
- return;
654
+ const stepDbId = store.insertTaskStep({
655
+ task_id: rec.id,
656
+ step_index: i,
657
+ prompt: step.prompt,
658
+ gates: step.gates ? JSON.stringify(step.gates) : null,
659
+ status: 'running',
660
+ exit_code: null,
661
+ output: null,
662
+ started_at: now(),
663
+ finished_at: null,
664
+ });
665
+ const stepMaxRetries = step.max_retries ?? rec.max_retries;
666
+ let stepResult = { success: false, output: '', exitCode: -1 };
667
+ let stepAttempt = 0;
668
+ while (stepAttempt <= stepMaxRetries) {
669
+ let stepPrompt = step.prompt;
670
+ if (stepAttempt > 0) {
671
+ stepPrompt = `Previous attempt failed.\nExit code: ${stepResult.exitCode}\nError output:\n${stepResult.output || '(no output)'}\n\nFix the issues and try again.\n\n` + step.prompt;
672
+ }
673
+ stepPrompt = wrap(stepPrompt);
674
+ // Each step is its own Task object; it is what the adapter attaches
675
+ // the process to, so it is what a kill has to name.
676
+ const remaining = deadline - Date.now();
677
+ const stepTask = {
678
+ id: rec.id,
679
+ prompt: stepPrompt,
680
+ agent: rec.agent,
681
+ timeout: msToTimeout(Math.max(1000, remaining)),
682
+ depends_on: [],
683
+ files: parseJsonList(rec.files),
684
+ description: `step ${i + 1}`,
685
+ max_retries: stepMaxRetries,
686
+ };
687
+ stepResult = await runAgent(rec.id, taskAdapter, stepTask, baseOptions, remaining);
688
+ addTaskUsage(rec.id, usageOf(stepResult, stepPrompt, rec.model));
689
+ // A step that timed out or was killed is not retried: the task's time
690
+ // is spent, or someone asked it to stop.
691
+ if (stepResult.success || stepResult._timedOut || ctl.interrupted || Date.now() >= deadline)
692
+ break;
693
+ stepAttempt++;
694
+ if (stepAttempt <= stepMaxRetries) {
695
+ progress.line(` ${c.yellow('↺')} ${c.bold(`[${rec.id}]`)} step ${i + 1}/${steps.length} failed, retry ${stepAttempt}/${stepMaxRetries}`);
696
+ }
697
+ }
698
+ lastExitCode = stepResult.exitCode;
699
+ combinedOutput += `\n[Step ${i + 1}]\n${stepResult.output}`;
700
+ if (step.id)
701
+ stepResults.set(step.id, { exitCode: stepResult.exitCode });
702
+ if (step.gates && step.gates.length > 0 && stepResult.success) {
703
+ for (const command of step.gates) {
704
+ const r = await runShell(command, { cwd: worktreePath, timeoutMs: Math.max(1000, deadline - Date.now()), signal: ctl.signal });
705
+ if (r.code !== 0) {
706
+ const output = (r.stderr || r.stdout).trim();
707
+ stepResult = { success: false, output: `Gate failed: ${command}\nExit code: ${r.code}\n${output}`, exitCode: r.code };
708
+ lastExitCode = r.code;
709
+ combinedOutput += `\n[Step ${i + 1} gate failed: ${command}]`;
710
+ break;
711
+ }
858
712
  }
859
713
  }
860
- }
861
- // ── Circuit breaker check ──────────────────────────────────────────────
862
- if (circuitBreakerConfig) {
863
- if (!circuitBreaker.canAssign(taskRecord.agent)) {
864
- const fallback = circuitBreaker.fallback;
865
- if (fallback) {
866
- events.emit('circuit_breaker_fallback', {
867
- original_agent: taskRecord.agent,
868
- fallback_agent: fallback,
869
- state: circuitBreaker.getState(taskRecord.agent),
870
- }, { convoy_id: convoyId, task_id: taskRecord.id });
871
- }
872
- else {
873
- events.emit('circuit_breaker_blocked', {
874
- agent: taskRecord.agent,
875
- state: circuitBreaker.getState(taskRecord.agent),
876
- }, { convoy_id: convoyId, task_id: taskRecord.id });
877
- }
878
- store.updateTaskStatus(taskRecord.id, convoyId, 'skipped', {
879
- output: `Circuit breaker open for agent "${taskRecord.agent}". ${fallback ? `No fallback available.` : `No fallback configured.`}`,
880
- });
881
- completedCount++;
882
- taskAdapterMap.delete(taskRecord.id);
883
- cascadeFailure(taskRecord.id);
884
- return;
714
+ store.updateTaskStep(stepDbId, {
715
+ status: stepResult.success ? 'done' : 'failed',
716
+ exit_code: stepResult.exitCode,
717
+ output: redactSecrets(stepResult.output).text,
718
+ finished_at: now(),
719
+ });
720
+ if (!stepResult.success) {
721
+ return { ...stepResult, output: combinedOutput.trim() };
885
722
  }
886
723
  }
887
- // Create worktree (skip for copilot adapter)
724
+ return { success: true, output: combinedOutput.trim(), exitCode: lastExitCode };
725
+ }
726
+ // ── One task, start to merge ───────────────────────────────────────────────
727
+ const statusLabel = {
728
+ 'failed': 'failed',
729
+ 'timed-out': 'timed out',
730
+ 'gate-failed': 'gate failed',
731
+ 'review-blocked': 'review blocked',
732
+ 'hook-failed': 'hook failed',
733
+ };
734
+ async function runTask(initial) {
735
+ // Re-read: the snapshot this was picked from can be stale by now.
736
+ const rec = store.getTask(initial.id, convoyId);
737
+ if (!rec || rec.status !== 'pending' || ctl.stopDispatch)
738
+ return;
739
+ const now = () => new Date().toISOString();
740
+ const taskStart = Date.now();
741
+ const specTask = specTasks.get(rec.id);
742
+ const files = parseJsonList(rec.files);
743
+ const attempt = rec.retries + 1;
744
+ const elapsed = () => `(${formatDuration(Date.now() - taskStart)})`;
745
+ let workerId = null;
888
746
  let worktreePath = null;
889
- if (taskAdapter.name !== 'copilot') {
747
+ const cleanup = async (keepBranch = false) => {
748
+ if (!worktreePath)
749
+ return;
890
750
  try {
891
- worktreePath = await wtManager.create(workerId, baseBranch);
751
+ await wtManager.remove(worktreePath, keepBranch ? { keepBranch: true } : undefined);
892
752
  }
893
- catch (err) {
894
- if (verbose) {
895
- process.stderr.write(`Warning: failed to create worktree for ${taskRecord.id}: ${err.message}\n`);
896
- }
753
+ catch { /* best effort */ }
754
+ worktreePath = null;
755
+ };
756
+ const telemetry = (outcome, retries, filesChanged = 0) => {
757
+ const row = store.getTask(rec.id, convoyId);
758
+ const model = row?.model ?? null;
759
+ events.emit('session', {
760
+ agent: rec.agent,
761
+ model,
762
+ task: rec.id,
763
+ outcome,
764
+ duration_min: Math.round((Date.now() - taskStart) / 60_000),
765
+ files_changed: filesChanged,
766
+ retries,
767
+ convoy_id: convoyId,
768
+ }, { convoy_id: convoyId, task_id: rec.id });
769
+ events.emit('delegation', {
770
+ session_id: convoyId,
771
+ agent: rec.agent,
772
+ model,
773
+ tier: tierForAgent(rec.agent),
774
+ mechanism: 'convoy',
775
+ outcome,
776
+ retries,
777
+ phase: rec.phase,
778
+ convoy_id: convoyId,
779
+ }, { convoy_id: convoyId, task_id: rec.id });
780
+ };
781
+ /** Put an interrupted task back in the queue, as if it had not started. */
782
+ const requeue = async () => {
783
+ await cleanup();
784
+ store.updateTaskStatus(rec.id, convoyId, 'pending', { worker_id: null, worktree: null, started_at: null });
785
+ if (workerId)
786
+ store.updateWorkerStatus(workerId, 'killed', { finished_at: now() });
787
+ };
788
+ /** Record a task as failed for good, and everything that follows from it. */
789
+ const fail = async (status, reason, opts = {}) => {
790
+ await cleanup(Boolean(opts.keepBranch));
791
+ const fresh = store.getTask(rec.id, convoyId) ?? rec;
792
+ store.withTransaction(() => {
793
+ store.updateTaskStatus(rec.id, convoyId, status, {
794
+ finished_at: now(),
795
+ output: redactSecrets(opts.output ?? reason).text,
796
+ exit_code: opts.exitCode ?? 1,
797
+ ...(opts.keepBranch ? { branch: opts.keepBranch } : {}),
798
+ });
799
+ if (workerId)
800
+ store.updateWorkerStatus(workerId, 'failed', { finished_at: now() });
801
+ });
802
+ const label = statusLabel[status] ?? status;
803
+ progress.line(` ${c.red('✗')} ${c.bold(`[${rec.id}]`)} ${label} ${elapsed()}: ${firstLine(redactSecrets(reason).text)}`);
804
+ events.emit('task_failed', {
805
+ reason: opts.kind ?? status,
806
+ message: firstLine(reason, 400),
807
+ ...(opts.gate ? { gate: opts.gate } : {}),
808
+ ...(opts.hook ? { hook: opts.hook } : {}),
809
+ ...(opts.exitCode !== undefined ? { exit_code: opts.exitCode } : {}),
810
+ ...(workerId ? { worker_id: workerId } : {}),
811
+ }, { convoy_id: convoyId, task_id: rec.id, ...(workerId ? { worker_id: workerId } : {}) });
812
+ telemetry('failed', fresh.retries);
813
+ handleExhaustion(fresh, opts.failureType ?? opts.kind ?? status, opts.output ?? reason);
814
+ if (spec.on_failure === 'stop')
815
+ stopDispatching(`on_failure: stop — task "${rec.id}" failed`);
816
+ };
817
+ /**
818
+ * Retry when the task has retries left, whatever `on_failure` says — that
819
+ * setting is about what happens *after* a task has failed for good. They
820
+ * were tangled: every retry site checked `on_failure !== 'stop'`, and the
821
+ * spec builder's default `stop` turned off every retry in every plan.
822
+ */
823
+ const retryOrFail = async (status, reason, opts = {}) => {
824
+ if (ctl.interrupted)
825
+ return requeue();
826
+ const fresh = store.getTask(rec.id, convoyId) ?? rec;
827
+ if (!opts.noRetry && fresh.retries < fresh.max_retries) {
828
+ await cleanup();
829
+ store.updateTaskStatus(rec.id, convoyId, 'pending', {
830
+ retries: fresh.retries + 1,
831
+ worker_id: null,
832
+ worktree: null,
833
+ started_at: null,
834
+ finished_at: null,
835
+ retry_note: redactSecrets(opts.note ?? reason).text,
836
+ });
837
+ if (workerId)
838
+ store.updateWorkerStatus(workerId, 'failed', { finished_at: now() });
839
+ const label = statusLabel[status] ?? status;
840
+ progress.line(` ${c.yellow('⟳')} ${c.bold(`[${rec.id}]`)} ${label}, retry ${fresh.retries + 1}/${fresh.max_retries}: ${firstLine(redactSecrets(reason).text)}`);
841
+ events.emit('task_retried', {
842
+ previous_status: status,
843
+ reason: firstLine(reason, 400),
844
+ attempt: fresh.retries + 2,
845
+ }, { convoy_id: convoyId, task_id: rec.id });
846
+ return;
847
+ }
848
+ return fail(status, reason, opts);
849
+ };
850
+ // ── Runtime ─────────────────────────────────────────────────────────────
851
+ let taskAdapter;
852
+ try {
853
+ taskAdapter = await adapterFor(rec.adapter);
854
+ }
855
+ catch (err) {
856
+ return fail('failed', `No usable runtime "${rec.adapter}": ${err.message}`, { kind: 'adapter' });
857
+ }
858
+ // ── Circuit breaker ─────────────────────────────────────────────────────
859
+ if (circuitBreakerConfig && !circuitBreaker.canAssign(rec.agent)) {
860
+ const fallback = circuitBreaker.fallback;
861
+ // The fallback agent takes the task. It used to be announced and then
862
+ // skipped all the same, so a configured fallback never ran anything.
863
+ if (fallback && fallback !== rec.agent && circuitBreaker.canAssign(fallback)) {
864
+ events.emit('circuit_breaker_fallback', {
865
+ original_agent: rec.agent,
866
+ fallback_agent: fallback,
867
+ task_id: rec.id,
868
+ }, { convoy_id: convoyId, task_id: rec.id });
869
+ progress.line(` ${c.yellow('⟳')} ${c.bold(`[${rec.id}]`)} ${rec.agent} keeps failing; running it as ${fallback}`);
870
+ rec.agent = fallback;
871
+ }
872
+ }
873
+ if (circuitBreakerConfig && !circuitBreaker.canAssign(rec.agent)) {
874
+ events.emit('circuit_breaker_blocked', { agent: rec.agent, task_id: rec.id }, { convoy_id: convoyId, task_id: rec.id });
875
+ const reason = `Circuit breaker open for agent "${rec.agent}"`;
876
+ store.updateTaskStatus(rec.id, convoyId, 'skipped', { output: reason });
877
+ progress.line(` ${c.dim('⊘')} ${c.bold(`[${rec.id}]`)} skipped: ${reason}`);
878
+ events.emit('task_skipped', { reason }, { convoy_id: convoyId, task_id: rec.id });
879
+ cascadeFailure(rec.id);
880
+ return;
881
+ }
882
+ // ── Inputs ──────────────────────────────────────────────────────────────
883
+ const inputs = rec.inputs ? JSON.parse(rec.inputs) : [];
884
+ for (const input of inputs) {
885
+ if (!store.getArtifact(convoyId, input.name)) {
886
+ return fail('failed', `Input "${input.name}" from task "${input.from}" was never produced`, { kind: 'missing-input' });
897
887
  }
898
888
  }
889
+ // ── Worktree ────────────────────────────────────────────────────────────
890
+ workerId = `${short}-${slugify(rec.id, 24) || 'task'}-${(workerSeq++).toString(36).slice(-5)}`;
891
+ store.updateTaskStatus(rec.id, convoyId, 'assigned', { worker_id: workerId });
892
+ try {
893
+ worktreePath = await wtManager.create(workerId, branch);
894
+ }
895
+ catch (err) {
896
+ return retryOrFail('failed', `Could not create a worktree: ${firstLine(err.stderr) || err.message}`, { kind: 'worktree' });
897
+ }
898
+ const wt = worktreePath;
899
+ const startSha = wtManager.head ? await wtManager.head(wt) : null;
899
900
  store.insertWorker({
900
901
  id: workerId,
901
- task_id: taskRecord.id,
902
+ task_id: rec.id,
902
903
  adapter: taskAdapter.name,
903
904
  pid: null,
904
905
  session_id: null,
905
- status: 'spawned',
906
- worktree: worktreePath,
906
+ status: 'running',
907
+ worktree: wt,
907
908
  created_at: now(),
908
909
  });
909
- // Mark assigned then running
910
- store.updateTaskStatus(taskRecord.id, convoyId, 'assigned', {
910
+ store.updateTaskStatus(rec.id, convoyId, 'running', { started_at: now(), worktree: wt, worker_id: workerId });
911
+ const runtime = taskAdapter.name !== adapter.name ? ` ${c.dim(`(${taskAdapter.name})`)}` : '';
912
+ const attemptNote = attempt > 1 ? c.dim(` attempt ${attempt}/${rec.max_retries + 1}`) : '';
913
+ progress.line(` ${c.cyan('▶')} ${c.bold(`[${rec.id}]`)} ${rec.agent}${runtime}${attemptNote}`);
914
+ events.emit('task_started', {
911
915
  worker_id: workerId,
912
- worktree: worktreePath,
916
+ mechanism: 'worktree',
917
+ adapter: taskAdapter.name,
918
+ attempt,
919
+ }, { convoy_id: convoyId, task_id: rec.id, worker_id: workerId });
920
+ // ── Prompt ──────────────────────────────────────────────────────────────
921
+ let instructions = rec.prompt;
922
+ for (const input of inputs) {
923
+ const artifact = store.getArtifact(convoyId, input.name);
924
+ instructions = instructions.replaceAll(`{{input.${input.as ?? input.name}}}`, artifact.content);
925
+ }
926
+ instructions = instructions.replace(/\{\{scratchpad\.([a-zA-Z0-9_.-]+)\}\}/g, (whole, key) => {
927
+ const value = store.getScratchpadValue(key);
928
+ return value ?? whole;
913
929
  });
914
- store.updateTaskStatus(taskRecord.id, convoyId, 'running', { started_at: now() });
915
- store.updateWorkerStatus(workerId, 'running');
916
- const task = taskRecordToTask(taskRecord);
917
- activeTaskMap.set(taskRecord.id, task);
918
- // ── Inject inputs into prompt ────────────────────────────────────────────
919
- if (taskRecord.inputs) {
920
- const inputs = JSON.parse(taskRecord.inputs);
921
- for (const input of inputs) {
922
- const artifact = store.getArtifact(convoyId, input.name);
923
- const templateVar = input.as ?? input.name;
924
- task.prompt = task.prompt.replaceAll(`{{input.${templateVar}}}`, artifact.content);
925
- }
926
- }
927
- // ── Scratchpad template substitution (Phase 17.1) ───────────────────────
928
- const scratchpadRe = /\{\{scratchpad\.([a-zA-Z0-9_.-]+)\}\}/g;
929
- let scratchpadMatch;
930
- while ((scratchpadMatch = scratchpadRe.exec(task.prompt)) !== null) {
931
- const spKey = scratchpadMatch[1];
932
- const spVal = store.getScratchpadValue(spKey);
933
- if (spVal !== null) {
934
- task.prompt = task.prompt.replaceAll(`{{scratchpad.${spKey}}}`, spVal);
935
- scratchpadRe.lastIndex = 0; // reset after replaceAll
936
- }
937
- }
938
- process.stdout.write(` ${c.cyan('▶')} ${c.bold(`[${taskRecord.id}]`)} ${taskRecord.agent}${worktreePath ? c.dim(' (worktree)') : ''}\n`);
939
- events.emit('task_started', { worker_id: workerId, mechanism: worktreePath ? 'background' : 'sub-agent' }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
940
- const taskStartTime = Date.now();
941
- // ── Outbound prompt scan — NEVER send a prompt containing secrets ─────────
942
- const promptScan = scanForSecrets(taskRecord.prompt, `task:${taskRecord.id}`);
930
+ let previousWork = [];
931
+ if (specTask?.persistent) {
932
+ try {
933
+ previousWork = store.getAgentIdentities(rec.agent, 3).map(i => i.summary);
934
+ }
935
+ catch { /* non-critical */ }
936
+ }
937
+ const dependencyResults = resolveDependencyResults(store, convoyId, parseJsonList(rec.depends_on), repoRoot);
938
+ const promptFor = (text, retryNote) => composePrompt(sharedContext, buildTaskSection({
939
+ id: rec.id,
940
+ agent: rec.agent,
941
+ files,
942
+ prompt: text,
943
+ dependencyResults,
944
+ previousWork,
945
+ retryNote,
946
+ contract: buildContractInstruction(rec.agent),
947
+ }));
948
+ const promptText = promptFor(instructions, rec.retry_note);
949
+ const promptScan = scanForSecrets(promptText, `task:${rec.id}`);
943
950
  if (!promptScan.clean) {
944
- store.updateTaskStatus(taskRecord.id, convoyId, 'failed', {
945
- finished_at: now(),
946
- output: `Secret detected in prompt — task blocked before execution.\nFindings:\n${promptScan.findings
947
- .map((f) => ` ${f.pattern} at line ${f.line}: ${f.snippet}`)
948
- .join('\n')}`,
949
- });
950
- store.updateWorkerStatus(workerId, 'failed', { finished_at: now() });
951
- completedCount++;
952
951
  events.emit('secret_leak_prevented', {
953
- task_id: taskRecord.id,
952
+ task_id: rec.id,
954
953
  findings_count: promptScan.findings.length,
955
- patterns: promptScan.findings.map((f) => f.pattern),
956
- }, { convoy_id: convoyId, task_id: taskRecord.id });
957
- cascadeFailure(taskRecord.id);
958
- taskAdapterMap.delete(taskRecord.id);
959
- return;
954
+ patterns: promptScan.findings.map(f => f.pattern),
955
+ context: 'prompt',
956
+ }, { convoy_id: convoyId, task_id: rec.id });
957
+ return fail('failed', `Secret detected in the prompt (${promptScan.findings.map(f => f.pattern).join(', ')}) — the task was not sent to the agent`, { kind: 'secret-in-prompt' });
960
958
  }
961
- const timeout = makeTimeoutPromise(taskRecord.timeout_ms);
962
- let result;
963
- // Retrieve steps from spec if defined
964
- const specTask = (spec.tasks ?? []).find(t => t.id === taskRecord.id);
965
- const steps = specTask?.steps;
966
959
  const taskHooks = specTask?.hooks ?? [];
967
- // ── Context isolation preamble (Phase 41) ────────────────────────────
968
- try {
969
- const taskFiles = taskRecord.files ? JSON.parse(taskRecord.files) : [];
970
- const depIds = taskRecord.depends_on ? JSON.parse(taskRecord.depends_on) : [];
971
- const depResults = resolveDependencyResults(store, convoyId, depIds);
972
- const preamble = buildIsolationPreamble({ id: taskRecord.id, description: taskRecord.prompt.slice(0, 200), prompt: taskRecord.prompt, files: taskFiles, agent: taskRecord.agent }, depResults);
973
- task.prompt = preamble + '\n\n' + task.prompt;
974
- }
975
- catch { /* non-critical — isolation preamble is best-effort */ }
976
- // ── Artifact output instructions (Phase 43) ────────────────────────────
977
- try {
978
- const artifactDir = getArtifactDir(convoyId, taskRecord.id, basePath);
979
- const artifactInstructions = [
980
- '',
981
- '## Artifact Output (for large results)',
982
- 'If your output includes large content (>100 lines of code, full reports, data dumps),',
983
- 'write it to an artifact file instead of including it inline:',
984
- '',
985
- '1. Write the content to: ' + artifactDir + '{filename}',
986
- '2. In your response, reference it: `[ARTIFACT: {filename}] {1-line summary}`',
987
- '3. Keep your inline response focused on the summary and key decisions.',
988
- '',
989
- 'Small outputs (< 100 lines) can remain inline.',
990
- ].join('\n');
991
- task.prompt = task.prompt + '\n' + artifactInstructions;
960
+ if (taskHooks.length > 0) {
961
+ const pre = await runHooks(taskHooks, 'pre_task', { taskId: rec.id, cwd: wt, taskAdapter });
962
+ if (!pre.passed) {
963
+ const label = pre.failedHook?.name ?? pre.failedHook?.type ?? 'unknown';
964
+ return fail('hook-failed', `pre_task hook "${label}" failed: ${pre.error ?? ''}`, { kind: 'hook-failed', hook: label });
965
+ }
992
966
  }
993
- catch { /* non-critical */ }
994
- // ── Intelligence: inject persistent agent identity (Phase 17.2) ────────
995
- const specTaskForPersistent = (spec.tasks ?? []).find(t => t.id === taskRecord.id);
996
- if (specTaskForPersistent?.persistent) {
967
+ if (files.length > 0) {
997
968
  try {
998
- const identities = store.getAgentIdentities(taskRecord.agent, 3);
999
- if (identities.length > 0) {
1000
- const contextBlock = '\n\n[Previous work context]\n'
1001
- + identities.map(id => id.summary).join('\n\n')
1002
- + '\n[End previous context]\n\n';
1003
- task.prompt = contextBlock + task.prompt;
1004
- }
969
+ scanSymlinks(files, wt);
1005
970
  }
1006
- catch { /* non-critical */ }
971
+ catch (err) {
972
+ return fail('failed', `Symlink security check failed: ${err.message}`, { kind: 'symlink-escape' });
973
+ }
974
+ }
975
+ // ── The agent ───────────────────────────────────────────────────────────
976
+ const deadline = taskStart + rec.timeout_ms;
977
+ // The spec's model when it names one; otherwise the runtime's model for the
978
+ // agent's tier, so a writer does not run on the model an architect needs.
979
+ const model = rec.model ?? taskAdapter.tierModels?.[tierForAgent(rec.agent)];
980
+ const execOptions = {
981
+ cwd: wt,
982
+ permissionMode,
983
+ ...(model ? { model } : {}),
984
+ };
985
+ const steps = specTask?.steps;
986
+ let result;
987
+ if (steps && steps.length > 0) {
988
+ // Each step is sent as the task's own text would be: shared context
989
+ // first, then the role, the files, and the step.
990
+ result = await executeSteps(rec, steps, taskAdapter, wt, deadline, execOptions, (text) => promptFor(text, rec.retry_note));
1007
991
  }
1008
- // ── Output contract injection ─────────────────────────────────────────
1009
- const contractInstruction = buildContractInstruction(taskRecord.agent);
1010
- if (contractInstruction) {
1011
- task.prompt = task.prompt + '\n\n' + contractInstruction;
992
+ else {
993
+ const task = taskRecordToTask(rec);
994
+ task.prompt = promptText;
995
+ result = await runAgent(rec.id, taskAdapter, task, execOptions, deadline - Date.now());
996
+ addTaskUsage(rec.id, usageOf(result, promptText, rec.model));
1012
997
  }
1013
- // ── pre_task hooks ────────────────────────────────────────────────────────
1014
- if (taskHooks.length > 0) {
1015
- const preResult = await runHooks(taskHooks, 'pre_task', {
1016
- taskId: taskRecord.id,
1017
- convoyId,
1018
- cwd: worktreePath ?? basePath,
998
+ if (ctl.interrupted)
999
+ return requeue();
1000
+ if (result._timedOut) {
1001
+ return retryOrFail('timed-out', `Timed out after ${formatDuration(rec.timeout_ms)}`, {
1002
+ kind: 'timeout',
1003
+ output: result.output,
1004
+ note: `Your previous attempt ran out of time after ${formatDuration(rec.timeout_ms)}. Work in smaller steps and finish within the limit.`,
1005
+ });
1006
+ }
1007
+ if (!result.success) {
1008
+ const out = result.output || '(no output)';
1009
+ return retryOrFail('failed', firstLine(out) || `exit code ${result.exitCode}`, {
1010
+ kind: 'error',
1011
+ output: out,
1012
+ exitCode: result.exitCode,
1013
+ note: `Your previous attempt failed (exit code ${result.exitCode}). Its last output:\n${out.slice(-3000)}`,
1019
1014
  });
1020
- if (!preResult.passed) {
1021
- await removeWorktree();
1022
- const hookLabel = preResult.failedHook?.name ?? preResult.failedHook?.type ?? 'unknown';
1023
- store.withTransaction(() => {
1024
- store.updateTaskStatus(taskRecord.id, convoyId, 'hook-failed', {
1025
- finished_at: now(),
1026
- output: `pre_task hook "${hookLabel}" failed: ${preResult.error ?? ''}`,
1027
- exit_code: 1,
1028
- });
1029
- store.updateWorkerStatus(workerId, 'failed', { finished_at: now() });
1030
- });
1031
- completedCount++;
1032
- process.stdout.write(` ${c.red('✗')} ${c.bold(`[${taskRecord.id}]`)} pre_task hook failed ${c.dim(`[${completedCount}/${totalTasks}]`)}\n`);
1033
- events.emit('task_failed', { reason: 'hook-failed', hook: hookLabel, worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
1034
- cascadeFailure(taskRecord.id);
1035
- taskAdapterMap.delete(taskRecord.id);
1036
- return;
1037
- }
1038
1015
  }
1039
- // ── Symlink security scan (pre-execution) ────────────────────────────────
1040
- const taskFiles = taskRecord.files ? JSON.parse(taskRecord.files) : [];
1041
- if (taskFiles.length > 0 && worktreePath) {
1016
+ // ── Commit, so every check below sees the change ──────────────────────
1017
+ //
1018
+ // Gates and review sizing diffed `base..HEAD` before anything was
1019
+ // committed, so unless the agent committed itself they saw an empty change:
1020
+ // secret_scan scanned nothing and every review was sized as tiny.
1021
+ const summary = summarizeTask({ id: rec.id, description: specTask?.description, prompt: rec.prompt });
1022
+ if (wtManager.commitAll) {
1042
1023
  try {
1043
- scanSymlinks(taskFiles, worktreePath);
1024
+ await wtManager.commitAll(wt, `convoy(${rec.id}): ${summary}`.slice(0, 200));
1044
1025
  }
1045
1026
  catch (err) {
1046
- await removeWorktree();
1047
- store.withTransaction(() => {
1048
- store.updateTaskStatus(taskRecord.id, convoyId, 'failed', {
1049
- finished_at: now(),
1050
- output: `Symlink security check failed: ${err.message}`,
1051
- exit_code: 1,
1052
- });
1053
- store.updateWorkerStatus(workerId, 'failed', { finished_at: now() });
1027
+ return retryOrFail('failed', `Could not commit the task's work: ${firstLine(err.stderr) || err.message}`, { kind: 'commit' });
1028
+ }
1029
+ }
1030
+ const changes = startSha && wtManager.changes ? await wtManager.changes(wt, startSha) : null;
1031
+ const changedFiles = changes?.files ?? [];
1032
+ const diff = changes?.diff ?? '';
1033
+ // ── Per-task gates from the spec ────────────────────────────────────────
1034
+ const taskGates = parseJsonList(rec.gates);
1035
+ for (const command of taskGates) {
1036
+ const r = await runShell(command, { cwd: wt, timeoutMs: (spec.defaults?.gate_timeout ?? 300) * 1000, signal: ctl.signal });
1037
+ // A gate the interrupt killed did not fail; nothing is recorded for it.
1038
+ if (ctl.interrupted)
1039
+ return requeue();
1040
+ events.emit('gate_result', { command, passed: r.code === 0, exit_code: r.code, scope: 'task' }, { convoy_id: convoyId, task_id: rec.id });
1041
+ if (r.code !== 0) {
1042
+ const output = [r.stderr, r.stdout].filter(Boolean).join('\n').trim() || '(no output)';
1043
+ return retryOrFail('gate-failed', `Gate "${command}" failed (exit ${r.code})`, {
1044
+ kind: 'gate-failed',
1045
+ gate: command,
1046
+ exitCode: r.code,
1047
+ output: `Gate failed: ${command}\nExit code: ${r.code}\n${output}`,
1048
+ note: `The gate \`${command}\` failed on your previous attempt (exit ${r.code}):\n${output.slice(-3000)}\n\nMake it pass.`,
1054
1049
  });
1055
- completedCount++;
1056
- events.emit('task_failed', { reason: 'symlink-escape', worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
1057
- cascadeFailure(taskRecord.id);
1058
- taskAdapterMap.delete(taskRecord.id);
1059
- return;
1060
1050
  }
1061
1051
  }
1062
- try {
1063
- if (steps && steps.length > 0) {
1064
- result = await Promise.race([
1065
- executeSteps(taskRecord, steps, taskAdapter, worktreePath, basePath, store, convoyId, verbose, spec.defaults?.permission_mode),
1066
- timeout.promise,
1067
- ]);
1068
- }
1069
- else {
1070
- result = await Promise.race([
1071
- taskAdapter.execute(task, { verbose, cwd: worktreePath ?? basePath, permissionMode: spec.defaults?.permission_mode }),
1072
- timeout.promise,
1073
- ]);
1074
- }
1075
- timeout.clear();
1076
- }
1077
- catch (err) {
1078
- timeout.clear();
1079
- result = { success: false, output: err.message, exitCode: -1 };
1080
- }
1081
- activeTaskMap.delete(taskRecord.id);
1082
- const finishedAt = now();
1083
- const elapsed = `(${formatDuration(Date.now() - taskStartTime)})`;
1084
- async function removeWorktree() {
1085
- if (worktreePath) {
1086
- try {
1087
- await wtManager.remove(worktreePath);
1088
- }
1089
- catch { /* ignore cleanup errors */ }
1090
- }
1091
- }
1092
- // ── Timed out ───────────────────────────────────────────────────────────
1093
- if (result._timedOut) {
1094
- if (typeof taskAdapter.kill === 'function')
1095
- taskAdapter.kill(task);
1096
- await removeWorktree();
1097
- const freshRecord = store.getTask(taskRecord.id, convoyId);
1098
- if (freshRecord.retries < freshRecord.max_retries && spec.on_failure !== 'stop') {
1099
- const contextPrefix = `Previous attempt timed out.\n\nFix the issues and try again.\n\n`;
1100
- store.updateTaskStatus(taskRecord.id, convoyId, 'pending', {
1101
- retries: freshRecord.retries + 1,
1102
- worker_id: null,
1103
- worktree: null,
1104
- started_at: null,
1105
- finished_at: null,
1106
- prompt: contextPrefix + taskRecord.prompt,
1107
- });
1108
- store.updateWorkerStatus(workerId, 'killed', { finished_at: finishedAt });
1109
- process.stdout.write(` ${c.yellow('⟳')} ${c.bold(`[${taskRecord.id}]`)} timed out, retry ${freshRecord.retries + 1}/${freshRecord.max_retries}\n`);
1110
- }
1111
- else {
1112
- // Estimate tokens even for timed-out tasks — you still paid for them
1113
- const estimatedPrompt = Math.ceil(taskRecord.prompt.length / 4);
1114
- const estimatedCompletion = Math.ceil((result.output?.length ?? 0) / 4);
1115
- const timeoutModel = taskRecord.model ?? taskAdapter.name;
1116
- const timeoutCost = calculateCost(timeoutModel, estimatedPrompt, estimatedCompletion);
1117
- store.withTransaction(() => {
1118
- store.updateTaskStatus(taskRecord.id, convoyId, 'timed-out', {
1119
- finished_at: finishedAt,
1120
- output: result.output,
1121
- prompt_tokens: estimatedPrompt,
1122
- completion_tokens: estimatedCompletion,
1123
- total_tokens: estimatedPrompt + estimatedCompletion,
1124
- model: timeoutModel,
1125
- cost_usd: timeoutCost,
1126
- });
1127
- store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
1052
+ const builtInGates = spec.defaults?.built_in_gates;
1053
+ const contractResult = validateOutput(rec.agent, result.output);
1054
+ // ── No-op gate ──────────────────────────────────────────────────────────
1055
+ // A clean exit is not proof the work happened: a worker refused write
1056
+ // permission exits 0 having written nothing. On unless the spec turns it off.
1057
+ if (files.length > 0 && (builtInGates ? builtInGates.no_op !== false : true)) {
1058
+ const noOp = noOpGate({
1059
+ declaredFiles: files,
1060
+ changedFiles: changes ? changedFiles : null,
1061
+ agent: rec.agent,
1062
+ contractData: contractResult.data,
1063
+ });
1064
+ if (!noOp.passed) {
1065
+ events.emit('built_in_gate_result', { gate: 'no_op', passed: false, output: noOp.output }, { convoy_id: convoyId, task_id: rec.id });
1066
+ return retryOrFail('gate-failed', 'Produced no changes', {
1067
+ kind: 'no-op',
1068
+ gate: 'no_op',
1069
+ output: `Built-in gate (no_op) failed:\n${noOp.output}`,
1070
+ failureType: 'no-op',
1071
+ note: `Your previous attempt produced no changes.\n${noOp.output}\n\nWrite the files the task asks for. If you cannot, say why and stop.`,
1128
1072
  });
1129
- completedCount++;
1130
- process.stdout.write(` ${c.red('⏱')} ${c.bold(`[${taskRecord.id}]`)} timed out ${c.dim(`[${completedCount}/${totalTasks}]`)}\n`);
1131
- events.emit('task_failed', { reason: 'timeout', worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
1132
- events.emit('session', {
1133
- agent: taskRecord.agent,
1134
- model: taskRecord.model ?? taskAdapter.name,
1135
- task: taskRecord.id,
1136
- outcome: 'failed',
1137
- duration_min: Math.round((Date.now() - taskStartTime) / 60_000),
1138
- files_changed: 0,
1139
- retries: freshRecord.retries,
1140
- convoy_id: convoyId,
1141
- }, { convoy_id: convoyId, task_id: taskRecord.id });
1142
- events.emit('delegation', {
1143
- session_id: convoyId,
1144
- agent: taskRecord.agent,
1145
- model: taskRecord.model ?? taskAdapter.name,
1146
- tier: 'standard',
1147
- mechanism: 'convoy',
1148
- outcome: 'failed',
1149
- retries: freshRecord.retries,
1150
- phase: taskRecord.phase,
1151
- convoy_id: convoyId,
1152
- }, { convoy_id: convoyId, task_id: taskRecord.id });
1153
- handleExhaustion(freshRecord, 'timeout', result.output || null);
1154
1073
  }
1155
- taskAdapterMap.delete(taskRecord.id);
1156
- return;
1157
1074
  }
1158
- // ── Success ─────────────────────────────────────────────────────────────
1159
- if (result.success) { // ── Per-task gates ─────────────────────────────────────────────────────
1160
- const taskGates = taskRecord.gates ? JSON.parse(taskRecord.gates) : [];
1161
- if (taskGates.length > 0) {
1162
- let gateFailure = null;
1163
- for (const command of taskGates) {
1164
- try {
1165
- // SECURITY: Gate/hook commands come from the .convoy.yml spec file, which is operator-controlled.
1166
- // They are NOT user-supplied and are part of the trusted build configuration.
1167
- await execFile('sh', ['-c', command], { cwd: worktreePath ?? basePath, maxBuffer: 10 * 1024 * 1024 });
1168
- }
1169
- catch (err) {
1170
- const execErr = err;
1171
- const code = typeof execErr.code === 'number' ? execErr.code : 1;
1172
- const output = [execErr.stderr, execErr.stdout].filter(Boolean).join('\n').trim() || execErr.message || '';
1173
- gateFailure = { command, exitCode: code, output };
1174
- break;
1175
- }
1075
+ // ── Built-in per-task gates ─────────────────────────────────────────────
1076
+ if (builtInGates) {
1077
+ if (builtInGates.browser_test) {
1078
+ const browserConfig = specTask?.browser_test ?? spec.defaults?.browser_test;
1079
+ if (!browserConfig) {
1080
+ progress.line(` ${c.yellow('⚠')} ${c.bold(`[${rec.id}]`)} browser_test is on but no browser_test.urls are set — skipped`);
1176
1081
  }
1177
- if (gateFailure !== null) {
1178
- await removeWorktree();
1179
- const freshRecord = store.getTask(taskRecord.id, convoyId);
1180
- if (freshRecord.retries < freshRecord.max_retries && spec.on_failure !== 'stop') {
1181
- const contextPrefix = `Previous attempt's gate check failed.\nGate: ${gateFailure.command}\nExit code: ${gateFailure.exitCode}\nOutput:\n${gateFailure.output || '(no output)'}\n\nFix the issues and try again.\n\n`;
1182
- store.updateTaskStatus(taskRecord.id, convoyId, 'pending', {
1183
- retries: freshRecord.retries + 1,
1184
- worker_id: null,
1185
- worktree: null,
1186
- started_at: null,
1187
- finished_at: null,
1188
- prompt: contextPrefix + taskRecord.prompt,
1189
- });
1190
- store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
1191
- process.stdout.write(` ${c.yellow('⟳')} ${c.bold(`[${taskRecord.id}]`)} gate failed, retry ${freshRecord.retries + 1}/${freshRecord.max_retries}\n`);
1192
- }
1193
- else {
1194
- store.withTransaction(() => {
1195
- store.updateTaskStatus(taskRecord.id, convoyId, 'gate-failed', {
1196
- finished_at: finishedAt,
1197
- output: `Gate failed: ${gateFailure.command}\nExit code: ${gateFailure.exitCode}\n${gateFailure.output}`,
1198
- exit_code: gateFailure.exitCode,
1199
- });
1200
- store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
1082
+ else {
1083
+ const browserResult = await browserTestGate({
1084
+ mcpServers: spec.defaults?.mcp_servers ?? [],
1085
+ taskConfig: browserConfig,
1086
+ worktreePath: wt,
1087
+ approvalTimeout: spec.defaults?.mcp_server_approval_timeout,
1088
+ });
1089
+ events.emit('built_in_gate_result', { gate: 'browser_test', passed: browserResult.passed, output: browserResult.output }, { convoy_id: convoyId, task_id: rec.id });
1090
+ if (!browserResult.passed) {
1091
+ return retryOrFail('gate-failed', 'Browser test gate failed', {
1092
+ kind: 'gate-failed', gate: 'browser_test', output: `Built-in gate (browser_test) failed:\n${browserResult.output}`, failureType: 'browser-test',
1093
+ note: `The browser test gate failed on your previous attempt:\n${browserResult.output.slice(-3000)}`,
1201
1094
  });
1202
- completedCount++;
1203
- process.stdout.write(` ${c.red('✗')} ${c.bold(`[${taskRecord.id}]`)} gate failed ${elapsed} ${c.dim(`[${completedCount}/${totalTasks}]`)}\n`);
1204
- events.emit('task_failed', { reason: 'gate-failed', gate: gateFailure.command, exit_code: gateFailure.exitCode, worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
1205
- events.emit('session', {
1206
- agent: taskRecord.agent,
1207
- model: taskRecord.model ?? taskAdapter.name,
1208
- task: taskRecord.id,
1209
- outcome: 'failed',
1210
- duration_min: Math.round((Date.now() - taskStartTime) / 60_000),
1211
- files_changed: 0,
1212
- retries: freshRecord.retries,
1213
- convoy_id: convoyId,
1214
- }, { convoy_id: convoyId, task_id: taskRecord.id });
1215
- events.emit('delegation', {
1216
- session_id: convoyId,
1217
- agent: taskRecord.agent,
1218
- model: taskRecord.model ?? taskAdapter.name,
1219
- tier: 'standard',
1220
- mechanism: 'convoy',
1221
- outcome: 'failed',
1222
- retries: freshRecord.retries,
1223
- phase: taskRecord.phase,
1224
- convoy_id: convoyId,
1225
- }, { convoy_id: convoyId, task_id: taskRecord.id });
1226
- handleExhaustion(freshRecord, 'gate-failed', gateFailure.output || null);
1227
1095
  }
1228
- taskAdapterMap.delete(taskRecord.id);
1229
- return;
1230
1096
  }
1231
1097
  }
1232
- const builtInGates = spec.defaults?.built_in_gates;
1233
- // ── No-op gate ────────────────────────────────────────────────────────
1234
- // A clean exit is not proof the work happened. This one is on unless the
1235
- // spec turns it off, because the state it catches — a task that promised
1236
- // files and produced none — used to be recorded as `done` with exit 0, and
1237
- // a silent green is worse than a loud red.
1238
- const contractResult = validateOutput(taskRecord.agent, result.output);
1239
- if (taskFiles.length > 0 && (builtInGates ? builtInGates.no_op !== false : true)) {
1240
- const noOpResult = noOpGate({
1241
- declaredFiles: taskFiles,
1242
- changedFiles: worktreePath ? await collectWorktreeChanges(worktreePath, baseBranch) : null,
1243
- agent: taskRecord.agent,
1244
- contractData: contractResult.data,
1245
- });
1246
- if (!noOpResult.passed) {
1247
- events.emit('built_in_gate_result', { gate: 'no_op', passed: false, output: noOpResult.output }, { convoy_id: convoyId, task_id: taskRecord.id });
1248
- await removeWorktree();
1249
- const freshRecord = store.getTask(taskRecord.id, convoyId);
1250
- if (freshRecord.retries < freshRecord.max_retries && spec.on_failure !== 'stop') {
1251
- store.updateTaskStatus(taskRecord.id, convoyId, 'pending', {
1252
- retries: freshRecord.retries + 1,
1253
- worker_id: null,
1254
- worktree: null,
1255
- started_at: null,
1256
- finished_at: null,
1257
- prompt: `Your previous attempt produced no changes.\n${noOpResult.output}\n\nWrite the files the task asks for. If you cannot, say why and stop.\n\n${taskRecord.prompt}`,
1258
- });
1259
- store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
1260
- process.stdout.write(` ${c.yellow('⟳')} ${c.bold(`[${taskRecord.id}]`)} no changes produced, retry ${freshRecord.retries + 1}/${freshRecord.max_retries}\n`);
1261
- }
1262
- else {
1263
- store.withTransaction(() => {
1264
- store.updateTaskStatus(taskRecord.id, convoyId, 'gate-failed', {
1265
- finished_at: finishedAt,
1266
- output: `Built-in gate (no_op) failed:\n${noOpResult.output}`,
1267
- exit_code: 1,
1268
- contract_result: JSON.stringify(contractResult),
1269
- });
1270
- store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
1271
- });
1272
- completedCount++;
1273
- process.stdout.write(` ${c.red('✗')} ${c.bold(`[${taskRecord.id}]`)} produced no changes ${elapsed} ${c.dim(`[${completedCount}/${totalTasks}]`)}\n`);
1274
- events.emit('task_failed', { reason: 'no-op', gate: 'no_op', worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
1275
- handleExhaustion(freshRecord, 'no-op', noOpResult.output);
1276
- }
1277
- taskAdapterMap.delete(taskRecord.id);
1278
- return;
1098
+ if (builtInGates.secret_scan && changedFiles.length > 0) {
1099
+ const scanResult = await runSecretScanGate(changedFiles, wt);
1100
+ events.emit('built_in_gate_result', { gate: 'secret_scan', passed: scanResult.passed, output: scanResult.output }, { convoy_id: convoyId, task_id: rec.id });
1101
+ if (!scanResult.passed) {
1102
+ return retryOrFail('gate-failed', 'Secret scan found a credential in the change', {
1103
+ kind: 'gate-failed', gate: 'secret_scan', output: `Built-in gate (secret_scan) failed:\n${scanResult.output}`, failureType: 'secret-scan',
1104
+ note: `The secret scan found credentials in your previous change:\n${scanResult.output}\n\nRemove them; read secrets from the environment instead.`,
1105
+ });
1279
1106
  }
1280
1107
  }
1281
- // ── Built-in gates ────────────────────────────────────────────────────
1282
- if (builtInGates && worktreePath) {
1283
- if (builtInGates.browser_test) {
1284
- const specTask = (spec.tasks ?? []).find(t => t.id === taskRecord.id);
1285
- const taskBrowserConfig = specTask?.browser_test ?? spec.defaults?.browser_test;
1286
- if (!taskBrowserConfig) {
1287
- process.stderr.write(`Warning: browser_test gate enabled but no browser_test config (urls) found — skipping\n`);
1288
- }
1289
- else {
1290
- const browserResult = await browserTestGate({
1291
- mcpServers: spec.defaults?.mcp_servers ?? [],
1292
- taskConfig: taskBrowserConfig,
1293
- worktreePath,
1294
- approvalTimeout: spec.defaults?.mcp_server_approval_timeout,
1295
- });
1296
- events.emit('built_in_gate_result', { gate: 'browser_test', passed: browserResult.passed, output: browserResult.output }, { convoy_id: convoyId, task_id: taskRecord.id });
1297
- if (!browserResult.passed) {
1298
- await removeWorktree();
1299
- const freshRecord = store.getTask(taskRecord.id, convoyId);
1300
- if (freshRecord.retries < freshRecord.max_retries && spec.on_failure !== 'stop') {
1301
- store.updateTaskStatus(taskRecord.id, convoyId, 'pending', {
1302
- retries: freshRecord.retries + 1,
1303
- worker_id: null,
1304
- worktree: null,
1305
- started_at: null,
1306
- finished_at: null,
1307
- });
1308
- store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
1309
- process.stdout.write(` ${c.yellow('⟳')} ${c.bold(`[${taskRecord.id}]`)} browser test gate failed, retry ${freshRecord.retries + 1}/${freshRecord.max_retries}\n`);
1310
- }
1311
- else {
1312
- store.withTransaction(() => {
1313
- store.updateTaskStatus(taskRecord.id, convoyId, 'gate-failed', {
1314
- finished_at: finishedAt,
1315
- output: `Built-in gate (browser_test) failed:\n${browserResult.output}`,
1316
- exit_code: 1,
1317
- });
1318
- store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
1319
- });
1320
- completedCount++;
1321
- process.stdout.write(` ${c.red('✗')} ${c.bold(`[${taskRecord.id}]`)} browser test gate failed ${elapsed} ${c.dim(`[${completedCount}/${totalTasks}]`)}\n`);
1322
- events.emit('task_failed', { reason: 'gate-failed', gate: 'browser_test', worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
1323
- handleExhaustion(freshRecord, 'browser-test', browserResult.output);
1324
- }
1325
- taskAdapterMap.delete(taskRecord.id);
1326
- return;
1327
- }
1328
- }
1329
- }
1330
- let changedFiles = [];
1331
- let diff = '';
1332
- try {
1333
- const { stdout: filesOut } = await execFile('git', ['diff', '--name-only', `${baseBranch}..HEAD`], { cwd: worktreePath });
1334
- changedFiles = filesOut.split('\n').filter(Boolean);
1335
- const { stdout: diffOut } = await execFile('git', ['diff', `${baseBranch}..HEAD`], { cwd: worktreePath });
1336
- diff = diffOut;
1108
+ if (builtInGates.blast_radius && diff) {
1109
+ const blast = runBlastRadiusGate(diff);
1110
+ events.emit('built_in_gate_result', { gate: 'blast_radius', level: blast.level, passed: blast.passed, output: blast.output }, { convoy_id: convoyId, task_id: rec.id });
1111
+ if (!blast.passed) {
1112
+ return retryOrFail('gate-failed', blast.output, {
1113
+ kind: 'gate-failed', gate: 'blast_radius', output: `Built-in gate (blast_radius) failed:\n${blast.output}`,
1114
+ note: `Your previous change was too large: ${blast.output}\n\nKeep the change to what the task asks for.`,
1115
+ });
1337
1116
  }
1338
- catch { /* no commits in worktree yet — skip */ }
1339
- // Secret scan gate
1340
- if (builtInGates.secret_scan && changedFiles.length > 0) {
1341
- const scanResult = await runSecretScanGate(changedFiles, worktreePath);
1342
- events.emit('built_in_gate_result', { gate: 'secret_scan', passed: scanResult.passed, output: scanResult.output }, { convoy_id: convoyId, task_id: taskRecord.id });
1343
- if (!scanResult.passed) {
1344
- await removeWorktree();
1345
- const freshRecord = store.getTask(taskRecord.id, convoyId);
1346
- if (freshRecord.retries < freshRecord.max_retries && spec.on_failure !== 'stop') {
1347
- store.updateTaskStatus(taskRecord.id, convoyId, 'pending', {
1348
- retries: freshRecord.retries + 1,
1349
- worker_id: null,
1350
- worktree: null,
1351
- started_at: null,
1352
- finished_at: null,
1353
- prompt: `Secret scan gate failed.\n${scanResult.output}\n\nFix the issues and try again.\n\n${taskRecord.prompt}`,
1354
- });
1355
- store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
1356
- process.stdout.write(` ${c.yellow('⟳')} ${c.bold(`[${taskRecord.id}]`)} secret scan gate failed, retry ${freshRecord.retries + 1}/${freshRecord.max_retries}\n`);
1357
- }
1358
- else {
1359
- store.withTransaction(() => {
1360
- store.updateTaskStatus(taskRecord.id, convoyId, 'gate-failed', {
1361
- finished_at: finishedAt,
1362
- output: `Built-in gate (secret_scan) failed:\n${scanResult.output}`,
1363
- exit_code: 1,
1364
- });
1365
- store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
1366
- });
1367
- completedCount++;
1368
- process.stdout.write(` ${c.red('✗')} ${c.bold(`[${taskRecord.id}]`)} secret scan gate failed ${elapsed} ${c.dim(`[${completedCount}/${totalTasks}]`)}\n`);
1369
- events.emit('task_failed', { reason: 'gate-failed', gate: 'secret_scan', worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
1370
- handleExhaustion(freshRecord, 'secret-scan', scanResult.output);
1371
- }
1372
- taskAdapterMap.delete(taskRecord.id);
1373
- return;
1374
- }
1117
+ }
1118
+ if (builtInGates.tdd_check && changedFiles.length > 0) {
1119
+ const tddConfig = typeof builtInGates.tdd_check === 'object'
1120
+ ? { ...DEFAULT_TDD_CONFIG, ...builtInGates.tdd_check }
1121
+ : DEFAULT_TDD_CONFIG;
1122
+ const tdd = checkTDD(changedFiles, changedFiles, tddConfig, rec.agent);
1123
+ if (tdd.skipped) {
1124
+ events.emit('tdd_check_skipped', { task_id: rec.id, reason: tdd.skip_reason, agent: rec.agent }, { convoy_id: convoyId, task_id: rec.id });
1375
1125
  }
1376
- // Blast radius gate
1377
- if (builtInGates.blast_radius && diff) {
1378
- const blastResult = runBlastRadiusGate(diff);
1379
- events.emit('built_in_gate_result', { gate: 'blast_radius', level: blastResult.level, passed: blastResult.passed, output: blastResult.output }, { convoy_id: convoyId, task_id: taskRecord.id });
1380
- if (!blastResult.passed) {
1381
- await removeWorktree();
1382
- const freshRecord = store.getTask(taskRecord.id, convoyId);
1383
- if (freshRecord.retries < freshRecord.max_retries && spec.on_failure !== 'stop') {
1384
- store.updateTaskStatus(taskRecord.id, convoyId, 'pending', {
1385
- retries: freshRecord.retries + 1,
1386
- worker_id: null,
1387
- worktree: null,
1388
- started_at: null,
1389
- finished_at: null,
1390
- prompt: `Blast radius gate failed.\n${blastResult.output}\n\nFix the issues and try again.\n\n${taskRecord.prompt}`,
1391
- });
1392
- store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
1393
- process.stdout.write(` ${c.yellow('⟳')} ${c.bold(`[${taskRecord.id}]`)} blast radius gate failed, retry ${freshRecord.retries + 1}/${freshRecord.max_retries}\n`);
1394
- }
1395
- else {
1396
- store.withTransaction(() => {
1397
- store.updateTaskStatus(taskRecord.id, convoyId, 'gate-failed', {
1398
- finished_at: finishedAt,
1399
- output: `Built-in gate (blast_radius) failed:\n${blastResult.output}`,
1400
- exit_code: 1,
1401
- });
1402
- store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
1403
- });
1404
- completedCount++;
1405
- process.stdout.write(` ${c.red('✗')} ${c.bold(`[${taskRecord.id}]`)} blast radius gate failed ${elapsed} ${c.dim(`[${completedCount}/${totalTasks}]`)}\n`);
1406
- events.emit('task_failed', { reason: 'gate-failed', gate: 'blast_radius', worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
1407
- handleExhaustion(freshRecord, 'gate-failed', blastResult.output);
1408
- }
1409
- taskAdapterMap.delete(taskRecord.id);
1410
- return;
1411
- }
1126
+ else if (tdd.passed) {
1127
+ events.emit('tdd_check_passed', {
1128
+ task_id: rec.id,
1129
+ new_source_files: tdd.new_source_files.length,
1130
+ existing_test_files: tdd.existing_test_files.length,
1131
+ }, { convoy_id: convoyId, task_id: rec.id });
1412
1132
  }
1413
- // Dependency audit and regression test gates
1414
- //
1415
- // Both were declared in the spec validator, implemented in full, and set to
1416
- // 'auto' by `spec-builder.ts` on its own — and never called from here. A
1417
- // spec could ask for `regression_test`, validate, run green, and never run
1418
- // the test suite. Nothing failed, which is the worst way for a gate to be
1419
- // broken. `built-in-gates.test.ts` now derives the accepted-gate list from
1420
- // the validator and fails if any of them is not branched on and invoked.
1421
- //
1422
- // The failure path is shared between the two rather than copied, because
1423
- // copying it is how the three gates above came to hold three near-identical
1424
- // 40-line blocks that have to be kept in step by hand.
1425
- const failGate = async (gate, label, output) => {
1426
- await removeWorktree();
1427
- const freshRecord = store.getTask(taskRecord.id, convoyId);
1428
- if (freshRecord.retries < freshRecord.max_retries && spec.on_failure !== 'stop') {
1429
- store.updateTaskStatus(taskRecord.id, convoyId, 'pending', {
1430
- retries: freshRecord.retries + 1,
1431
- worker_id: null,
1432
- worktree: null,
1433
- started_at: null,
1434
- finished_at: null,
1435
- prompt: `${label} gate failed.\n${output}\n\nFix the issues and try again.`,
1436
- });
1437
- store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
1438
- process.stdout.write(` ${c.yellow('⟳')} ${c.bold(`[${taskRecord.id}]`)} ${label} gate failed, retry ${freshRecord.retries + 1}/${freshRecord.max_retries}\n`);
1439
- }
1440
- else {
1441
- store.withTransaction(() => {
1442
- store.updateTaskStatus(taskRecord.id, convoyId, 'gate-failed', {
1443
- finished_at: finishedAt,
1444
- output: `Built-in gate (${gate}) failed:\n${output}`,
1445
- exit_code: 1,
1446
- });
1447
- store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
1133
+ else {
1134
+ const failureMsg = formatTDDFailure(tdd);
1135
+ events.emit('tdd_check_failed', {
1136
+ task_id: rec.id,
1137
+ missing_test_files: tdd.missing_test_files,
1138
+ new_source_files: tdd.new_source_files.length,
1139
+ }, { convoy_id: convoyId, task_id: rec.id });
1140
+ if (tddConfig.mode === 'block') {
1141
+ return retryOrFail('gate-failed', 'TDD gate: source files without tests', {
1142
+ kind: 'gate-failed', gate: 'tdd_check', output: `Built-in gate (tdd_check) failed:\n${failureMsg}`, failureType: 'tdd-check',
1143
+ note: `The TDD gate failed on your previous attempt:\n${failureMsg}\n\nCreate the missing test files.`,
1448
1144
  });
1449
- completedCount++;
1450
- process.stdout.write(` ${c.red('✗')} ${c.bold(`[${taskRecord.id}]`)} ${label} gate failed ${elapsed} ${c.dim(`(worker ${workerId})`)}\n`);
1451
- events.emit('task_failed', { reason: 'gate-failed', gate, worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
1452
- handleExhaustion(freshRecord, 'gate-failed', output);
1453
- }
1454
- taskAdapterMap.delete(taskRecord.id);
1455
- };
1456
- // Both gates shell out to npm, and `runGateCommand` reports a spawn failure
1457
- // as a non-zero exit — so without this a project that is not an npm package
1458
- // would have every task fail on a gate it cannot possibly satisfy. Announced
1459
- // and skipped, the way the browser_test gate handles a missing config.
1460
- const pkgJsonPath = resolve(worktreePath, 'package.json');
1461
- let pkgScripts = null;
1462
- if (existsSync(pkgJsonPath)) {
1463
- try {
1464
- pkgScripts = JSON.parse(readFileSync(pkgJsonPath, 'utf8'))
1465
- .scripts ?? {};
1466
- }
1467
- catch {
1468
- pkgScripts = null;
1469
- }
1470
- }
1471
- if (builtInGates.dependency_audit) {
1472
- if (pkgScripts === null) {
1473
- process.stderr.write(`Warning: dependency_audit gate enabled but ${worktreePath} has no readable package.json — skipping\n`);
1474
- }
1475
- else {
1476
- const auditResult = await runDependencyAuditGate(worktreePath);
1477
- events.emit('built_in_gate_result', { gate: 'dependency_audit', passed: auditResult.passed, output: auditResult.output }, { convoy_id: convoyId, task_id: taskRecord.id });
1478
- if (!auditResult.passed) {
1479
- await failGate('dependency_audit', 'dependency audit', auditResult.output);
1480
- return;
1481
- }
1482
- }
1483
- }
1484
- if (builtInGates.regression_test) {
1485
- if (pkgScripts === null || typeof pkgScripts.test !== 'string') {
1486
- process.stderr.write(`Warning: regression_test gate enabled but no "test" script found in package.json — skipping\n`);
1487
1145
  }
1488
- else {
1489
- const regressionResult = await runRegressionTestGate(worktreePath);
1490
- events.emit('built_in_gate_result', { gate: 'regression_test', passed: regressionResult.passed, output: regressionResult.output }, { convoy_id: convoyId, task_id: taskRecord.id });
1491
- if (!regressionResult.passed) {
1492
- await failGate('regression_test', 'regression test', regressionResult.output);
1493
- return;
1494
- }
1495
- }
1496
- }
1497
- // ── Partition violation check (Phase 41) ────────────────────────────
1498
- if (changedFiles.length > 0) {
1499
- try {
1500
- const taskFiles = taskRecord.files ? JSON.parse(taskRecord.files) : [];
1501
- if (taskFiles.length > 0) {
1502
- const violation = detectPartitionViolations(taskRecord.id, taskFiles, changedFiles);
1503
- if (violation) {
1504
- events.emit('partition_violation', {
1505
- task_id: taskRecord.id,
1506
- allowed: violation.allowedFiles,
1507
- actual: violation.actualFiles,
1508
- violations: violation.violations,
1509
- }, { convoy_id: convoyId, task_id: taskRecord.id });
1510
- process.stdout.write(` ${c.yellow('⚠')} ${c.bold(`[${taskRecord.id}]`)} partition violation: ${violation.violations.join(', ')}\n`);
1511
- }
1512
- }
1513
- }
1514
- catch { /* non-critical */ }
1515
- }
1516
- // ── TDD gate ──────────────────────────────────────────────────────────
1517
- if (builtInGates.tdd_check && changedFiles.length > 0) {
1518
- const tddConfig = typeof builtInGates.tdd_check === 'object'
1519
- ? { ...DEFAULT_TDD_CONFIG, ...builtInGates.tdd_check }
1520
- : DEFAULT_TDD_CONFIG;
1521
- const specTaskForTDD = (spec.tasks ?? []).find(t => t.id === taskRecord.id);
1522
- const tddResult = checkTDD(changedFiles, changedFiles, tddConfig, specTaskForTDD?.agent ?? taskRecord.agent);
1523
- if (tddResult.skipped) {
1524
- events.emit('tdd_check_skipped', {
1525
- task_id: taskRecord.id,
1526
- reason: tddResult.skip_reason,
1527
- agent: specTaskForTDD?.agent ?? taskRecord.agent,
1528
- }, { convoy_id: convoyId, task_id: taskRecord.id });
1529
- }
1530
- else if (tddResult.passed) {
1531
- events.emit('tdd_check_passed', {
1532
- task_id: taskRecord.id,
1533
- new_source_files: tddResult.new_source_files.length,
1534
- existing_test_files: tddResult.existing_test_files.length,
1535
- }, { convoy_id: convoyId, task_id: taskRecord.id });
1536
- }
1537
- else {
1538
- const failureMsg = formatTDDFailure(tddResult);
1539
- events.emit('tdd_check_failed', {
1540
- task_id: taskRecord.id,
1541
- missing_test_files: tddResult.missing_test_files,
1542
- new_source_files: tddResult.new_source_files.length,
1543
- }, { convoy_id: convoyId, task_id: taskRecord.id });
1544
- if (tddConfig.mode === 'block') {
1545
- await removeWorktree();
1546
- const freshRecord = store.getTask(taskRecord.id, convoyId);
1547
- if (freshRecord.retries < freshRecord.max_retries && spec.on_failure !== 'stop') {
1548
- store.updateTaskStatus(taskRecord.id, convoyId, 'pending', {
1549
- retries: freshRecord.retries + 1,
1550
- worker_id: null,
1551
- worktree: null,
1552
- started_at: null,
1553
- finished_at: null,
1554
- prompt: `TDD gate failed.\n${failureMsg}\n\nCreate the missing test files and try again.\n\n${taskRecord.prompt}`,
1555
- });
1556
- store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
1557
- process.stdout.write(` ${c.yellow('⟳')} ${c.bold(`[${taskRecord.id}]`)} TDD gate failed, retry ${freshRecord.retries + 1}/${freshRecord.max_retries}\n`);
1558
- }
1559
- else {
1560
- store.withTransaction(() => {
1561
- store.updateTaskStatus(taskRecord.id, convoyId, 'gate-failed', {
1562
- finished_at: finishedAt,
1563
- output: `Built-in gate (tdd_check) failed:\n${failureMsg}`,
1564
- exit_code: 1,
1565
- });
1566
- store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
1567
- });
1568
- completedCount++;
1569
- process.stdout.write(` ${c.red('✗')} ${c.bold(`[${taskRecord.id}]`)} TDD gate failed ${elapsed} ${c.dim(`[${completedCount}/${totalTasks}]`)}\n`);
1570
- events.emit('task_failed', { reason: 'gate-failed', gate: 'tdd_check', worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
1571
- handleExhaustion(freshRecord, 'tdd-check', failureMsg);
1572
- }
1573
- taskAdapterMap.delete(taskRecord.id);
1574
- return;
1575
- }
1576
- else {
1577
- // warn mode — log but continue
1578
- process.stdout.write(` ${c.yellow('⚠')} ${c.bold(`[${taskRecord.id}]`)} TDD gate warning: ${tddResult.missing_test_files.length} source file(s) without tests\n`);
1579
- }
1580
- }
1581
- }
1146
+ progress.line(` ${c.yellow('⚠')} ${c.bold(`[${rec.id}]`)} ${tdd.missing_test_files.length} source file(s) without tests`);
1147
+ }
1148
+ }
1149
+ }
1150
+ // ── Partition check: a warning, the work stays ─────────────────────────
1151
+ if (files.length > 0 && changedFiles.length > 0) {
1152
+ const violation = detectPartitionViolations(rec.id, files, changedFiles);
1153
+ if (violation) {
1154
+ events.emit('partition_violation', {
1155
+ task_id: rec.id,
1156
+ allowed: violation.allowedFiles,
1157
+ actual: violation.actualFiles,
1158
+ violations: violation.violations,
1159
+ }, { convoy_id: convoyId, task_id: rec.id });
1160
+ progress.line(` ${c.yellow('⚠')} ${c.bold(`[${rec.id}]`)} changed files outside its list: ${violation.violations.join(', ')}`);
1161
+ }
1162
+ }
1163
+ // ── Review ──────────────────────────────────────────────────────────────
1164
+ const reviewSetting = specTask?.review ?? spec.defaults?.review ?? 'auto';
1165
+ if (reviewSetting !== 'none') {
1166
+ const diffStats = {
1167
+ linesChanged: countChangedLines(diff),
1168
+ filesChanged: changedFiles.length,
1169
+ filePaths: changedFiles,
1170
+ };
1171
+ const level = reviewSetting === 'fast' || reviewSetting === 'panel'
1172
+ ? reviewSetting
1173
+ : evaluateReviewLevel(rec, diffStats, spec.defaults?.review_heuristics, true);
1174
+ const reviewerModel = spec.defaults?.reviewer_model ?? 'default';
1175
+ const recordSkip = (why) => {
1176
+ store.updateTaskReview(rec.id, convoyId, { review_level: level, review_verdict: 'skipped', review_tokens: 0, review_model: null });
1177
+ events.emit('review_skipped', { level, reason: why }, { convoy_id: convoyId, task_id: rec.id });
1178
+ progress.line(` ${c.yellow('⚠')} ${c.bold(`[${rec.id}]`)} review skipped: ${why}`);
1179
+ };
1180
+ if (level === 'auto-pass') {
1181
+ store.updateTaskReview(rec.id, convoyId, { review_level: 'auto-pass', review_verdict: 'pass', review_tokens: 0, review_model: null });
1182
+ events.emit('review_verdict', { level: 'auto-pass', verdict: 'pass', tokens: 0, model: null, feedback_length: 0 }, { convoy_id: convoyId, task_id: rec.id });
1582
1183
  }
1583
- // ── Drift detection ──────────────────────────────────────────────────
1584
- const specTaskForDrift = (spec.tasks ?? []).find(t => t.id === taskRecord.id);
1585
- const isDriftEnabled = specTaskForDrift?.detect_drift ?? spec.defaults?.detect_drift ?? false;
1586
- if (isDriftEnabled && taskRecord.drift_retried === 0) {
1587
- const driftResult = await detectDrift(taskRecord, taskAdapter);
1588
- events.emit('drift_check_result', {
1589
- task_id: taskRecord.id,
1590
- score: driftResult.score,
1591
- threshold: driftResult.threshold,
1592
- explanation: driftResult.explanation,
1593
- drifted: driftResult.drifted,
1594
- }, { convoy_id: convoyId, task_id: taskRecord.id });
1595
- store.updateTaskDrift(taskRecord.id, convoyId, { drift_score: driftResult.score });
1596
- if (driftResult.drifted) {
1597
- events.emit('drift_detected', {
1598
- task_id: taskRecord.id,
1599
- score: driftResult.score,
1600
- threshold: driftResult.threshold,
1601
- }, { convoy_id: convoyId, task_id: taskRecord.id });
1602
- await removeWorktree();
1603
- store.updateTaskDrift(taskRecord.id, convoyId, { drift_retried: 1 });
1604
- store.updateTaskStatus(taskRecord.id, convoyId, 'pending', {
1605
- worker_id: null,
1606
- worktree: null,
1607
- started_at: null,
1608
- finished_at: null,
1609
- });
1610
- store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
1611
- process.stdout.write(` ${c.yellow('⟳')} ${c.bold(`[${taskRecord.id}]`)} drift detected (score: ${driftResult.score.toFixed(2)}), retrying\n`);
1612
- taskAdapterMap.delete(taskRecord.id);
1613
- return;
1184
+ else if (spec.defaults?.review_budget != null && reviewTokensTotal >= spec.defaults.review_budget) {
1185
+ if ((spec.defaults.on_review_budget_exceeded ?? 'skip') === 'stop') {
1186
+ stopDispatching('review budget spent (on_review_budget_exceeded: stop)');
1187
+ return fail('review-blocked', 'Review budget exceeded', { kind: 'review-blocked' });
1614
1188
  }
1189
+ recordSkip('the review budget is spent');
1615
1190
  }
1616
- // ── Review pipeline ──────────────────────────────────────────────────
1617
- const specTaskForReview = (spec.tasks ?? []).find(t => t.id === taskRecord.id);
1618
- const taskReviewSetting = specTaskForReview?.review ?? spec.defaults?.review ?? 'auto';
1619
- if (taskReviewSetting !== 'none') {
1620
- // Compute diff stats from worktree
1621
- let reviewChangedFiles = [];
1622
- let reviewDiffLines = 0;
1623
- if (worktreePath) {
1624
- try {
1625
- const { stdout: filesOut } = await execFile('git', ['diff', '--name-only', `${baseBranch}..HEAD`], { cwd: worktreePath });
1626
- reviewChangedFiles = filesOut.split('\n').filter(Boolean);
1627
- const { stdout: diffOut } = await execFile('git', ['diff', `${baseBranch}..HEAD`], { cwd: worktreePath });
1628
- reviewDiffLines = diffOut.split('\n').filter(l => l.startsWith('+') || l.startsWith('-')).filter(l => !l.startsWith('+++') && !l.startsWith('---')).length;
1629
- }
1630
- catch { /* no commits yet */ }
1631
- }
1632
- const diffStats = {
1633
- linesChanged: reviewDiffLines,
1634
- filesChanged: reviewChangedFiles.length,
1635
- filePaths: reviewChangedFiles,
1191
+ else {
1192
+ const reviewContext = {
1193
+ prompt: rec.prompt,
1194
+ files,
1195
+ diff,
1196
+ cwd: wt,
1197
+ adapterName: taskAdapter.name,
1198
+ execute: (task, options) => runAgent(rec.id, taskAdapter, task, options, Math.min(rec.timeout_ms, 900_000)),
1199
+ canRunReadOnly: supportsPermissionMode(taskAdapter.name, 'plan'),
1200
+ timeoutMs: Math.min(rec.timeout_ms, 900_000),
1201
+ defaultModel: taskAdapter.tierModels?.economy,
1636
1202
  };
1637
- // Determine review level
1638
- let reviewLevel;
1639
- if (taskReviewSetting === 'fast') {
1640
- reviewLevel = 'fast';
1641
- }
1642
- else if (taskReviewSetting === 'panel') {
1643
- reviewLevel = 'panel';
1203
+ // The model the reviewer is asked for, not the spec's 'default' placeholder.
1204
+ const askedModel = reviewerModel !== 'default' ? reviewerModel : (reviewContext.defaultModel ?? 'runtime default');
1205
+ events.emit('review_started', { level, task_id: rec.id, model: askedModel }, { convoy_id: convoyId, task_id: rec.id });
1206
+ const reviews = level === 'panel'
1207
+ ? await Promise.all([0, 1, 2].map(() => reviewSemaphore.use(() => reviewRunner(rec, 'panel', reviewerModel, reviewContext))))
1208
+ : [await reviewSemaphore.use(() => reviewRunner(rec, 'fast', reviewerModel, reviewContext))];
1209
+ if (ctl.interrupted)
1210
+ return requeue();
1211
+ const reviewTokens = reviews.reduce((s, r) => s + (r.tokens ?? 0), 0);
1212
+ const reviewCost = reviews.reduce((s, r) => s + (r.costUsd ?? 0), 0);
1213
+ reviewTokensTotal += reviewTokens;
1214
+ if (reviewTokens > 0)
1215
+ store.updateConvoyReviewTokens(convoyId, reviewTokensTotal);
1216
+ if (reviewCost > 0) {
1217
+ const row = store.getTask(rec.id, convoyId);
1218
+ store.updateTaskStatus(rec.id, convoyId, row.status, { cost_usd: (row.cost_usd ?? 0) + reviewCost });
1219
+ }
1220
+ const decided = reviews.filter(r => r.verdict !== 'skipped');
1221
+ const passes = decided.filter(r => r.verdict === 'pass').length;
1222
+ const blocks = decided.filter(r => r.verdict === 'block').length;
1223
+ const needed = level === 'panel' ? 2 : 1;
1224
+ const freshForPanel = store.getTask(rec.id, convoyId);
1225
+ if (passes < needed && blocks < needed) {
1226
+ recordSkip(reviews.find(r => r.verdict === 'skipped')?.feedback || 'no verdict');
1644
1227
  }
1645
1228
  else {
1646
- reviewLevel = evaluateReviewLevel(taskRecord, diffStats, spec.defaults?.review_heuristics, true);
1647
- }
1648
- const reviewerModel = spec.defaults?.reviewer_model ?? 'default';
1649
- events.emit('review_started', { level: reviewLevel, task_id: taskRecord.id, model: reviewerModel }, { convoy_id: convoyId, task_id: taskRecord.id });
1650
- if (reviewLevel === 'auto-pass') {
1651
- store.updateTaskReview(taskRecord.id, convoyId, {
1652
- review_level: 'auto-pass',
1653
- review_verdict: 'pass',
1654
- review_tokens: 0,
1655
- review_model: reviewerModel,
1229
+ const verdict = blocks >= needed ? 'block' : 'pass';
1230
+ const model = decided.find(r => r.model)?.model ?? null;
1231
+ store.updateTaskReview(rec.id, convoyId, {
1232
+ review_level: level,
1233
+ review_verdict: verdict,
1234
+ review_tokens: reviewTokens,
1235
+ review_model: model,
1236
+ ...(level === 'panel' ? { panel_attempts: freshForPanel.panel_attempts + 1 } : {}),
1656
1237
  });
1657
- events.emit('review_verdict', { level: 'auto-pass', verdict: 'pass', tokens: 0, model: reviewerModel, feedback_length: 0 }, { convoy_id: convoyId, task_id: taskRecord.id });
1658
- }
1659
- else if (reviewLevel === 'fast') {
1660
- // Check review budget
1661
- const reviewBudget = spec.defaults?.review_budget;
1662
- const onBudgetExceeded = spec.defaults?.on_review_budget_exceeded ?? 'skip';
1663
- if (reviewBudget != null && reviewTokensTotal >= reviewBudget) {
1664
- if (onBudgetExceeded === 'stop') {
1665
- const allPending = store.getTasksByConvoy(convoyId).filter(t => t.status === 'pending');
1666
- for (const t of allPending)
1667
- skipTask(t.id, 'review_budget exceeded with on_review_budget_exceeded: stop');
1668
- store.withTransaction(() => {
1669
- store.updateTaskStatus(taskRecord.id, convoyId, 'review-blocked', { finished_at: finishedAt, output: 'Review budget exceeded', exit_code: 1 });
1670
- store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
1671
- });
1672
- completedCount++;
1673
- process.stdout.write(` ${c.red('✗')} ${c.bold(`[${taskRecord.id}]`)} review budget exceeded (stop) ${elapsed} ${c.dim(`[${completedCount}/${totalTasks}]`)}\n`);
1674
- events.emit('review_verdict', { level: 'fast', verdict: 'skip', tokens: 0, model: reviewerModel, feedback_length: 0, budget_exceeded: true }, { convoy_id: convoyId, task_id: taskRecord.id });
1675
- taskAdapterMap.delete(taskRecord.id);
1676
- return;
1677
- }
1678
- else if (onBudgetExceeded === 'downgrade') {
1679
- store.updateTaskReview(taskRecord.id, convoyId, { review_level: 'fast', review_verdict: 'pass', review_tokens: 0, review_model: reviewerModel });
1680
- events.emit('review_verdict', { level: 'fast', verdict: 'pass', tokens: 0, model: reviewerModel, feedback_length: 0, budget_downgrade: true }, { convoy_id: convoyId, task_id: taskRecord.id });
1681
- }
1682
- else {
1683
- // 'skip': treat as passed
1684
- events.emit('review_verdict', { level: 'fast', verdict: 'pass', tokens: 0, model: reviewerModel, feedback_length: 0, budget_skip: true }, { convoy_id: convoyId, task_id: taskRecord.id });
1685
- }
1686
- }
1687
- else {
1688
- await reviewSemaphore.acquire();
1689
- let reviewResult;
1690
- try {
1691
- if (reviewRunner && spec.defaults?.review_stages !== false) {
1692
- // Two-stage review: spec compliance first, then code quality
1693
- const twoStageResult = await runTwoStageReview(taskRecord, reviewRunner, reviewerModel);
1694
- for (const stage of twoStageResult.stages) {
1695
- events.emit('review_stage_completed', { stage: stage.stage, verdict: stage.verdict, tokens: stage.tokens_used, task_id: taskRecord.id, model: reviewerModel }, { convoy_id: convoyId, task_id: taskRecord.id });
1696
- }
1697
- reviewResult = {
1698
- verdict: twoStageResult.overall_verdict,
1699
- feedback: twoStageResult.stages.flatMap(s => s.issues).join('\n'),
1700
- tokens: twoStageResult.total_tokens,
1701
- model: reviewerModel,
1702
- };
1703
- }
1704
- else if (reviewRunner) {
1705
- reviewResult = await reviewRunner(taskRecord, 'fast', reviewerModel);
1706
- }
1707
- else {
1708
- reviewResult = { verdict: 'pass', feedback: '', tokens: 0, model: reviewerModel };
1709
- }
1710
- }
1711
- finally {
1712
- reviewSemaphore.release();
1713
- }
1714
- reviewTokensTotal += reviewResult.tokens;
1715
- store.updateTaskReview(taskRecord.id, convoyId, {
1716
- review_level: 'fast',
1717
- review_verdict: reviewResult.verdict,
1718
- review_tokens: reviewResult.tokens,
1719
- review_model: reviewResult.model,
1720
- });
1721
- store.updateConvoyReviewTokens(convoyId, reviewTokensTotal);
1722
- events.emit('review_verdict', { level: 'fast', verdict: reviewResult.verdict, tokens: reviewResult.tokens, model: reviewResult.model, feedback_length: reviewResult.feedback.length }, { convoy_id: convoyId, task_id: taskRecord.id });
1723
- if (reviewResult.verdict === 'block') {
1724
- await removeWorktree();
1725
- const freshRecord = store.getTask(taskRecord.id, convoyId);
1726
- if (freshRecord.retries < freshRecord.max_retries && spec.on_failure !== 'stop') {
1727
- const contextPrefix = `Previous attempt was blocked by review.\nFeedback:\n${reviewResult.feedback}\n\nFix the issues and try again.\n\n`;
1728
- store.updateTaskStatus(taskRecord.id, convoyId, 'pending', {
1729
- retries: freshRecord.retries + 1,
1730
- worker_id: null,
1731
- worktree: null,
1732
- started_at: null,
1733
- finished_at: null,
1734
- prompt: contextPrefix + taskRecord.prompt,
1735
- });
1736
- store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
1737
- process.stdout.write(` ${c.yellow('⟳')} ${c.bold(`[${taskRecord.id}]`)} review blocked, retry ${freshRecord.retries + 1}/${freshRecord.max_retries}\n`);
1738
- taskAdapterMap.delete(taskRecord.id);
1739
- return;
1740
- }
1741
- else {
1742
- store.withTransaction(() => {
1743
- store.updateTaskStatus(taskRecord.id, convoyId, 'review-blocked', {
1744
- finished_at: finishedAt,
1745
- output: `Review blocked: ${reviewResult.feedback}`,
1746
- exit_code: 1,
1747
- });
1748
- store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
1749
- });
1750
- completedCount++;
1751
- process.stdout.write(` ${c.red('✗')} ${c.bold(`[${taskRecord.id}]`)} review blocked ${elapsed} ${c.dim(`[${completedCount}/${totalTasks}]`)}\n`);
1752
- events.emit('task_failed', { reason: 'review-blocked', worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
1753
- handleExhaustion(freshRecord, 'review-blocked', reviewResult.feedback || null);
1754
- taskAdapterMap.delete(taskRecord.id);
1755
- return;
1756
- }
1757
- }
1758
- }
1759
- }
1760
- else {
1761
- // panel: 3 concurrent reviewer calls, majority vote
1762
- await reviewSemaphore.acquire();
1763
- let panelResults;
1764
- try {
1765
- const noopRunner = (_t, _l, m) => Promise.resolve({ verdict: 'pass', feedback: '', tokens: 0, model: m });
1766
- const runner = reviewRunner ?? noopRunner;
1767
- const twoStageEnabled = spec.defaults?.review_stages !== false;
1768
- if (twoStageEnabled && reviewRunner) {
1769
- // Each panel reviewer runs both stages; majority vote on overall_verdict
1770
- const twoStageResults = await Promise.all([
1771
- runTwoStageReview(taskRecord, runner, reviewerModel),
1772
- runTwoStageReview(taskRecord, runner, reviewerModel),
1773
- runTwoStageReview(taskRecord, runner, reviewerModel),
1774
- ]);
1775
- for (const tsr of twoStageResults) {
1776
- for (const stage of tsr.stages) {
1777
- events.emit('review_stage_completed', { stage: stage.stage, verdict: stage.verdict, tokens: stage.tokens_used, task_id: taskRecord.id, model: reviewerModel }, { convoy_id: convoyId, task_id: taskRecord.id });
1778
- }
1779
- }
1780
- panelResults = twoStageResults.map(tsr => ({
1781
- verdict: tsr.overall_verdict,
1782
- feedback: tsr.stages.flatMap(s => s.issues).join('\n'),
1783
- tokens: tsr.total_tokens,
1784
- model: reviewerModel,
1785
- }));
1786
- }
1787
- else {
1788
- panelResults = await Promise.all([
1789
- runner(taskRecord, 'panel', reviewerModel),
1790
- runner(taskRecord, 'panel', reviewerModel),
1791
- runner(taskRecord, 'panel', reviewerModel),
1792
- ]);
1793
- }
1794
- }
1795
- finally {
1796
- reviewSemaphore.release();
1797
- }
1798
- const panelPasses = panelResults.filter(r => r.verdict === 'pass').length;
1799
- const panelBlocks = panelResults.filter(r => r.verdict === 'block').length;
1800
- const totalPanelTokens = panelResults.reduce((sum, r) => sum + r.tokens, 0);
1801
- reviewTokensTotal += totalPanelTokens;
1802
- const freshForPanel = store.getTask(taskRecord.id, convoyId);
1803
- store.updateTaskReview(taskRecord.id, convoyId, {
1804
- review_level: 'panel',
1805
- review_verdict: panelPasses >= 2 ? 'pass' : 'block',
1806
- review_tokens: totalPanelTokens,
1807
- review_model: reviewerModel,
1808
- panel_attempts: freshForPanel.panel_attempts + 1,
1809
- });
1810
- if (totalPanelTokens > 0)
1811
- store.updateConvoyReviewTokens(convoyId, reviewTokensTotal);
1812
- events.emit('review_verdict', { level: 'panel', verdict: panelPasses >= 2 ? 'pass' : 'block', tokens: totalPanelTokens, model: reviewerModel, feedback_length: panelResults.map(r => r.feedback).join('').length, passes: panelPasses, blocks: panelBlocks }, { convoy_id: convoyId, task_id: taskRecord.id });
1813
- if (panelBlocks >= 2) {
1814
- const blockFeedback = panelResults.filter(r => r.verdict === 'block').map(r => r.feedback).join('\n\n---\n\n');
1815
- await removeWorktree();
1816
- // Check for dispute trigger
1817
- const updatedTask = store.getTask(taskRecord.id, convoyId);
1818
- if (updatedTask.panel_attempts >= 3) {
1819
- const disputeId = `dispute-${taskRecord.id}-${Date.now()}`;
1820
- const onDispute = spec.defaults?.on_dispute ?? 'stop';
1821
- store.updateTaskDisputeStatus(taskRecord.id, convoyId, 'disputed', disputeId);
1822
- writeDisputeToMarkdown(disputeId, convoyId, taskRecord, panelResults, basePath, events);
1238
+ events.emit('review_verdict', {
1239
+ level,
1240
+ verdict,
1241
+ tokens: reviewTokens,
1242
+ model,
1243
+ feedback_length: decided.map(r => r.feedback).join('').length,
1244
+ ...(level === 'panel' ? { passes, blocks } : {}),
1245
+ }, { convoy_id: convoyId, task_id: rec.id });
1246
+ if (verdict === 'block') {
1247
+ const feedback = decided.filter(r => r.verdict === 'block').map(r => r.feedback).join('\n\n---\n\n');
1248
+ if (level === 'panel' && freshForPanel.panel_attempts + 1 >= 3) {
1249
+ const disputeId = `dispute-${rec.id}-${Date.now()}`;
1250
+ await cleanup();
1251
+ store.updateTaskDisputeStatus(rec.id, convoyId, 'disputed', disputeId);
1252
+ writeDispute(disputeId, rec, decided, freshForPanel.panel_attempts + 1);
1823
1253
  events.emit('dispute_opened', {
1824
1254
  dispute_id: disputeId,
1825
- task_id: taskRecord.id,
1826
- agent: taskRecord.agent,
1827
- panel_attempts: updatedTask.panel_attempts,
1828
- }, { convoy_id: convoyId, task_id: taskRecord.id });
1829
- if (onDispute === 'stop') {
1830
- const allPending = store.getTasksByConvoy(convoyId).filter(t => t.status === 'pending');
1831
- for (const t of allPending) {
1832
- skipTask(t.id, `on_dispute: stop — task "${taskRecord.id}" disputed`);
1833
- }
1834
- }
1835
- completedCount++;
1836
- process.stdout.write(` ${c.red('⚡')} ${c.bold(`[${taskRecord.id}]`)} disputed after ${updatedTask.panel_attempts} panel attempts\n`);
1837
- taskAdapterMap.delete(taskRecord.id);
1838
- return;
1839
- }
1840
- const freshRecord = store.getTask(taskRecord.id, convoyId);
1841
- if (freshRecord.retries < freshRecord.max_retries && spec.on_failure !== 'stop') {
1842
- const contextPrefix = `Previous attempt was blocked by panel review (${panelBlocks}/3 reviewers).\nMUST-FIX:\n${blockFeedback}\n\nFix the issues and try again.\n\n`;
1843
- store.updateTaskStatus(taskRecord.id, convoyId, 'pending', {
1844
- retries: freshRecord.retries + 1,
1845
- worker_id: null,
1846
- worktree: null,
1847
- started_at: null,
1848
- finished_at: null,
1849
- prompt: contextPrefix + taskRecord.prompt,
1850
- });
1851
- store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
1852
- process.stdout.write(` ${c.yellow('⟳')} ${c.bold(`[${taskRecord.id}]`)} panel blocked (${panelBlocks}/3), retry ${freshRecord.retries + 1}/${freshRecord.max_retries}\n`);
1853
- taskAdapterMap.delete(taskRecord.id);
1854
- return;
1855
- }
1856
- else {
1857
- store.withTransaction(() => {
1858
- store.updateTaskStatus(taskRecord.id, convoyId, 'review-blocked', {
1859
- finished_at: finishedAt,
1860
- output: `Panel review blocked (${panelBlocks}/3): ${blockFeedback}`,
1861
- exit_code: 1,
1862
- });
1863
- store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
1864
- });
1865
- completedCount++;
1866
- process.stdout.write(` ${c.red('✗')} ${c.bold(`[${taskRecord.id}]`)} panel blocked ${elapsed} ${c.dim(`[${completedCount}/${totalTasks}]`)}\n`);
1867
- events.emit('task_failed', { reason: 'review-blocked', worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
1868
- handleExhaustion(freshRecord, 'review-blocked', blockFeedback || null);
1869
- taskAdapterMap.delete(taskRecord.id);
1255
+ task_id: rec.id,
1256
+ agent: rec.agent,
1257
+ panel_attempts: freshForPanel.panel_attempts + 1,
1258
+ reason: firstLine(feedback, 400),
1259
+ }, { convoy_id: convoyId, task_id: rec.id });
1260
+ progress.line(` ${c.red('⚡')} ${c.bold(`[${rec.id}]`)} disputed after ${freshForPanel.panel_attempts + 1} panel reviews`);
1261
+ if ((spec.defaults?.on_dispute ?? 'stop') === 'stop')
1262
+ stopDispatching(`on_dispute: stop — task "${rec.id}" disputed`);
1263
+ cascadeFailure(rec.id);
1870
1264
  return;
1871
1265
  }
1872
- }
1873
- }
1874
- }
1875
- // ── post_task hooks ───────────────────────────────────────────────────
1876
- if (taskHooks.length > 0) {
1877
- const postResult = await runHooks(taskHooks, 'post_task', {
1878
- taskId: taskRecord.id,
1879
- convoyId,
1880
- cwd: worktreePath ?? basePath,
1881
- });
1882
- if (!postResult.passed) {
1883
- await removeWorktree();
1884
- const hookLabel = postResult.failedHook?.name ?? postResult.failedHook?.type ?? 'unknown';
1885
- store.withTransaction(() => {
1886
- store.updateTaskStatus(taskRecord.id, convoyId, 'hook-failed', {
1887
- finished_at: finishedAt,
1888
- output: `post_task hook "${hookLabel}" failed: ${postResult.error ?? ''}`,
1889
- exit_code: 1,
1266
+ return retryOrFail('review-blocked', firstLine(feedback) || 'no reason given', {
1267
+ kind: 'review-blocked',
1268
+ output: `Review blocked: ${firstLine(feedback) || 'no reason given'}\n\n${feedback}`,
1269
+ note: `A reviewer blocked your previous change:\n${feedback}\n\nFix these and finish the task.`,
1890
1270
  });
1891
- store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
1892
- });
1893
- completedCount++;
1894
- process.stdout.write(` ${c.red('✗')} ${c.bold(`[${taskRecord.id}]`)} post_task hook failed ${elapsed} ${c.dim(`[${completedCount}/${totalTasks}]`)}\n`);
1895
- events.emit('task_failed', { reason: 'hook-failed', hook: hookLabel, worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
1896
- cascadeFailure(taskRecord.id);
1897
- taskAdapterMap.delete(taskRecord.id);
1898
- return;
1271
+ }
1899
1272
  }
1900
1273
  }
1901
- // ── Symlink security scan (post-execution) ───────────────────────────
1902
- if (taskFiles.length > 0 && worktreePath) {
1903
- try {
1904
- scanNewSymlinks(worktreePath, taskFiles);
1905
- }
1906
- catch (err) {
1907
- await removeWorktree();
1908
- store.withTransaction(() => {
1909
- store.updateTaskStatus(taskRecord.id, convoyId, 'failed', {
1910
- finished_at: finishedAt,
1911
- output: `Post-execution symlink security check failed: ${err.message}`,
1912
- exit_code: 1,
1913
- });
1914
- store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
1915
- });
1916
- completedCount++;
1917
- events.emit('task_failed', { reason: 'symlink-escape-post', worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
1918
- cascadeFailure(taskRecord.id);
1919
- taskAdapterMap.delete(taskRecord.id);
1920
- return;
1921
- }
1274
+ }
1275
+ // ── post_task hooks and the post-run symlink scan ───────────────────────
1276
+ if (taskHooks.length > 0) {
1277
+ const post = await runHooks(taskHooks, 'post_task', { taskId: rec.id, cwd: wt, taskAdapter });
1278
+ if (!post.passed) {
1279
+ const label = post.failedHook?.name ?? post.failedHook?.type ?? 'unknown';
1280
+ return fail('hook-failed', `post_task hook "${label}" failed: ${post.error ?? ''}`, { kind: 'hook-failed', hook: label });
1922
1281
  }
1923
- if (worktreePath) {
1924
- let mergeAttempt = 0;
1925
- const maxMergeAttempts = 2;
1926
- let merged = false;
1927
- while (mergeAttempt < maxMergeAttempts && !merged) {
1928
- try {
1929
- await mergeQueue.merge(worktreePath, `convoy-${workerId}`, baseBranch);
1930
- merged = true;
1931
- }
1932
- catch (err) {
1933
- if (err instanceof MergeConflictError) {
1934
- mergeAttempt++;
1935
- events.emit('merge_conflict_detected', {
1936
- attempt: mergeAttempt,
1937
- conflicting_files: err.conflictingFiles,
1938
- }, { convoy_id: convoyId, task_id: taskRecord.id });
1939
- if (mergeAttempt >= maxMergeAttempts) {
1940
- events.emit('merge_conflict_failed', {
1941
- attempts: mergeAttempt,
1942
- conflicting_files: err.conflictingFiles,
1943
- }, { convoy_id: convoyId, task_id: taskRecord.id });
1944
- const freshRecord = store.getTask(taskRecord.id, convoyId);
1945
- store.withTransaction(() => {
1946
- store.updateTaskStatus(taskRecord.id, convoyId, 'failed', {
1947
- finished_at: now(),
1948
- output: `Merge conflict could not be resolved after ${mergeAttempt} attempts. Files: ${err.conflictingFiles.join(', ')}`,
1949
- exit_code: 1,
1950
- });
1951
- store.updateWorkerStatus(workerId, 'failed', { finished_at: now() });
1952
- });
1953
- completedCount++;
1954
- process.stdout.write(` ${c.red('✗')} ${c.bold(`[${taskRecord.id}]`)} merge conflict unresolved ${elapsed} ${c.dim(`[${completedCount}/${totalTasks}]`)}\n`);
1955
- events.emit('task_failed', { reason: 'merge-conflict', worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
1956
- cascadeFailure(taskRecord.id);
1957
- handleExhaustion(freshRecord, 'merge-conflict', err.conflictingFiles.join(', '));
1958
- break;
1959
- }
1960
- // Per spec: backoff on second attempt (unreachable with maxMergeAttempts=2 but follows spec)
1961
- if (mergeAttempt === 2) {
1962
- await new Promise(resolve => setTimeout(resolve, 30_000));
1963
- }
1964
- // Inject a resolution task
1965
- const fileHash = createHash('sha256')
1966
- .update(err.conflictingFiles.sort().join(','))
1967
- .digest('hex')
1968
- .slice(0, 12);
1969
- const idempotencyKey = `merge-conflict:${taskRecord.phase}:${fileHash}`;
1970
- const resolutionTaskId = `merge-fix-${taskRecord.id}-${mergeAttempt}`;
1971
- const conflictPrompt = `Resolve merge conflicts in: ${err.conflictingFiles.join(', ')}. Ensure no conflict markers remain (<<<<<<<, =======, >>>>>>>), syntax is valid, no duplicate imports.`;
1972
- const resolutionRecord = {
1973
- id: resolutionTaskId,
1974
- convoy_id: convoyId,
1975
- phase: taskRecord.phase,
1976
- prompt: conflictPrompt,
1977
- agent: taskRecord.agent,
1978
- adapter: null,
1979
- model: null,
1980
- timeout_ms: 600_000,
1981
- status: 'pending',
1982
- worker_id: null,
1983
- worktree: null,
1984
- output: null,
1985
- exit_code: null,
1986
- started_at: null,
1987
- finished_at: null,
1988
- retries: 0,
1989
- max_retries: 1,
1990
- files: JSON.stringify(err.conflictingFiles),
1991
- depends_on: null,
1992
- prompt_tokens: null,
1993
- completion_tokens: null,
1994
- total_tokens: null,
1995
- cost_usd: null,
1996
- gates: null,
1997
- on_exhausted: 'dlq',
1998
- injected: 1,
1999
- provenance: 'merge-conflict',
2000
- idempotency_key: idempotencyKey,
2001
- current_step: null,
2002
- total_steps: null,
2003
- review_level: null,
2004
- review_verdict: null,
2005
- review_tokens: null,
2006
- review_model: null,
2007
- panel_attempts: 0,
2008
- dispute_id: null,
2009
- drift_score: null,
2010
- drift_retried: 0,
2011
- outputs: null,
2012
- inputs: null,
2013
- };
2014
- store.insertInjectedTask(resolutionRecord);
2015
- const storedResolutionRecord = store.getTask(resolutionTaskId, convoyId);
2016
- await executeOneTask(storedResolutionRecord);
2017
- // Next loop iteration will retry the merge
2018
- }
2019
- else {
2020
- // Non-conflict merge error — log warning and continue to done path
2021
- if (verbose) {
2022
- process.stderr.write(`Warning: merge failed for ${taskRecord.id}: ${err.message}\n`);
2023
- }
2024
- merged = true; // Preserve original behavior: continue despite error
2025
- break;
2026
- }
2027
- }
2028
- }
2029
- await removeWorktree();
2030
- if (!merged) {
2031
- taskAdapterMap.delete(taskRecord.id);
2032
- return;
2033
- }
1282
+ }
1283
+ if (files.length > 0) {
1284
+ try {
1285
+ scanNewSymlinks(wt, files);
2034
1286
  }
2035
- const usageExtra = {};
2036
- if (result.usage) {
2037
- if (result.usage.prompt_tokens != null)
2038
- usageExtra.prompt_tokens = result.usage.prompt_tokens;
2039
- if (result.usage.completion_tokens != null)
2040
- usageExtra.completion_tokens = result.usage.completion_tokens;
2041
- if (result.usage.total_tokens != null)
2042
- usageExtra.total_tokens = result.usage.total_tokens;
1287
+ catch (err) {
1288
+ return fail('failed', `Post-execution symlink security check failed: ${err.message}`, { kind: 'symlink-escape-post' });
1289
+ }
1290
+ }
1291
+ // ── Output contract: a warning, never a re-run ──────────────────────────
1292
+ // The re-run used to happen after the first attempt had already merged,
1293
+ // so a missing block ran — and merged — the whole task twice.
1294
+ if (!contractResult.valid) {
1295
+ const missing = contractResult.missing.filter(m => m !== '__contract_block');
1296
+ events.emit('contract_violation', {
1297
+ task_id: rec.id,
1298
+ agent: rec.agent,
1299
+ missing: contractResult.missing,
1300
+ warnings: contractResult.warnings,
1301
+ }, { convoy_id: convoyId, task_id: rec.id });
1302
+ if (verbose) {
1303
+ progress.line(` ${c.dim(` [${rec.id}] no complete output summary${missing.length ? ` (missing ${missing.join(', ')})` : ''}`)}`);
2043
1304
  }
2044
- else {
2045
- // Estimate tokens from prompt/output text length (~4 chars per token)
2046
- const estimatedPrompt = Math.ceil(taskRecord.prompt.length / 4);
2047
- const estimatedCompletion = Math.ceil((result.output?.length ?? 0) / 4);
2048
- usageExtra.prompt_tokens = estimatedPrompt;
2049
- usageExtra.completion_tokens = estimatedCompletion;
2050
- usageExtra.total_tokens = estimatedPrompt + estimatedCompletion;
2051
- if (verbose) {
2052
- process.stdout.write(` ${c.dim('ℹ')} Estimated ${usageExtra.total_tokens} tokens (adapter ${taskAdapter.name} returned no usage data)\n`);
2053
- }
1305
+ }
1306
+ if (ctl.interrupted)
1307
+ return requeue();
1308
+ // ── Merge ───────────────────────────────────────────────────────────────
1309
+ const workerBranch = workerBranchName(workerId);
1310
+ const nothingToMerge = changes !== null && changedFiles.length === 0;
1311
+ if (!nothingToMerge) {
1312
+ try {
1313
+ await mergeQueue.merge(wt, workerBranch, branch);
2054
1314
  }
2055
- // ── Capture outputs as artifacts ────────────────────────────────────────
2056
- if (taskRecord.outputs) {
2057
- const outputs = JSON.parse(taskRecord.outputs);
2058
- for (const output of outputs) {
2059
- let content;
2060
- if (output.type === 'summary') {
2061
- content = result.output.slice(-4096);
2062
- }
2063
- else if (output.type === 'json') {
2064
- const jsonMatch = result.output.match(/```json\n([\s\S]*?)```/);
2065
- content = jsonMatch ? jsonMatch[1].trim() : result.output;
2066
- }
2067
- else {
2068
- content = result.output;
2069
- }
2070
- try {
2071
- store.insertArtifact({
2072
- id: `artifact-${taskRecord.id}-${output.name}-${Date.now()}`,
2073
- convoy_id: convoyId,
2074
- task_id: taskRecord.id,
2075
- name: output.name,
2076
- type: output.type,
2077
- content,
2078
- created_at: new Date().toISOString(),
1315
+ catch (err) {
1316
+ const fresh = store.getTask(rec.id, convoyId) ?? rec;
1317
+ if (err instanceof MergeConflictError) {
1318
+ events.emit('merge_conflict_detected', {
1319
+ attempt,
1320
+ conflicting_files: err.conflictingFiles,
1321
+ }, { convoy_id: convoyId, task_id: rec.id });
1322
+ // Once, from the current tip — which now holds the change it collided
1323
+ // with — and named, so the agent knows what moved under it. Aborting
1324
+ // and handing the conflict to a fresh worktree cut from the old base,
1325
+ // as before, recreated the same conflict every time.
1326
+ if (!conflictReruns.has(rec.id) && fresh.retries < fresh.max_retries) {
1327
+ conflictReruns.add(rec.id);
1328
+ const listed = err.conflictingFiles.join(', ') || 'files another task changed';
1329
+ return retryOrFail('failed', `Merge conflict in ${listed}`, {
1330
+ kind: 'merge-conflict',
1331
+ note: `Your previous change conflicted with work merged while you ran, in: ${listed}.\n` +
1332
+ 'Your worktree now starts from the convoy branch with that work in it. Make your change on top of it — keep what is there.',
2079
1333
  });
2080
1334
  }
2081
- catch (err) {
2082
- if (err instanceof ConvoyArtifactLimitError) {
2083
- events.emit('artifact_limit_reached', {
2084
- task_id: taskRecord.id,
2085
- artifact_name: output.name,
2086
- }, { convoy_id: convoyId, task_id: taskRecord.id });
2087
- }
2088
- else {
2089
- throw err;
2090
- }
2091
- }
2092
1335
  }
1336
+ const conflicting = err instanceof MergeConflictError ? err.conflictingFiles : undefined;
1337
+ const message = err instanceof MergeConflictError
1338
+ ? `conflict in ${conflicting.join(', ') || 'unknown files'}`
1339
+ : err.message;
1340
+ events.emit('merge_failed', {
1341
+ branch: workerBranch,
1342
+ error: message,
1343
+ ...(conflicting ? { conflicting_files: conflicting } : {}),
1344
+ }, { convoy_id: convoyId, task_id: rec.id });
1345
+ return fail('failed', `Merge failed (${message}); the work is kept on branch ${workerBranch}`, {
1346
+ kind: 'merge-failed',
1347
+ keepBranch: workerBranch,
1348
+ failureType: 'merge-failed',
1349
+ });
2093
1350
  }
2094
- // ── Extract filesystem artifacts (Phase 43) ────────────────────────
1351
+ events.emit('task_merged', { branch, files: changedFiles.length }, { convoy_id: convoyId, task_id: rec.id });
1352
+ }
1353
+ await cleanup();
1354
+ if (rec.branch && rec.branch !== workerBranch && wtManager.commitAll) {
1355
+ // A branch kept from an earlier failed merge is superseded now.
2095
1356
  try {
2096
- const fsArtifactRefs = extractArtifactRefs(taskRecord.id, convoyId, result.output);
2097
- if (fsArtifactRefs.length > 0) {
2098
- events.emit('artifacts_extracted', {
2099
- task_id: taskRecord.id,
2100
- count: fsArtifactRefs.length,
2101
- artifacts: fsArtifactRefs.map(r => ({ filename: r.filename, summary: r.summary })),
2102
- }, { convoy_id: convoyId, task_id: taskRecord.id });
2103
- }
2104
- }
2105
- catch (err) {
2106
- process.stderr.write(`[artifacts] Warning: extraction failed for task ${taskRecord.id}: ${err.message}\n`);
1357
+ await git(['branch', '-D', rec.branch], repoRoot);
2107
1358
  }
2108
- // ── Create file artifacts from task file list ────────────────────────
2109
- if (taskRecord.files && !taskRecord.outputs) {
2110
- try {
2111
- const fileList = JSON.parse(taskRecord.files);
2112
- for (const filePath of fileList.slice(0, 20)) {
2113
- try {
2114
- store.insertArtifact({
2115
- id: `artifact-${taskRecord.id}-file-${filePath.replace(/[^a-z0-9]/gi, '-')}-${Date.now()}`,
2116
- convoy_id: convoyId,
2117
- task_id: taskRecord.id,
2118
- name: filePath,
2119
- type: 'file',
2120
- content: '',
2121
- created_at: new Date().toISOString(),
2122
- });
2123
- }
2124
- catch (err) {
2125
- if (err instanceof ConvoyArtifactLimitError)
2126
- break;
2127
- // Other errors are non-critical
2128
- }
2129
- }
1359
+ catch { /* already gone */ }
1360
+ }
1361
+ // ── Outputs and artifacts ──────────────────────────────────────────────
1362
+ if (rec.outputs) {
1363
+ const outputs = JSON.parse(rec.outputs);
1364
+ for (const output of outputs) {
1365
+ let content;
1366
+ if (output.type === 'summary') {
1367
+ content = result.output.slice(-4096);
2130
1368
  }
2131
- catch { /* files not parseable */ }
2132
- }
2133
- // ── Output contract validation ────────────────────────────────────────
2134
- // Validated once, up at the no-op gate, which reads the same block.
2135
- if (!contractResult.valid) {
2136
- const freshRecordForContract = store.getTask(taskRecord.id, convoyId);
2137
- if (freshRecordForContract.retries < freshRecordForContract.max_retries) {
2138
- const retryPrefix = buildContractRetryPrompt(contractResult) + '\n\n';
2139
- store.updateTaskStatus(taskRecord.id, convoyId, 'pending', {
2140
- retries: freshRecordForContract.retries + 1,
2141
- worker_id: null,
2142
- worktree: null,
2143
- started_at: null,
2144
- finished_at: null,
2145
- prompt: retryPrefix + taskRecord.prompt,
2146
- });
2147
- store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
2148
- process.stdout.write(` ${c.yellow('⟳')} ${c.bold(`[${taskRecord.id}]`)} contract retry ${freshRecordForContract.retries + 1}/${freshRecordForContract.max_retries}\n`);
2149
- taskAdapterMap.delete(taskRecord.id);
2150
- return;
1369
+ else if (output.type === 'json') {
1370
+ const jsonMatch = result.output.match(/```json\n([\s\S]*?)```/);
1371
+ content = jsonMatch ? jsonMatch[1].trim() : result.output;
1372
+ }
1373
+ else {
1374
+ content = result.output;
2151
1375
  }
2152
- events.emit('contract_violation', {
2153
- task_id: taskRecord.id,
2154
- agent: taskRecord.agent,
2155
- missing: contractResult.missing,
2156
- warnings: contractResult.warnings,
2157
- }, { convoy_id: convoyId, task_id: taskRecord.id });
2158
- process.stdout.write(` ${c.yellow('⚠')} ${c.bold(`[${taskRecord.id}]`)} contract violation: missing ${contractResult.missing.join(', ')}\n`);
2159
- }
2160
- // ── Intelligence: capture persistent agent identity (Phase 17.2) ─────
2161
- const specTaskForCapture = (spec.tasks ?? []).find(t => t.id === taskRecord.id);
2162
- if (specTaskForCapture?.persistent && result.output) {
2163
1376
  try {
2164
- // Extract last 300 words, cap at 4KB
2165
- const words = result.output.split(/\s+/);
2166
- const lastWords = words.slice(-300).join(' ');
2167
- let summary = lastWords.length > 4096 ? lastWords.slice(-4096) : lastWords;
2168
- // Secret-scan the summary before storing
2169
- const summaryScan = scanForSecrets(summary, `identity:${taskRecord.id}`);
2170
- if (summaryScan.clean) {
2171
- store.insertAgentIdentity({
2172
- id: `identity-${taskRecord.id}-${Date.now()}`,
2173
- agent: taskRecord.agent,
2174
- convoy_id: convoyId,
2175
- task_id: taskRecord.id,
2176
- summary,
2177
- created_at: new Date().toISOString(),
2178
- retention_days: 90,
2179
- });
2180
- events.emit('agent_identity_captured', {
2181
- agent: taskRecord.agent,
2182
- summary_length: summary.length,
2183
- }, { convoy_id: convoyId, task_id: taskRecord.id });
2184
- }
2185
- else {
2186
- events.emit('agent_identity_rejected', {
2187
- agent: taskRecord.agent,
2188
- reason: 'secrets_detected',
2189
- findings_count: summaryScan.findings.length,
2190
- }, { convoy_id: convoyId, task_id: taskRecord.id });
2191
- }
1377
+ store.insertArtifact({
1378
+ id: `artifact-${rec.id}-${output.name}-${Date.now()}`,
1379
+ convoy_id: convoyId,
1380
+ task_id: rec.id,
1381
+ name: output.name,
1382
+ type: output.type,
1383
+ content: redactSecrets(content).text,
1384
+ created_at: now(),
1385
+ });
1386
+ }
1387
+ catch (err) {
1388
+ if (!(err instanceof ConvoyArtifactLimitError))
1389
+ throw err;
1390
+ events.emit('artifact_limit_reached', { task_id: rec.id, limit: 50 }, { convoy_id: convoyId, task_id: rec.id });
2192
1391
  }
2193
- catch { /* non-critical */ }
2194
1392
  }
2195
- const taskModel = taskRecord.model ?? taskAdapter.name;
2196
- const taskCost = calculateCost(taskModel, usageExtra.prompt_tokens, usageExtra.completion_tokens);
2197
- store.withTransaction(() => {
2198
- store.updateTaskStatus(taskRecord.id, convoyId, 'done', {
2199
- finished_at: finishedAt,
2200
- output: result.output,
2201
- exit_code: result.exitCode,
2202
- ...usageExtra,
2203
- model: taskModel,
2204
- cost_usd: taskCost,
2205
- contract_result: JSON.stringify(contractResult),
2206
- });
2207
- store.updateWorkerStatus(workerId, 'done', { finished_at: finishedAt });
2208
- });
2209
- // ── Circuit breaker: record success ────────────────────────────────────
2210
- if (circuitBreakerConfig) {
2211
- circuitBreaker.recordSuccess(taskRecord.agent);
1393
+ }
1394
+ else if (files.length > 0) {
1395
+ for (const filePath of files.slice(0, 20)) {
2212
1396
  try {
2213
- store.updateConvoyCircuitState(convoyId, circuitBreaker.serialize());
1397
+ store.insertArtifact({
1398
+ id: `artifact-${rec.id}-file-${filePath.replace(/[^a-z0-9]/gi, '-')}-${Date.now()}`,
1399
+ convoy_id: convoyId,
1400
+ task_id: rec.id,
1401
+ name: filePath,
1402
+ type: 'file',
1403
+ content: '',
1404
+ created_at: now(),
1405
+ });
1406
+ }
1407
+ catch (err) {
1408
+ if (err instanceof ConvoyArtifactLimitError)
1409
+ break;
2214
1410
  }
2215
- catch { /* non-critical */ }
2216
1411
  }
2217
- completedCount++;
2218
- process.stdout.write(` ${c.green('✓')} ${c.bold(`[${taskRecord.id}]`)} ${elapsed} ${c.dim(`[${completedCount}/${totalTasks}]`)}\n`);
2219
- events.emit('task_done', { exit_code: result.exitCode, worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
2220
- events.emit('session', {
2221
- agent: taskRecord.agent,
2222
- model: taskRecord.model ?? taskAdapter.name,
2223
- task: taskRecord.id,
2224
- outcome: 'success',
2225
- duration_min: Math.round((Date.now() - taskStartTime) / 60_000),
2226
- files_changed: 0,
2227
- retries: taskRecord.retries,
2228
- convoy_id: convoyId,
2229
- }, { convoy_id: convoyId, task_id: taskRecord.id });
2230
- events.emit('delegation', {
2231
- session_id: convoyId,
2232
- agent: taskRecord.agent,
2233
- model: taskRecord.model ?? taskAdapter.name,
2234
- tier: 'standard',
2235
- mechanism: 'convoy',
2236
- outcome: 'success',
2237
- retries: taskRecord.retries,
2238
- phase: taskRecord.phase,
2239
- convoy_id: convoyId,
2240
- }, { convoy_id: convoyId, task_id: taskRecord.id });
2241
- taskAdapterMap.delete(taskRecord.id);
2242
- return;
2243
1412
  }
2244
- // ── Failure ─────────────────────────────────────────────────────────────
2245
- if (typeof taskAdapter.kill === 'function')
2246
- taskAdapter.kill(task);
2247
- await removeWorktree();
2248
- const freshRecord = store.getTask(taskRecord.id, convoyId);
2249
- if (freshRecord.retries < freshRecord.max_retries && spec.on_failure !== 'stop') {
2250
- const failedOutput = result.output || '(no output)';
2251
- const contextPrefix = `Previous attempt failed.\nExit code: ${result.exitCode}\nError output:\n${failedOutput}\n\nFix the issues and try again.\n\n`;
2252
- store.updateTaskStatus(taskRecord.id, convoyId, 'pending', {
2253
- retries: freshRecord.retries + 1,
2254
- worker_id: null,
2255
- worktree: null,
2256
- started_at: null,
2257
- finished_at: null,
2258
- prompt: contextPrefix + taskRecord.prompt,
2259
- });
2260
- store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
2261
- process.stdout.write(` ${c.yellow('⟳')} ${c.bold(`[${taskRecord.id}]`)} retry ${freshRecord.retries + 1}/${freshRecord.max_retries}\n`);
1413
+ try {
1414
+ const refs = extractArtifactRefs(rec.id, convoyId, result.output, repoRoot);
1415
+ if (refs.length > 0) {
1416
+ events.emit('artifacts_extracted', {
1417
+ task_id: rec.id,
1418
+ count: refs.length,
1419
+ artifacts: refs.map(r => ({ filename: r.filename, summary: r.summary })),
1420
+ }, { convoy_id: convoyId, task_id: rec.id });
1421
+ }
2262
1422
  }
2263
- else {
2264
- // Estimate tokens even for failed tasks — you still paid for them
2265
- const estimatedPrompt = Math.ceil(taskRecord.prompt.length / 4);
2266
- const estimatedCompletion = Math.ceil((result.output?.length ?? 0) / 4);
2267
- const failModel = taskRecord.model ?? taskAdapter.name;
2268
- const failCost = calculateCost(failModel, estimatedPrompt, estimatedCompletion);
2269
- store.withTransaction(() => {
2270
- store.updateTaskStatus(taskRecord.id, convoyId, 'failed', {
2271
- finished_at: finishedAt,
2272
- output: result.output,
2273
- exit_code: result.exitCode,
2274
- prompt_tokens: estimatedPrompt,
2275
- completion_tokens: estimatedCompletion,
2276
- total_tokens: estimatedPrompt + estimatedCompletion,
2277
- model: failModel,
2278
- cost_usd: failCost,
2279
- });
2280
- store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
2281
- });
2282
- // ── Circuit breaker: record failure ────────────────────────────────────
2283
- if (circuitBreakerConfig) {
2284
- const { tripped } = circuitBreaker.recordFailure(taskRecord.agent);
2285
- try {
2286
- store.updateConvoyCircuitState(convoyId, circuitBreaker.serialize());
1423
+ catch { /* non-critical */ }
1424
+ if (specTask?.persistent && result.output) {
1425
+ try {
1426
+ const words = result.output.split(/\s+/);
1427
+ const lastWords = words.slice(-300).join(' ');
1428
+ const identitySummary = lastWords.length > 4096 ? lastWords.slice(-4096) : lastWords;
1429
+ const summaryScan = scanForSecrets(identitySummary, `identity:${rec.id}`);
1430
+ if (summaryScan.clean) {
1431
+ store.insertAgentIdentity({
1432
+ id: `identity-${rec.id}-${Date.now()}`,
1433
+ agent: rec.agent,
1434
+ convoy_id: convoyId,
1435
+ task_id: rec.id,
1436
+ summary: identitySummary,
1437
+ created_at: now(),
1438
+ retention_days: 90,
1439
+ });
1440
+ events.emit('agent_identity_captured', { agent: rec.agent, task_id: rec.id }, { convoy_id: convoyId, task_id: rec.id });
2287
1441
  }
2288
- catch { /* non-critical */ }
2289
- if (tripped) {
2290
- events.emit('circuit_breaker_tripped', {
2291
- agent: taskRecord.agent,
2292
- state: circuitBreaker.getState(taskRecord.agent),
2293
- }, { convoy_id: convoyId, task_id: taskRecord.id });
1442
+ else {
1443
+ events.emit('agent_identity_rejected', { agent: rec.agent, task_id: rec.id, reason: 'secrets_detected' }, { convoy_id: convoyId, task_id: rec.id });
2294
1444
  }
2295
1445
  }
2296
- completedCount++;
2297
- process.stdout.write(` ${c.red('✗')} ${c.bold(`[${taskRecord.id}]`)} failed ${elapsed} ${c.dim(`[${completedCount}/${totalTasks}]`)}\n`);
2298
- if (verbose) {
2299
- const outputPreview = result.output.split('\n').slice(0, 5).join('\n');
2300
- process.stdout.write(`${outputPreview}\n`);
1446
+ catch { /* non-critical */ }
1447
+ }
1448
+ // ── Done ────────────────────────────────────────────────────────────────
1449
+ store.withTransaction(() => {
1450
+ store.updateTaskStatus(rec.id, convoyId, 'done', {
1451
+ finished_at: now(),
1452
+ output: redactSecrets(result.output).text,
1453
+ exit_code: result.exitCode,
1454
+ contract_result: JSON.stringify(contractResult),
1455
+ branch: null,
1456
+ retry_note: null,
1457
+ });
1458
+ store.updateWorkerStatus(workerId, 'done', { finished_at: now() });
1459
+ });
1460
+ if (circuitBreakerConfig) {
1461
+ circuitBreaker.recordSuccess(rec.agent);
1462
+ try {
1463
+ store.updateConvoyCircuitState(convoyId, circuitBreaker.serialize());
2301
1464
  }
2302
- events.emit('task_failed', { reason: 'error', exit_code: result.exitCode, worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
2303
- events.emit('session', {
2304
- agent: taskRecord.agent,
2305
- model: taskRecord.model ?? taskAdapter.name,
2306
- task: taskRecord.id,
2307
- outcome: 'failed',
2308
- duration_min: Math.round((Date.now() - taskStartTime) / 60_000),
2309
- files_changed: 0,
2310
- retries: freshRecord.retries,
2311
- convoy_id: convoyId,
2312
- }, { convoy_id: convoyId, task_id: taskRecord.id });
2313
- events.emit('delegation', {
2314
- session_id: convoyId,
2315
- agent: taskRecord.agent,
2316
- model: taskRecord.model ?? taskAdapter.name,
2317
- tier: 'standard',
2318
- mechanism: 'convoy',
2319
- outcome: 'failed',
2320
- retries: freshRecord.retries,
2321
- phase: taskRecord.phase,
2322
- convoy_id: convoyId,
2323
- }, { convoy_id: convoyId, task_id: taskRecord.id });
2324
- handleExhaustion(freshRecord, 'error', result.output || null);
1465
+ catch { /* non-critical */ }
1466
+ }
1467
+ const row = store.getTask(rec.id, convoyId);
1468
+ const cost = formatCost(row.cost_usd, Boolean(row.cost_estimated));
1469
+ progress.line(` ${c.green('✓')} ${c.bold(`[${rec.id}]`)} ${elapsed()}${cost ? c.dim(` · ${cost}`) : ''}`);
1470
+ events.emit('task_done', {
1471
+ exit_code: result.exitCode,
1472
+ worker_id: workerId,
1473
+ tokens: row.total_tokens,
1474
+ cost_usd: row.cost_usd,
1475
+ estimated: Boolean(row.cost_estimated),
1476
+ model: row.model,
1477
+ }, { convoy_id: convoyId, task_id: rec.id, worker_id: workerId });
1478
+ telemetry('success', row.retries, changedFiles.length);
1479
+ }
1480
+ function writeDispute(disputeId, task, panelResults, attempts) {
1481
+ const marker = `<!-- dispute:${disputeId} -->`;
1482
+ const blockingReasons = panelResults.filter(r => r.verdict === 'block').map(r => r.feedback).join('\n\n');
1483
+ const entry = `\n${marker}\n## Dispute: ${task.id}\n\n| Field | Value |\n|-------|-------|\n| Convoy | ${convoyId} |\n| Task | ${task.id} |\n| Date | ${new Date().toISOString()} |\n| Panel attempts | ${attempts} |\n| Agent | ${task.agent} |\n| Status | Open |\n\n**Blocking reasons:**\n\n${redactSecrets(blockingReasons).text}\n`;
1484
+ const scan = scanForSecrets(entry, '.opencastle/DISPUTES.md');
1485
+ if (!scan.clean) {
1486
+ events.emit('secret_leak_prevented', {
1487
+ task_id: task.id,
1488
+ findings_count: scan.findings.length,
1489
+ patterns: scan.findings.map(f => f.pattern),
1490
+ context: 'dispute_markdown_write',
1491
+ }, { convoy_id: convoyId, task_id: task.id });
1492
+ return;
2325
1493
  }
2326
- taskAdapterMap.delete(taskRecord.id);
1494
+ appendLedger(repoRoot, 'DISPUTES.md', marker, entry);
1495
+ }
1496
+ // ── Scheduler: a ready queue, not phase barriers ──────────────────────────
1497
+ //
1498
+ // Waves used to run in fixed batches and the next wave waited for the whole
1499
+ // previous one, so a task whose dependency finished early sat idle behind the
1500
+ // slowest task of its wave. Now any finished task frees its slot and the
1501
+ // ready set is recomputed at once.
1502
+ const slots = typeof spec.concurrency === 'number' && spec.concurrency >= 1
1503
+ ? spec.concurrency
1504
+ : (spec.defaults?.max_swarm_concurrency ?? 4);
1505
+ function prerequisites(t) {
1506
+ // An input names the task that produces it; that is a dependency too.
1507
+ const inputs = t.inputs ? JSON.parse(t.inputs).map(i => i.from) : [];
1508
+ return [...parseJsonList(t.depends_on), ...inputs];
1509
+ }
1510
+ /**
1511
+ * Ready tasks, most-blocking first: a task that others wait on starts before
1512
+ * one nobody needs, and ties keep the spec's order. Picking alphabetically
1513
+ * could leave the run's longest task for the second round.
1514
+ */
1515
+ const specOrder = new Map((spec.tasks ?? []).map((t, i) => [t.id, i]));
1516
+ function readyTasks(all) {
1517
+ const ids = new Set(all.map(t => t.id));
1518
+ const done = new Set(all.filter(t => t.status === 'done').map(t => t.id));
1519
+ const dependents = new Map();
1520
+ for (const t of all) {
1521
+ for (const d of prerequisites(t))
1522
+ dependents.set(d, [...(dependents.get(d) ?? []), t.id]);
1523
+ }
1524
+ const reach = (id, seen = new Set()) => {
1525
+ for (const next of dependents.get(id) ?? []) {
1526
+ if (!seen.has(next)) {
1527
+ seen.add(next);
1528
+ reach(next, seen);
1529
+ }
1530
+ }
1531
+ return seen.size;
1532
+ };
1533
+ return all
1534
+ .filter(t => t.status === 'pending' && !running.has(t.id) && prerequisites(t).every(d => done.has(d) || !ids.has(d)))
1535
+ .map(t => ({ t, weight: reach(t.id), order: specOrder.get(t.id) ?? Number.MAX_SAFE_INTEGER }))
1536
+ .sort((a, b) => b.weight - a.weight || a.order - b.order)
1537
+ .map(x => x.t);
2327
1538
  }
2328
- // ── Main execution loop ───────────────────────────────────────────────────
2329
- let lastPhase = -1;
2330
- const isSwarmMode = spec.concurrency === 'auto';
2331
- const maxSwarmConcurrency = spec.defaults?.max_swarm_concurrency ?? 8;
2332
- let lastInjectPoll = 0;
2333
- const INJECT_POLL_INTERVAL = 2000; // 2 seconds
1539
+ progress.setStatus(() => {
1540
+ const all = store.getTasksByConvoy(convoyId);
1541
+ const names = all.filter(t => running.has(t.id)).map(t => t.id);
1542
+ const queued = all.filter(t => t.status === 'pending' && !running.has(t.id)).length;
1543
+ const done = all.filter(t => t.status === 'done').length;
1544
+ let cost = extraCost;
1545
+ let anyCost = extraCost > 0;
1546
+ let estimated = extraEstimated;
1547
+ for (const t of all) {
1548
+ if (t.cost_usd != null) {
1549
+ cost += t.cost_usd;
1550
+ anyCost = true;
1551
+ }
1552
+ if (t.cost_estimated)
1553
+ estimated = true;
1554
+ }
1555
+ const parts = [
1556
+ names.length > 0 ? names.join(', ') : (ctl.stopDispatch ? 'stopping' : 'idle'),
1557
+ `${queued} queued`,
1558
+ `${done}/${all.length} done`,
1559
+ formatDuration(Date.now() - startTime).replace(/ /g, ''),
1560
+ ];
1561
+ const costText = anyCost ? formatCost(cost, estimated) : null;
1562
+ if (costText)
1563
+ parts.push(costText);
1564
+ return ` ${c.cyan('▸')} ${parts.join(' · ')}`;
1565
+ });
1566
+ let graceTimer;
1567
+ const graceExpired = ctl.interruptedPromise.then(() => new Promise(res => { graceTimer = setTimeout(() => res('grace'), INTERRUPT_GRACE_MS); }));
2334
1568
  try {
2335
- let ready = store.getReadyTasks(convoyId);
2336
- while (ready.length > 0) {
2337
- // Compute effective concurrency for this phase
2338
- const effectiveConcurrency = isSwarmMode
2339
- ? Math.min(ready.length, maxSwarmConcurrency)
2340
- : (typeof spec.concurrency === 'number' ? spec.concurrency : 1);
2341
- for (const t of ready) {
2342
- if (t.phase !== lastPhase) {
2343
- lastPhase = t.phase;
2344
- const tasksInPhase = ready.filter(r => r.phase === t.phase);
2345
- const ids = tasksInPhase.map(r => r.id).join(', ');
2346
- process.stdout.write(`\n ${c.bold(`Phase ${t.phase + 1}:`)} ${c.dim(ids)}\n`);
2347
- if (isSwarmMode) {
2348
- events.emit('swarm_concurrency_update', {
2349
- phase: t.phase,
2350
- pending_count: ready.length,
2351
- effective_concurrency: effectiveConcurrency,
2352
- }, { convoy_id: convoyId });
2353
- }
2354
- }
2355
- }
2356
- for (let i = 0; i < ready.length; i += effectiveConcurrency) {
2357
- // Poll for file-based injection between batches
2358
- const now = Date.now();
2359
- if (now - lastInjectPoll >= INJECT_POLL_INTERVAL) {
2360
- pollInjectFile(convoyId, store, events, basePath);
2361
- lastInjectPoll = now;
1569
+ for (;;) {
1570
+ if (!ctl.stopDispatch) {
1571
+ const all = store.getTasksByConvoy(convoyId);
1572
+ const runningRecords = all.filter(t => running.has(t.id));
1573
+ const startable = pickStartable(readyTasks(all), runningRecords, slots - running.size);
1574
+ for (const t of startable) {
1575
+ const p = runTask(t)
1576
+ .catch(async (err) => {
1577
+ // An unexpected throw fails the one task, not the convoy.
1578
+ const msg = err?.message ?? String(err);
1579
+ try {
1580
+ const row = store.getTask(t.id, convoyId);
1581
+ if (row && (row.status === 'running' || row.status === 'assigned' || row.status === 'pending')) {
1582
+ store.updateTaskStatus(t.id, convoyId, ctl.interrupted ? 'pending' : 'failed', {
1583
+ finished_at: ctl.interrupted ? null : new Date().toISOString(),
1584
+ output: redactSecrets(`Engine error: ${msg}`).text,
1585
+ });
1586
+ if (!ctl.interrupted) {
1587
+ progress.line(` ${c.red('✗')} ${c.bold(`[${t.id}]`)} failed: engine error: ${firstLine(msg)}`);
1588
+ events.emit('task_failed', { reason: 'engine-error', message: firstLine(msg, 400) }, { convoy_id: convoyId, task_id: t.id });
1589
+ cascadeFailure(t.id);
1590
+ }
1591
+ }
1592
+ }
1593
+ catch { /* store closed */ }
1594
+ })
1595
+ .finally(() => { running.delete(t.id); });
1596
+ running.set(t.id, p);
2362
1597
  }
2363
- await Promise.all(ready.slice(i, i + effectiveConcurrency).map(t => executeOneTask(t)));
2364
- }
2365
- // Reset wait-for-input tasks to pending so they are re-evaluated after
2366
- // upstream artifacts may have been captured in this batch
2367
- const waitingTasks = store.getTasksByConvoy(convoyId).filter(t => t.status === 'wait-for-input');
2368
- for (const wt of waitingTasks) {
2369
- store.updateTaskStatus(wt.id, convoyId, 'pending');
2370
1598
  }
2371
- ready = store.getReadyTasks(convoyId);
1599
+ if (running.size === 0)
1600
+ break;
1601
+ const winner = await Promise.race([
1602
+ ...running.values(),
1603
+ ctl.interruptedPromise.then(() => (ctl.interrupted ? graceExpired : undefined)),
1604
+ ]);
1605
+ if (winner === 'grace')
1606
+ break;
2372
1607
  }
2373
1608
  }
2374
1609
  finally {
2375
- healthMonitor.stop();
1610
+ if (graceTimer)
1611
+ clearTimeout(graceTimer);
1612
+ }
1613
+ // ── After the queue ───────────────────────────────────────────────────────
1614
+ if (ctl.interrupted) {
1615
+ return finishInterrupted();
1616
+ }
1617
+ // Tasks never started because dispatch stopped are skipped, with the reason.
1618
+ if (ctl.stopDispatch) {
1619
+ for (const t of store.getTasksByConvoy(convoyId).filter(x => x.status === 'pending')) {
1620
+ skipTask(t.id, 'not started: the run stopped dispatching after a failure');
1621
+ }
1622
+ }
1623
+ for (const t of store.getTasksByConvoy(convoyId).filter(x => x.status === 'pending')) {
1624
+ skipTask(t.id, 'its dependencies never finished');
2376
1625
  }
2377
- // ── Validation gates ──────────────────────────────────────────────────────
1626
+ // ── Run-once gates ────────────────────────────────────────────────────────
1627
+ //
1628
+ // `npm test` and `npm audit` used to run once per task, in each worktree —
1629
+ // N copies of the test suite. They run once, here, on the merged result,
1630
+ // together with the spec's own gates.
2378
1631
  const maxGateRetries = spec.gate_retries ?? 0;
2379
1632
  let gateAttempt = 0;
2380
1633
  let gateResults = [];
2381
- while (gateAttempt <= maxGateRetries) {
2382
- if (!spec.gates || spec.gates.length === 0)
2383
- break;
1634
+ const anyDone = store.getTasksByConvoy(convoyId).some(t => t.status === 'done');
1635
+ const builtInGates = spec.defaults?.built_in_gates ?? {};
1636
+ const pkgScripts = readPackageScripts(workRoot);
1637
+ const wantRegression = Boolean(builtInGates.regression_test);
1638
+ const wantAudit = Boolean(builtInGates.dependency_audit);
1639
+ // npm is the only runner these two know; a project that is not an npm
1640
+ // package is told so once, not failed on a gate it cannot satisfy.
1641
+ const runRegression = wantRegression && pkgScripts !== null && typeof pkgScripts.test === 'string';
1642
+ const runAudit = wantAudit && pkgScripts !== null;
1643
+ const hasGates = (spec.gates?.length ?? 0) > 0 || runRegression || runAudit;
1644
+ const gateTimeoutMs = (builtInGates.gate_timeout ?? spec.defaults?.gate_timeout ?? 300) * 1000;
1645
+ if (wantRegression && !runRegression) {
1646
+ progress.line(` ${c.dim('regression_test is on but there is no "test" script in package.json — skipped')}`);
1647
+ }
1648
+ if (wantAudit && !runAudit) {
1649
+ progress.line(` ${c.dim('dependency_audit is on but there is no package.json — skipped')}`);
1650
+ }
1651
+ while (hasGates && anyDone && !ctl.interrupted) {
2384
1652
  gateResults = [];
2385
- process.stdout.write(`\n ${c.bold(gateAttempt === 0 ? 'Gates:' : `Gates (retry ${gateAttempt}/${maxGateRetries}):`)}\n`);
2386
- for (const command of spec.gates) {
2387
- try {
2388
- // SECURITY: Gate/hook commands come from the .convoy.yml spec file, which is operator-controlled.
2389
- // They are NOT user-supplied and are part of the trusted build configuration.
2390
- await execFile('sh', ['-c', command], { cwd: basePath, maxBuffer: 10 * 1024 * 1024 });
2391
- gateResults.push({ command, exitCode: 0, passed: true });
2392
- process.stdout.write(` ${c.green('✓')} ${c.dim(command)}\n`);
2393
- }
2394
- catch (err) {
2395
- const execErr = err;
2396
- const code = typeof execErr.code === 'number' ? execErr.code : 1;
2397
- const output = [execErr.stderr, execErr.stdout].filter(Boolean).join('\n').trim() || execErr.message || '';
2398
- gateResults.push({ command, exitCode: code, passed: false, output });
2399
- process.stdout.write(` ${c.red('✗')} ${c.dim(command)}\n`);
2400
- }
1653
+ progress.line(`\n ${c.bold(gateAttempt === 0 ? 'Gates:' : `Gates (fix ${gateAttempt}/${maxGateRetries}):`)}`);
1654
+ for (const command of spec.gates ?? []) {
1655
+ const r = await runShell(command, { cwd: workRoot, timeoutMs: gateTimeoutMs, signal: ctl.signal });
1656
+ // A gate the interrupt killed did not fail; nothing is recorded for it.
1657
+ if (ctl.interrupted)
1658
+ break;
1659
+ const output = [r.stderr, r.stdout].filter(Boolean).join('\n').trim();
1660
+ gateResults.push({ command, exitCode: r.code, passed: r.code === 0, ...(r.code !== 0 ? { output } : {}) });
1661
+ events.emit('gate_result', { command, passed: r.code === 0, exit_code: r.code, scope: 'convoy', ...(r.code !== 0 ? { output: output.slice(-2000) } : {}) }, { convoy_id: convoyId });
1662
+ progress.line(` ${r.code === 0 ? c.green('✓') : c.red('✗')} ${c.dim(command)}${r.code !== 0 && output ? `: ${firstLine(output)}` : ''}`);
1663
+ }
1664
+ if (runRegression && !ctl.interrupted) {
1665
+ const reg = await runRegressionTestGate(workRoot, 'npm test', gateTimeoutMs, ctl.signal);
1666
+ gateResults.push({ command: 'npm test', exitCode: reg.passed ? 0 : 1, passed: reg.passed, ...(reg.passed ? {} : { output: reg.output }) });
1667
+ events.emit('built_in_gate_result', { gate: 'regression_test', passed: reg.passed, output: reg.output.slice(-2000) }, { convoy_id: convoyId });
1668
+ progress.line(` ${reg.passed ? c.green('✓') : c.red('✗')} ${c.dim('npm test (regression_test)')}`);
1669
+ }
1670
+ if (runAudit && !ctl.interrupted) {
1671
+ const audit = await runDependencyAuditGate(workRoot, gateTimeoutMs, ctl.signal);
1672
+ gateResults.push({ command: 'npm audit', exitCode: audit.passed ? 0 : 1, passed: audit.passed, ...(audit.passed ? {} : { output: audit.output }) });
1673
+ events.emit('built_in_gate_result', { gate: 'dependency_audit', passed: audit.passed, output: audit.output.slice(-2000) }, { convoy_id: convoyId });
1674
+ progress.line(` ${audit.passed ? c.green('✓') : c.red('✗')} ${c.dim('npm audit (dependency_audit)')}`);
2401
1675
  }
2402
1676
  const failedGates = gateResults.filter(g => !g.passed);
2403
- if (failedGates.length === 0)
2404
- break; // All gates passed
2405
- // Can we retry?
2406
- if (gateAttempt >= maxGateRetries)
2407
- break; // No more retries
2408
- // Create and execute a fix task
1677
+ if (ctl.interrupted || failedGates.length === 0 || gateAttempt >= maxGateRetries)
1678
+ break;
2409
1679
  gateAttempt++;
2410
1680
  const failureSummary = failedGates
2411
- .map(g => `Command: ${g.command}\nExit code: ${g.exitCode}\nOutput:\n${g.output ?? '(no output)'}`)
1681
+ .map(g => `Command: ${g.command}\nExit code: ${g.exitCode}\nOutput:\n${(g.output ?? '(no output)').slice(-4000)}`)
2412
1682
  .join('\n\n---\n\n');
2413
- // Gather files touched by convoy tasks to give the fix agent context
2414
- const allTasks = store.getTasksByConvoy(convoyId);
2415
- const touchedFiles = allTasks
2416
- .filter(t => t.files)
2417
- .flatMap(t => { try {
2418
- return JSON.parse(t.files);
2419
- }
2420
- catch {
2421
- return [];
2422
- } });
1683
+ const touchedFiles = store.getTasksByConvoy(convoyId).flatMap(t => parseJsonList(t.files));
2423
1684
  const filesContext = touchedFiles.length > 0
2424
- ? `\n\nFiles modified by the convoy tasks:\n${touchedFiles.map(f => `- ${f}`).join('\n')}\n`
1685
+ ? `\n\nFiles changed by the convoy's tasks:\n${touchedFiles.map(f => `- ${f}`).join('\n')}\n`
2425
1686
  : '';
2426
- const fixPrompt = `The following validation gates failed after all convoy tasks completed. Fix the issues so these commands pass.${filesContext}\n\n${failureSummary}`;
2427
1687
  const fixTaskId = `gate-fix-${gateAttempt}`;
2428
- process.stdout.write(`\n ${c.yellow('⟳')} ${c.bold(`[${fixTaskId}]`)} fixing gate failures (attempt ${gateAttempt}/${maxGateRetries})\n`);
1688
+ progress.line(`\n ${c.yellow('⟳')} ${c.bold(`[${fixTaskId}]`)} fixing the failed gates (attempt ${gateAttempt}/${maxGateRetries})`);
2429
1689
  const fixTask = {
2430
1690
  id: fixTaskId,
2431
- prompt: fixPrompt,
1691
+ prompt: `${sharedContext}\n\n---\n\n## Your task: ${fixTaskId}\nThese checks failed after every task was merged. Fix the code so they pass.${filesContext}\n\n${failureSummary}\n`,
2432
1692
  agent: spec.defaults?.agent ?? 'developer',
2433
1693
  timeout: spec.defaults?.timeout ?? '30m',
2434
1694
  depends_on: [],
2435
1695
  files: [],
2436
- description: `Auto-fix gate failures (attempt ${gateAttempt})`,
1696
+ description: `Fix gate failures (attempt ${gateAttempt})`,
2437
1697
  max_retries: 0,
2438
1698
  };
2439
- const fixResult = await adapter.execute(fixTask, { verbose, cwd: basePath, permissionMode: spec.defaults?.permission_mode });
2440
- if (fixResult.success) {
2441
- process.stdout.write(` ${c.green('✓')} ${c.bold(`[${fixTaskId}]`)} fix applied\n`);
1699
+ const fixResult = await runAgent(fixTaskId, adapter, fixTask, { cwd: workRoot, permissionMode }, parseTimeout(fixTask.timeout));
1700
+ const fixUsage = usageOf(fixResult, fixTask.prompt, spec.defaults?.model ?? null);
1701
+ extraTokens += fixUsage.total;
1702
+ extraCost += fixUsage.cost ?? 0;
1703
+ extraEstimated = extraEstimated || fixUsage.estimated;
1704
+ if (ctl.interrupted)
1705
+ break;
1706
+ if (!fixResult.success) {
1707
+ progress.line(` ${c.red('✗')} ${c.bold(`[${fixTaskId}]`)} the fix attempt failed: ${firstLine(fixResult.output)}`);
1708
+ break;
2442
1709
  }
2443
- else {
2444
- process.stdout.write(` ${c.red('✗')} ${c.bold(`[${fixTaskId}]`)} fix failed\n`);
2445
- break; // Don't retry if the fix task itself fails
1710
+ if (wtManager.commitAll) {
1711
+ try {
1712
+ await commitAllIn(workRoot, `convoy: fix gates (attempt ${gateAttempt})`);
1713
+ }
1714
+ catch (err) {
1715
+ progress.line(` ${c.red('✗')} could not commit the gate fix: ${firstLine(err.message)}`);
1716
+ break;
1717
+ }
2446
1718
  }
1719
+ progress.line(` ${c.green('✓')} ${c.bold(`[${fixTaskId}]`)} fix applied`);
2447
1720
  }
1721
+ if (ctl.interrupted)
1722
+ return finishInterrupted();
2448
1723
  // ── post_convoy hooks ─────────────────────────────────────────────────────
2449
1724
  const specLevelHooks = spec.hooks ?? [];
2450
1725
  if (specLevelHooks.length > 0) {
2451
- const postConvoyResult = await runHooks(specLevelHooks, 'post_convoy', {
2452
- convoyId,
2453
- cwd: basePath,
2454
- });
2455
- if (!postConvoyResult.passed) {
2456
- const hookLabel = postConvoyResult.failedHook?.name ?? postConvoyResult.failedHook?.type ?? 'unknown';
2457
- events.emit('post_convoy_hook_failed', {
2458
- hook: hookLabel,
2459
- error: postConvoyResult.error,
2460
- }, { convoy_id: convoyId });
2461
- process.stdout.write(` ${c.red('✗')} post_convoy hook "${hookLabel}" failed\n`);
1726
+ const post = await runHooks(specLevelHooks, 'post_convoy', { cwd: workRoot });
1727
+ if (!post.passed) {
1728
+ const hookLabel = post.failedHook?.name ?? post.failedHook?.type ?? 'unknown';
1729
+ events.emit('post_convoy_hook_failed', { hook: hookLabel, error: post.error }, { convoy_id: convoyId });
1730
+ progress.line(` ${c.red('✗')} post_convoy hook "${hookLabel}" failed: ${firstLine(post.error)}`);
2462
1731
  }
2463
1732
  }
2464
- // ── Intelligence: post-convoy consolidation ──────────────────────────────
2465
- // ── Final status & summary ────────────────────────────────────────────────
1733
+ // ── Final status ──────────────────────────────────────────────────────────
2466
1734
  const allTasksFinal = store.getTasksByConvoy(convoyId);
2467
- const summary = {
2468
- total: allTasksFinal.length,
2469
- done: allTasksFinal.filter(t => t.status === 'done').length,
2470
- failed: allTasksFinal.filter(t => t.status === 'failed' || t.status === 'gate-failed' || t.status === 'review-blocked' || t.status === 'disputed').length,
2471
- skipped: allTasksFinal.filter(t => t.status === 'skipped').length,
2472
- timedOut: allTasksFinal.filter(t => t.status === 'timed-out').length,
2473
- };
1735
+ const summary = summarize(allTasksFinal);
2474
1736
  const anyGateFailed = gateResults.some(g => !g.passed);
2475
- const finalStatus = anyGateFailed
2476
- ? 'gate-failed'
2477
- : summary.failed > 0 || summary.timedOut > 0
2478
- ? 'failed'
2479
- : 'done';
2480
- // Aggregate token usage and cost across completed tasks
2481
- let convoyTotalTokens = null;
2482
- let convoyTotalCost = null;
2483
- for (const t of allTasksFinal) {
2484
- if (t.total_tokens != null) {
2485
- convoyTotalTokens = (convoyTotalTokens ?? 0) + t.total_tokens;
2486
- }
2487
- if (t.cost_usd != null) {
2488
- convoyTotalCost = (convoyTotalCost ?? 0) + (typeof t.cost_usd === 'number' ? t.cost_usd : parseFloat(t.cost_usd));
2489
- }
2490
- }
2491
- store.updateConvoyStatus(convoyId, finalStatus, {
2492
- finished_at: new Date().toISOString(),
2493
- total_tokens: convoyTotalTokens,
2494
- total_cost_usd: convoyTotalCost,
2495
- });
1737
+ const notDone = allTasksFinal.filter(t => t.status !== 'done');
1738
+ // A skipped task is not done: the run is not finished while one remains.
1739
+ const finalStatus = anyGateFailed ? 'gate-failed' : notDone.length > 0 ? 'failed' : 'done';
1740
+ const totals = persistTotals(allTasksFinal, finalStatus);
2496
1741
  if (finalStatus === 'done') {
2497
1742
  events.emit('convoy_finished', { status: 'done' }, { convoy_id: convoyId });
2498
1743
  }
2499
1744
  else {
2500
- events.emit('convoy_failed', { status: finalStatus, reason: finalStatus === 'gate-failed' ? 'Gate check failed' : 'One or more tasks failed' }, { convoy_id: convoyId });
2501
- }
2502
- // Run convoy guard checks
2503
- const guardResult = runConvoyGuard(store, convoyId, wtManager, ndjsonPath, spec.guard);
2504
- if (guardResult.warnings.length > 0) {
2505
- process.stdout.write(`\n ${c.yellow('Guard warnings:')}\n`);
2506
- for (const w of guardResult.warnings) {
2507
- process.stdout.write(` ${c.dim('⚠')} ${w}\n`);
2508
- }
2509
- events.emit('convoy_guard', {
2510
- passed: guardResult.passed,
2511
- warnings: guardResult.warnings,
1745
+ events.emit('convoy_failed', {
1746
+ status: finalStatus,
1747
+ reason: anyGateFailed ? 'Gate check failed' : `${notDone.length} task(s) not done`,
2512
1748
  }, { convoy_id: convoyId });
2513
1749
  }
1750
+ const guard = runConvoyGuard(store, convoyId, wtManager, ndjsonPath, spec.guard);
1751
+ if (guard.warnings.length > 0) {
1752
+ events.emit('convoy_guard', { passed: guard.passed, warnings: guard.warnings }, { convoy_id: convoyId });
1753
+ if (verbose)
1754
+ for (const w of guard.warnings)
1755
+ progress.line(` ${c.dim(`guard: ${w}`)}`);
1756
+ }
2514
1757
  return {
2515
1758
  convoyId,
2516
1759
  status: finalStatus,
2517
1760
  summary,
2518
1761
  duration: formatDuration(Date.now() - startTime),
2519
- gateResults: spec.gates && spec.gates.length > 0 ? gateResults : undefined,
2520
- cost: convoyTotalTokens != null || convoyTotalCost != null
2521
- ? { total_tokens: convoyTotalTokens ?? 0, total_cost_usd: convoyTotalCost ?? undefined }
2522
- : undefined,
1762
+ gateResults: hasGates && gateResults.length > 0 ? gateResults : undefined,
1763
+ cost: totals,
1764
+ exitCode: finalStatus === 'done' ? 0 : 1,
1765
+ branch,
1766
+ baseRef: ctx.baseRef,
1767
+ logPath: ndjsonPath,
1768
+ keptBranches: allTasksFinal.filter(t => t.branch).map(t => ({ taskId: t.id, branch: t.branch })),
2523
1769
  };
1770
+ function summarize(tasks) {
1771
+ return {
1772
+ total: tasks.length,
1773
+ done: tasks.filter(t => t.status === 'done').length,
1774
+ failed: tasks.filter(t => ['failed', 'gate-failed', 'review-blocked', 'disputed', 'hook-failed'].includes(t.status)).length,
1775
+ skipped: tasks.filter(t => t.status === 'skipped').length,
1776
+ timedOut: tasks.filter(t => t.status === 'timed-out').length,
1777
+ };
1778
+ }
1779
+ function persistTotals(tasks, status) {
1780
+ let tokens = extraTokens > 0 ? extraTokens : null;
1781
+ let cost = extraCost > 0 ? extraCost : null;
1782
+ let estimated = extraEstimated;
1783
+ for (const t of tasks) {
1784
+ const taskTokens = (t.total_tokens ?? 0) + (t.review_tokens ?? 0);
1785
+ if (t.total_tokens != null || t.review_tokens)
1786
+ tokens = (tokens ?? 0) + taskTokens;
1787
+ if (t.cost_usd != null)
1788
+ cost = (cost ?? 0) + t.cost_usd;
1789
+ if (t.cost_estimated)
1790
+ estimated = true;
1791
+ }
1792
+ store.updateConvoyStatus(convoyId, status, {
1793
+ finished_at: new Date().toISOString(),
1794
+ total_tokens: tokens,
1795
+ total_cost_usd: cost,
1796
+ cost_estimated: estimated,
1797
+ });
1798
+ return tokens != null || cost != null
1799
+ ? { total_tokens: tokens ?? 0, total_cost_usd: cost ?? undefined, estimated }
1800
+ : undefined;
1801
+ }
1802
+ function finishInterrupted() {
1803
+ const requeued = [];
1804
+ for (const t of store.getTasksByConvoy(convoyId)) {
1805
+ if (t.status === 'running' || t.status === 'assigned') {
1806
+ store.updateTaskStatus(t.id, convoyId, 'pending', { worker_id: null, worktree: null, started_at: null });
1807
+ if (t.worker_id) {
1808
+ try {
1809
+ store.updateWorkerStatus(t.worker_id, 'killed', { finished_at: new Date().toISOString() });
1810
+ }
1811
+ catch { /* gone */ }
1812
+ }
1813
+ requeued.push(t.id);
1814
+ }
1815
+ }
1816
+ const all = store.getTasksByConvoy(convoyId);
1817
+ const totals = persistTotals(all, 'interrupted');
1818
+ events.emit('convoy_interrupted', { signal: ctl.interrupted ?? 'abort', requeued }, { convoy_id: convoyId });
1819
+ return {
1820
+ convoyId,
1821
+ status: 'interrupted',
1822
+ summary: summarize(all),
1823
+ duration: formatDuration(Date.now() - startTime),
1824
+ cost: totals,
1825
+ exitCode: 130,
1826
+ branch,
1827
+ baseRef: ctx.baseRef,
1828
+ logPath: ndjsonPath,
1829
+ keptBranches: all.filter(t => t.branch).map(t => ({ taskId: t.id, branch: t.branch })),
1830
+ };
1831
+ }
1832
+ }
1833
+ function readPackageScripts(dir) {
1834
+ try {
1835
+ const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
1836
+ return pkg.scripts ?? {};
1837
+ }
1838
+ catch {
1839
+ return null;
1840
+ }
1841
+ }
1842
+ // ── The summary a run ends with ───────────────────────────────────────────────
1843
+ function printSummary(progress, result, store, repoRoot) {
1844
+ const tasks = store.getTasksByConvoy(result.convoyId);
1845
+ const icon = result.status === 'done' ? c.green('✓') : result.status === 'interrupted' ? c.yellow('■') : c.red('✗');
1846
+ const s = result.summary;
1847
+ const lines = ['', ` ${c.dim('──────────────────────────────────────')}`];
1848
+ lines.push(` ${icon} ${c.bold(`Convoy ${result.status}`)} in ${result.duration} — ${s.done}/${s.total} tasks done` +
1849
+ (s.failed ? `, ${s.failed} failed` : '') + (s.timedOut ? `, ${s.timedOut} timed out` : '') + (s.skipped ? `, ${s.skipped} skipped` : ''));
1850
+ for (const t of tasks.filter(x => x.status !== 'done')) {
1851
+ const why = t.status === 'pending'
1852
+ ? (result.status === 'interrupted' ? 'stopped; runs again on resume' : 'not started')
1853
+ : firstLine(t.output, 120) || t.status;
1854
+ lines.push(` ${c.dim('•')} ${t.id} ${c.dim(`(${t.status})`)}: ${why}`);
1855
+ }
1856
+ if (result.gateResults) {
1857
+ const passed = result.gateResults.filter(g => g.passed).length;
1858
+ lines.push(` Gates: ${passed}/${result.gateResults.length} passed`);
1859
+ for (const g of result.gateResults.filter(x => !x.passed)) {
1860
+ lines.push(` ${c.dim('•')} ${g.command} ${c.dim(`(exit ${g.exitCode})`)}: ${firstLine(g.output, 120) || 'no output'}`);
1861
+ }
1862
+ }
1863
+ if (result.cost) {
1864
+ const cost = formatCost(result.cost.total_cost_usd, Boolean(result.cost.estimated));
1865
+ lines.push(` Spent: ${formatTokens(result.cost.total_tokens)} tokens${result.cost.estimated && !cost ? ' (est.)' : ''}${cost ? ` · ${cost}` : ''}`);
1866
+ }
1867
+ lines.push(` Convoy: ${result.convoyId}`);
1868
+ if (result.branch) {
1869
+ lines.push(` Branch: ${c.bold(result.branch)}${result.baseRef ? c.dim(` (from ${result.baseRef})`) : ''}`);
1870
+ if (s.done > 0) {
1871
+ if (result.baseRef)
1872
+ lines.push(` Review: git diff ${result.baseRef}...${result.branch}`);
1873
+ lines.push(` Merge: git merge ${result.branch}`);
1874
+ }
1875
+ }
1876
+ for (const k of result.keptBranches ?? []) {
1877
+ lines.push(` Kept: ${k.branch} ${c.dim(`— ${k.taskId}'s work, which could not be merged`)}`);
1878
+ }
1879
+ if (result.logPath) {
1880
+ const rel = relative(repoRoot, result.logPath);
1881
+ lines.push(` Log: ${rel.startsWith('..') ? result.logPath : rel}`);
1882
+ }
1883
+ if (result.status !== 'done') {
1884
+ lines.push(` Resume with: ${c.cyan('opencastle convoy resume')}`);
1885
+ }
1886
+ for (const l of lines)
1887
+ progress.line(l);
1888
+ }
1889
+ /**
1890
+ * Refuse a spec the run would fail on, before anything is recorded:
1891
+ * overlapping files within a phase, globs, `..`, an unknown per-task runtime.
1892
+ * These used to surface mid-run, after earlier tasks had merged, or after a
1893
+ * failed row was already written. Exported so `--dry-run` refuses exactly what
1894
+ * a run refuses.
1895
+ */
1896
+ export async function checkConvoyPlan(spec, runAdapterName) {
1897
+ const tasks = spec.tasks ?? [];
1898
+ const partition = validateFilePartitions(tasks, buildPhases(tasks));
1899
+ if (!partition.valid) {
1900
+ const conflictSummary = partition.conflicts
1901
+ .map(cf => `Phase ${cf.phase + 1}: tasks "${cf.taskA}" and "${cf.taskB}" overlap on [${cf.overlapping.join(', ')}]`)
1902
+ .join('\n');
1903
+ throw new Error(`File partition conflicts detected:\n${conflictSummary}`);
1904
+ }
1905
+ const names = new Set(tasks.map(t => t.adapter).filter((a) => Boolean(a) && a !== 'auto' && a !== runAdapterName));
1906
+ for (const name of names) {
1907
+ await getAdapter(name);
1908
+ }
2524
1909
  }
2525
1910
  // ── Factory ───────────────────────────────────────────────────────────────────
2526
1911
  export function createConvoyEngine(options) {
2527
1912
  const { spec, specYaml, adapter, verbose = false } = options;
2528
1913
  const basePath = resolve(options.basePath ?? process.cwd());
2529
1914
  const dbPath = options.dbPath ?? join(basePath, '.opencastle', 'convoy.db');
2530
- async function getCurrentBranch() {
2531
- try {
2532
- const { stdout } = await execFile('git', ['rev-parse', '--abbrev-ref', 'HEAD'], {
2533
- cwd: basePath,
2534
- });
2535
- return stdout.trim();
2536
- }
2537
- catch {
2538
- return 'main';
2539
- }
1915
+ const injectedCheckout = options._convoyWorktreeDir !== undefined || options._ensureBranch !== undefined;
1916
+ /**
1917
+ * The main checkout, where `.opencastle/` lives — never a worktree that is
1918
+ * about to be removed. A caller that supplies its own checkout (tests) says
1919
+ * where with `repoRoot`, or gets `basePath`.
1920
+ */
1921
+ async function resolveRepoRoot() {
1922
+ if (options.repoRoot)
1923
+ return resolve(options.repoRoot);
1924
+ if (injectedCheckout)
1925
+ return basePath;
1926
+ return (await mainRepoRoot(basePath)) ?? basePath;
2540
1927
  }
2541
- async function run() {
2542
- const startTime = Date.now();
2543
- const convoyId = `convoy-${startTime}`;
2544
- const specHash = createHash('sha256').update(specYaml).digest('hex');
2545
- const baseBranch = spec.branch ?? (await getCurrentBranch());
2546
- // Create convoy-level worktree for branch isolation.
2547
- // Skipped when _convoyWorktreeDir is null or _ensureBranch is injected (test mode).
2548
- let effectiveBasePath = basePath;
2549
- let convoyWorktreeDir;
2550
- if (spec.branch !== undefined) {
2551
- const skipWorktree = options._convoyWorktreeDir === null || options._ensureBranch !== undefined;
2552
- if (!skipWorktree) {
2553
- if (typeof options._convoyWorktreeDir === 'string') {
2554
- effectiveBasePath = options._convoyWorktreeDir;
2555
- convoyWorktreeDir = options._convoyWorktreeDir;
2556
- }
2557
- else {
2558
- const worktreeId = `convoy-root-${Date.now()}`;
2559
- convoyWorktreeDir = join(basePath, '.opencastle', 'worktrees', worktreeId);
2560
- mkdirSync(dirname(convoyWorktreeDir), { recursive: true });
2561
- let branchExists = false;
2562
- try {
2563
- await execFile('git', ['rev-parse', '--verify', spec.branch], { cwd: basePath });
2564
- branchExists = true;
2565
- }
2566
- catch { /* branch doesn't exist */ }
2567
- if (branchExists) {
2568
- await execFile('git', ['worktree', 'add', convoyWorktreeDir, spec.branch], { cwd: basePath });
2569
- }
2570
- else {
2571
- await execFile('git', ['worktree', 'add', '-b', spec.branch, convoyWorktreeDir], { cwd: basePath });
2572
- }
2573
- effectiveBasePath = convoyWorktreeDir;
2574
- }
2575
- }
2576
- }
1928
+ function openLock() {
2577
1929
  mkdirSync(dirname(dbPath), { recursive: true });
2578
1930
  const lockDb = new DatabaseSync(dbPath);
2579
1931
  lockDb.exec('PRAGMA journal_mode = WAL');
@@ -2584,15 +1936,14 @@ export function createConvoyEngine(options) {
2584
1936
  started_at TEXT NOT NULL,
2585
1937
  last_heartbeat TEXT NOT NULL
2586
1938
  )`);
2587
- const lock = (() => {
2588
- try {
2589
- return acquireEngineLock(lockDb, dbPath);
2590
- }
2591
- catch (err) {
2592
- lockDb.close();
2593
- throw err;
2594
- }
2595
- })();
1939
+ let lock;
1940
+ try {
1941
+ lock = acquireEngineLock(lockDb, dbPath);
1942
+ }
1943
+ catch (err) {
1944
+ lockDb.close();
1945
+ throw err;
1946
+ }
2596
1947
  const versionRow = lockDb.prepare('SELECT sqlite_version() as v').get();
2597
1948
  const [major, minor] = versionRow.v.split('.').map(Number);
2598
1949
  if (major < 3 || (major === 3 && minor < 35)) {
@@ -2601,36 +1952,145 @@ export function createConvoyEngine(options) {
2601
1952
  throw new Error(`SQLite version ${versionRow.v} is too old. Requires >= 3.35.0`);
2602
1953
  }
2603
1954
  lock.startHeartbeat();
1955
+ return {
1956
+ release() {
1957
+ lock.release();
1958
+ lockDb.close();
1959
+ },
1960
+ };
1961
+ }
1962
+ const validatePlan = () => checkConvoyPlan(spec, adapter.name);
1963
+ /** Stop on SIGINT/SIGTERM or the abort signal; a second Ctrl+C stops at once. */
1964
+ function installInterrupts(ctl, progress) {
1965
+ const disposers = [];
1966
+ const onSignal = (sig) => {
1967
+ if (ctl.interrupted) {
1968
+ // A second Ctrl+C means "now". Agents get SIGKILL through their
1969
+ // adapters; the exit is unavoidable, because the person has said they
1970
+ // will not wait for the cleanup the first signal started. The rows
1971
+ // already read pending or running, and `resume` handles both.
1972
+ for (const fn of ctl.onInterrupt) {
1973
+ try {
1974
+ fn();
1975
+ }
1976
+ catch { /* best effort */ }
1977
+ }
1978
+ process.exit(130);
1979
+ }
1980
+ progress.line(`\n ${c.yellow('■')} ${sig} — stopping: killing running agents, no new tasks. Press Ctrl+C again to quit at once.`);
1981
+ ctl.interrupt(sig);
1982
+ };
1983
+ if (options.handleSignals !== false) {
1984
+ process.on('SIGINT', onSignal);
1985
+ process.on('SIGTERM', onSignal);
1986
+ disposers.push(() => {
1987
+ process.removeListener('SIGINT', onSignal);
1988
+ process.removeListener('SIGTERM', onSignal);
1989
+ });
1990
+ }
1991
+ if (options.signal) {
1992
+ const onAbort = () => ctl.interrupt('abort');
1993
+ if (options.signal.aborted)
1994
+ onAbort();
1995
+ else
1996
+ options.signal.addEventListener('abort', onAbort, { once: true });
1997
+ disposers.push(() => options.signal?.removeEventListener('abort', onAbort));
1998
+ }
1999
+ return () => { for (const d of disposers)
2000
+ d(); };
2001
+ }
2002
+ /** The integration checkout for `branch`, and whether this run owns it. */
2003
+ async function integrationCheckout(repoRoot, branch, base, dirName) {
2004
+ if (typeof options._convoyWorktreeDir === 'string')
2005
+ return { path: resolve(options._convoyWorktreeDir), owned: false };
2006
+ if (injectedCheckout) {
2007
+ // `basePath` is the merge target here. That must never be the user's own
2008
+ // checkout — the main worktree — however the caller got there. (Tests
2009
+ // that inject `_ensureBranch` use a scratch directory and are spared the
2010
+ // git call.)
2011
+ let main;
2012
+ if (options._ensureBranch === undefined) {
2013
+ try {
2014
+ main = (await listAllWorktrees(basePath))[0]?.path;
2015
+ }
2016
+ catch { /* not a git repository */ }
2017
+ }
2018
+ const real = (p) => { try {
2019
+ return realpathSync(p);
2020
+ }
2021
+ catch {
2022
+ return resolve(p);
2023
+ } };
2024
+ if (main && real(main) === real(basePath)) {
2025
+ throw new Error(`Refusing to merge convoy work into ${basePath}, the repository's own checkout. ` +
2026
+ 'Give the convoy a worktree of its branch (_convoyWorktreeDir), or let it create one.');
2027
+ }
2028
+ return { path: basePath, owned: false };
2029
+ }
2030
+ return { path: await ensureRootWorktree({ repoRoot, branch, base, dirName }), owned: true };
2031
+ }
2032
+ /** The branch checked out in the user's own checkout, which a convoy must not merge into. */
2033
+ async function userBranch(repoRoot) {
2034
+ try {
2035
+ const main = (await listAllWorktrees(repoRoot))[0];
2036
+ return main?.branch ? main.branch.replace(/^refs\/heads\//, '') : null;
2037
+ }
2038
+ catch {
2039
+ return null;
2040
+ }
2041
+ }
2042
+ async function run() {
2043
+ const startTime = Date.now();
2044
+ const convoyId = `convoy-${startTime}`;
2045
+ const specHash = createHash('sha256').update(specYaml).digest('hex');
2046
+ await validatePlan();
2047
+ const lock = openLock();
2604
2048
  const store = createConvoyStore(dbPath);
2605
- const ndjsonPath = options.logsDir
2606
- ? join(options.logsDir, 'convoys', `${convoyId}.ndjson`)
2607
- : ndjsonPathForConvoy(convoyId, effectiveBasePath);
2608
- const events = createEventEmitter(store, { ndjsonPath });
2609
- const wtManager = options._worktreeManager ?? createWorktreeManager(effectiveBasePath);
2610
- const mergeQueue = options._mergeQueue ?? createMergeQueue(effectiveBasePath);
2611
- let result;
2049
+ const progress = createProgress({ stream: options.output });
2050
+ const ctl = createRunControl();
2051
+ let events = null;
2052
+ let checkout = null;
2053
+ let repoRoot = basePath;
2054
+ let disposeInterrupts = () => { };
2055
+ let inserted = false;
2612
2056
  try {
2057
+ repoRoot = await resolveRepoRoot();
2058
+ const branch = spec.branch ?? defaultBranchName(spec.name, convoyId);
2059
+ let baseRef = injectedCheckout ? null : await currentRef(basePath);
2060
+ if (!injectedCheckout) {
2061
+ // Work lands on a branch of its own. A spec naming the branch the
2062
+ // user has checked out would have the convoy commit into their tree.
2063
+ const mine = await userBranch(repoRoot);
2064
+ if (mine && mine === branch)
2065
+ throw new BranchInUseError(branch, repoRoot);
2066
+ checkout = await integrationCheckout(repoRoot, branch, baseRef ?? 'HEAD', shortConvoyId(convoyId));
2067
+ }
2068
+ else {
2069
+ checkout = await integrationCheckout(repoRoot, branch, 'HEAD', shortConvoyId(convoyId));
2070
+ baseRef = null;
2071
+ }
2072
+ const ndjsonPath = options.logsDir
2073
+ ? join(options.logsDir, 'convoys', `${convoyId}.ndjson`)
2074
+ : ndjsonPathForConvoy(convoyId, repoRoot);
2075
+ events = createEventEmitter(store, { ndjsonPath });
2076
+ const wtManager = options._worktreeManager ?? createWorktreeManager(repoRoot);
2077
+ const mergeQueue = options._mergeQueue ?? createMergeQueue(checkout.path, { worktreesDir: worktreesDirFor(repoRoot) });
2078
+ // From here on a throw is a crash of this convoy, and its row is marked so.
2079
+ inserted = true;
2613
2080
  store.insertConvoy({
2614
2081
  id: convoyId,
2615
2082
  name: spec.name,
2616
2083
  spec_hash: specHash,
2617
2084
  status: 'pending',
2618
- branch: baseBranch,
2085
+ branch,
2086
+ base_ref: baseRef,
2087
+ adapter: adapter.name,
2619
2088
  created_at: new Date().toISOString(),
2620
2089
  spec_yaml: specYaml,
2621
- pipeline_id: options.pipelineId ?? null,
2090
+ pipeline_id: null,
2622
2091
  });
2623
2092
  const tasks = spec.tasks ?? [];
2624
2093
  const phases = buildPhases(tasks);
2625
- // Validate file partitions before inserting tasks
2626
- const partitionResult = validateFilePartitions(tasks, phases);
2627
- if (!partitionResult.valid) {
2628
- const conflictSummary = partitionResult.conflicts
2629
- .map((cf) => `Phase ${cf.phase}: tasks "${cf.taskA}" and "${cf.taskB}" overlap on [${cf.overlapping.join(', ')}]`)
2630
- .join('\n');
2631
- events.emit('file_partition_conflict', { conflicts: partitionResult.conflicts }, { convoy_id: convoyId });
2632
- throw new Error(`File partition conflicts detected:\n${conflictSummary}`);
2633
- }
2634
2094
  for (let phaseIdx = 0; phaseIdx < phases.length; phaseIdx++) {
2635
2095
  for (const task of phases[phaseIdx]) {
2636
2096
  store.insertTask({
@@ -2653,180 +2113,123 @@ export function createConvoyEngine(options) {
2653
2113
  });
2654
2114
  }
2655
2115
  }
2116
+ const concurrency = typeof spec.concurrency === 'number' ? spec.concurrency : (spec.defaults?.max_swarm_concurrency ?? 4);
2656
2117
  store.updateConvoyStatus(convoyId, 'running', { started_at: new Date().toISOString() });
2657
- events.emit('convoy_started', { name: spec.name }, { convoy_id: convoyId });
2658
- result = await runConvoy(convoyId, spec, adapter, store, events, wtManager, mergeQueue, effectiveBasePath, baseBranch, verbose, startTime, ndjsonPath, options._reviewRunner);
2118
+ events.emit('convoy_started', { name: spec.name, branch, base: baseRef, concurrency }, { convoy_id: convoyId });
2119
+ progress.line(` ${c.dim('Branch')} ${branch}${baseRef ? c.dim(` (from ${baseRef})`) : ''} ${c.dim(`· ${tasks.length} tasks · up to ${concurrency} at once`)}`);
2120
+ disposeInterrupts = installInterrupts(ctl, progress);
2121
+ const result = await runConvoy({
2122
+ convoyId, spec, adapter, store, events, wtManager, mergeQueue, repoRoot,
2123
+ workRoot: checkout.path, branch, baseRef, verbose, startTime, ndjsonPath,
2124
+ reviewRunner: options._reviewRunner ?? defaultReviewer, progress, ctl,
2125
+ });
2126
+ progress.stop();
2127
+ printSummary(progress, result, store, repoRoot);
2128
+ return result;
2659
2129
  }
2660
2130
  catch (err) {
2661
- // Without this, an unexpected throw from runConvoy leaves the convoy row
2662
- // reading 'running' forever, and a later resume() refuses to touch it.
2663
- markConvoyCrashed(store, events, convoyId, err);
2131
+ if (inserted)
2132
+ markConvoyCrashed(store, events, convoyId, err);
2664
2133
  throw err;
2665
2134
  }
2666
2135
  finally {
2667
- events.close();
2136
+ disposeInterrupts();
2137
+ progress.stop();
2138
+ events?.close();
2668
2139
  store.close();
2669
2140
  lock.release();
2670
- lockDb.close();
2671
- if (convoyWorktreeDir) {
2672
- try {
2673
- await execFile('git', ['worktree', 'remove', convoyWorktreeDir, '--force'], { cwd: basePath });
2674
- }
2675
- catch { /* ignore cleanup errors */ }
2676
- }
2141
+ if (checkout?.owned)
2142
+ await removeRootWorktree(repoRoot, checkout.path);
2677
2143
  }
2678
- return result;
2679
2144
  }
2145
+ /**
2146
+ * Continue whatever is not done.
2147
+ *
2148
+ * Everything `retry` used to do happens here: failed, timed-out, gate-failed,
2149
+ * review-blocked, disputed, interrupted (running/assigned) and skipped tasks
2150
+ * go back to pending. A stale integration worktree is reused or pruned, a dead
2151
+ * owner's lock is taken over, and a convoy recorded without a branch of its
2152
+ * own gets one.
2153
+ */
2680
2154
  async function resume(convoyId) {
2681
2155
  const startTime = Date.now();
2682
- mkdirSync(dirname(dbPath), { recursive: true });
2683
- const lockDb = new DatabaseSync(dbPath);
2684
- lockDb.exec('PRAGMA journal_mode = WAL');
2685
- lockDb.exec(`CREATE TABLE IF NOT EXISTS engine_lock (
2686
- id INTEGER PRIMARY KEY CHECK (id = 1),
2687
- pid INTEGER NOT NULL,
2688
- hostname TEXT NOT NULL,
2689
- started_at TEXT NOT NULL,
2690
- last_heartbeat TEXT NOT NULL
2691
- )`);
2692
- const lock = (() => {
2693
- try {
2694
- return acquireEngineLock(lockDb, dbPath);
2695
- }
2696
- catch (err) {
2697
- lockDb.close();
2698
- throw err;
2699
- }
2700
- })();
2701
- const versionRow = lockDb.prepare('SELECT sqlite_version() as v').get();
2702
- const [major, minor] = versionRow.v.split('.').map(Number);
2703
- if (major < 3 || (major === 3 && minor < 35)) {
2704
- lock.release();
2705
- lockDb.close();
2706
- throw new Error(`SQLite version ${versionRow.v} is too old. Requires >= 3.35.0`);
2707
- }
2708
- lock.startHeartbeat();
2156
+ const lock = openLock();
2709
2157
  const store = createConvoyStore(dbPath);
2710
- let effectiveBasePath = basePath;
2711
- let convoyWorktreeDir;
2712
- let events;
2713
- let result;
2158
+ const progress = createProgress({ stream: options.output });
2159
+ const ctl = createRunControl();
2160
+ let events = null;
2161
+ let checkout = null;
2162
+ let repoRoot = basePath;
2163
+ let disposeInterrupts = () => { };
2714
2164
  try {
2715
2165
  const convoy = store.getConvoy(convoyId);
2716
2166
  if (!convoy) {
2717
2167
  throw new Error(`Convoy "${convoyId}" not found in store`);
2718
2168
  }
2719
- const baseBranch = convoy.branch ?? spec.branch ?? (await getCurrentBranch());
2720
- const convoyBranch = convoy.branch ?? spec.branch;
2721
- // Create convoy-level worktree for branch isolation.
2722
- if (convoyBranch !== undefined) {
2723
- const skipWorktree = options._convoyWorktreeDir === null || options._ensureBranch !== undefined;
2724
- if (!skipWorktree) {
2725
- if (typeof options._convoyWorktreeDir === 'string') {
2726
- effectiveBasePath = options._convoyWorktreeDir;
2727
- convoyWorktreeDir = options._convoyWorktreeDir;
2728
- }
2729
- else {
2730
- const worktreeId = `convoy-root-${Date.now()}`;
2731
- convoyWorktreeDir = join(basePath, '.opencastle', 'worktrees', worktreeId);
2732
- mkdirSync(dirname(convoyWorktreeDir), { recursive: true });
2733
- let branchExists = false;
2734
- try {
2735
- await execFile('git', ['rev-parse', '--verify', convoyBranch], { cwd: basePath });
2736
- branchExists = true;
2737
- }
2738
- catch { /* branch doesn't exist */ }
2739
- if (branchExists) {
2740
- await execFile('git', ['worktree', 'add', convoyWorktreeDir, convoyBranch], { cwd: basePath });
2741
- }
2742
- else {
2743
- await execFile('git', ['worktree', 'add', '-b', convoyBranch, convoyWorktreeDir], { cwd: basePath });
2744
- }
2745
- effectiveBasePath = convoyWorktreeDir;
2746
- }
2169
+ repoRoot = await resolveRepoRoot();
2170
+ let branch = convoy.branch ?? spec.branch ?? defaultBranchName(convoy.name, convoyId);
2171
+ let baseRef = convoy.base_ref ?? null;
2172
+ if (!injectedCheckout) {
2173
+ // Older runs recorded the user's own branch here even when the spec
2174
+ // named none, and merged into their checkout. Such a run continues on a
2175
+ // branch of its own, cut from where it left off.
2176
+ const mine = await userBranch(repoRoot);
2177
+ if (!convoy.branch || convoy.branch === mine) {
2178
+ baseRef = convoy.branch ?? (await currentRef(basePath));
2179
+ branch = defaultBranchName(convoy.name, convoyId);
2180
+ store.updateConvoyBranch(convoyId, branch, baseRef);
2181
+ progress.line(` ${c.dim(`This run had no branch of its own; continuing on ${branch}.`)}`);
2747
2182
  }
2748
2183
  }
2749
2184
  const ndjsonPath = options.logsDir
2750
2185
  ? join(options.logsDir, 'convoys', `${convoyId}.ndjson`)
2751
- : ndjsonPathForConvoy(convoyId, effectiveBasePath);
2186
+ : ndjsonPathForConvoy(convoyId, repoRoot);
2752
2187
  events = createEventEmitter(store, { ndjsonPath });
2753
- const wtManager = options._worktreeManager ?? createWorktreeManager(effectiveBasePath);
2754
- const mergeQueue = options._mergeQueue ?? createMergeQueue(effectiveBasePath);
2755
- // Reset interrupted tasks and mark their workers as killed
2756
- const allTasks = store.getTasksByConvoy(convoyId);
2757
- for (const task of allTasks) {
2758
- if (task.status === 'running' || task.status === 'assigned') {
2759
- if (task.worker_id) {
2760
- try {
2761
- store.updateWorkerStatus(task.worker_id, 'killed', {
2762
- finished_at: new Date().toISOString(),
2763
- });
2764
- }
2765
- catch {
2766
- // worker record may already be absent
2767
- }
2768
- }
2769
- store.updateTaskStatus(task.id, convoyId, 'pending', {
2770
- worker_id: null,
2771
- worktree: null,
2772
- started_at: null,
2773
- finished_at: null,
2774
- });
2775
- }
2776
- }
2777
- // Remove all orphaned worktrees from the crashed run
2778
- await wtManager.removeAll();
2779
- // NDJSON recovery: truncate partial lines, replay missing events
2188
+ checkout = await integrationCheckout(repoRoot, branch, baseRef ?? 'HEAD', shortConvoyId(convoyId));
2189
+ const wtManager = options._worktreeManager ?? createWorktreeManager(repoRoot);
2190
+ const mergeQueue = options._mergeQueue ?? createMergeQueue(checkout.path, { worktreesDir: worktreesDirFor(repoRoot) });
2191
+ const reset = resetForResume(store, events, convoyId);
2192
+ // Worktrees left by a run that died — not the integration checkout.
2193
+ await wtManager.removeAll({ except: [checkout.path] });
2780
2194
  recoverNdjson(store, convoyId, ndjsonPath);
2781
- events.emit('convoy_resumed', { original_created_at: convoy.created_at }, { convoy_id: convoyId });
2782
- result = await runConvoy(convoyId, spec, adapter, store, events, wtManager, mergeQueue, effectiveBasePath, baseBranch, verbose, startTime, ndjsonPath, options._reviewRunner);
2195
+ store.updateConvoyStatus(convoyId, 'running', {});
2196
+ events.emit('convoy_resumed', { original_created_at: convoy.created_at, reset }, { convoy_id: convoyId });
2197
+ const pendingCount = store.getTasksByConvoy(convoyId).filter(t => t.status === 'pending').length;
2198
+ progress.line(` ${c.dim('Branch')} ${branch}${baseRef ? c.dim(` (from ${baseRef})`) : ''} ${c.dim(`· ${pendingCount} task(s) to run`)}`);
2199
+ disposeInterrupts = installInterrupts(ctl, progress);
2200
+ const result = await runConvoy({
2201
+ convoyId, spec, adapter, store, events, wtManager, mergeQueue, repoRoot,
2202
+ workRoot: checkout.path, branch, baseRef, verbose, startTime, ndjsonPath,
2203
+ reviewRunner: options._reviewRunner ?? defaultReviewer, progress, ctl,
2204
+ });
2205
+ progress.stop();
2206
+ printSummary(progress, result, store, repoRoot);
2207
+ return result;
2783
2208
  }
2784
2209
  catch (err) {
2785
- markConvoyCrashed(store, events ?? null, convoyId, err);
2210
+ markConvoyCrashed(store, events, convoyId, err);
2786
2211
  throw err;
2787
2212
  }
2788
2213
  finally {
2214
+ disposeInterrupts();
2215
+ progress.stop();
2789
2216
  events?.close();
2790
2217
  store.close();
2791
2218
  lock.release();
2792
- lockDb.close();
2793
- if (convoyWorktreeDir) {
2794
- try {
2795
- await execFile('git', ['worktree', 'remove', convoyWorktreeDir, '--force'], { cwd: basePath });
2796
- }
2797
- catch { /* ignore cleanup errors */ }
2798
- }
2219
+ if (checkout?.owned)
2220
+ await removeRootWorktree(repoRoot, checkout.path);
2799
2221
  }
2800
- return result;
2801
2222
  }
2802
2223
  async function retryFailed(convoyId, taskIds) {
2803
2224
  mkdirSync(dirname(dbPath), { recursive: true });
2804
2225
  const store = createConvoyStore(dbPath);
2226
+ const repoRoot = await resolveRepoRoot();
2805
2227
  const ndjsonPath = options.logsDir
2806
2228
  ? join(options.logsDir, 'convoys', `${convoyId}.ndjson`)
2807
- : ndjsonPathForConvoy(convoyId, basePath);
2229
+ : ndjsonPathForConvoy(convoyId, repoRoot);
2808
2230
  const events = createEventEmitter(store, { ndjsonPath });
2809
2231
  try {
2810
- const allTasks = store.getTasksByConvoy(convoyId);
2811
- const retryableStatuses = ['failed', 'gate-failed', 'timed-out', 'review-blocked', 'disputed'];
2812
- const tasksToRetry = allTasks.filter(t => {
2813
- if (!retryableStatuses.includes(t.status))
2814
- return false;
2815
- if (taskIds && taskIds.length > 0)
2816
- return taskIds.includes(t.id);
2817
- return true;
2818
- });
2819
- for (const task of tasksToRetry) {
2820
- store.updateTaskStatus(task.id, convoyId, 'pending', {
2821
- retries: 0,
2822
- worker_id: null,
2823
- worktree: null,
2824
- started_at: null,
2825
- finished_at: null,
2826
- });
2827
- events.emit('task_retried', { previous_status: task.status }, { convoy_id: convoyId, task_id: task.id });
2828
- }
2829
- // Reset convoy status to running so resume can pick it up
2232
+ resetForResume(store, events, convoyId, taskIds);
2830
2233
  store.updateConvoyStatus(convoyId, 'running', {});
2831
2234
  }
2832
2235
  finally {
@@ -2838,49 +2241,39 @@ export function createConvoyEngine(options) {
2838
2241
  mkdirSync(dirname(dbPath), { recursive: true });
2839
2242
  const store = createConvoyStore(dbPath);
2840
2243
  try {
2841
- // Idempotency check
2842
2244
  if (task.idempotency_key) {
2843
2245
  const existing = store.getTaskByIdempotencyKey(convoyId, task.idempotency_key);
2844
2246
  if (existing)
2845
2247
  return existing;
2846
2248
  }
2847
2249
  const allTasks = store.getTasksByConvoy(convoyId);
2848
- // Check max injectable tasks (10)
2849
2250
  const injectedCount = allTasks.filter(t => t.injected === 1).length;
2850
2251
  if (injectedCount >= 10) {
2851
2252
  throw new Error(`Max injectable tasks (10) reached for convoy ${convoyId}`);
2852
2253
  }
2853
- // Validate ID uniqueness
2854
2254
  if (allTasks.some(t => t.id === task.id)) {
2855
2255
  throw new Error(`Task ID "${task.id}" already exists in convoy ${convoyId}`);
2856
2256
  }
2857
- // Validate depends_on references exist
2858
2257
  const deps = task.depends_on ?? [];
2859
2258
  for (const dep of deps) {
2860
2259
  if (!allTasks.some(t => t.id === dep)) {
2861
2260
  throw new Error(`Dependency "${dep}" not found in convoy ${convoyId}`);
2862
2261
  }
2863
2262
  }
2864
- // Validate no file partition overlap with pending/running tasks
2865
- const taskFiles = task.files ?? [];
2866
- if (taskFiles.length > 0) {
2867
- // Normalize injected task file paths
2868
- const normalizedTaskFiles = taskFiles.map(normalizePath);
2869
- // Symlink pre-scan on injected files
2870
- const basePath = options.basePath ?? process.cwd();
2263
+ const taskFilesIn = task.files ?? [];
2264
+ if (taskFilesIn.length > 0) {
2265
+ const normalizedTaskFiles = taskFilesIn.map(normalizePath);
2871
2266
  try {
2872
2267
  scanSymlinks(normalizedTaskFiles, basePath);
2873
2268
  }
2874
2269
  catch (err) {
2875
2270
  throw new Error(`Injected task "${task.id}" failed symlink check: ${err.message}`);
2876
2271
  }
2877
- // Full partition validation against active tasks
2878
2272
  const activeTasks = allTasks.filter(t => t.status === 'pending' || t.status === 'running' || t.status === 'assigned');
2879
2273
  for (const other of activeTasks) {
2880
- const otherFiles = other.files ? JSON.parse(other.files) : [];
2881
- if (otherFiles.length === 0)
2274
+ const normalizedOther = taskFiles(other);
2275
+ if (normalizedOther.length === 0)
2882
2276
  continue;
2883
- const normalizedOther = otherFiles.map(normalizePath);
2884
2277
  const overlapping = [];
2885
2278
  for (const fileA of normalizedTaskFiles) {
2886
2279
  for (const fileB of normalizedOther) {
@@ -2894,18 +2287,18 @@ export function createConvoyEngine(options) {
2894
2287
  }
2895
2288
  }
2896
2289
  }
2897
- // Detect dependency cycles
2898
2290
  const depGraph = new Map();
2899
- for (const t of allTasks) {
2900
- depGraph.set(t.id, t.depends_on ? JSON.parse(t.depends_on) : []);
2901
- }
2291
+ for (const t of allTasks)
2292
+ depGraph.set(t.id, parseJsonList(t.depends_on));
2902
2293
  depGraph.set(task.id, deps);
2903
- function hasCycle(nodeId, visited, stack) {
2294
+ const visited = new Set();
2295
+ const stack = new Set();
2296
+ const hasCycle = (nodeId) => {
2904
2297
  visited.add(nodeId);
2905
2298
  stack.add(nodeId);
2906
2299
  for (const dep of depGraph.get(nodeId) ?? []) {
2907
2300
  if (!visited.has(dep)) {
2908
- if (hasCycle(dep, visited, stack))
2301
+ if (hasCycle(dep))
2909
2302
  return true;
2910
2303
  }
2911
2304
  else if (stack.has(dep)) {
@@ -2914,17 +2307,12 @@ export function createConvoyEngine(options) {
2914
2307
  }
2915
2308
  stack.delete(nodeId);
2916
2309
  return false;
2917
- }
2918
- const visited = new Set();
2919
- const stack = new Set();
2310
+ };
2920
2311
  for (const nodeId of depGraph.keys()) {
2921
- if (!visited.has(nodeId)) {
2922
- if (hasCycle(nodeId, visited, stack)) {
2923
- throw new Error(`Dependency cycle detected when injecting task "${task.id}"`);
2924
- }
2312
+ if (!visited.has(nodeId) && hasCycle(nodeId)) {
2313
+ throw new Error(`Dependency cycle detected when injecting task "${task.id}"`);
2925
2314
  }
2926
2315
  }
2927
- // Insert the task
2928
2316
  const record = {
2929
2317
  id: task.id,
2930
2318
  convoy_id: convoyId,
@@ -2943,7 +2331,7 @@ export function createConvoyEngine(options) {
2943
2331
  finished_at: null,
2944
2332
  retries: 0,
2945
2333
  max_retries: task.max_retries ?? 1,
2946
- files: taskFiles.length > 0 ? JSON.stringify(taskFiles) : null,
2334
+ files: taskFilesIn.length > 0 ? JSON.stringify(taskFilesIn) : null,
2947
2335
  depends_on: deps.length > 0 ? JSON.stringify(deps) : null,
2948
2336
  prompt_tokens: null,
2949
2337
  completion_tokens: null,
@@ -2976,4 +2364,57 @@ export function createConvoyEngine(options) {
2976
2364
  }
2977
2365
  return { run, resume, retryFailed, injectTask };
2978
2366
  }
2367
+ /**
2368
+ * Put every unfinished task back to pending. Returns the ids it reset.
2369
+ *
2370
+ * With `taskIds`, only those and the tasks skipped because of them. A failed
2371
+ * task gets its retry budget back; an interrupted one keeps the retries it had.
2372
+ */
2373
+ function resetForResume(store, events, convoyId, taskIds) {
2374
+ const all = store.getTasksByConvoy(convoyId);
2375
+ let selected = null;
2376
+ if (taskIds && taskIds.length > 0) {
2377
+ selected = new Set(taskIds);
2378
+ // The dependents a failure skipped come along with it.
2379
+ let grew = true;
2380
+ while (grew) {
2381
+ grew = false;
2382
+ for (const t of all) {
2383
+ if (selected.has(t.id) || t.status !== 'skipped')
2384
+ continue;
2385
+ if (parseJsonList(t.depends_on).some(d => selected.has(d))) {
2386
+ selected.add(t.id);
2387
+ grew = true;
2388
+ }
2389
+ }
2390
+ }
2391
+ }
2392
+ const reset = [];
2393
+ for (const task of all) {
2394
+ if (!RESUME_RESET_STATUSES.includes(task.status))
2395
+ continue;
2396
+ if (selected && !selected.has(task.id))
2397
+ continue;
2398
+ if (task.worker_id && (task.status === 'running' || task.status === 'assigned')) {
2399
+ try {
2400
+ store.updateWorkerStatus(task.worker_id, 'killed', { finished_at: new Date().toISOString() });
2401
+ }
2402
+ catch { /* worker record may already be absent */ }
2403
+ }
2404
+ store.updateTaskStatus(task.id, convoyId, 'pending', {
2405
+ worker_id: null,
2406
+ worktree: null,
2407
+ started_at: null,
2408
+ finished_at: null,
2409
+ ...(FAILED_STATUSES.has(task.status) ? { retries: 0 } : {}),
2410
+ ...(task.status === 'skipped' ? { retry_note: null } : {}),
2411
+ });
2412
+ if (task.status === 'disputed') {
2413
+ store.updateTaskReview(task.id, convoyId, { panel_attempts: 0 });
2414
+ }
2415
+ events.emit('task_retried', { previous_status: task.status }, { convoy_id: convoyId, task_id: task.id });
2416
+ reset.push(task.id);
2417
+ }
2418
+ return reset;
2419
+ }
2979
2420
  //# sourceMappingURL=engine.js.map