@apralabs/apra-fleet 0.4.2 → 0.4.3

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 (370) hide show
  1. package/README.md +38 -5
  2. package/dist/agents/backlog-groomer.md +25 -0
  3. package/dist/agents/ci-watcher.md +11 -0
  4. package/dist/agents/deployer.md +37 -2
  5. package/dist/agents/doer.md +36 -12
  6. package/dist/agents/harvester.md +11 -0
  7. package/dist/agents/integ-test-runner.md +11 -0
  8. package/dist/agents/kb-reconciler.md +9 -0
  9. package/dist/agents/plan-reviewer.md +110 -22
  10. package/dist/agents/planner.md +125 -37
  11. package/dist/agents/regression-test-runner.md +11 -0
  12. package/dist/agents/reviewer.md +13 -2
  13. package/dist/agents/schemas/plan-reviewer-output.json +37 -0
  14. package/dist/cli/agent-transform.d.ts +83 -2
  15. package/dist/cli/agent-transform.d.ts.map +1 -1
  16. package/dist/cli/agent-transform.js +266 -21
  17. package/dist/cli/agent-transform.js.map +1 -1
  18. package/dist/cli/auth.d.ts.map +1 -1
  19. package/dist/cli/auth.js +28 -9
  20. package/dist/cli/auth.js.map +1 -1
  21. package/dist/cli/config.d.ts +7 -5
  22. package/dist/cli/config.d.ts.map +1 -1
  23. package/dist/cli/config.js +44 -34
  24. package/dist/cli/config.js.map +1 -1
  25. package/dist/cli/install.d.ts +33 -0
  26. package/dist/cli/install.d.ts.map +1 -1
  27. package/dist/cli/install.js +290 -23
  28. package/dist/cli/install.js.map +1 -1
  29. package/dist/cli/kb-directives.d.ts.map +1 -1
  30. package/dist/cli/kb-directives.js +2 -1
  31. package/dist/cli/kb-directives.js.map +1 -1
  32. package/dist/cli/register-member.d.ts.map +1 -1
  33. package/dist/cli/register-member.js +6 -2
  34. package/dist/cli/register-member.js.map +1 -1
  35. package/dist/commands/kb-server.d.ts +3 -0
  36. package/dist/commands/kb-server.d.ts.map +1 -1
  37. package/dist/commands/kb-server.js +43 -3
  38. package/dist/commands/kb-server.js.map +1 -1
  39. package/dist/index.js +3 -3
  40. package/dist/os/linux.d.ts +6 -0
  41. package/dist/os/linux.d.ts.map +1 -1
  42. package/dist/os/linux.js +35 -2
  43. package/dist/os/linux.js.map +1 -1
  44. package/dist/os/os-commands.d.ts +61 -2
  45. package/dist/os/os-commands.d.ts.map +1 -1
  46. package/dist/os/windows-gitbash.d.ts +5 -0
  47. package/dist/os/windows-gitbash.d.ts.map +1 -1
  48. package/dist/os/windows-gitbash.js +15 -0
  49. package/dist/os/windows-gitbash.js.map +1 -1
  50. package/dist/os/windows.d.ts +6 -0
  51. package/dist/os/windows.d.ts.map +1 -1
  52. package/dist/os/windows.js +46 -3
  53. package/dist/os/windows.js.map +1 -1
  54. package/dist/providers/agy.d.ts +115 -6
  55. package/dist/providers/agy.d.ts.map +1 -1
  56. package/dist/providers/agy.js +569 -53
  57. package/dist/providers/agy.js.map +1 -1
  58. package/dist/providers/claude.d.ts +81 -3
  59. package/dist/providers/claude.d.ts.map +1 -1
  60. package/dist/providers/claude.js +344 -10
  61. package/dist/providers/claude.js.map +1 -1
  62. package/dist/providers/codex.d.ts +4 -2
  63. package/dist/providers/codex.d.ts.map +1 -1
  64. package/dist/providers/codex.js +19 -2
  65. package/dist/providers/codex.js.map +1 -1
  66. package/dist/providers/copilot.d.ts +4 -2
  67. package/dist/providers/copilot.d.ts.map +1 -1
  68. package/dist/providers/copilot.js +20 -2
  69. package/dist/providers/copilot.js.map +1 -1
  70. package/dist/providers/none.d.ts +4 -2
  71. package/dist/providers/none.d.ts.map +1 -1
  72. package/dist/providers/none.js +17 -2
  73. package/dist/providers/none.js.map +1 -1
  74. package/dist/providers/opencode.d.ts +3 -1
  75. package/dist/providers/opencode.d.ts.map +1 -1
  76. package/dist/providers/opencode.js +22 -2
  77. package/dist/providers/opencode.js.map +1 -1
  78. package/dist/providers/provider.d.ts +201 -6
  79. package/dist/providers/provider.d.ts.map +1 -1
  80. package/dist/providers/provider.js +56 -0
  81. package/dist/providers/provider.js.map +1 -1
  82. package/dist/services/agy-project.d.ts +102 -0
  83. package/dist/services/agy-project.d.ts.map +1 -0
  84. package/dist/services/agy-project.js +356 -0
  85. package/dist/services/agy-project.js.map +1 -0
  86. package/dist/services/auth-socket.js +4 -4
  87. package/dist/services/auth-web.js +1 -1
  88. package/dist/services/cloud/lifecycle.d.ts.map +1 -1
  89. package/dist/services/cloud/lifecycle.js +33 -4
  90. package/dist/services/cloud/lifecycle.js.map +1 -1
  91. package/dist/services/credential-cleanup.d.ts.map +1 -1
  92. package/dist/services/credential-cleanup.js +35 -17
  93. package/dist/services/credential-cleanup.js.map +1 -1
  94. package/dist/services/exit-drain.d.ts +44 -0
  95. package/dist/services/exit-drain.d.ts.map +1 -0
  96. package/dist/services/exit-drain.js +52 -0
  97. package/dist/services/exit-drain.js.map +1 -0
  98. package/dist/services/github-app.d.ts.map +1 -1
  99. package/dist/services/github-app.js +32 -4
  100. package/dist/services/github-app.js.map +1 -1
  101. package/dist/services/http-transport.d.ts +1 -0
  102. package/dist/services/http-transport.d.ts.map +1 -1
  103. package/dist/services/http-transport.js +48 -1
  104. package/dist/services/http-transport.js.map +1 -1
  105. package/dist/services/knowledge/kb-config.d.ts +42 -0
  106. package/dist/services/knowledge/kb-config.d.ts.map +1 -0
  107. package/dist/services/knowledge/kb-config.js +54 -0
  108. package/dist/services/knowledge/kb-config.js.map +1 -0
  109. package/dist/services/knowledge/kb-providers.d.ts +7 -1
  110. package/dist/services/knowledge/kb-providers.d.ts.map +1 -1
  111. package/dist/services/knowledge/kb-providers.js +191 -17
  112. package/dist/services/knowledge/kb-providers.js.map +1 -1
  113. package/dist/services/knowledge/require-sqlite-project.d.ts +32 -0
  114. package/dist/services/knowledge/require-sqlite-project.d.ts.map +1 -0
  115. package/dist/services/knowledge/require-sqlite-project.js +38 -0
  116. package/dist/services/knowledge/require-sqlite-project.js.map +1 -0
  117. package/dist/services/model-pricing.d.ts.map +1 -1
  118. package/dist/services/model-pricing.js +7 -3
  119. package/dist/services/model-pricing.js.map +1 -1
  120. package/dist/services/secret-token.d.ts +38 -0
  121. package/dist/services/secret-token.d.ts.map +1 -0
  122. package/dist/services/secret-token.js +51 -0
  123. package/dist/services/secret-token.js.map +1 -0
  124. package/dist/services/service-manager/types.d.ts +3 -1
  125. package/dist/services/service-manager/types.d.ts.map +1 -1
  126. package/dist/services/service-manager/windows.d.ts +14 -2
  127. package/dist/services/service-manager/windows.d.ts.map +1 -1
  128. package/dist/services/service-manager/windows.js +65 -7
  129. package/dist/services/service-manager/windows.js.map +1 -1
  130. package/dist/services/ssh.d.ts.map +1 -1
  131. package/dist/services/ssh.js +58 -2
  132. package/dist/services/ssh.js.map +1 -1
  133. package/dist/services/stall/read-log-tail.d.ts.map +1 -1
  134. package/dist/services/stall/read-log-tail.js +20 -10
  135. package/dist/services/stall/read-log-tail.js.map +1 -1
  136. package/dist/services/stall/stall-detector.d.ts +53 -4
  137. package/dist/services/stall/stall-detector.d.ts.map +1 -1
  138. package/dist/services/stall/stall-detector.js +212 -34
  139. package/dist/services/stall/stall-detector.js.map +1 -1
  140. package/dist/services/strategy.d.ts.map +1 -1
  141. package/dist/services/strategy.js +79 -2
  142. package/dist/services/strategy.js.map +1 -1
  143. package/dist/services/substitution-engine.js +2 -2
  144. package/dist/services/substitution-engine.js.map +1 -1
  145. package/dist/services/tool-registry.d.ts.map +1 -1
  146. package/dist/services/tool-registry.js +5 -3
  147. package/dist/services/tool-registry.js.map +1 -1
  148. package/dist/services/vcs/azure-devops.d.ts +66 -1
  149. package/dist/services/vcs/azure-devops.d.ts.map +1 -1
  150. package/dist/services/vcs/azure-devops.js +192 -21
  151. package/dist/services/vcs/azure-devops.js.map +1 -1
  152. package/dist/services/vcs/types.d.ts +1 -1
  153. package/dist/skills/fleet-sprint-cli/SKILL.md +18 -0
  154. package/dist/skills/pm/SKILL.md +1 -1
  155. package/dist/skills/pm/cost.md +0 -3
  156. package/dist/skills/pm/fleet-addendum.md +2 -2
  157. package/dist/tools/check-status.d.ts +7 -4
  158. package/dist/tools/check-status.d.ts.map +1 -1
  159. package/dist/tools/check-status.js +2 -0
  160. package/dist/tools/check-status.js.map +1 -1
  161. package/dist/tools/compose-permissions.d.ts +6 -0
  162. package/dist/tools/compose-permissions.d.ts.map +1 -1
  163. package/dist/tools/compose-permissions.js +182 -34
  164. package/dist/tools/compose-permissions.js.map +1 -1
  165. package/dist/tools/credential-store-set.js +1 -1
  166. package/dist/tools/execute-command.d.ts.map +1 -1
  167. package/dist/tools/execute-command.js +31 -20
  168. package/dist/tools/execute-command.js.map +1 -1
  169. package/dist/tools/execute-prompt.d.ts +15 -2
  170. package/dist/tools/execute-prompt.d.ts.map +1 -1
  171. package/dist/tools/execute-prompt.js +1196 -892
  172. package/dist/tools/execute-prompt.js.map +1 -1
  173. package/dist/tools/kb-capture.d.ts +2 -2
  174. package/dist/tools/kb-capture.d.ts.map +1 -1
  175. package/dist/tools/kb-capture.js +29 -5
  176. package/dist/tools/kb-capture.js.map +1 -1
  177. package/dist/tools/kb-export.d.ts +2 -2
  178. package/dist/tools/kb-export.d.ts.map +1 -1
  179. package/dist/tools/kb-export.js +3 -28
  180. package/dist/tools/kb-export.js.map +1 -1
  181. package/dist/tools/kb-feedback.d.ts.map +1 -1
  182. package/dist/tools/kb-feedback.js +3 -1
  183. package/dist/tools/kb-feedback.js.map +1 -1
  184. package/dist/tools/kb-freshness-sweep.d.ts.map +1 -1
  185. package/dist/tools/kb-freshness-sweep.js +3 -1
  186. package/dist/tools/kb-freshness-sweep.js.map +1 -1
  187. package/dist/tools/kb-import.d.ts.map +1 -1
  188. package/dist/tools/kb-import.js +2 -1
  189. package/dist/tools/kb-import.js.map +1 -1
  190. package/dist/tools/kb-list.d.ts.map +1 -1
  191. package/dist/tools/kb-list.js +3 -1
  192. package/dist/tools/kb-list.js.map +1 -1
  193. package/dist/tools/kb-query.d.ts +2 -2
  194. package/dist/tools/kb-reconcile-prefilter.d.ts.map +1 -1
  195. package/dist/tools/kb-reconcile-prefilter.js +3 -1
  196. package/dist/tools/kb-reconcile-prefilter.js.map +1 -1
  197. package/dist/tools/kb-resolve-contradiction.d.ts.map +1 -1
  198. package/dist/tools/kb-resolve-contradiction.js +3 -1
  199. package/dist/tools/kb-resolve-contradiction.js.map +1 -1
  200. package/dist/tools/kb-setup.d.ts.map +1 -1
  201. package/dist/tools/kb-setup.js +125 -20
  202. package/dist/tools/kb-setup.js.map +1 -1
  203. package/dist/tools/kb-stats.d.ts.map +1 -1
  204. package/dist/tools/kb-stats.js +64 -43
  205. package/dist/tools/kb-stats.js.map +1 -1
  206. package/dist/tools/list-members.d.ts +2 -2
  207. package/dist/tools/list-members.d.ts.map +1 -1
  208. package/dist/tools/list-members.js +1 -0
  209. package/dist/tools/list-members.js.map +1 -1
  210. package/dist/tools/member-detail.d.ts +2 -2
  211. package/dist/tools/member-detail.d.ts.map +1 -1
  212. package/dist/tools/member-detail.js +17 -0
  213. package/dist/tools/member-detail.js.map +1 -1
  214. package/dist/tools/member-reservation.d.ts +58 -1
  215. package/dist/tools/member-reservation.d.ts.map +1 -1
  216. package/dist/tools/member-reservation.js +61 -20
  217. package/dist/tools/member-reservation.js.map +1 -1
  218. package/dist/tools/provision-auth.d.ts +80 -1
  219. package/dist/tools/provision-auth.d.ts.map +1 -1
  220. package/dist/tools/provision-auth.js +142 -54
  221. package/dist/tools/provision-auth.js.map +1 -1
  222. package/dist/tools/provision-vcs-auth.d.ts +91 -1
  223. package/dist/tools/provision-vcs-auth.d.ts.map +1 -1
  224. package/dist/tools/provision-vcs-auth.js +209 -49
  225. package/dist/tools/provision-vcs-auth.js.map +1 -1
  226. package/dist/tools/register-member.d.ts +12 -9
  227. package/dist/tools/register-member.d.ts.map +1 -1
  228. package/dist/tools/register-member.js +99 -12
  229. package/dist/tools/register-member.js.map +1 -1
  230. package/dist/tools/remove-member.d.ts.map +1 -1
  231. package/dist/tools/remove-member.js +27 -2
  232. package/dist/tools/remove-member.js.map +1 -1
  233. package/dist/tools/send-email.d.ts +2 -2
  234. package/dist/tools/setup-git-app.d.ts.map +1 -1
  235. package/dist/tools/setup-git-app.js +11 -7
  236. package/dist/tools/setup-git-app.js.map +1 -1
  237. package/dist/tools/shutdown-server.d.ts +2 -0
  238. package/dist/tools/shutdown-server.d.ts.map +1 -1
  239. package/dist/tools/shutdown-server.js +23 -1
  240. package/dist/tools/shutdown-server.js.map +1 -1
  241. package/dist/tools/update-member.d.ts +12 -9
  242. package/dist/tools/update-member.d.ts.map +1 -1
  243. package/dist/tools/update-member.js +43 -11
  244. package/dist/tools/update-member.js.map +1 -1
  245. package/dist/tools/vcs-credential-exec.d.ts +127 -0
  246. package/dist/tools/vcs-credential-exec.d.ts.map +1 -0
  247. package/dist/tools/vcs-credential-exec.js +197 -0
  248. package/dist/tools/vcs-credential-exec.js.map +1 -0
  249. package/dist/types.d.ts +13 -0
  250. package/dist/types.d.ts.map +1 -1
  251. package/dist/utils/log-helpers.d.ts.map +1 -1
  252. package/dist/utils/log-helpers.js +2 -2
  253. package/dist/utils/log-helpers.js.map +1 -1
  254. package/dist/utils/prompt-errors.d.ts.map +1 -1
  255. package/dist/utils/prompt-errors.js +7 -1
  256. package/dist/utils/prompt-errors.js.map +1 -1
  257. package/dist/utils/shell-escape.d.ts +16 -0
  258. package/dist/utils/shell-escape.d.ts.map +1 -1
  259. package/dist/utils/shell-escape.js +22 -2
  260. package/dist/utils/shell-escape.js.map +1 -1
  261. package/dist/utils/vcs-provider-detect.d.ts +65 -0
  262. package/dist/utils/vcs-provider-detect.d.ts.map +1 -0
  263. package/dist/utils/vcs-provider-detect.js +109 -0
  264. package/dist/utils/vcs-provider-detect.js.map +1 -0
  265. package/dist/utils/workspace-trust.d.ts +20 -17
  266. package/dist/utils/workspace-trust.d.ts.map +1 -1
  267. package/dist/utils/workspace-trust.js +87 -1
  268. package/dist/utils/workspace-trust.js.map +1 -1
  269. package/dist/workflows/auto-sprint.js +176 -15
  270. package/package.json +6 -4
  271. package/packages/apra-fleet-client/src/client/api.mjs +319 -17
  272. package/packages/apra-fleet-client/src/client/errors.mjs +6 -2
  273. package/packages/apra-fleet-se/apra-pm/agents/_shared/GRAPH-SEMANTICS.md +10 -2
  274. package/packages/apra-fleet-se/apra-pm/agents/backlog-groomer.md +25 -0
  275. package/packages/apra-fleet-se/apra-pm/agents/ci-watcher.md +11 -0
  276. package/packages/apra-fleet-se/apra-pm/agents/deployer.md +37 -2
  277. package/packages/apra-fleet-se/apra-pm/agents/doer.md +36 -12
  278. package/packages/apra-fleet-se/apra-pm/agents/harvester.md +11 -0
  279. package/packages/apra-fleet-se/apra-pm/agents/integ-test-runner.md +11 -0
  280. package/packages/apra-fleet-se/apra-pm/agents/kb-reconciler.md +9 -0
  281. package/packages/apra-fleet-se/apra-pm/agents/plan-reviewer.md +110 -22
  282. package/packages/apra-fleet-se/apra-pm/agents/planner.md +125 -37
  283. package/packages/apra-fleet-se/apra-pm/agents/regression-test-runner.md +11 -0
  284. package/packages/apra-fleet-se/apra-pm/agents/reviewer.md +13 -2
  285. package/packages/apra-fleet-se/apra-pm/agents/schemas/plan-reviewer-output.json +37 -0
  286. package/packages/apra-fleet-se/apra-pm/skills/pm/SKILL.md +1 -1
  287. package/packages/apra-fleet-se/apra-pm/skills/pm/cost.md +0 -3
  288. package/packages/apra-fleet-se/apra-pm/skills/pm/fleet-addendum.md +2 -2
  289. package/packages/apra-fleet-se/bin/cli.mjs +149 -1
  290. package/packages/apra-fleet-se/bin/serve.mjs +78 -4
  291. package/packages/apra-fleet-se/fleet-sprint/abort.mjs +481 -0
  292. package/packages/apra-fleet-se/fleet-sprint/beads-children.mjs +491 -0
  293. package/packages/apra-fleet-se/fleet-sprint/beads-identity-check.mjs +282 -0
  294. package/packages/apra-fleet-se/fleet-sprint/beads-identity.mjs +208 -0
  295. package/packages/apra-fleet-se/fleet-sprint/beads-scope.mjs +638 -0
  296. package/packages/apra-fleet-se/fleet-sprint/beads-transitions.mjs +301 -0
  297. package/packages/apra-fleet-se/fleet-sprint/branch-ensure.mjs +96 -0
  298. package/packages/apra-fleet-se/fleet-sprint/conflict-ladder.mjs +8 -0
  299. package/packages/apra-fleet-se/fleet-sprint/contracts.mjs +61 -14
  300. package/packages/apra-fleet-se/fleet-sprint/coordination.mjs +516 -0
  301. package/packages/apra-fleet-se/fleet-sprint/dispatch-failure.mjs +184 -0
  302. package/packages/apra-fleet-se/fleet-sprint/dispatch-role.mjs +1121 -0
  303. package/packages/apra-fleet-se/fleet-sprint/dispatch-safety-guard.mjs +216 -4
  304. package/packages/apra-fleet-se/fleet-sprint/docs/README.md +1 -1
  305. package/packages/apra-fleet-se/fleet-sprint/docs/dolt-sync-redesign.md +276 -0
  306. package/packages/apra-fleet-se/fleet-sprint/docs/escalate-to-llm-design.md +1 -1
  307. package/packages/apra-fleet-se/fleet-sprint/docs/run-sprint-cycle-prelude-decision.md +215 -0
  308. package/packages/apra-fleet-se/fleet-sprint/dolt-literal-guard.mjs +56 -1
  309. package/packages/apra-fleet-se/fleet-sprint/dolt-sync.mjs +996 -32
  310. package/packages/apra-fleet-se/fleet-sprint/errors.mjs +267 -0
  311. package/packages/apra-fleet-se/fleet-sprint/explicit-id-create-guard.mjs +501 -0
  312. package/packages/apra-fleet-se/fleet-sprint/fatal-diagnostics.mjs +134 -0
  313. package/packages/apra-fleet-se/fleet-sprint/full-db-fetch-guard.mjs +102 -0
  314. package/packages/apra-fleet-se/fleet-sprint/git-sync.mjs +556 -0
  315. package/packages/apra-fleet-se/fleet-sprint/git-topology.mjs +495 -0
  316. package/packages/apra-fleet-se/fleet-sprint/guarded-modules.mjs +564 -0
  317. package/packages/apra-fleet-se/fleet-sprint/inline-ladder-guard.mjs +216 -0
  318. package/packages/apra-fleet-se/fleet-sprint/kb.mjs +728 -0
  319. package/packages/apra-fleet-se/fleet-sprint/mcp-result.mjs +75 -0
  320. package/packages/apra-fleet-se/fleet-sprint/member-provisioning.mjs +252 -0
  321. package/packages/apra-fleet-se/fleet-sprint/member-sync.mjs +581 -0
  322. package/packages/apra-fleet-se/fleet-sprint/member-target.mjs +93 -0
  323. package/packages/apra-fleet-se/fleet-sprint/newtask-text.mjs +266 -0
  324. package/packages/apra-fleet-se/fleet-sprint/parent-notes-staleness.mjs +201 -0
  325. package/packages/apra-fleet-se/fleet-sprint/phases/deploy.mjs +136 -0
  326. package/packages/apra-fleet-se/fleet-sprint/phases/develop.mjs +822 -0
  327. package/packages/apra-fleet-se/fleet-sprint/phases/ensure-sprint-branch.mjs +294 -0
  328. package/packages/apra-fleet-se/fleet-sprint/phases/final-review.mjs +403 -0
  329. package/packages/apra-fleet-se/fleet-sprint/phases/harvest.mjs +180 -0
  330. package/packages/apra-fleet-se/fleet-sprint/phases/integ-test.mjs +358 -0
  331. package/packages/apra-fleet-se/fleet-sprint/phases/plan.mjs +390 -0
  332. package/packages/apra-fleet-se/fleet-sprint/phases/publish-pr.mjs +323 -0
  333. package/packages/apra-fleet-se/fleet-sprint/phases/re-review.mjs +232 -0
  334. package/packages/apra-fleet-se/fleet-sprint/phases/regression-test.mjs +174 -0
  335. package/packages/apra-fleet-se/fleet-sprint/phases/replan.mjs +197 -0
  336. package/packages/apra-fleet-se/fleet-sprint/phases/review.mjs +305 -0
  337. package/packages/apra-fleet-se/fleet-sprint/prompts.mjs +559 -0
  338. package/packages/apra-fleet-se/fleet-sprint/role-policies.mjs +1416 -0
  339. package/packages/apra-fleet-se/fleet-sprint/round-session.mjs +100 -0
  340. package/packages/apra-fleet-se/fleet-sprint/runner.js +1467 -9798
  341. package/packages/apra-fleet-se/fleet-sprint/se-posix.mjs +17 -12
  342. package/packages/apra-fleet-se/fleet-sprint/shell-command-guard.mjs +304 -0
  343. package/packages/apra-fleet-se/fleet-sprint/skills/fleet-sprint-cli/SKILL.md +18 -0
  344. package/packages/apra-fleet-se/fleet-sprint/skills/fleet-supervisor/SKILL.md +21 -2
  345. package/packages/apra-fleet-se/fleet-sprint/sprint-args.mjs +454 -0
  346. package/packages/apra-fleet-se/fleet-sprint/sprint-report.mjs +239 -0
  347. package/packages/apra-fleet-se/fleet-sprint/sprint-state.mjs +163 -0
  348. package/packages/apra-fleet-se/fleet-sprint/unbracketed-push-guard.mjs +234 -0
  349. package/packages/apra-fleet-se/fleet-sprint/usage-limit-controller.mjs +211 -0
  350. package/packages/apra-fleet-se/fleet-sprint/vcs-auth.mjs +1279 -0
  351. package/packages/apra-fleet-se/fleet-sprint/vcs-module.mjs +153 -19
  352. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/azure-devops.mjs +71 -21
  353. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/bitbucket.mjs +28 -0
  354. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/github.mjs +131 -0
  355. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/index.mjs +140 -16
  356. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/shell-helpers.mjs +1 -0
  357. package/packages/apra-fleet-se/fleet-sprint/viewer-extensions.mjs +77 -2
  358. package/packages/apra-fleet-se/fleet-sprint/worklists.mjs +559 -0
  359. package/packages/apra-fleet-se/package.json +1 -1
  360. package/packages/apra-fleet-workflow/src/viewer/index.mjs +17 -6
  361. package/packages/apra-fleet-workflow/src/workflow/index.mjs +49 -7
  362. package/skills/fleet/SKILL.md +8 -8
  363. package/skills/fleet/auth-azdevops.md +14 -3
  364. package/skills/fleet/auth-bitbucket.md +2 -2
  365. package/skills/fleet/auth-github.md +5 -4
  366. package/skills/fleet/onboarding.md +3 -3
  367. package/skills/fleet/permissions.md +5 -1
  368. package/skills/fleet/profiles/node.json +1 -1
  369. package/skills/fleet/troubleshooting.md +3 -3
  370. package/version.json +1 -1
@@ -51,6 +51,11 @@ import { createScopeGuard, formatScopeConflict } from '../src/supervisor/scope-o
51
51
  import { listFleetMembers, executeFleetCommand } from '../src/supervisor/fleet-members.mjs';
52
52
  import { createDoltOrphanSweep, normalizeMsysPathForPlatform } from '../src/supervisor/dolt-orphan-sweep.mjs';
53
53
  import { resolveFleetServerConnection } from './cli.mjs';
54
+ import {
55
+ discoverBeadsDir, resolveBeadsDirArg, probeBeadsIdentity, createBeadsIdentityState,
56
+ formatNoBeadsWarning, formatProbeFailedWarning,
57
+ } from '../src/supervisor/beads-identity.mjs';
58
+ import { formatBeadsIdentity, serializeExpectedIdentity } from '../fleet-sprint/beads-identity.mjs';
54
59
 
55
60
  const SERVE_USAGE = `
56
61
  Usage: fleet-se serve [options]
@@ -59,8 +64,15 @@ Starts the always-on fleet-sprint supervisor. Runs until POST /api/shutdown or a
59
64
  termination signal (Ctrl-C / SIGTERM).
60
65
 
61
66
  Options:
62
- --port <port> HTTP service port for the supervisor API. Default: ${DEFAULT_SERVICE_PORT}.
63
- -h, --help Show this help message.
67
+ --port <port> HTTP service port for the supervisor API. Default: ${DEFAULT_SERVICE_PORT}.
68
+ --beads-dir <path> Project folder (or its .beads dir) whose beads tracker
69
+ this supervisor runs against. Default: discovered by
70
+ walking up from the current directory, exactly like
71
+ bd does. None found: the supervisor still starts,
72
+ logs a WARNING and reports beads as unknown until
73
+ GET /api/health?refresh=1 finds one. A path that
74
+ does not exist is an error.
75
+ -h, --help Show this help message.
64
76
 
65
77
  Environment:
66
78
  FLEET_SE_DATA_DIR Service data dir (ledger/history/logs).
@@ -112,6 +124,7 @@ export function parseServeArgs(argv) {
112
124
  args: argv,
113
125
  options: {
114
126
  port: { type: 'string' },
127
+ 'beads-dir': { type: 'string' },
115
128
  help: { type: 'boolean', short: 'h' },
116
129
  },
117
130
  strict: true,
@@ -150,6 +163,53 @@ export async function serveMain(argv = process.argv.slice(2)) {
150
163
  }
151
164
  }
152
165
 
166
+ // Which .beads this supervisor runs against -- resolved ONCE, up front,
167
+ // BEFORE any seam is built or the port is bound, so a supervisor started
168
+ // from the wrong folder says so loudly instead of silently serving an
169
+ // empty backlog or dispatching sprints at an unrelated tracker. Every bd
170
+ // the supervisor itself runs (backlog/scope-overlap) resolves by walking
171
+ // up from process.cwd(), so `--beads-dir` is honored by chdir'ing there
172
+ // (nothing sets BEADS_DIR, nothing is persisted); the sprint children
173
+ // below then get repoRoot as their cwd and the resolved identity as
174
+ // --expect-beads.
175
+ //
176
+ // Severity: a `--beads-dir` that does not exist is an operator typo and
177
+ // still a startup ERROR. No .beads reachable from cwd, or a failing
178
+ // identity probe, is an environment condition: a WARNING (with the fix),
179
+ // the identity stays "unknown" (health `beads: null` + `beadsWarning`,
180
+ // amber dashboard header, no --expect-beads handed to sprints -- the
181
+ // engine then verifies members against the orchestrator's own beads),
182
+ // and GET /api/health?refresh=1 can recover it without a restart.
183
+ if (values['beads-dir'] !== undefined) {
184
+ let target;
185
+ try {
186
+ target = resolveBeadsDirArg(values['beads-dir']);
187
+ process.chdir(target);
188
+ } catch (err) {
189
+ console.error(`Error: ${err && err.message ? err.message : err}`);
190
+ return { exitCode: 1 };
191
+ }
192
+ }
193
+ const discovered = discoverBeadsDir({ cwd: process.cwd() });
194
+ const repoRoot = discovered ? discovered.repoRoot : process.cwd();
195
+ let beadsIdentityRecord = null;
196
+ let beadsWarning = null;
197
+ if (!discovered) {
198
+ beadsWarning = formatNoBeadsWarning(process.cwd());
199
+ } else {
200
+ try {
201
+ beadsIdentityRecord = await probeBeadsIdentity({ cwd: repoRoot });
202
+ } catch (err) {
203
+ beadsWarning = formatProbeFailedWarning(repoRoot, err);
204
+ }
205
+ }
206
+ const beadsIdentity = createBeadsIdentityState({ cwd: repoRoot, initial: beadsIdentityRecord, warning: beadsWarning });
207
+ if (beadsIdentityRecord) {
208
+ console.log(`[supervisor] ${formatBeadsIdentity(beadsIdentityRecord, { label: 'supervisor' })}`);
209
+ } else {
210
+ console.warn(`[supervisor] WARNING: ${beadsWarning}`);
211
+ }
212
+
153
213
  // The durable reservation ledger (eft.5.1) and its terminal-event history
154
214
  // (eft.5.4) are the restart-surviving source of truth. Wire them as real
155
215
  // collaborators so a restarted supervisor reconciles against on-disk state.
@@ -191,6 +251,19 @@ export async function serveMain(argv = process.argv.slice(2)) {
191
251
  // discoverable even after the reservation is eventually released.
192
252
  const spawner = createSpawner({
193
253
  serviceUrl: `http://localhost:${port}`,
254
+ // Sprint children run from the project root (the folder holding the
255
+ // discovered .beads, not whatever subfolder the operator started in)
256
+ // and carry the resolved identity so the engine can verify every
257
+ // member's own `bd where` against it (see beads-identity.mjs). Read
258
+ // at each spawn (not captured at startup) so an identity recovered
259
+ // by GET /api/health?refresh=1 reaches later sprints; while it is
260
+ // unknown, --expect-beads is omitted and the engine falls back to
261
+ // the orchestrator member's own identity.
262
+ cwd: repoRoot,
263
+ expectBeads: () => {
264
+ const id = beadsIdentity.get();
265
+ return id ? serializeExpectedIdentity(id) : undefined;
266
+ },
194
267
  onChildExit: async ({ runId, exitCode, signal, at, logPath }) => {
195
268
  if (!runId) return;
196
269
  try {
@@ -261,7 +334,7 @@ export async function serveMain(argv = process.argv.slice(2)) {
261
334
  // Backlog, then the Launch Sprint form (launch-form.mjs attaches itself
262
335
  // via dashboard.mjs's renderIndexPageHtml default; see the import comment
263
336
  // above for why no separate launch-form seam is constructed here).
264
- const dashboard = createDashboard({ ledger, watchdog, backlog });
337
+ const dashboard = createDashboard({ ledger, watchdog, backlog, beadsIdentity });
265
338
 
266
339
  // docs/dolt-sync-redesign.md Part 3.3: kill any orphaned ephemeral
267
340
  // `dolt sql-server` a mid-settle orchestrator death left behind on a
@@ -299,7 +372,7 @@ export async function serveMain(argv = process.argv.slice(2)) {
299
372
  ownerDataDirPrefix: sweepOwnerDataDir,
300
373
  });
301
374
 
302
- const supervisor = createSupervisor({ port, ledger, spawner, watchdog, dashboard, idAllocator, doltMutex, doltOrphanSweep });
375
+ const supervisor = createSupervisor({ port, ledger, spawner, watchdog, dashboard, idAllocator, doltMutex, doltOrphanSweep, beadsIdentity });
303
376
  registerIdAllocatorRoutes(supervisor, idAllocator, { readJsonBody, sendJson });
304
377
  registerDoltMutexRoutes(supervisor, doltMutex, { readJsonBody, sendJson });
305
378
 
@@ -346,6 +419,7 @@ export async function serveMain(argv = process.argv.slice(2)) {
346
419
  listMembers: listMembersForLaunch,
347
420
  getBacklog: async () => ({ tree: await backlog.buildTree() }),
348
421
  beforeLaunch,
422
+ beadsIdentity,
349
423
  });
350
424
  registerSprintRoutes(supervisor, sprintController);
351
425
 
@@ -0,0 +1,481 @@
1
+ // Typed sprint-abort detection, abort-path PR publish and the newTask
2
+ // validation/persistence helpers for fleet-sprint (apra-fleet-3swo.3.6).
3
+ // Moved verbatim out of runner.js -- runner.js re-exports isTypedAbortError,
4
+ // finalizeAbort and persistNewTaskBestEffort so existing importers keep
5
+ // working. This is a move-only extraction: predicate logic, the finalizeAbort
6
+ // degrade-on-failed-provider-resolution path, and the persistNewTaskBestEffort
7
+ // non-fatal fallback ladder are all unchanged.
8
+ //
9
+ // Scope note (apra-fleet-3swo.3.6): the bead names only two new files
10
+ // (abort.mjs, branch-ensure.mjs) for three conceptual clusters -- abort
11
+ // predicates, the pure branch-selection helper, and newTask
12
+ // validation/persistence. branch-ensure.mjs's name is unambiguous (the
13
+ // branch-selection helper only), so the newTask validation/persistence
14
+ // cluster is folded into this file to stay within the bead's three-file
15
+ // budget (abort.mjs, branch-ensure.mjs, runner.js) rather than adding a
16
+ // fourth file for a small, self-contained cluster.
17
+ //
18
+ // SAFE_TEXT_RE, runGitStep, sanitizePrText and stageCommandBodyMemberSide stay
19
+ // in runner.js (out of this bead's scope -- each has a second, non-moving
20
+ // caller: SAFE_TEXT_RE/sanitizePrText also gate the Publish PR step's text,
21
+ // runGitStep is the main withGitSync dispatch bracket's own helper, and
22
+ // stageCommandBodyMemberSide also backs createChildBeadWithAllocatedId) and
23
+ // are imported back here; findDoltDivergedCause similarly stays (used
24
+ // elsewhere in runner.js) and is imported back for isTypedAbortError. The
25
+ // resulting runner.js <-> abort.mjs cycle is safe because every use is inside
26
+ // a function body, never at module-evaluation time.
27
+ import { CommandError, BudgetExceededError, CancelledError } from '@apralabs/apra-fleet-workflow';
28
+ import {
29
+ SprintPlanRejectedError, StalledSprintError, ReviewerContractViolationError, GitDivergedError,
30
+ UsageLimitWaitExhaustedError,
31
+ } from './errors.mjs';
32
+ import { ApraFleet } from '@apralabs/apra-fleet-client';
33
+ import { resolveProvider, capabilities as vcsCapabilities } from './vcs-module.mjs';
34
+ import { raiseVcsPrForMember, PR_SKIPPED_NO_MCP_CLIENT } from './vcs-auth.mjs';
35
+ import {
36
+ findDoltDivergedCause, runGitStep, sanitizePrText, stageCommandBodyMemberSide, SAFE_TEXT_RE,
37
+ } from './runner.js';
38
+
39
+ /**
40
+ * Follow-up-task persistence is bookkeeping -- it must NEVER abort the sprint.
41
+ * Every persistence path degrades instead of throwing: bd create ->
42
+ * parent-bead notes -> this run log, in that order.
43
+ */
44
+ export async function persistNewTaskBestEffort({ createFn, command, member, parentId, newTask, cycle, log = () => {}, stage }) {
45
+ try {
46
+ // createFn's return value (when it forwards createChildBeadWithAllocatedId's
47
+ // { childId }) lets callers log exactly which bead id was created, not just
48
+ // a count. Existing callers that ignore the return value are unaffected --
49
+ // this is still truthy either way.
50
+ const result = await createFn();
51
+ return result ?? true;
52
+ } catch (err) {
53
+ log(`[fleet-sprint] newTask bd create FAILED (non-fatal, ${stage}): ${err.message} -- falling back to parent-bead notes.`);
54
+ try {
55
+ await appendRejectedFindingToParentNotes({
56
+ command, member, parentId, newTask,
57
+ reason: `bd create failed (${stage}): ${err.message}`, cycle, log,
58
+ });
59
+ } catch (err2) {
60
+ log(`[fleet-sprint] newTask persistence FAILED at every level (non-fatal, ${stage}); finding preserved VERBATIM in this run log: ${JSON.stringify(newTask)} -- last error: ${err2.message}`);
61
+ }
62
+ return false;
63
+ }
64
+ }
65
+
66
+ const SAFE_DESCRIPTION_RE = /^[\t\n\r\x20-\x7E]+$/;
67
+ const SAFE_PRIORITY_RE = /^P[0-4]$/;
68
+
69
+ /**
70
+ * Rewrites the handful of common non-ASCII punctuation characters LLM
71
+ * reviewers routinely emit in newTask descriptions -- em/en dashes, curly
72
+ * quotes, ellipsis -- to ASCII equivalents before SAFE_DESCRIPTION_RE
73
+ * validation, so a description is not rejected wholesale over characters that
74
+ * lose no meaning when normalized. This is a fixed substitution table, not a
75
+ * general Unicode stripper: anything still outside the allowlist afterwards is
76
+ * still a hard rejection. See sanitizeNewTaskTitle() below for title's own,
77
+ * stricter table.
78
+ * @param {string} description
79
+ * @returns {string}
80
+ */
81
+ export function sanitizeNewTaskDescription(description) {
82
+ return String(description ?? '')
83
+ .replace(/[\u2014\u2013]/g, '--') // em dash (\u2014), en dash (\u2013)
84
+ .replace(/[\u2018\u2019]/g, "'") // curly single quotes (\u2018 \u2019)
85
+ .replace(/[\u201C\u201D]/g, '"') // curly double quotes (\u201C \u201D)
86
+ .replace(/\u2026/g, '...'); // horizontal ellipsis (\u2026)
87
+ }
88
+
89
+ /**
90
+ * Same idea as sanitizeNewTaskDescription() above, for title -- but with a
91
+ * STRICTER substitution table, since title still has to pass the tighter
92
+ * SAFE_TEXT_RE shell-safety allowlist afterwards (it is interpolated inline
93
+ * into a `bd create "..."` command; description is not). Every substitution
94
+ * here maps to a character SAFE_TEXT_RE already admits, so this never
95
+ * reopens the injection surface that allowlist exists to close -- it only
96
+ * rescues titles that would otherwise be needlessly rejected over benign,
97
+ * common LLM punctuation choices. Observed live (apra-fleet-vk0a's sibling
98
+ * finding): a reviewer wrote a title referencing a CLI command in backticks
99
+ * (`` `apra-fleet status` ``, ordinary Markdown inline-code style), which
100
+ * SAFE_TEXT_RE rejects outright (backtick is excluded as a POSIX
101
+ * command-substitution risk) -- the finding was then silently demoted to a
102
+ * freetext note on the parent bead instead of becoming its own actionable
103
+ * task. Backtick has no special meaning in a bd title (bd has no
104
+ * code-formatting concept), so it is rewritten to a single quote here rather
105
+ * than dropped or preserved. A literal `"`/`$`/backslash in a title is NOT
106
+ * rewritten (there is no safe ASCII stand-in that preserves meaning without
107
+ * reopening the injection question) -- those still hard-reject via
108
+ * SAFE_TEXT_RE below, exactly as before this function existed.
109
+ * @param {string} title
110
+ * @returns {string}
111
+ */
112
+ export function sanitizeNewTaskTitle(title) {
113
+ return String(title ?? '')
114
+ .replace(/[\u2014\u2013]/g, '--') // em dash (\u2014), en dash (\u2013)
115
+ .replace(/[\u2018\u2019]/g, "'") // curly single quotes (\u2018 \u2019)
116
+ .replace(/[\u201C\u201D]/g, "'") // curly double quotes -> single quote (a literal `"` stays disallowed in title, unlike description)
117
+ .replace(/\u2026/g, '...') // horizontal ellipsis (\u2026)
118
+ .replace(/`/g, "'"); // backtick (Markdown inline-code marker) -> single quote
119
+ }
120
+
121
+ /**
122
+ * Validates one reviewer-authored newTask entry. `title` is checked against
123
+ * SAFE_TEXT_RE because it is interpolated inline into a `bd create` command
124
+ * string; `description` is checked against the more permissive
125
+ * SAFE_DESCRIPTION_RE because it travels via `bd create --body-file` and is
126
+ * never shell-interpolated (see createChildBeadWithAllocatedId). Returns
127
+ * either `{ ok: true, title, description, priority }` (safe to use) or
128
+ * `{ ok: false, reason }`. A rejected entry must never reach `command()` as a
129
+ * `bd create` interpolation; rejection is non-fatal and the sprint continues.
130
+ * @param {{ title: unknown, description: unknown, priority: unknown }} newTask
131
+ * @returns {{ ok: true, title: string, description: string, priority: string } | { ok: false, reason: string }}
132
+ */
133
+ export function validateNewTask(newTask) {
134
+ const priority = String(newTask && newTask.priority);
135
+ if (!SAFE_PRIORITY_RE.test(priority)) {
136
+ return { ok: false, reason: `priority '${priority}' does not match required pattern ${SAFE_PRIORITY_RE}` };
137
+ }
138
+ const title = sanitizeNewTaskTitle(newTask && newTask.title);
139
+ if (!title || !SAFE_TEXT_RE.test(title)) {
140
+ return { ok: false, reason: `title fails safe-character allowlist ${SAFE_TEXT_RE} (or is empty): ${JSON.stringify(title)}` };
141
+ }
142
+ const description = sanitizeNewTaskDescription(newTask && newTask.description);
143
+ if (!description || !SAFE_DESCRIPTION_RE.test(description)) {
144
+ return { ok: false, reason: `description fails ASCII-printable validation ${SAFE_DESCRIPTION_RE} (or is empty): ${JSON.stringify(description)}` };
145
+ }
146
+ return { ok: true, title, description, priority };
147
+ }
148
+
149
+ /**
150
+ * Persists a newTask that failed validateNewTask() into the parent bead's
151
+ * notes, raw and unmodified (title/description/priority plus the rejection
152
+ * reason), so a rejected finding is still recoverable by a human or the next
153
+ * planner even though it was not filed as its own child bead. The note body
154
+ * goes through the same member-side staging seam as the description path
155
+ * (stageCommandBodyMemberSide) and is never interpolated into a shell string.
156
+ *
157
+ * A failure to append is logged AND re-thrown. Every call site wraps this in
158
+ * its own try/catch whose purpose is to log the raw finding verbatim as the
159
+ * last fallback rung; swallowing the failure here would make that rung
160
+ * unreachable on exactly the path it exists to cover. Re-throwing is still
161
+ * non-fatal to the sprint -- the caller's catch is what contains it.
162
+ * @param {{ command: Function, member: string, parentId: string, newTask: unknown, reason: string, cycle?: string|number, log?: Function }} opts
163
+ */
164
+ export async function appendRejectedFindingToParentNotes({ command, member, parentId, newTask, reason, cycle, log = () => {} }) {
165
+ const raw = {
166
+ cycle,
167
+ rejectionReason: reason,
168
+ title: newTask && newTask.title,
169
+ description: newTask && newTask.description,
170
+ priority: newTask && newTask.priority,
171
+ };
172
+ const noteBody = `[fleet-sprint newTask REJECTED -- residual validation failure, appended verbatim]\n${JSON.stringify(raw, null, 2)}`;
173
+ try {
174
+ const noteFile = await stageCommandBodyMemberSide({
175
+ command, member, content: noteBody,
176
+ label: `Stage rejected newTask finding for ${parentId} notes`,
177
+ });
178
+ await command(
179
+ `bd note ${parentId} --file "${noteFile}"`,
180
+ { member_name: member, silent: true, label: `Append rejected newTask finding to ${parentId} notes` }
181
+ );
182
+ log(`Rejected newTask finding appended verbatim to '${parentId}' notes (residual validation failure: ${reason}).`);
183
+ } catch (err) {
184
+ log(`[newTask notes-fallback] FAILED to append rejected finding to '${parentId}' notes: ${err.message}`);
185
+ throw err;
186
+ }
187
+ }
188
+
189
+ // ---------------------------------------------------------------------------
190
+ // Typed sprint-abort detection
191
+ // ---------------------------------------------------------------------------
192
+ //
193
+ // The single predicate deciding whether an error thrown out of
194
+ // runSprintCycle() is a "sprint-abort" the caller routes through
195
+ // finalizeAbort() plus a terminal history record, as opposed to an unexpected
196
+ // failure that keeps the plain grace-window/exit-1 path with no PR and no
197
+ // history record. The intended set is:
198
+ // - StalledSprintError, SprintPlanRejectedError and
199
+ // ReviewerContractViolationError (errors.mjs), which this runner throws
200
+ // itself, plus BudgetExceededError, which the workflow package throws on
201
+ // its behalf;
202
+ // - GitDivergedError and DoltDivergedError, the state-integrity divergences.
203
+ // A divergence means the single-writer invariant this engine relies on is
204
+ // already violated (or the shared beads DB genuinely cannot be
205
+ // fast-forwarded), so no retry or later phase can recover the run -- it
206
+ // must terminate with an operator-visible record. A DoltDivergedError also
207
+ // arrives WRAPPED one level down inside a PostDispatchSyncError (the D-push
208
+ // bracket's shape), so membership is decided by findDoltDivergedCause()
209
+ // walking the cause chain rather than by the outermost class. That the
210
+ // divergences belong in this set is not an inference: main()'s typed-abort
211
+ // catch below already calls resolveTerminalReason()/captureDoltConflictDump()
212
+ // precisely to report them as the distinct BEADS_SYNC_CONFLICT terminal
213
+ // state, which is dead code unless they reach it;
214
+ // - UsageLimitWaitExhaustedError (apra-fleet-hzeb.4.1/.4.2): the usage-limit
215
+ // pause/reprobe controller's own give-up error, thrown once its budget
216
+ // (role-policies.mjs's USAGE_LIMIT_BUDGET_DEFAULTS) is spent with no
217
+ // successful resume. A member still rate-limited past every allowed wait
218
+ // is as terminal as a stalled sprint -- no retry or later phase recovers it
219
+ // either -- so it gets the same finalizeAbort()/[ABORTED]-PR treatment;
220
+ // - the plain `Error` pre-sprint validation failures, which are not
221
+ // WorkflowError subclasses and are identified by the stable
222
+ // 'Pre-sprint validation failed:' message prefix every such throw site
223
+ // uses.
224
+ //
225
+ // Everything else is deliberately EXCLUDED, and the check is an explicit class
226
+ // list rather than the blanket `instanceof WorkflowError` it used to be --
227
+ // which swept in every routine, non-terminal failure and turned it into a
228
+ // spurious `verdict: 'ABORTED'`:
229
+ // - CancelledError: a cooperative cancellation is a requested shutdown, not
230
+ // an aborted sprint, and must keep flowing through its own 'cancelled'
231
+ // status path;
232
+ // - AgentOutputError, AgentDispatchError, FleetTransportError, CommandError:
233
+ // dispatch-level failures each phase's own retry/soft-fail policy owns;
234
+ // - GitSyncError, DoltSyncError, and a PostDispatchSyncError whose cause
235
+ // chain carries NO divergence: transient sync failures that are retried in
236
+ // place and, if they still surface, are ordinary run failures rather than
237
+ // sprint aborts;
238
+ // - SprintLockHeldError: structurally unreachable here. acquireSprintLock()
239
+ // runs in main() BEFORE its try block, so a held lock never reaches this
240
+ // predicate; there is also no sprint of our own to finalize when another
241
+ // engine already owns the branch.
242
+ export function isTypedAbortError(err) {
243
+ if (!err || err instanceof CancelledError) return false;
244
+ if (err instanceof StalledSprintError) return true;
245
+ if (err instanceof SprintPlanRejectedError) return true;
246
+ if (err instanceof ReviewerContractViolationError) return true;
247
+ if (err instanceof BudgetExceededError) return true;
248
+ if (err instanceof GitDivergedError) return true;
249
+ if (err instanceof UsageLimitWaitExhaustedError) return true;
250
+ // Bare DoltDivergedError, or one wrapped inside a PostDispatchSyncError.
251
+ if (findDoltDivergedCause(err)) return true;
252
+ return typeof err.message === 'string' && err.message.startsWith('Pre-sprint validation failed:');
253
+ }
254
+
255
+ // ---------------------------------------------------------------------------
256
+ // Abort-path PR publish
257
+ // ---------------------------------------------------------------------------
258
+ //
259
+ // The ordinary Publish PR step only runs when the sprint reaches a final
260
+ // PASS/FAIL verdict. A sprint that instead aborts by throwing a typed error
261
+ // would otherwise propagate straight to the CLI's top-level catch with no
262
+ // branch push and no PR, leaving any work a doer already committed visible
263
+ // only to someone willing to dig through git history. Called from the
264
+ // typed-abort catch site with the causing error, finalizeAbort():
265
+ // 1. counts commits on the sprint branch beyond base, which decides whether
266
+ // there is anything for a human to look at;
267
+ // 2. with >=1 commit, pushes the branch and raises an idempotent
268
+ // 'Auto-sprint [ABORTED]: <branch>' PR whose body carries the error's
269
+ // code/message/details, sanitized by sanitizePrText for the same reason
270
+ // the PASS/FAIL step sanitizes reviewer notes;
271
+ // 3. with 0 commits, raises no PR -- there is no diff, so the PR would be
272
+ // noise -- and reports that in its return value, so the caller can still
273
+ // write a terminal history record.
274
+ // `command` and `log` are dependency-injected rather than closed over
275
+ // `context`, so this is callable both from the catch site and directly from
276
+ // unit tests with a mock `command`.
277
+ /**
278
+ * @param {{
279
+ * error: { code?: string, message?: string, details?: unknown },
280
+ * branch: string,
281
+ * baseBranch: string,
282
+ * member: string,
283
+ * command: (cmd: string, opts: object) => Promise<any>,
284
+ * log?: (msg: string) => void,
285
+ * onAuthFailure?: (info: { member: string, label: string, cmd?: string, error: string, kind: 'git'|'dolt' }) => Promise<void>,
286
+ * callTool?: (name: string, args: object) => Promise<any>,
287
+ * }} opts
288
+ * @returns {Promise<{ prUrl: string|null, reason: string, pushed: boolean, commitCount: number }>}
289
+ */
290
+ export async function finalizeAbort({ error, branch, baseBranch, member, command, log = () => {}, onAuthFailure, callTool }) {
291
+ // Built up-front (not just at the PR-creation step further down) so the
292
+ // SAME ApraFleet client can also resolve `member`'s VCS provider
293
+ // (apra-fleet-417.7) for the runGitStep calls below -- avoids
294
+ // constructing a second client just for that lookup. `null` when no
295
+ // callTool is wired (e.g. a mock-sprint scenario with no MCP client);
296
+ // every downstream use already guards on this being non-null.
297
+ const fleetApi = typeof callTool === 'function' ? new ApraFleet({ callTool }) : null;
298
+
299
+ // apra-fleet-417.7: resolve `member`'s VCS provider ONCE up-front so the
300
+ // git failures below (fetch/rev-list/push) classify via that member's own
301
+ // provider chain, not just the default 'github' one. Fails closed to
302
+ // `undefined` (today's default chain) on any error -- a provider-
303
+ // resolution hiccup here must never abort an otherwise-recoverable abort
304
+ // finalization.
305
+ let provider;
306
+ if (fleetApi) {
307
+ try {
308
+ ({ provider } = await resolveProvider(member, { fleetApi }));
309
+ } catch (err) {
310
+ log(`finalizeAbort: could not resolve member '${member}'s VCS provider for git-failure classification (falling back to the default provider chain, no verdict change for GitHub members): ${err.message}`);
311
+ }
312
+ }
313
+
314
+ // 1. How many commits (if any) does the sprint branch carry beyond base?
315
+ // Every command() call below passes an explicit `member_name` -- this
316
+ // runner never lets a git/gh dispatch fall back to an ambient member.
317
+ //
318
+ // `member` need not be a member that ever checked out a LOCAL branch named
319
+ // `baseBranch`; it may only have the sprint branch. A bare
320
+ // `git rev-list base..branch` would then fail with "unknown revision", so
321
+ // fetch first and diff against the remote-tracking ref, which is always
322
+ // resolvable: baseBranch is the ref the sprint branch was created from.
323
+ //
324
+ // apra-fleet-5d5.1: these three git calls now go through runGitStep()
325
+ // (the same helper the main withGitSync dispatch bracket uses) instead of
326
+ // calling `command()` directly, so a git-auth failure here gets the SAME
327
+ // provision_vcs_auth self-heal-and-retry-once treatment instead of being
328
+ // silently swallowed (live: apra-fleet-l7n Cycle 3 abort hit exactly this
329
+ // -- "Authentication failed ... Password authentication is not
330
+ // supported" while writing the terminal history record, with no self-heal
331
+ // available). runGitStep never throws; a non-ok result here is re-thrown
332
+ // as a CommandError so finalizeAbort()'s own external throw-on-failure
333
+ // contract (see main()'s catch site, which falls back to "no PR lookup"
334
+ // on any thrown error) is unchanged for callers.
335
+ const fetchRes = await runGitStep({
336
+ command, member, cmd: `git fetch origin ${baseBranch}`,
337
+ label: `Fetch base branch '${baseBranch}' for abort-path diff`,
338
+ log, maxTransientRetries: 1, onAuthFailure, provider,
339
+ });
340
+ if (!fetchRes.ok) {
341
+ throw new CommandError(
342
+ `[Abort Finalize Failed] git fetch origin ${baseBranch} failed: ${fetchRes.error}`,
343
+ { details: { branch, baseBranch, error: fetchRes.error, kind: fetchRes.kind } }
344
+ );
345
+ }
346
+ const revListRes = await runGitStep({
347
+ command, member, cmd: `git rev-list --count origin/${baseBranch}..${branch}`,
348
+ label: `Count commits beyond base for abort-path branch '${branch}'`,
349
+ log, maxTransientRetries: 1, onAuthFailure, provider,
350
+ });
351
+ if (!revListRes.ok) {
352
+ throw new CommandError(
353
+ `[Abort Finalize Failed] git rev-list --count origin/${baseBranch}..${branch} failed: ${revListRes.error}`,
354
+ { details: { branch, baseBranch, error: revListRes.error, kind: revListRes.kind } }
355
+ );
356
+ }
357
+ const commitCount = parseInt(String(revListRes.output).trim(), 10) || 0;
358
+
359
+ if (commitCount < 1) {
360
+ log(`finalizeAbort: branch '${branch}' has 0 commits beyond '${baseBranch}' -- no [ABORTED] PR raised (zero-commit-abort policy).`);
361
+ return { prUrl: null, reason: 'zero-commit-abort', pushed: false, commitCount };
362
+ }
363
+
364
+ // 2. There is real work on the branch -- publish it and raise the PR.
365
+ const pushRes = await runGitStep({
366
+ command, member, cmd: `git push -u origin ${branch}`,
367
+ label: `Push abort-path sprint branch '${branch}'`,
368
+ log, maxTransientRetries: 1, onAuthFailure, provider,
369
+ });
370
+ if (!pushRes.ok) {
371
+ throw new CommandError(
372
+ `[Abort Finalize Failed] git push -u origin ${branch} failed: ${pushRes.error}`,
373
+ { details: { branch, baseBranch, error: pushRes.error, kind: pushRes.kind } }
374
+ );
375
+ }
376
+
377
+ // Same origin-remote gate as the Publish PR step, via
378
+ // VCSModule.capabilities(): a remote whose provider cannot open a PR (a
379
+ // file:// bare mirror, or any other host with no hosting API support)
380
+ // must never hit raiseVcsPrForMember()'s doomed REST call, which would
381
+ // surface as a hard-to-diagnose failure while the sprint is already
382
+ // aborting. Resolving the remote is itself failSoft -- an unresolvable
383
+ // remote fails closed to canOpenPullRequest:false -- so a probe hiccup
384
+ // here degrades to "PR skipped", never a thrown error. The branch above
385
+ // is already pushed either way.
386
+ const originUrlRes = await command('git remote get-url origin', {
387
+ member_name: member,
388
+ silent: true,
389
+ failSoft: true,
390
+ label: 'Resolve origin remote URL for abort-path PR gate',
391
+ });
392
+ const originUrl = originUrlRes.ok ? originUrlRes.output.trim() : '';
393
+ const abortPathCapabilities = vcsCapabilities(originUrl);
394
+ if (!abortPathCapabilities.canOpenPullRequest) {
395
+ log(`finalizeAbort: origin remote '${originUrl || '(unresolved)'}' cannot open a pull request (host: ${abortPathCapabilities.host || 'unknown'}) -- skipping [ABORTED] PR creation; branch '${branch}' is still pushed.`);
396
+ return { prUrl: null, reason: 'non-hosted-remote', pushed: true, commitCount };
397
+ }
398
+
399
+ const prTitle = `Auto-sprint [ABORTED]: ${branch}`;
400
+ // The error's code/message/details can originate from agent output, and
401
+ // this text is embedded in a VCSModule-built PR body -- same sanitization
402
+ // rationale as the PASS/FAIL Publish PR step.
403
+ const safeCode = sanitizePrText(error && error.code);
404
+ const safeMessage = sanitizePrText(error && error.message);
405
+ const safeDetails = sanitizePrText(
406
+ error && error.details !== undefined ? JSON.stringify(error.details) : ''
407
+ );
408
+ const prBody = [
409
+ `Automated apra-fleet-se sprint ABORTED before reaching a final PASS/FAIL verdict.`,
410
+ '',
411
+ safeCode ? `Error code: ${safeCode}` : null,
412
+ safeMessage ? `Error message: ${safeMessage}` : null,
413
+ safeDetails ? `Error details: ${safeDetails}` : null,
414
+ '',
415
+ 'Do NOT auto-merge -- see pm skill R12; a human must review and merge this PR.',
416
+ ].filter((line) => line !== null).join('\n');
417
+
418
+ // The reverted gh-based PR creation is gone (apra-fleet-tfx.8): raise the [ABORTED] PR via
419
+ // VCSModule's orchestrator-built curl command, dispatched to `member`
420
+ // through execute_command, using a push+pr credential minted
421
+ // just-in-time immediately before this one call (never at sprint setup).
422
+ // (fleetApi is built at the top of this function, above.)
423
+ if (!fleetApi) {
424
+ // Graceful degradation (apra-fleet-tfx.8.1): raising the [ABORTED] PR
425
+ // needs an MCP client to mint a just-in-time push+pr credential on
426
+ // `member`. When no callTool is wired (e.g. a mock-sprint scenario
427
+ // that never opted into an MCP client), the abort-path branch is
428
+ // ALREADY pushed above -- so instead of an unconditional hard-throw
429
+ // that would break every such pre-existing scenario, this degrades to
430
+ // a typed 'pr-skipped-no-mcp-client' outcome: a clear log line, the
431
+ // pushed branch still returned to the caller, only the auto-raised PR
432
+ // skipped. In production callTool is always wired (bin/cli.mjs), so
433
+ // this branch never runs there; it exists purely so PR creation is not
434
+ // a hard MCP dependency for callers that legitimately have none.
435
+ log(`[Publish Abort PR Skipped] no MCP callTool available to mint a push+pr credential for member '${member}' -- branch '${branch}' is pushed but the [ABORTED] PR was not raised.`);
436
+ return { prUrl: null, reason: PR_SKIPPED_NO_MCP_CLIENT, pushed: true, commitCount };
437
+ }
438
+ const prResult = await raiseVcsPrForMember({
439
+ fleetApi,
440
+ command,
441
+ member,
442
+ base: baseBranch,
443
+ head: branch,
444
+ title: prTitle,
445
+ body: prBody,
446
+ log,
447
+ logPrefix: '[Publish Abort PR]',
448
+ // Already resolved just above (the origin-remote PR-capability gate)
449
+ // via a real git-capable member -- skip re-deriving it a second time
450
+ // by shelling out to `member`, which may be orchestratorMember and
451
+ // have no git checkout of its own to read a remote from.
452
+ remoteUrlOverride: originUrl,
453
+ });
454
+
455
+ if (!prResult.ok) {
456
+ if (prResult.authFailure) {
457
+ // apra-fleet-647.1.1.1: a PR auth failure survives the reactive
458
+ // one-shot self-heal+retry inside raiseVcsPrForMember (i.e. the
459
+ // credential is still no good after re-provisioning) -- degrade
460
+ // to a logged, non-throwing outcome instead of a CommandError, so
461
+ // finalizeAbort() -- whose whole job is to record a sprint abort
462
+ // -- can never itself be killed by the very auth failure it is
463
+ // trying to report. The branch is still pushed (`pushed: true`)
464
+ // even though the [ABORTED] PR could not be raised.
465
+ log(`finalizeAbort: [Publish Abort PR] failed with an auth failure that survived the reactive self-heal retry for branch '${branch}' -> '${baseBranch}': ${prResult.error} -- degrading (not throwing) so the abort can still be recorded.`);
466
+ return { prUrl: null, reason: 'pr-auth-failed', pushed: true, commitCount };
467
+ }
468
+ throw new CommandError(
469
+ `[Publish Abort PR Failed] VCSModule create-pull-request failed for branch '${branch}' -> '${baseBranch}': ${prResult.error}`,
470
+ { details: { branch, baseBranch, error: prResult.error } }
471
+ );
472
+ }
473
+ if (prResult.alreadyExists) {
474
+ // Idempotent: the desired end state -- a PR open for this branch --
475
+ // already holds, so this is swallowed rather than thrown.
476
+ log(`finalizeAbort: an [ABORTED] PR for branch '${branch}' already exists -- treating as idempotent success.`);
477
+ return { prUrl: prResult.prUrl, reason: 'already-exists', pushed: true, commitCount };
478
+ }
479
+
480
+ return { prUrl: prResult.prUrl, reason: 'aborted-pr-created', pushed: true, commitCount };
481
+ }