@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
@@ -0,0 +1,556 @@
1
+ // =============================================================================
2
+ // fleet-sprint git/dolt SYNC BRACKETS (apra-fleet-3swo.4.1).
3
+ //
4
+ // This module owns `openSyncBracketCount` -- the clean-state pause-guard
5
+ // counter that used to live as a closure variable inside runSprintCycle() in
6
+ // runner.js. Owning it here is the point of the extraction: every git/dolt
7
+ // sync and every push now runs inside a bracket THIS module opens and closes,
8
+ // so a caller cannot forget the bracket and leave the engine reporting
9
+ // "safe to pause" while a pull/push is in flight.
10
+ //
11
+ // EVERY sync/push goes through one of the entry points createGitSync()
12
+ // returns:
13
+ // withGitSync() -- the full dispatch bracket (pre-dispatch G-pull/D-pull,
14
+ // the dispatch itself, post-dispatch G-push/D-push).
15
+ // syncBeadsBefore() -- a standalone bracketed DoltSync.syncBefore().
16
+ // syncBeadsAfter() -- a standalone bracketed DoltSync.syncAfter().
17
+ // pushBeadsAfter() -- a standalone bracketed DoltSync.syncAfter() D-push
18
+ // (apra-fleet-3swo.4.9 part b -- routes through the
19
+ // same degrade-by-default/settle-callback surface as
20
+ // syncBeadsAfter, no longer a bare doltPushAfter()).
21
+ // pushGitAfter() -- a standalone bracketed syncMemberAfter() G-push.
22
+ // runner.js holds NO counter arithmetic and hand-rolls NO bracket of its own.
23
+ //
24
+ // STATE IS INJECTED, NEVER CAPTURED: withGitSync() and withOpenSyncBracket()
25
+ // were nested closures over runSprintCycle()'s `command`, `log`, `validated`,
26
+ // `doltPushMutex`, `sprintMutexId`, `agent` and `setPauseGuard`, so the move
27
+ // has to pass that state in explicitly. createGitSync(deps) takes it once and
28
+ // binds it; withGitSync() itself is exported as a plain function whose first
29
+ // argument is that dependency context, so it stays unit-testable without a
30
+ // live sprint.
31
+ //
32
+ // DOLT LITERAL CONSTRAINT (dolt-literal-guard.mjs): this module must call
33
+ // dolt-sync.mjs's exported entry points and must NEVER re-inline a
34
+ // `bd dolt pull`/`bd dolt push` command string. dolt-sync.mjs is the single
35
+ // permitted dolt command surface.
36
+ // =============================================================================
37
+
38
+ import { ApraFleet } from "@apralabs/apra-fleet-client";
39
+ import { DoltSync } from "./dolt-sync.mjs";
40
+ import { buildSettleCallback } from "./dolt-settle.mjs";
41
+ import { PostDispatchSyncError, ConcurrentSyncBracketError } from "./errors.mjs";
42
+ import { resolveMemberTarget } from "./member-target.mjs";
43
+
44
+ // (apra-fleet-3swo.4.9 part a) The shared `exclusiveKey` every CODE-WRITING
45
+ // (pushCode:true) withGitSync() bracket opens under. This is the resource
46
+ // mutual exclusion actually protects: the shared git branch a G-push lands
47
+ // on, not any one member -- two DIFFERENT members' pushCode:true dispatches
48
+ // overlapping is exactly as damaging to the fast-forward-by-construction
49
+ // invariant as the same member somehow dispatching twice at once. Read-only
50
+ // brackets (pushCode:false) and the standalone D-only/G-only helpers never
51
+ // pass an exclusiveKey -- their concurrency is either harmless (nothing is
52
+ // pushed) or already serialized by a purpose-built mechanism of their own
53
+ // (the dolt push mutex), so folding them into this check would only add
54
+ // false-positive risk with no corresponding safety gain.
55
+ export const CODE_WRITE_BRACKET_KEY = 'code-write';
56
+
57
+ // (apra-fleet-3swo.4.12) DECIDED: the bracket does NOT record the owning
58
+ // STREAK/lane, and the coarse key above plus the cosmetic `label` stays as
59
+ // shipped. Recorded here so the question is not re-litigated:
60
+ // - As a finer-grained KEY it would be unsound. The protected resource is
61
+ // the ONE shared sprint branch: `branch` is bound once into
62
+ // createGitSync()'s ctx and every code-writing bracket pushes to it --
63
+ // there is no per-streak branch (runner.js's "streak branch" wording is
64
+ // loose prose for that same sprint branch). Keying by streak would let
65
+ // two streaks' pushCode:true brackets overlap UNDETECTED, i.e. a strict
66
+ // weakening of exactly the fast-forward-by-construction check this key
67
+ // exists to make.
68
+ // - As richer ATTRIBUTION it would be partial and misleading. Streaks are
69
+ // anonymous by the time they reach the dispatch site:
70
+ // groupStreaksFromLaneMetadata() uses `metadata.streak` only to group and
71
+ // sort, then returns Array<Array<bead>> and DISCARDS the lane id, and the
72
+ // selectStreaks() dependency path never has one at all. The other
73
+ // pushCode:true role (harvester) has no streak in any sense. Giving the
74
+ // bracket a real streak identity means changing worklists.mjs's return
75
+ // contract and the runner call sites, not just this module.
76
+ // - Nothing is lost. A ConcurrentSyncBracketError on this key can only mean
77
+ // the globalDoerTurn FIFO gate (runner.js:5121, which serializes ALL doer
78
+ // streak turns globally) has been broken or a new unbracketed code-write
79
+ // path was added; diagnosing that needs the overlapping CALL SITES, which
80
+ // `withGitSync(<member>)` plus the per-streak bead-id log lines already
81
+ // give.
82
+
83
+ // Backoff for retrying ONLY the post-dispatch sync step of a bracket whose
84
+ // dispatch already completed. Short and bounded: this is a git/dolt push round
85
+ // trip, not an LLM turn, and letting the failure escape the bracket would
86
+ // redispatch the whole turn.
87
+ export const POST_DISPATCH_SYNC_RETRY_DELAYS_MS = [0, 5000, 15000];
88
+
89
+ /** True when the hermetic mock harness has opted into zero-wait backoffs
90
+ * (APRA_FLEET_MOCK_INSTANT_RETRY_BACKOFF=1, set by mock-sprint-harness.mjs).
91
+ * Production behavior -- real timed sleeps -- is unaffected. */
92
+ const mockInstantRetryBackoff = () => process.env.APRA_FLEET_MOCK_INSTANT_RETRY_BACKOFF === "1";
93
+
94
+ /**
95
+ * Creates the open-sync-bracket counter and its withOpenSyncBracket() wrapper,
96
+ * registering the clean-state pause guard with the engine when one is wired.
97
+ * The returned object is the ONLY handle to the counter: nothing outside this
98
+ * module can increment or decrement it.
99
+ *
100
+ * @param {{ setPauseGuard?: Function }} deps
101
+ * @returns {{ withOpenSyncBracket: (fn: () => Promise<any>, opts?: { exclusiveKey?: string, label?: string }) => Promise<any>, openBracketCount: () => number }}
102
+ */
103
+ export function createSyncBrackets({ setPauseGuard } = {}) {
104
+ // (apra-fleet-p2to.4.1) Clean-state pause guard: this is fleet-sprint's OWN
105
+ // pause-awareness -- the engine's cooperative pause primitive
106
+ // (apra-fleet-p2to.1's requestPause()/setPauseGuard()) only ever engages
107
+ // a pending pause at a zero-in-flight-activity boundary that ALSO passes
108
+ // this predicate, so registering it here is what keeps a pause from
109
+ // landing mid-git/mid-dolt-sync (e.g. between a pull and its matching
110
+ // push, or mid-D-push) and leaving the workspace/beads clone in an
111
+ // inconsistent state to resume from. `openSyncBracketCount` counts every
112
+ // currently-open "bracket": withGitSync()'s FULL body (pre-dispatch sync
113
+ // through post-dispatch sync, wrapped as a single bracket below) and
114
+ // every standalone DoltSync.syncBefore()/syncAfter()/doltPushAfter()/
115
+ // syncMemberAfter() call in runner.js that is NOT already nested inside a
116
+ // withGitSync bracket (a
117
+ // nested one is harmless double-counting, never a leak, since
118
+ // withOpenSyncBracket()'s increment/decrement is always paired). The
119
+ // guard itself is trivial and adds NO behavior when no pause is pending
120
+ // -- the engine only ever consults it while a pause is deferred (see
121
+ // FleetWorkflow._guardPermitsPause(), packages/apra-fleet-workflow/src/
122
+ // workflow/index.mjs), so a clean run with setPauseGuard registered but
123
+ // no pause ever requested behaves identically to one with no guard at
124
+ // all. `setPauseGuard` is only present on `context` when this script
125
+ // runs through WorkflowEngine.executeFile() (see that module's
126
+ // _bindPrimitives()) -- guarded so direct/legacy callers of
127
+ // runSprintCycle() that never go through the engine (existing tests)
128
+ // keep working unchanged.
129
+ let openSyncBracketCount = 0;
130
+ if (typeof setPauseGuard === 'function') {
131
+ setPauseGuard(() => openSyncBracketCount === 0);
132
+ }
133
+
134
+ // MUTUAL-EXCLUSION TRACKING (apra-fleet-3swo.4.9 part a). Before this, the
135
+ // counter above ONLY counted -- it could not tell a legitimately NESTED
136
+ // pair of brackets (bracket B opens and fully closes while bracket A,
137
+ // opened first, is still open -- harmless, LIFO) apart from a genuine
138
+ // OVERLAP (bracket A closes while a LATER-opened bracket B is still
139
+ // open -- a crossing, non-LIFO close that proves the two never should
140
+ // have been open at the same time). A caller that opts in by passing
141
+ // `exclusiveKey` gets that distinction enforced: brackets sharing a key
142
+ // are tracked on a per-key STACK, so any depth of legitimate nesting for
143
+ // that key is free (push on open, pop on close, never throws as long as
144
+ // closes happen LIFO), and a crossing close throws
145
+ // ConcurrentSyncBracketError naming both the closing bracket and every
146
+ // other bracket sharing the key that is still open. Every bracket that
147
+ // does NOT pass `exclusiveKey` (the default) is completely unaffected --
148
+ // this is opt-in per key, not a global exclusivity rule, because most
149
+ // concurrent brackets in this codebase are LEGITIMATE (different
150
+ // members' D-pushes serialize via their own dolt push mutex, not via
151
+ // this counter) and must never throw.
152
+ const exclusiveStacks = new Map();
153
+ let bracketSeq = 0;
154
+
155
+ /**
156
+ * Runs `fn` with the open-sync-bracket counter incremented for its
157
+ * duration, decrementing again on EVERY exit path (success or throw) via
158
+ * `finally` -- never leaves a stale increment behind on an error.
159
+ * @template T
160
+ * @param {() => Promise<T>} fn
161
+ * @param {{ exclusiveKey?: string, label?: string }} [opts] - opt in to
162
+ * mutual-exclusion tracking for `exclusiveKey`; `label` is cosmetic,
163
+ * used only in the thrown error's message.
164
+ * @returns {Promise<T>}
165
+ */
166
+ async function withOpenSyncBracket(fn, { exclusiveKey, label } = {}) {
167
+ openSyncBracketCount += 1;
168
+ let token = null;
169
+ if (exclusiveKey !== undefined && exclusiveKey !== null) {
170
+ token = { id: ++bracketSeq, label: label || exclusiveKey };
171
+ const stack = exclusiveStacks.get(exclusiveKey) || [];
172
+ stack.push(token);
173
+ exclusiveStacks.set(exclusiveKey, stack);
174
+ }
175
+ // apra-fleet-3swo.26: captured ONLY so a CROSSING close below can
176
+ // attach it as that error's `cause` -- the overlap is usually a
177
+ // CONSEQUENCE of the bracketed body's own failure, not its cause, so
178
+ // the more diagnosable original error must not be silently discarded
179
+ // in favor of the crossing-close symptom. On a NORMAL (LIFO) close,
180
+ // this plays no part: the `catch` block below immediately re-throws
181
+ // the exact same instance it received (`throw err`), so that path's
182
+ // error identity is unchanged (never wrapped, never replaced).
183
+ let bodyError;
184
+ let bodyThrew = false;
185
+ try {
186
+ return await fn();
187
+ } catch (err) {
188
+ bodyThrew = true;
189
+ bodyError = err;
190
+ throw err;
191
+ } finally {
192
+ openSyncBracketCount -= 1;
193
+ // (apra-fleet-3swo.43) The crossing-close error below is captured
194
+ // rather than thrown immediately, so that a CROSSING close cannot
195
+ // abandon this finally block before the pause-guard poke further
196
+ // down runs. Resolve the stack first (still needed either way to
197
+ // keep exclusiveStacks correct), but defer the throw itself until
198
+ // after the poke.
199
+ let crossingError = null;
200
+ if (token) {
201
+ const stack = exclusiveStacks.get(exclusiveKey) || [];
202
+ const top = stack[stack.length - 1];
203
+ if (top && top.id === token.id) {
204
+ // Normal case, whatever the nesting depth: we are the
205
+ // most-recently-opened bracket for this key, so this is
206
+ // a valid LIFO close.
207
+ stack.pop();
208
+ if (stack.length === 0) exclusiveStacks.delete(exclusiveKey);
209
+ } else {
210
+ // CROSSING close: a bracket that opened AFTER us, sharing
211
+ // our key, is still open. That is true overlap, not
212
+ // nesting -- remove ourselves from the stack (wherever we
213
+ // are in it) and throw (after the poke below), naming
214
+ // every bracket still open.
215
+ const idx = stack.findIndex((t) => t.id === token.id);
216
+ if (idx !== -1) stack.splice(idx, 1);
217
+ if (stack.length === 0) exclusiveStacks.delete(exclusiveKey);
218
+ else exclusiveStacks.set(exclusiveKey, stack);
219
+ const stillOpenLabels = stack.map((t) => t.label);
220
+ crossingError = new ConcurrentSyncBracketError(
221
+ `[Sync] mutual-exclusion violation on key '${exclusiveKey}': bracket '${token.label}' closed while ` +
222
+ `${stack.length} other bracket(s) sharing the same key ${stack.length === 1 ? 'is' : 'are'} still open ` +
223
+ `(${stillOpenLabels.join(', ')}) -- these OVERLAPPED rather than nested, which breaks the ` +
224
+ `fast-forward-by-construction invariant this key protects.`,
225
+ // apra-fleet-3swo.26: `cause` is the bracketed body's
226
+ // OWN rejection when it threw one (undefined when the
227
+ // body succeeded, which WorkflowError's constructor
228
+ // treats as "no cause" -- see errors.mjs), reachable
229
+ // as `.cause` on the thrown ConcurrentSyncBracketError
230
+ // per the native Error cause chain, without changing
231
+ // this class's signature.
232
+ { exclusiveKey, closingLabel: token.label, stillOpenLabels, cause: bodyThrew ? bodyError : undefined },
233
+ );
234
+ }
235
+ }
236
+ // (apra-fleet-p2to.4.4.1) Closing the LAST open sync bracket is
237
+ // itself a clean-state boundary a deferred pause may complete at,
238
+ // but the engine only re-checks its pause-engage condition
239
+ // (WorkflowEngine._maybeEngagePause()) at specific trigger points
240
+ // -- requestPause(), an in-flight activity draining to zero, the
241
+ // gate at the next agent()/command() dispatch, or setPauseGuard()
242
+ // itself (which re-checks as a side effect of registering). None
243
+ // of those necessarily fire here: this bracket can close with no
244
+ // further dispatch immediately following. Re-registering the SAME
245
+ // guard predicate is a deliberate poke -- it engages a pause
246
+ // requested while sync brackets were open the instant this guard
247
+ // opens, rather than leaving it stranded until some later
248
+ // dispatch happens to hit the gate.
249
+ //
250
+ // (apra-fleet-3swo.43) The poke check is placed ahead of the
251
+ // `crossingError` throw below so it always RUNS (is evaluated) on
252
+ // a CROSSING close, not just a LIFO one. apra-fleet-3swo.47 proved
253
+ // this is currently inert on the crossing path specifically: a
254
+ // crossing close is only ever entered while another bracket
255
+ // sharing the same exclusiveKey is still open (that is what makes
256
+ // it "crossing" rather than nesting), and that other bracket has
257
+ // not yet decremented -- so openSyncBracketCount is provably >= 1
258
+ // here and the `=== 0` check below is always false at this exact
259
+ // call site (confirmed empirically: setPauseGuard's call trace is
260
+ // identical with and without this hoist). It is kept anyway as
261
+ // defensive hardening -- it costs nothing today and is what keeps
262
+ // this correct if a future change ever decouples the counter from
263
+ // the per-key stack. Do not delete this ordering as dead code.
264
+ if (openSyncBracketCount === 0 && typeof setPauseGuard === 'function') {
265
+ setPauseGuard(() => openSyncBracketCount === 0);
266
+ }
267
+ if (crossingError) throw crossingError;
268
+ }
269
+ }
270
+
271
+ return {
272
+ withOpenSyncBracket,
273
+ /** Current number of open sync brackets -- read-only observability. */
274
+ openBracketCount: () => openSyncBracketCount,
275
+ };
276
+ }
277
+
278
+ // ONE shared bracket wrapping EVERY role-identified agent() dispatch below
279
+ // -- planner, plan-reviewer, doer, reviewer, deployer, integ-test-runner,
280
+ // harvester. No phase-based exemptions: a deployer or integ-test-runner
281
+ // running against a stale checkout/beads clone is exactly as damaging as a
282
+ // stale doer/reviewer diff. Bracket order: VCS-auth preflight gate, G-pull,
283
+ // D-pull, dispatch, G-push, D-push.
284
+ //
285
+ // Two orthogonal sync axes, each pulled before and (optionally) pushed
286
+ // after:
287
+ // - CODE (git): `pushCode` is true ONLY for the code-writing roles (doer,
288
+ // harvester); every other role is read-side (G-pull before, a no-op
289
+ // G-push after -- see syncMemberAfter's short-circuit).
290
+ // - BEADS (dolt): `pushBeads` is true for every role that MUTATES beads
291
+ // -- planner (creates tasks), doer (closes them), integ-test-runner
292
+ // (closes features / files bugs), harvester (defers issues). The pure
293
+ // read-side roles (reviewer, plan-reviewer, deployer) D-pull before and
294
+ // no-op D-push after. integ-test-runner D-pushes WITHOUT a git push: it
295
+ // never touches code, only beads.
296
+ //
297
+ // The orchestrator's OWN beads mutations/reads are NOT dispatches and are
298
+ // bracketed separately at their own call sites below. Deliberately NOT
299
+ // applied to the Streak Assignment call: that dispatch carries no
300
+ // `agentType`/persona of its own and is not one of the seven types.
301
+ //
302
+ // Option flags:
303
+ // - needsVcsAuth: gates the proactive ensureVcsAuthFresh preflight,
304
+ // independently of `pushCode` (apra-fleet-647.1.1.2). Defaults to
305
+ // `pushCode || pushBeads`: a code-writing role always needed it
306
+ // already, and this extends the same proactive preflight to read-side
307
+ // roles whose bracket still D-pushes beads (planner, integ-test-
308
+ // runner, regression-test-runner) -- `bd dolt push` hits the same
309
+ // credential surface as `git push`. Explicitly pass `needsVcsAuth:
310
+ // true` for a bracket that will raise a PR (or otherwise needs a
311
+ // fresh credential) even with pushCode:false and pushBeads:false.
312
+ // - skipPreDispatchSync: the prior attempt failed TERMINALLY with nothing
313
+ // published, so the local G/D workspace is unchanged since that
314
+ // attempt's pull -- skip the pre-dispatch sync entirely.
315
+ // - skipPreDispatchDoltPull: skip only the `bd dolt pull` spawn while
316
+ // still running doltPullBefore's sync.remote pre-gate probe and the
317
+ // G-side pull; for a dispatch whose beads clone was provably just
318
+ // freshened.
319
+ // - resumeOntoRemoteTip: the prior attempt was NOT provably a no-mutation
320
+ // failure (it may have committed and/or pushed), so run the full
321
+ // pre-dispatch sync in syncMemberBefore's resetToRemoteTip mode -- fetch
322
+ // and reset onto the remote tip BEFORE the doer can commit, resuming on
323
+ // published work instead of re-implementing it and diverging.
324
+ // skipPreDispatchSync and resumeOntoRemoteTip encode opposite assumptions
325
+ // about whether the prior attempt published anything and MUST never be
326
+ // passed together. Nothing in the code enforces this today.
327
+ //
328
+ // Post-dispatch: when the dispatch COMPLETED, only the SYNC step is retried
329
+ // on failure -- the turn is never re-dispatched. A push failure is
330
+ // frequently transient (a racing writer, a momentarily unreachable remote,
331
+ // a credential refresh in flight) and re-running the sync costs nothing,
332
+ // whereas re-running the LLM turn costs a full dispatch and risks duplicate
333
+ // beads/commit mutations. `agent` is threaded to syncMemberAfterOrdered so
334
+ // a G-push hitting a real content conflict can attempt exactly one
335
+ // agent-with-runbook resolution before failing the streak (a no-op for
336
+ // non-code-writing roles; never fires for a plain divergence).
337
+ //
338
+ // `ctx` is the dependency context createGitSync() binds: the sync-bracket
339
+ // handle plus the runSprintCycle state this function used to close over
340
+ // lexically (command, log, branch, args, agent, doltPushMutex, sprintId,
341
+ // onAuthFailure, resolveMemberProvider, ensureVcsAuthFresh) and the three
342
+ // runner.js helpers it calls (syncMemberBefore, syncMemberAfterOrdered,
343
+ // isNoMutationDispatchFailure), injected rather than imported so this
344
+ // module never has to import runner.js back (a cycle).
345
+ export async function withGitSync(ctx, member, pushCode, dispatchFn, { pushBeads = false, needsVcsAuth = pushCode || pushBeads, skipPreDispatchSync = false, skipPreDispatchDoltPull = false, resumeOntoRemoteTip = false } = {}) {
346
+ const {
347
+ brackets, command, log, branch, baseBranch, args, agent, doltPushMutex, sprintId,
348
+ onAuthFailure, resolveMemberProvider, ensureVcsAuthFresh, warnWorkflowsPermissionMissing,
349
+ syncMemberBefore, syncMemberAfterOrdered, isNoMutationDispatchFailure,
350
+ } = ctx;
351
+ // (apra-fleet-p2to.4.1) The WHOLE withGitSync bracket -- pre-dispatch
352
+ // G-pull/D-pull, the dispatch itself, and post-dispatch G-push/D-push
353
+ // -- counts as ONE open sync bracket for the clean-state pause guard
354
+ // above: a pause must never land between, say, a pre-dispatch pull and
355
+ // its matching post-dispatch push, which would leave the workspace/
356
+ // beads clone mid-cycle. It runs through the SAME withOpenSyncBracket()
357
+ // every standalone bracket uses (apra-fleet-3swo.4.1 -- it used to
358
+ // hand-roll its own increment/try/finally copy), whose `finally`
359
+ // guarantees the decrement fires on every exit path (the normal return,
360
+ // or any of the throws below), never leaving a stale increment behind.
361
+ return brackets.withOpenSyncBracket(async () => {
362
+ if (skipPreDispatchSync) {
363
+ log(`[Sync] Skipping pre-dispatch G-pull/D-pull for member '${member}' on a retry after a terminal no-mutation dispatch failure (prior attempt published nothing -- workspace unchanged since the last pull).`);
364
+ } else {
365
+ // Proactively refresh this member's VCS credentials before the
366
+ // G-pull/D-push, gated on `needsVcsAuth` rather than directly on
367
+ // `pushCode`: a code-writing role always needs it (pushCode implies
368
+ // needsVcsAuth by the default above), but so does any read-side
369
+ // role whose bracket still D-pushes beads (planner, integ-test-
370
+ // runner, regression-test-runner) or will raise a PR -- `bd dolt
371
+ // push` shells out to git under the hood and hits the exact same
372
+ // credential surface a `git push` does (apra-fleet-647.1.1.2). A
373
+ // pure read-only role (reviewer, plan-reviewer, deployer -- no
374
+ // push of either kind) passes needsVcsAuth:false (the computed
375
+ // default) and gets no preflight, since it has nothing to
376
+ // preflight for. ensureVcsAuthFresh is itself a no-op when a
377
+ // still-fresh credential is cached, and NEVER throws -- a
378
+ // preflight failure degrades silently and never aborts a
379
+ // dispatch.
380
+ if (needsVcsAuth) {
381
+ log(`[Sync] preflight: member '${member}' needs a fresh VCS credential before this dispatch (pushCode=${pushCode}, pushBeads=${pushBeads}, needsVcsAuth=${needsVcsAuth}).`);
382
+ await ensureVcsAuthFresh(member);
383
+ }
384
+ // (apra-fleet-2wdc.6) Workflows-permission preflight: only a
385
+ // CODE-writing dispatch (pushCode) can ever push a
386
+ // .github/workflows/** change, so this is gated on pushCode
387
+ // specifically -- not needsVcsAuth, which also covers
388
+ // beads-only (D-push) roles that never touch the git branch at
389
+ // all. warnWorkflowsPermissionMissing is undefined for any
390
+ // caller that has not wired createWorkflowsPermissionPreflightCallback
391
+ // (e.g. a pre-existing test's hand-built ctx) -- optional and a
392
+ // no-op in that case, exactly like the other injected callbacks
393
+ // here. Never throws; see that function's own doc comment.
394
+ if (pushCode && typeof warnWorkflowsPermissionMissing === 'function') {
395
+ await warnWorkflowsPermissionMissing(member, branch, baseBranch);
396
+ }
397
+ await syncMemberBefore(member, { command, log, branch, onAuthFailure, resetToRemoteTip: resumeOntoRemoteTip, resolveMemberProvider });
398
+ // EXPLICITLY FATAL (apra-fleet-417.3.1): a pre-dispatch D-pull that
399
+ // silently degraded would hand the agent a STALE beads clone and
400
+ // let it act on it -- worse than not dispatching at all.
401
+ //
402
+ // Thread this member's REGISTERED shell into dolt-settle
403
+ // (apra-fleet-7dir.16) so a settle triggered for a Windows member
404
+ // whose shell is Git-for-Windows bash gets bash-dialect dolt
405
+ // commands instead of being force-assumed PowerShell.
406
+ // resolveMemberTarget never throws (degrades to { os: 'linux',
407
+ // shell: '' } on any lookup failure), and is a no-op when no
408
+ // callTool is wired (e.g. a mock-sprint scenario with no MCP
409
+ // client), matching this call site's pre-existing behavior.
410
+ const settleTarget = (args && typeof args.callTool === 'function')
411
+ ? await resolveMemberTarget({ fleetApi: new ApraFleet({ callTool: args.callTool }), member, log })
412
+ : { os: 'linux', shell: '' };
413
+ await DoltSync.syncBefore(member, { command, log, skipRefresh: skipPreDispatchDoltPull, onAuthFailure, fatal: true, settle: buildSettleCallback(member, { command, log, shell: settleTarget.shell }) });
414
+ }
415
+ // The teardown is deliberately NOT a `finally`. A throw out of a
416
+ // `finally` replaces the (successful) dispatch result and is
417
+ // indistinguishable, to the caller's retry ladder, from "the dispatch
418
+ // itself failed" -- which would let a pure sync failure trigger a brand
419
+ // new LLM turn over work already committed locally. Splitting the two
420
+ // lets the sync be retried on its own and, if it still fails, surfaced
421
+ // as a typed PostDispatchSyncError no retry caller may answer by
422
+ // redispatching.
423
+ let dispatchThrew = null;
424
+ let dispatchResult;
425
+ try {
426
+ dispatchResult = await dispatchFn();
427
+ } catch (err) {
428
+ dispatchThrew = err;
429
+ }
430
+ {
431
+ // On a TERMINAL dispatch failure the agent never delivered a usable
432
+ // result, so there is provably nothing new to publish -- skip the
433
+ // G-push/D-push teardown entirely. This deliberately EXCLUDES
434
+ // every case where the agent DID run and may have committed code/
435
+ // beads that still must be published: max_turns_exhausted and
436
+ // watchdog_timeout dispatch failures, and an AgentOutputError
437
+ // (the LLM answered, only its output was unusable).
438
+ if (dispatchThrew && isNoMutationDispatchFailure(dispatchThrew)) {
439
+ log(`[Sync] Skipping post-dispatch G-push/D-push for member '${member}' after a terminal dispatch failure (nothing to publish): ${dispatchThrew.message}`);
440
+ } else {
441
+ // G-push (code) before D-push (beads) -- see
442
+ // syncMemberAfterOrdered() for the unreachable-close rationale
443
+ // behind that ordering. When the dispatch already threw, the
444
+ // teardown keeps a single-attempt shape: the dispatch error is
445
+ // what surfaces either way, so retrying the sync buys nothing.
446
+ const syncAttemptDelaysMs = dispatchThrew ? [0] : POST_DISPATCH_SYNC_RETRY_DELAYS_MS;
447
+ let syncErr = null;
448
+ for (let attempt = 0; attempt < syncAttemptDelaysMs.length; attempt++) {
449
+ if (syncAttemptDelaysMs[attempt] > 0) {
450
+ log(`[Sync] Post-dispatch sync for member '${member}' failed; retrying ONLY the sync step in ${syncAttemptDelaysMs[attempt] / 1000}s (attempt ${attempt + 1}/${syncAttemptDelaysMs.length}) -- the dispatch already completed and must NOT be re-run.`);
451
+ if (!mockInstantRetryBackoff()) {
452
+ await new Promise((resolve) => setTimeout(resolve, syncAttemptDelaysMs[attempt]));
453
+ }
454
+ }
455
+ try {
456
+ await syncMemberAfterOrdered(member, {
457
+ command, pushCode, pushBeads, log, branch,
458
+ mutex: doltPushMutex, sprintId, agent, onAuthFailure,
459
+ resolveMemberProvider, args,
460
+ });
461
+ syncErr = null;
462
+ break;
463
+ } catch (err) {
464
+ syncErr = err;
465
+ }
466
+ }
467
+ if (syncErr) {
468
+ // A dispatch error always wins over a sync error: it is the
469
+ // more fundamental failure.
470
+ if (dispatchThrew) throw dispatchThrew;
471
+ throw new PostDispatchSyncError(
472
+ `Post-dispatch sync (G-push/D-push) failed for member '${member}' AFTER the dispatch completed successfully: ${syncErr.message}. The dispatch's work is already committed locally -- it must NOT be re-dispatched; fix the sync (credentials/remote) and re-run.`,
473
+ { member, dispatchResult, syncAttempts: syncAttemptDelaysMs.length, cause: syncErr },
474
+ );
475
+ }
476
+ }
477
+ }
478
+ if (dispatchThrew) throw dispatchThrew;
479
+ return dispatchResult;
480
+ }, pushCode ? { exclusiveKey: CODE_WRITE_BRACKET_KEY, label: `withGitSync(${member})` } : undefined);
481
+ }
482
+
483
+ /**
484
+ * Binds the sync-bracket handle and every piece of runSprintCycle state the
485
+ * bracketed helpers need, and returns the sync/push surface runner.js calls.
486
+ * Pass either an existing `brackets` handle (runner.js creates one early, so
487
+ * the pause guard is registered before any dispatch can happen) or a
488
+ * `setPauseGuard` for this factory to create one from.
489
+ */
490
+ export function createGitSync(deps = {}) {
491
+ const brackets = deps.brackets ?? createSyncBrackets({ setPauseGuard: deps.setPauseGuard });
492
+ const ctx = { ...deps, brackets };
493
+ const { command, log, branch, doltPushMutex, sprintId, onAuthFailure, resolveMemberProvider, syncMemberAfter } = ctx;
494
+ return {
495
+ brackets,
496
+ /** Current number of open sync brackets -- read-only observability. */
497
+ openBracketCount: () => brackets.openBracketCount(),
498
+ /**
499
+ * The generic bracket, for a caller whose sync is not one of the
500
+ * named helpers below -- e.g. a runner.js helper that D-pulls
501
+ * internally and must count as ONE bracket around its whole call.
502
+ * This is the only way to open a bracket from outside this module:
503
+ * the counter itself is unreachable.
504
+ */
505
+ withOpenSyncBracket: (fn, options) => brackets.withOpenSyncBracket(fn, options),
506
+ /** The full dispatch bracket. See withGitSync() above. */
507
+ withGitSync: (memberName, pushCode, dispatchFn, options) => withGitSync(ctx, memberName, pushCode, dispatchFn, options),
508
+ /**
509
+ * A standalone bracketed beads D-pull. `command`/`log` default to the
510
+ * bound sprint state; anything else (fatal, readinessGate, settle) is
511
+ * passed through verbatim.
512
+ */
513
+ syncBeadsBefore: (memberName, options = {}) => brackets.withOpenSyncBracket(
514
+ () => DoltSync.syncBefore(memberName, { command, log, ...options }),
515
+ ),
516
+ /**
517
+ * A standalone bracketed beads D-push. `command`/`log` and the
518
+ * cross-member D-push mutex default to the bound sprint state.
519
+ */
520
+ syncBeadsAfter: (memberName, options = {}) => brackets.withOpenSyncBracket(
521
+ () => DoltSync.syncAfter(memberName, { command, log, mutex: doltPushMutex, sprintId, ...options }),
522
+ ),
523
+ /**
524
+ * A standalone bracketed beads D-push, routed through
525
+ * DoltSync.syncAfter() (apra-fleet-3swo.4.9 part b) exactly like its
526
+ * sibling syncBeadsAfter() above. This is what closes the Final
527
+ * Review findings D-push hole: that site used to call doltPushAfter()
528
+ * bare, outside every bracket, so the pause guard read "safe to
529
+ * pause" with a dolt push in flight (apra-fleet-3swo.4.1). Routing
530
+ * through DoltSync.syncAfter() (rather than calling doltPushAfter()
531
+ * directly the way this function used to) closes a SECOND gap: a
532
+ * bare doltPushAfter() always THROWS on an unresolved failure, which
533
+ * made this call site behave inconsistently with every other
534
+ * orchestrator post-mutation D-push (all of which go through
535
+ * syncBeadsAfter and are deliberately non-fatal -- see dolt-sync.mjs's
536
+ * module header, "The orchestrator's post-mutation D-pushes are
537
+ * deliberately NOT fatal"). Now this site DEGRADES the same way: an
538
+ * unresolved D-push here is logged and recorded
539
+ * (DoltSync.getDegradedSyncRecords()) rather than aborting the
540
+ * sprint, and the next D-push bracket for this member is the queued
541
+ * retry, same as every sibling site. Pass `fatal: true` in `options`
542
+ * to opt back into the old throwing behavior at this call site.
543
+ */
544
+ pushBeadsAfter: (memberName, options = {}) => brackets.withOpenSyncBracket(
545
+ () => DoltSync.syncAfter(memberName, { command, log, mutex: doltPushMutex, sprintId, ...options }),
546
+ ),
547
+ /**
548
+ * A standalone bracketed G-push through runner.js's syncMemberAfter().
549
+ * This is what closes the Publish-PR git-push hole: that site used to
550
+ * call syncMemberAfter() bare, outside any bracket.
551
+ */
552
+ pushGitAfter: (memberName, options = {}) => brackets.withOpenSyncBracket(
553
+ () => syncMemberAfter(memberName, { command, log, branch, onAuthFailure, resolveMemberProvider, ...options }),
554
+ ),
555
+ };
556
+ }