@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,1279 @@
1
+ // VCS/LLM auth for fleet-sprint: credential provisioning, credential read-back,
2
+ // PR raising, and the reactive/proactive auth self-heal callbacks
3
+ // (apra-fleet-3swo.3.1). Moved verbatim out of runner.js -- runner.js re-exports
4
+ // every symbol it previously exported from this region, so existing importers of
5
+ // fleet-sprint/runner.js resolve unchanged. Behaviour was originally kept
6
+ // deliberately identical to the pre-move code (a move-only extraction), but
7
+ // apra-fleet-3swo.13 is exactly the "separately-reviewed behaviour PR" that
8
+ // note used to point at: it replaced the mojibake provision-result regexes'
9
+ // role as the source of truth with structuredContent.ok/.reason
10
+ // (provisionOutcome below), keeping the prose regexes only as a fallback for
11
+ // a result with no structuredContent at all.
12
+ import { ApraFleet } from '@apralabs/apra-fleet-client';
13
+ import { buildCreatePrCommand, resolveProvider, capabilities as vcsCapabilities, parseProviderRepoRef, getVcsProvider, resolveVcsAuthProviderForHost, isAuthBackend, VCS_NO_REGISTERED_PROVIDER, DEFAULT_VCS_PROVIDER } from './vcs-module.mjs';
14
+ import { getSeCommands } from './se-os-commands.mjs';
15
+ import { resolveMemberTarget } from './member-target.mjs';
16
+ import { resultText } from './mcp-result.mjs';
17
+
18
+ /**
19
+ * Best-effort, GENERIC extraction of an "owner/repo" string from a git remote
20
+ * URL (https, scp-like git@host:owner/repo(.git), or ssh://). Deliberately
21
+ * target-agnostic: fleet-sprint develops many different repos, so the `repos`
22
+ * argument passed to provision_vcs_auth must be DERIVED at runtime from the
23
+ * member's own git remote, never hardcoded to a literal repo name. Returns
24
+ * null on anything unrecognized so the caller can omit `repos` (optional
25
+ * server-side) rather than guess.
26
+ *
27
+ * @param {string|null|undefined} url
28
+ * @returns {string|null}
29
+ */
30
+ export function parseOwnerRepoFromRemoteUrl(url) {
31
+ const text = String(url == null ? '' : url).trim();
32
+ if (!text) return null;
33
+ let m = text.match(/^https?:\/\/[^/]+\/([^/]+)\/([^/]+?)(\.git)?\/?$/i);
34
+ if (m) return `${m[1]}/${m[2]}`;
35
+ m = text.match(/^ssh:\/\/[^@/]+@[^/]+\/([^/]+)\/([^/]+?)(\.git)?\/?$/i);
36
+ if (m) return `${m[1]}/${m[2]}`;
37
+ // scp-like syntax, e.g. git@github.com:owner/repo.git
38
+ m = text.match(/^[\w.-]+@[^:]+:([^/]+)\/([^/]+?)(\.git)?\/?$/i);
39
+ if (m) return `${m[1]}/${m[2]}`;
40
+ return null;
41
+ }
42
+
43
+ /**
44
+ * Resolve the `repos` scope for a member's git remote (apra-fleet-5co8.1.2).
45
+ *
46
+ * The two-line-generic parse above cannot express every provider's repository
47
+ * identity: Azure DevOps' is org/project/repo behind a '_git' marker, which
48
+ * the owner/repo regexes score as "unrecognized" (null) and therefore silently
49
+ * drop the repos scope. So the URL is first offered to whichever registered
50
+ * provider CLAIMS its host, via VCSModule.parseProviderRepoRef() -> that
51
+ * provider's own parseRepoRef hook, and only falls back to the generic parse
52
+ * when no provider claims the host or the claiming one has no hook. Every
53
+ * provider-specific rule (legal URL shapes, coordinate names, remedy text)
54
+ * stays in the provider file: this function -- and runner.js as a whole --
55
+ * never names or branches on a provider.
56
+ *
57
+ * A host CLAIMED by a provider whose hook rejects the URL is a different
58
+ * failure from an unrecognized one: the remote is malformed, and proceeding
59
+ * with no scope would provision credentials against the wrong (or no) repo.
60
+ * That case returns a typed `error` naming the shape the provider expects, for
61
+ * the caller to raise as a PREFLIGHT failure -- not a stderr classification.
62
+ *
63
+ * `ref` carries the provider's full coordinate object when one was produced
64
+ * (null otherwise), so a caller can hand it back to that same provider's other
65
+ * hooks -- e.g. buildProvisionArgs, which derives an org URL from it
66
+ * (apra-fleet-5co8.2.1) -- without re-parsing or interpreting it here.
67
+ *
68
+ * @param {string|null|undefined} url
69
+ * @returns {{ repo: string|null, ref: object|null, error: string|null }}
70
+ */
71
+ export function parseRepoScopeFromRemoteUrl(url) {
72
+ const text = String(url == null ? '' : url).trim();
73
+ if (!text) return { repo: null, ref: null, error: null };
74
+
75
+ const providerRef = parseProviderRepoRef(text);
76
+ if (providerRef && providerRef.error) return { repo: null, ref: null, error: providerRef.error };
77
+ if (providerRef && providerRef.canonical) return { repo: providerRef.canonical, ref: providerRef.ref, error: null };
78
+
79
+ return { repo: parseOwnerRepoFromRemoteUrl(text), ref: null, error: null };
80
+ }
81
+
82
+ /**
83
+ * Read the credential-store entry NAMES (never values) currently registered on
84
+ * the hub, for a provider hook that needs to fail fast when the secret it
85
+ * intends to reference as a {{secret.NAME}} placeholder does not exist
86
+ * (apra-fleet-5co8.2.1).
87
+ *
88
+ * Returns null -- not an empty list -- when the store cannot be read or its
89
+ * response cannot be parsed, so a hook can tell "the store definitely lacks
90
+ * this entry" apart from "unknown" and skip the check rather than emit a
91
+ * false, sprint-stopping ERROR. A genuinely missing secret still fails loudly
92
+ * hub-side when placeholder resolution runs.
93
+ *
94
+ * @param {object} fleetApi
95
+ * @returns {Promise<string[]|null>}
96
+ */
97
+ async function listCredentialStoreNames(fleetApi) {
98
+ if (!fleetApi || typeof fleetApi.credentialStoreList !== 'function') return null;
99
+ try {
100
+ const parsed = JSON.parse(resultText(await fleetApi.credentialStoreList()));
101
+ if (!Array.isArray(parsed)) return null;
102
+ return parsed
103
+ .map((entry) => (entry && typeof entry.name === 'string' ? entry.name : null))
104
+ .filter((name) => name !== null);
105
+ } catch {
106
+ return null;
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Build the provision_vcs_auth arguments for a member, dispatched through the
112
+ * resolved provider's OPTIONAL buildProvisionArgs hook (apra-fleet-5co8.2.1).
113
+ *
114
+ * A provider with no hook gets `base` verbatim -- the GitHub-App-shaped
115
+ * `git_access`/`repos` arguments this function has always sent -- so nothing
116
+ * changes for GitHub or any other existing provider. A provider WITH a hook
117
+ * owns its own argument shape entirely, including which credential-store entry
118
+ * it references and what remedy text a missing one prints. No provider name,
119
+ * no auth-mode knowledge and no raw credential value appears here.
120
+ *
121
+ * `remoteUrl` / `remoteReadError` are passed through so a hook can (a) bind
122
+ * the credential to the host the member actually pushes to and (b) word an
123
+ * underivable-org error by its real cause -- an unreadable remote is not a
124
+ * malformed one. A hook may also return a `note`, logged verbatim: an
125
+ * advisory the operator should see (e.g. an ssh remote the PAT cannot
126
+ * serve) that is NOT a failure.
127
+ *
128
+ * @param {{ provider: string, base: object, repoRef: object|null, fleetApi: object,
129
+ * secretName?: string, remoteUrl?: string, remoteReadError?: string|null,
130
+ * log?: Function, logPrefix?: string }} ctx
131
+ * @returns {Promise<object>} the arguments to send
132
+ */
133
+ async function buildProvisionArgsForProvider({ provider, base, repoRef, fleetApi, secretName, remoteUrl, remoteReadError, log = () => {}, logPrefix = '' }) {
134
+ const impl = getVcsProvider(provider);
135
+ if (!impl || typeof impl.buildProvisionArgs !== 'function') return base;
136
+
137
+ const availableSecrets = await listCredentialStoreNames(fleetApi);
138
+ const built = impl.buildProvisionArgs({ base, repoRef, availableSecrets, secretName, remoteUrl, remoteReadError });
139
+ if (built && typeof built.error === 'string') throw new Error(built.error);
140
+ if (!built || !built.args || typeof built.args !== 'object') {
141
+ throw new Error(`ERROR: VCS provider '${provider}' returned no provision arguments for member '${base.member_name}'.`);
142
+ }
143
+ if (typeof built.note === 'string' && built.note.trim()) {
144
+ log(`${logPrefix}: note: ${built.note.trim()}`);
145
+ }
146
+ return built.args;
147
+ }
148
+
149
+ // apra-fleet-3swo.13: provision_vcs_auth / provision_llm_auth used to be
150
+ // classified by matching a leading status emoji on the prose summary above
151
+ // (check mark = success, cross mark = failure, star = the LLM-auth
152
+ // local-member skip marker). The server retired those emoji -- src/tools/
153
+ // provision-auth.ts and src/tools/provision-vcs-auth.ts now emit ASCII
154
+ // [OK]/[FAIL]/[SKIP] prose -- and wrapTool() (src/services/tool-registry.ts)
155
+ // never sets `isError` on any path, so that prose/isError test had gone
156
+ // permanently false: a FAILED provision silently read as a success. Both
157
+ // tools now also return a `structuredContent` half (ProvisionAuthStructured
158
+ // / ProvisionVcsAuthStructured -- see packages/apra-fleet-client/src/client/
159
+ // api.mjs) with a machine-readable `ok`/`reason` pair that stays safe to
160
+ // branch on regardless of any future prose wording change. Read THAT when
161
+ // present; only fall back to the old prose/isError heuristic for a result
162
+ // that carries no structuredContent at all (e.g. a test double that mocks a
163
+ // bare `{ content }` shape).
164
+ function provisionOutcome(result, text) {
165
+ const structured = result && result.structuredContent;
166
+ if (structured && typeof structured.ok === 'boolean') {
167
+ return { ok: structured.ok, reason: typeof structured.reason === 'string' ? structured.reason : null };
168
+ }
169
+ return {
170
+ ok: !((result && result.isError) || /^\[FAIL\]/.test(String(text == null ? '' : text).trim())),
171
+ reason: null,
172
+ };
173
+ }
174
+
175
+ // Shared provisioning core used by BOTH the REACTIVE onAuthFailure self-heal
176
+ // (createVcsAuthSelfHealCallback) and the PROACTIVE preflight
177
+ // (createVcsAuthPreflightCallback) -- one call shape, one owner/repo
178
+ // derivation, one success/failure text-parsing rule, so the two paths can
179
+ // never drift on what "provisioned" means.
180
+ //
181
+ // Returns the newly-provisioned credential's `expiresAt` (a Date, or null
182
+ // when the response carries no expiry metadata -- PAT-mode credentials never
183
+ // expire) so a caller can cache it and skip a future redundant call.
184
+ //
185
+ // `gitAccess` defaults to DEFAULT_SYNC_GIT_ACCESS ('push') -- the shared
186
+ // self-heal/preflight callers below NEVER override it. The only callers
187
+ // permitted to pass a higher level ('push+pr') are the two PR-raising call
188
+ // sites (Publish PR, finalizeAbort), each via provisionPrCapableAuthForMember,
189
+ // invoked immediately before their PR-creation dispatch -- never at sprint
190
+ // setup, never from this shared self-heal/preflight path. See
191
+ // apra-fleet-tfx.8 and the just-in-time credential-scoping ADR
192
+ // (docs/adr-server-never-acts-on-repo.md) for the rogue-dispatch blast-radius
193
+ // rationale: widening this default would give every member standing
194
+ // pull_requests:write for the whole sprint.
195
+ //
196
+ // DEFAULT_SYNC_GIT_ACCESS is exported (not just a bare literal) so the Sync-
197
+ // step workflows-permission preflight below (apra-fleet-2wdc.6) can assert
198
+ // against the SAME value this function actually requests, rather than
199
+ // duplicating the 'push' literal and risking the two silently drifting apart.
200
+ export const DEFAULT_SYNC_GIT_ACCESS = 'push';
201
+
202
+ // GitHub App access levels that request the 'workflows' permission -- mirrors
203
+ // src/services/github-app.ts's mapAccessLevel() table (apra-fleet-2wdc.1):
204
+ // push, push+pr, admin and full carry it; read and issues do not. Duplicated
205
+ // here, not imported, because fleet-sprint is the GENERIC engine
206
+ // (docs/generic-engine-boundary.md) and a sprint run can target ANY fleet
207
+ // server, not necessarily one built from this same checkout.
208
+ //
209
+ // Being a hand-maintained copy, this set cannot by itself catch a regression
210
+ // in mapAccessLevel(): a change there would just leave this stale and silently
211
+ // wrong. The guard is therefore on the SERVER side, where both halves are
212
+ // readable at once -- tests/workflows-access-level-table-parity.test.ts parses
213
+ // this literal out of this file and asserts it matches mapAccessLevel()'s
214
+ // table exactly, so editing one without the other fails the server suite.
215
+ // That test is the reason this copy is safe to keep; do not delete it.
216
+ const GITHUB_ACCESS_LEVELS_WITH_WORKFLOWS = new Set(['push', 'push+pr', 'admin', 'full']);
217
+
218
+ /**
219
+ * Pure lookup: does GitHub App access level `gitAccess` carry the 'workflows'
220
+ * permission? See GITHUB_ACCESS_LEVELS_WITH_WORKFLOWS above for the table this
221
+ * mirrors and why it is a local copy.
222
+ * @param {string} gitAccess
223
+ * @returns {boolean}
224
+ */
225
+ export function accessLevelGrantsWorkflowsPermission(gitAccess) {
226
+ return GITHUB_ACCESS_LEVELS_WITH_WORKFLOWS.has(gitAccess);
227
+ }
228
+
229
+ /**
230
+ * @param {{ fleetApi: object, command: Function, member: string, log?: Function, logPrefix: string, gitAccess?: string, resolvedProvider?: { provider: string, authMode: string|null } }} opts
231
+ * @returns {Promise<{ expiresAt: Date|null, repo: string|null }>}
232
+ */
233
+ /**
234
+ * Map a member's git remote URL onto the VCS provider that hosts it, using the
235
+ * SAME registry that answers every other host question (vcs-module.mjs's
236
+ * capabilities() for the host parse, then resolveVcsAuthProviderForHost() for
237
+ * the claim). Returns the provider NAME, or null when the URL has no host or no
238
+ * registered AUTH BACKEND claims it -- provisioning credentials against an
239
+ * unclaimed host would be a guess, not a detection.
240
+ *
241
+ * Note which resolver this uses. resolveVcsAuthProviderForHost() (not the
242
+ * capabilities-axis resolveVcsProviderForHost()) asks each provider its
243
+ * ANCHORED auth matcher and never falls back to the 'generic-git' catch-all.
244
+ * That distinction is the whole point here: the caller below mints a real push
245
+ * credential from whatever this returns, and GitHub's capabilities-axis
246
+ * matchesHost() is a deliberate substring test for GitHub Enterprise Server,
247
+ * which would otherwise let 'mygithubmirror.attacker.io' claim the credential.
248
+ * See vcs-providers/github.mjs's matchesHostForAuth().
249
+ *
250
+ * @param {unknown} remoteUrl
251
+ * @returns {string|null}
252
+ */
253
+ function detectVcsProviderFromRemote(remoteUrl) {
254
+ const { host } = vcsCapabilities(remoteUrl);
255
+ if (!host) return null;
256
+ const impl = resolveVcsAuthProviderForHost(host);
257
+ return (impl && impl.name) || null;
258
+ }
259
+
260
+ async function provisionVcsAuthForMember({ fleetApi, command, member, log = () => {}, logPrefix, gitAccess = DEFAULT_SYNC_GIT_ACCESS, azdevopsPatSecretName, remoteUrlOverride, resolvedProvider }) {
261
+ let repos;
262
+ let derivedRepo = null;
263
+ let derivedRef = null;
264
+ // Reading the remote is best-effort (a failure here just means no explicit
265
+ // repos scope), but PARSING it is not: a malformed remote on a host some
266
+ // provider claims is a preflight ERROR that must escape this function
267
+ // rather than be swallowed by the read's catch -- hence the parse sits
268
+ // outside the try. See parseRepoScopeFromRemoteUrl (apra-fleet-5co8.1.2).
269
+ let remoteUrl = '';
270
+ let remoteReadFailed = false;
271
+ let remoteReadError = null;
272
+ // apra-fleet-8zr3-adjacent: a caller that already resolved the sprint's
273
+ // origin remote via a real git-capable member (e.g. Publish PR's
274
+ // publishGitMember) passes it here instead of making THIS function shell
275
+ // out its own 'git remote get-url origin' to `member` -- which matters
276
+ // when `member` is orchestratorMember and may be a git-less/shared member
277
+ // with no checkout to read a remote from at all. Skips the read entirely,
278
+ // never the parse below.
279
+ if (remoteUrlOverride) {
280
+ remoteUrl = String(remoteUrlOverride).trim();
281
+ } else {
282
+ try {
283
+ const remoteRes = await command('git remote get-url origin', { member_name: member, silent: true, failSoft: true });
284
+ remoteUrl = remoteRes && remoteRes.ok ? String(remoteRes.output || '').trim() : '';
285
+ if (!remoteUrl) {
286
+ // A non-ok / empty read is not a parse failure either: keep
287
+ // the reason so a provider hook that needs the remote can
288
+ // say "could not be read" instead of "not a recognized URL".
289
+ const detail = remoteRes && !remoteRes.ok
290
+ ? String(remoteRes.error || remoteRes.output || 'git remote get-url origin failed').trim()
291
+ : 'git remote get-url origin printed nothing';
292
+ remoteReadError = detail || 'git remote get-url origin printed nothing';
293
+ }
294
+ } catch (remoteErr) {
295
+ remoteReadFailed = true;
296
+ remoteReadError = remoteErr.message;
297
+ log(`${logPrefix}: failed to read member '${member}' git remote to derive 'repos' (continuing without an explicit repos scope): ${remoteErr.message}`);
298
+ }
299
+ }
300
+ if (!remoteReadFailed) {
301
+ const scope = parseRepoScopeFromRemoteUrl(remoteUrl);
302
+ if (scope.error) {
303
+ throw new Error(`${logPrefix}: cannot provision VCS auth for member '${member}': ${scope.error}`);
304
+ }
305
+ derivedRef = scope.ref;
306
+ if (scope.repo) {
307
+ repos = [scope.repo];
308
+ derivedRepo = scope.repo;
309
+ } else {
310
+ // remoteUrlOverride, when supplied, may belong to a DIFFERENT
311
+ // member/repo than `member` -- see the caller-note above -- so
312
+ // this log deliberately does not claim the URL is `member`'s own.
313
+ const remoteSource = remoteUrlOverride ? 'the supplied remote URL' : `member '${member}' git remote`;
314
+ log(`${logPrefix}: could not derive an owner/repo from ${remoteSource} (raw: '${remoteUrl}'); calling provision_vcs_auth without an explicit repos scope.`);
315
+ }
316
+ }
317
+
318
+ // apra-fleet-647.1.2.1: provider and auth-mode are resolved from the
319
+ // member's own persisted vcsProvider (VCSModule.resolveProvider), never
320
+ // hardcoded here -- resolveProvider throws its own typed "ERROR:" for a
321
+ // member with no registered provider rather than silently defaulting to
322
+ // GitHub. `authMode` is provider-owned (github: 'github-app'; other
323
+ // providers: null, no separate mode axis) and is only forwarded as
324
+ // `<provider>_mode` when non-null, matching provision_vcs_auth's own
325
+ // `github_mode` field name for the one provider that has one today.
326
+ // apra-fleet-5co8.13: a caller that already resolved the provider (e.g.
327
+ // the self-heal callback's authRemedy hint lookup) can thread it through
328
+ // via `resolvedProvider`, saving a second member_detail round trip. Falls
329
+ // back to this function's own lookup when not supplied.
330
+ //
331
+ // LAYER 2 -- dispatch-time self-heal. resolveProvider() throws for a member
332
+ // registered with NO vcsProvider at all, which is exactly the state
333
+ // register_member could leave a fully dispatch-capable member in before
334
+ // registration-time detection landed. For every such member ALREADY
335
+ // registered, that throw arrives reactively -- typically hours into an
336
+ // unattended sprint, on the first push -- and no amount of retrying can heal
337
+ // it, because the self-heal path itself dies on the same lookup.
338
+ //
339
+ // So: when the registry has nothing, fall back to `remoteUrl` -- the remote
340
+ // this function already read/received above for the repos scope (never a
341
+ // second dispatch). That URL is `member`'s own git remote ONLY when no
342
+ // `remoteUrlOverride` was supplied; when it was, the detected provider is
343
+ // still correct for provisioning `member` against that URL's host, but the
344
+ // URL itself may not be `member`'s own remote. The host is mapped through
345
+ // the SAME provider registry every other host decision goes through, so no
346
+ // provider literal appears here, and a host claimed only by the generic-git
347
+ // catch-all is deliberately NOT accepted.
348
+ //
349
+ // No separate persistence call is needed: fleetApi.provisionVcsAuth() below
350
+ // already writes vcsProvider back to the member registry as an existing side
351
+ // effect, so the very next lookup for this member resolves normally.
352
+ //
353
+ // An unreadable or unrecognized remote re-throws the ORIGINAL error -- that
354
+ // is a real failure with nothing to detect, and must stay loud. So does
355
+ // every OTHER way resolveProvider() can fail. Only the one failure that
356
+ // carries VCS_NO_REGISTERED_PROVIDER is self-healable, and it is matched by
357
+ // that stable code rather than by its message text.
358
+ let provider;
359
+ let authMode;
360
+ try {
361
+ ({ provider, authMode } = resolvedProvider || await resolveProvider(member, { fleetApi }));
362
+ } catch (resolveErr) {
363
+ if (!resolveErr || resolveErr.code !== VCS_NO_REGISTERED_PROVIDER) throw resolveErr;
364
+ const detected = (!remoteReadFailed && remoteUrl)
365
+ ? detectVcsProviderFromRemote(remoteUrl)
366
+ : null;
367
+ if (!detected) throw resolveErr;
368
+ provider = detected;
369
+ const impl = getVcsProvider(provider);
370
+ authMode = isAuthBackend(impl) ? impl.defaultAuthMode : null;
371
+ const remoteSource = remoteUrlOverride ? 'the supplied remote URL' : 'its git remote';
372
+ log(`${logPrefix}: member '${member}' had no registered VCS provider; detected '${provider}' from ${remoteSource} and will provision it now`);
373
+ }
374
+ // apra-fleet-5co8.2.1: the argument shape itself is now provider-owned.
375
+ // What follows is the DEFAULT (GitHub-App) shape; a provider that declares
376
+ // a buildProvisionArgs hook replaces it wholesale -- see
377
+ // buildProvisionArgsForProvider above.
378
+ const provisionArgs = await buildProvisionArgsForProvider({
379
+ provider,
380
+ base: {
381
+ member_name: member,
382
+ provider,
383
+ ...(authMode ? { [`${provider}_mode`]: authMode } : {}),
384
+ git_access: gitAccess,
385
+ ...(repos ? { repos } : {}),
386
+ },
387
+ repoRef: derivedRef,
388
+ fleetApi,
389
+ secretName: azdevopsPatSecretName,
390
+ remoteUrl,
391
+ remoteReadError,
392
+ log,
393
+ logPrefix,
394
+ });
395
+ const provisionRes = await fleetApi.provisionVcsAuth(provisionArgs);
396
+ const provisionText = resultText(provisionRes);
397
+ // provision_vcs_auth NEVER throws on failure -- it reports failure via
398
+ // structuredContent.ok === false (apra-fleet-3swo.13; see
399
+ // provisionOutcome above). A failed provision must never be allowed to
400
+ // report success: doing so burns the one-shot self-heal and logs a lie.
401
+ if (!provisionOutcome(provisionRes, provisionText).ok) {
402
+ throw new Error(`provision_vcs_auth failed for member '${member}': ${provisionText || '(no detail)'}`);
403
+ }
404
+
405
+ // (apra-fleet-3swo.7.5) Credential expiry comes from the STRUCTURED half of
406
+ // the provision result -- `structuredContent.expiresAt`, an ISO timestamp or
407
+ // null (ProvisionVcsAuthFields in src/tools/provision-vcs-auth.ts) -- and is
408
+ // no longer regex-scraped out of the prose summary by a dedicated prose
409
+ // scraper -- that scraper was retired by the facade-pin removal task
410
+ // (apra-fleet-3swo.7.15).
411
+ //
412
+ // Deliberately inlined rather than factored into a named helper: this
413
+ // module's top-level declarations are pinned symbol-for-symbol by the facade
414
+ // enumeration in test/vcs-auth-extraction-facade.test.mjs, so ADDING a
415
+ // top-level name here turns that gate red exactly as removing one would --
416
+ // and editing that enumeration belongs to the facade-pin task, not this one.
417
+ //
418
+ // The null semantics are preserved EXACTLY, because both the preflight
419
+ // freshness cache and the server's own checkVcsTokenExpiry read null as "no
420
+ // expiry tracked -> OK": an absent, non-string or unparseable value becomes
421
+ // null, never a NaN Date. That last case is load-bearing -- a truthy NaN
422
+ // Date would make every expiring-soon comparison false and silently disable
423
+ // the preflight refresh, the same trap the retired scraper's Number.isNaN
424
+ // guard existed to avoid.
425
+ const rawExpiresAt = provisionRes && provisionRes.structuredContent
426
+ ? provisionRes.structuredContent.expiresAt
427
+ : null;
428
+ const provisionedExpiry = typeof rawExpiresAt === 'string' && rawExpiresAt.trim() !== ''
429
+ ? new Date(rawExpiresAt)
430
+ : null;
431
+ return {
432
+ expiresAt: provisionedExpiry && !Number.isNaN(provisionedExpiry.getTime()) ? provisionedExpiry : null,
433
+ repo: derivedRepo,
434
+ };
435
+ }
436
+
437
+ // Narrowly-scoped, PR-capable provisioning. This is the ONLY call path in
438
+ // runner.js permitted to request git_access: 'push+pr' -- callers must be
439
+ // exactly the two PR-raising call sites (Publish PR, finalizeAbort), invoked
440
+ // immediately before their PR-creation dispatch, never at sprint setup and
441
+ // never from the shared self-heal/preflight path above (which always stays
442
+ // on 'push'). See the just-in-time credential-scoping rationale on
443
+ // provisionVcsAuthForMember above.
444
+ //
445
+ // Also returns the 'owner/repo' this call derived from the member's own git
446
+ // remote (same derivation provisionVcsAuthForMember already performs to
447
+ // scope the mint) -- reusing it here means the PR-raising call sites never
448
+ // need a SECOND `git remote get-url origin` dispatch of their own just to
449
+ // learn the repo VCSModule needs to build the PR-creation command.
450
+ /**
451
+ * @param {{ fleetApi: object, command: Function, member: string, log?: Function, logPrefix: string }} opts
452
+ * @returns {Promise<{ expiresAt: Date|null, repo: string|null }>}
453
+ */
454
+ async function provisionPrCapableAuthForMember({ fleetApi, command, member, log = () => {}, logPrefix, remoteUrlOverride }) {
455
+ return provisionVcsAuthForMember({ fleetApi, command, member, log, logPrefix, gitAccess: 'push+pr', remoteUrlOverride });
456
+ }
457
+
458
+ // Default credential label provision_vcs_auth deploys under when no explicit
459
+ // `label` is passed (src/tools/provision-vcs-auth.ts: `label = input.label ??
460
+ // input.provider`) -- the PR-raising call sites never pass a label either, so
461
+ // the deployed git-credential-helper file is always
462
+ // $HOME/.fleet-git-credential-<DEFAULT_VCS_PROVIDER> on POSIX (src/os/linux.ts
463
+ // gitCredentialHelperWrite), and
464
+ // $env:USERPROFILE\.fleet-git-credential-<DEFAULT_VCS_PROVIDER>.bat on Windows
465
+ // (src/os/windows.ts:279-294).
466
+ //
467
+ // (apra-fleet-3swo.4.10) Kept as a named constant rather than a second
468
+ // independently-hardcoded 'github' string literal: derives from
469
+ // vcs-providers/index.mjs's DEFAULT_VCS_PROVIDER, the SAME single source of
470
+ // truth vcs-module.mjs's classifyFailure()/resolveVcsProviderForHost() fall
471
+ // back to -- so this label default and the rest of the codebase's "which
472
+ // provider when nothing else is known" answer can never independently drift.
473
+ // Value is unchanged ('github') -- this is a routing fix, not a behavior
474
+ // change.
475
+ //
476
+ // REACHABILITY (recorded here so a future reader does not have to redo this
477
+ // analysis): this fallback name is defensive, not normally live. Both call
478
+ // sites below (raiseVcsPrForMember) always resolve a real `provider` via
479
+ // resolveProvider() BEFORE ever consulting vcsCredentialLabelForProvider(),
480
+ // and that call only succeeds after provisionPrCapableAuthForMember() has
481
+ // already run to completion -- which either used an already-registered
482
+ // provider or self-healed by detecting one from the member's git remote and
483
+ // persisting it server-side (provisionVcsAuthForMember's VCS_NO_REGISTERED_
484
+ // PROVIDER branch; see its own comment). resolveProvider() itself NEVER
485
+ // returns a falsy provider on success -- it throws VCS_NO_REGISTERED_PROVIDER
486
+ // instead (vcs-module.mjs) -- so by the time vcsCredentialLabelForProvider()
487
+ // runs in this file's real call graph, `provider` is always a genuine,
488
+ // resolved name and this fallback never fires. It exists purely so a FUTURE
489
+ // caller (or a refactor that loosens resolveProvider()'s contract) degrades
490
+ // to a named, documented default instead of `undefined`/`'undefined'`.
491
+ const DEFAULT_VCS_CREDENTIAL_LABEL = DEFAULT_VCS_PROVIDER;
492
+
493
+ // The credential-helper label provision_vcs_auth deploys a member's VCS
494
+ // credential under, for the PR-raising call sites to read it back from:
495
+ // `label = input.label ?? input.provider` server-side, and no fleet-sprint
496
+ // caller (neither the shared GitHub-App-shaped arguments in
497
+ // provisionVcsAuthForMember nor a provider's buildProvisionArgs hook) ever
498
+ // sends an explicit `label`, so the label IS the provider name -- 'github'
499
+ // -> $HOME/.fleet-git-credential-github, 'azure-devops' ->
500
+ // $HOME/.fleet-git-credential-azure-devops, etc. A member with no resolvable
501
+ // provider keeps the historical default (DEFAULT_VCS_PROVIDER, 'github') --
502
+ // see the reachability note above for why this branch is defensive-only.
503
+ /**
504
+ * @param {string|null|undefined} provider
505
+ * @returns {string}
506
+ */
507
+ export function vcsCredentialLabelForProvider(provider) {
508
+ const name = typeof provider === 'string' ? provider.trim() : '';
509
+ return name || DEFAULT_VCS_CREDENTIAL_LABEL;
510
+ }
511
+
512
+ // Typed marker returned by finalizeAbort() (and logged by the Publish PR step)
513
+ // when the callTool-absent graceful-degradation path is taken: PR creation was
514
+ // intentionally skipped because no MCP client was wired to mint the push+pr
515
+ // credential VCSModule needs, NOT because a PR-creation attempt failed. Callers
516
+ // (and tests) can discriminate this benign skip from a genuine PR failure by
517
+ // this exact reason string. See apra-fleet-tfx.8.1.
518
+ export const PR_SKIPPED_NO_MCP_CLIENT = 'pr-skipped-no-mcp-client';
519
+
520
+ // Builds the member-bound command that RUNS the deployed git-credential-helper
521
+ // and the human-readable descriptor used in this function's error messages
522
+ // (the descriptor must stay readable -- the Windows command itself is an
523
+ // opaque base64 blob).
524
+ //
525
+ // SHELL CONTRACT (confirmed, not assumed -- apra-fleet-ot2z.1):
526
+ // execute_command hands the caller's string to
527
+ // cmds.wrapPidCapture(cmds.wrapInWorkFolder(folder, cmd)) and then straight
528
+ // to the strategy's execCommand (src/tools/execute-command.ts:273 ->
529
+ // src/services/ssh.ts execCommand, which does NO shell branching of its
530
+ // own). wrapInWorkFolder/wrapPidCapture (src/os/windows.ts:328-335) still
531
+ // emit RAW PowerShell text (`Set-Location "<folder>"; ...`,
532
+ // `Write-Output "FLEET_PID:$pid"; ...`), NOT shell-normalized/encoded --
533
+ // they are NOT wrapped with -EncodedCommand, so on a Windows member whose
534
+ // sshd default shell is cmd.exe (not PowerShell) that outer wrapping is
535
+ // still garbage regardless of what this function returns. This function's
536
+ // own return value (the inner payload wrapPidCapture/wrapInWorkFolder wrap
537
+ // around) IS explicitly -EncodedCommand and is valid to launch from either
538
+ // PowerShell or cmd.exe on its own -- but that only protects the inner
539
+ // payload, not the outer Set-Location/Write-Output wrapper the codebase
540
+ // composes around it. Correctness end-to-end still depends on the target
541
+ // member's default shell being PowerShell.
542
+ // TODO: normalize wrapInWorkFolder/wrapPidCapture (and
543
+ // gitCredentialHelperWrite/gitCredentialHelperRemove/deploySSHPublicKey,
544
+ // which have the same raw-PowerShell issue on the write side) through a
545
+ // single shell-detecting wrapper so the whole composite string -- not just
546
+ // this function's inner payload -- is shell-agnostic.
547
+ //
548
+ // WHY $env:USERPROFILE AND NOT A JS-RESOLVED HOME PATH: the WRITE side
549
+ // (src/os/windows.ts:289 gitCredentialHelperWrite) writes the helper to
550
+ // `"$env:USERPROFILE\.fleet-git-credential-<label>.bat"` -- expanded ON THE
551
+ // MEMBER at write time. The read must resolve the home directory the same way
552
+ // the write did, or an independently-probed home could point somewhere the
553
+ // file was never written. This mirrors member-home.ts probeCommandFor(), which
554
+ // likewise resolves the OS in JS and interpolates a shell-appropriate string
555
+ // that still contains $env:USERPROFILE.
556
+ // RUNNER-WIDE POSIX-EXPANSION SWEEP (apra-fleet-ot2z.1, WORK item 2): every
557
+ // runner.js string passed to command()/execute_command was audited for `$VAR`,
558
+ // `~/`, backticks, `$( )` and POSIX-only shell plumbing (`&&`/`||` chains,
559
+ // `2>/dev/null`, `test -f`, pipes). Result: the credential read below was the
560
+ // ONLY member-bound string carrying a shell expansion. The surviving `$`
561
+ // occurrences in this file are all justified in place --
562
+ // - NOT_DONE_STATUSES (~line 278): quoting note about PowerShell's $OFS, a
563
+ // comment, not an expansion in the dispatched string;
564
+ // - the Windows branch below: deliberately PowerShell, base64-encoded (via
565
+ // se-os-commands.mjs's SeWindowsCommands#wrapForMember) so no host shell
566
+ // ever re-parses it;
567
+ // - the POSIX branch below: `$HOME` expanded by the POSIX member's own
568
+ // shell, matching what src/os/linux.ts wrote.
569
+ // Everything else dispatched to a member is plain `git`/`bd`/`node -e`
570
+ // argv-shaped text (see stageCommandBodyMemberSide ~line 2195 and the
571
+ // two-sequential-calls note at ~line 5685, which already document why they
572
+ // avoid `&&` and `$`), inert across POSIX, PowerShell and cmd.exe.
573
+ //
574
+ // `target` is whatever se-os-commands.mjs's getSeCommands() accepts: a bare
575
+ // OS string (back-compat -- resolves to the PowerShell implementation for
576
+ // 'windows', matching pre-shell-aware behavior) or a { os, shell } record
577
+ // (resolveMemberTarget's shape), so a Windows member whose shell is
578
+ // Git-for-Windows bash gets the bash-flavored credential-read command instead
579
+ // of a PowerShell one. Label validation and byte-identical string shapes are
580
+ // now owned by the SePosixCommands/SeWindowsCommands/SeWindowsGitbashCommands
581
+ // classes themselves -- see se-os-commands.mjs.
582
+ /**
583
+ * @param {{ os?: string, shell?: string }|string} target
584
+ * @param {string} label
585
+ * @returns {{ command: string, descriptor: string }}
586
+ */
587
+ export function buildCredentialReadCommand(target, label) {
588
+ return getSeCommands(target).readCredentialHelper(label);
589
+ }
590
+
591
+ // Splits a VCSModule create-pull-request curl result's captured stdout into
592
+ // its HTTP status code and JSON body. VCSModule's buildCreatePrCommand always
593
+ // appends `-w '\n%{http_code}'`, so curl's own stdout is "<json body>\n<status>".
594
+ /**
595
+ * @param {string} output
596
+ * @returns {{ status: number|null, body: unknown }}
597
+ */
598
+ function parseVcsCurlOutput(output) {
599
+ const text = String(output || '');
600
+ const lines = text.split('\n');
601
+ const statusLine = lines.length ? lines[lines.length - 1].trim() : '';
602
+ const status = /^\d+$/.test(statusLine) ? parseInt(statusLine, 10) : null;
603
+ const bodyText = (status !== null ? lines.slice(0, -1) : lines).join('\n').trim();
604
+ let body = null;
605
+ if (bodyText) {
606
+ try {
607
+ body = JSON.parse(bodyText);
608
+ } catch {
609
+ body = null;
610
+ }
611
+ }
612
+ return { status, body, bodyText };
613
+ }
614
+
615
+ const PR_AUTH_404_TEXT_RE = /not accessible by (this )?(integration|token|personal access token)|requires (authentication|additional scopes?)|insufficient (scope|permission)/i;
616
+
617
+ // A PR-creation response is REACTIVE-auth-classified (as opposed to a
618
+ // generic failure) when the token that raised it is stale/expired (401),
619
+ // lacks the scope/permission GitHub requires (403), or -- because GitHub
620
+ // sometimes answers a scope refusal with 404 instead of 403, to avoid
621
+ // leaking whether a private repo exists to a token that cannot see it -- a
622
+ // 404 whose body text itself names a scope/permission/authentication
623
+ // refusal. Anything else (422 already-exists, 5xx, malformed body, a bare
624
+ // 404 with no such text) is left exactly as it classified before this bead:
625
+ // a plain failure, never retried.
626
+ /**
627
+ * @param {number|null} status
628
+ * @param {string} errorText
629
+ * @returns {boolean}
630
+ */
631
+ function isPrAuthFailure(status, errorText) {
632
+ if (status === 401 || status === 403) return true;
633
+ if (status === 404 && PR_AUTH_404_TEXT_RE.test(String(errorText || ''))) return true;
634
+ return false;
635
+ }
636
+
637
+ // Mints a just-in-time push+pr credential for `member`, builds the
638
+ // create-pull-request command through VCSModule (the orchestrator-side
639
+ // command builder, apra-fleet-tfx.7) with a '{{vcs_token_inline}}'
640
+ // placeholder where the credential belongs, and dispatches it through the
641
+ // SERVER-SIDE handoff `fleetApi.vcsCredentialExec()` (vcs_credential_exec),
642
+ // which reads the credential, substitutes it and redacts it without the
643
+ // plaintext ever reaching this process -- `member` is still a dumb executor
644
+ // of a command this function (and VCSModule) decided, never `gh`, never a
645
+ // server-side fallback that picks its own command. Returns the
646
+ // same shape both PR-raising call sites need: { ok, alreadyExists, prUrl,
647
+ // error, authFailure }, mirroring the interpretation contract the reverted
648
+ // server-side create-pull-request.ts tool used (2xx -> success; 422 "already
649
+ // exists" -> idempotent success; anything else -> error).
650
+ //
651
+ // REACTIVE auth self-heal (apra-fleet-647.1.1.1): on an auth-classified
652
+ // response (see isPrAuthFailure above), this re-provisions a push+pr
653
+ // credential via provisionPrCapableAuthForMember and retries the SAME
654
+ // PR-creation command exactly once -- bounded one-shot semantics mirroring
655
+ // runGitStep/runDoltStep's onAuthFailure loop. The retry needs no token
656
+ // re-read of its own any more: the command still carries the placeholder, so
657
+ // the retry's handoff call re-reads the freshly re-provisioned credential
658
+ // server-side. If the retry still fails, the failure (auth or not) is
659
+ // returned as-is; the raw token is never logged (and is never even held
660
+ // here), only `built.logSafeCommand`.
661
+ /**
662
+ * @param {{ fleetApi: object, command: Function, member: string, base: string, head: string, title: string, body?: string, log?: Function, logPrefix: string }} opts
663
+ * @returns {Promise<{ ok: boolean, alreadyExists: boolean, prUrl: string|null, error: string|null, authFailure: boolean }>}
664
+ */
665
+ export async function raiseVcsPrForMember({ fleetApi, command, member, base, head, title, body, log = () => {}, logPrefix, remoteUrlOverride }) {
666
+ let repo;
667
+ try {
668
+ ({ repo } = await provisionPrCapableAuthForMember({ fleetApi, command, member, log, logPrefix, remoteUrlOverride }));
669
+ } catch (provisionErr) {
670
+ // apra-fleet-5co8.15: provisionPrCapableAuthForMember has no failSoft
671
+ // of its own (by design -- see its doc comment above), so a
672
+ // provisioning failure that happens BEFORE any PR-creation attempt
673
+ // (e.g. a missing Azure DevOps PAT credential-store entry) used to
674
+ // escape here as the raw provision_vcs_auth failure text and abort
675
+ // the whole sprint. Degrade it the same way the reactive
676
+ // auth-self-heal retry below already degrades a mid-retry failure:
677
+ // log the provider's own authRemedy hint (never a wording duplicated
678
+ // here) and return authFailure:true instead of throwing, so a caller
679
+ // (Publish PR, finalizeAbort) can report clean, actionable guidance
680
+ // and keep going rather than aborting on this condition.
681
+ let remedyHint = null;
682
+ try {
683
+ const { provider } = await resolveProvider(member, { fleetApi });
684
+ const impl = getVcsProvider(provider);
685
+ if (impl && impl.authRemedy && impl.authRemedy.hint) remedyHint = impl.authRemedy.hint;
686
+ } catch (resolveErr) {
687
+ log(`${logPrefix}: could not resolve member '${member}'s VCS provider to look up an auth remedy hint (falling back to the raw provisioning error): ${resolveErr.message}`);
688
+ }
689
+ // The provider's remedy text is generic ("PATs cannot be re-minted
690
+ // server-side ..."); on its own it hid WHY provisioning failed --
691
+ // an unreadable remote, a missing credential-store entry and a dead
692
+ // PAT all printed the same paragraph. Keep the hint, but lead with
693
+ // the actual cause so the operator fixes the right thing.
694
+ const message = remedyHint
695
+ ? `Could not provision a push+pr credential for member '${member}': ${provisionErr.message} -- ${remedyHint}`
696
+ : provisionErr.message;
697
+ log(`${logPrefix}: PR-capable credential provisioning failed for member '${member}'; degrading (not throwing): ${message}`);
698
+ return { ok: false, alreadyExists: false, prUrl: null, error: message, authFailure: true };
699
+ }
700
+ if (!repo) {
701
+ const remoteSource = remoteUrlOverride ? 'the supplied remote URL' : `member '${member}' git remote`;
702
+ throw new Error(`Could not derive an owner/repo from ${remoteSource} -- cannot build a VCSModule create-pull-request command without one.`);
703
+ }
704
+ // apra-fleet-lzfv.5: resolve the member's OWN registered VCS provider
705
+ // (VCSModule.resolveProvider(), never a hardcoded 'github' literal --
706
+ // same rule provisionVcsAuthForMember already follows) so
707
+ // buildCreatePrCommand dispatches to the right REST dialect for a
708
+ // dev.azure.com (or any other) remote, not just GitHub.
709
+ //
710
+ // Resolved BEFORE the handoff below because the credential is keyed
711
+ // by provider too: provision_vcs_auth deploys the credential helper
712
+ // under `label = input.label ?? input.provider`
713
+ // (src/tools/provision-vcs-auth.ts), and neither the shared
714
+ // GitHub-App-shaped arguments nor a provider's buildProvisionArgs hook
715
+ // sends an explicit label -- so the credential the handoff must read is
716
+ // the one under $HOME/.fleet-git-credential-<provider>. Passing the
717
+ // 'github' label unconditionally (the pre-fix default this path once
718
+ // carried, back when it read the token itself) made every Azure DevOps
719
+ // member's PR raise fail with "Failed to read VCS credential token ...
720
+ // from '$HOME/.fleet-git-credential-github'" (or, worse, silently reuse a
721
+ // stale GitHub token left over from an earlier provider and send it to
722
+ // dev.azure.com). `credentialLabel` is threaded into every
723
+ // vcsCredentialExec() call below for exactly that reason.
724
+ const { provider } = await resolveProvider(member, { fleetApi });
725
+ const credentialLabel = vcsCredentialLabelForProvider(provider);
726
+
727
+ // apra-fleet-3swo.7.6: the orchestrator never learns the token at all now.
728
+ // It passes the INLINE placeholder as the `token` parameter, so each
729
+ // provider's builder emits its existing shQuote()'d shape with the
730
+ // placeholder sitting inside its OWN quotes (github.mjs still emits
731
+ // -H 'Authorization: Bearer {{vcs_token_inline}}', azure-devops.mjs still
732
+ // emits -u ':{{vcs_token_inline}}' -- the authentication MECHANISM is
733
+ // unchanged, only the substituted word), and the SERVER substitutes it
734
+ // during the vcs_credential_exec dispatch below, escaped for the interior
735
+ // of those quotes with no quotes of its own (VCS_TOKEN_INLINE_PLACEHOLDER,
736
+ // src/tools/vcs-credential-exec.ts). Deliberately inlined here rather than
737
+ // hoisted to a module constant: the facade suite enumerates this module's
738
+ // top-level declarations symbol-for-symbol and a new const desyncs that
739
+ // census.
740
+ const token = '{{vcs_token_inline}}';
741
+ // Both os AND shell feed the command builder: os picks the curl binary
742
+ // token (curl.exe vs curl), shell picks the quoting dialect. A Windows
743
+ // member whose registered shell is gitbash needs POSIX quoting, not
744
+ // PowerShell doubled-quote escaping -- resolving only the OS here fed
745
+ // shell-less params to shQuote and corrupted the curl -d JSON payload
746
+ // (observed live: GitHub 400 "Problems parsing JSON" on the create-PR
747
+ // endpoint for a windows+gitbash member).
748
+ const { os, shell } = await resolveMemberTarget({ fleetApi, member, log });
749
+
750
+ // The provider's own coordinate shape (e.g. Azure DevOps' org/project/repo
751
+ // -- see VCSModule.parseProviderRepoRef()/that provider's parseRepoRef
752
+ // hook) when one exists; null for a provider with no such hook (GitHub),
753
+ // which keeps using the two-part `repo` string above unchanged. Only ONE
754
+ // of `repo`/`repoRef` is ever sent below: passing both would let the
755
+ // (possibly provider-specific, e.g. 3-part) canonical `repo` string
756
+ // silently override repoRef's own coordinates and mis-encode the request
757
+ // URL (see azure-devops.mjs's assertRepoCoords doc comment). Both real
758
+ // call sites (Publish PR, [ABORTED] PR) already resolve and pass
759
+ // `remoteUrlOverride` themselves (see their own comments), so this never
760
+ // needs a git-remote read of its own; a caller that omits it simply gets
761
+ // no repoRef (falls back to `repo`, unchanged from before this task).
762
+ const providerRef = remoteUrlOverride ? parseProviderRepoRef(remoteUrlOverride) : null;
763
+ if (providerRef && providerRef.error) {
764
+ throw new Error(providerRef.error);
765
+ }
766
+ const repoRef = providerRef ? providerRef.ref : null;
767
+
768
+ let authHealAttempted = false;
769
+ // apra-fleet PR-body length fix: buildCreatePrCommand deterministically
770
+ // truncates `body` to PR_DESCRIPTION_MAX_LENGTH and reports it back via
771
+ // `descriptionTruncated` (see vcs-module.mjs -- that module stays pure/
772
+ // I/O-free, so the warning is logged here). Guarded so a retry of the
773
+ // SAME (already-truncated) body after an auth self-heal never re-logs it.
774
+ let truncationWarned = false;
775
+ // eslint-disable-next-line no-constant-condition
776
+ while (true) {
777
+ const built = buildCreatePrCommand({
778
+ provider,
779
+ ...(repoRef ? { repoRef } : { repo }),
780
+ base, head, title, body, token, os, shell,
781
+ });
782
+
783
+ if (built.descriptionTruncated && !truncationWarned) {
784
+ truncationWarned = true;
785
+ const { originalLength, maxLength } = built.descriptionTruncated;
786
+ log(`${logPrefix}: WARNING: PR description for member '${member}' was ${originalLength} chars, exceeding the ${maxLength}-char limit; truncated to the first ${maxLength} chars before raising the PR.`);
787
+ }
788
+
789
+ // The server-side credential handoff, NOT command(): the placeholder
790
+ // built into `built.command` above is substituted INSIDE the server,
791
+ // the substituted command is dispatched from there, and the credential
792
+ // is redacted out of the stdout/stderr this process reads back. No
793
+ // plaintext token ever transits the orchestrator, so there is nothing
794
+ // here for a captured result, a log line or a written file to leak.
795
+ if (!fleetApi || typeof fleetApi.vcsCredentialExec !== 'function') {
796
+ throw new Error(
797
+ `Cannot raise a PR for member '${member}': this fleet client exposes no vcs_credential_exec tool, `
798
+ + 'and the orchestrator no longer reads VCS credential tokens itself. Upgrade the fleet server/client '
799
+ + 'to a version that provides the vcs_credential_exec tool.',
800
+ );
801
+ }
802
+ const execRes = await fleetApi.vcsCredentialExec({
803
+ member_name: member,
804
+ label: credentialLabel,
805
+ command: built.command,
806
+ });
807
+ const handoff = (execRes && execRes.structuredContent) || {};
808
+ const handoffText = resultText(execRes);
809
+ // A credential-side failure HARD-FAILS, exactly as reading the token
810
+ // ourselves used to throw -- never an advisory warning that lets the
811
+ // sprint carry on with no credential. 'dispatch_failed' is the one
812
+ // non-ok reason that is a COMMAND failure rather than a credential
813
+ // failure, so it degrades the same way a failed command() dispatch
814
+ // did: returned, not thrown.
815
+ if (!handoff.ok && handoff.reason !== 'dispatch_failed') {
816
+ throw new Error(
817
+ `Failed to read VCS credential token for member '${member}' from the `
818
+ + `'${credentialLabel}'-labelled credential helper via vcs_credential_exec `
819
+ + `(reason: ${handoff.reason || '(none)'}): ${handoffText || '(no detail)'}`,
820
+ );
821
+ }
822
+ if (!handoff.ok || (typeof handoff.exitCode === 'number' && handoff.exitCode !== 0)) {
823
+ const failText = handoff.stderr || handoffText || 'vcs_credential_exec failed';
824
+ return { ok: false, alreadyExists: false, prUrl: null, error: failText, authFailure: false };
825
+ }
826
+
827
+ const { status, body: respBody, bodyText } = parseVcsCurlOutput(handoff.stdout);
828
+ const [lo, hi] = built.interpret.successStatusRange;
829
+ if (status !== null && status >= lo && status <= hi) {
830
+ // apra-fleet-lzfv.5: read the created PR's id/url through the
831
+ // provider's OWN pullRequestResponse.map hook (declared on its
832
+ // descriptor -- see vcs-providers/github.mjs and
833
+ // vcs-providers/azure-devops.mjs) instead of a GitHub-dialect
834
+ // `html_url` field literal here. A provider with no mapping
835
+ // (should not happen for an auth-backend provider, but never
836
+ // throws) yields prUrl: null rather than crashing on an
837
+ // otherwise-successful PR.
838
+ const impl = getVcsProvider(provider);
839
+ const mapped = (impl && impl.pullRequestResponse && typeof impl.pullRequestResponse.map === 'function')
840
+ ? impl.pullRequestResponse.map(respBody, repoRef ? { repoRef } : { repo })
841
+ : { id: null, url: null };
842
+ return { ok: true, alreadyExists: false, prUrl: mapped.url, error: null, authFailure: false };
843
+ }
844
+
845
+ const errorMessages = [];
846
+ if (respBody && typeof respBody.message === 'string') errorMessages.push(respBody.message);
847
+ if (respBody && Array.isArray(respBody.errors)) {
848
+ for (const e of respBody.errors) {
849
+ if (e && typeof e.message === 'string') errorMessages.push(e.message);
850
+ }
851
+ }
852
+ const errorText = errorMessages.join('; ') || bodyText || `HTTP ${status ?? '(unknown)'}`;
853
+
854
+ if (status === built.interpret.alreadyExistsStatus && new RegExp(built.interpret.alreadyExistsPattern, 'i').test(errorText)) {
855
+ const urlMatch = /https?:\/\/\S+/.exec(errorText);
856
+ const existingUrl = urlMatch ? urlMatch[0].replace(/[.,)]+$/, '') : null;
857
+ return { ok: true, alreadyExists: true, prUrl: existingUrl, error: null, authFailure: false };
858
+ }
859
+
860
+ if (isPrAuthFailure(status, errorText) && !authHealAttempted) {
861
+ authHealAttempted = true;
862
+ log(`${logPrefix}: PR creation returned an auth-classified failure (HTTP ${status ?? '(unknown)'}) for member '${member}'; re-provisioning a push+pr credential and retrying once (command: ${built.logSafeCommand}): ${errorText}`);
863
+ try {
864
+ const reprov = await provisionPrCapableAuthForMember({ fleetApi, command, member, log, logPrefix, remoteUrlOverride });
865
+ if (reprov.repo) repo = reprov.repo;
866
+ // No token re-read here any more: `built.command` still
867
+ // carries the placeholder, so the retry's own
868
+ // vcs_credential_exec dispatch re-reads the FRESHLY
869
+ // re-provisioned credential server-side, once per call. The
870
+ // bounded one-shot retry semantics are unchanged.
871
+ } catch (healErr) {
872
+ log(`${logPrefix}: PR auth self-heal failed for member '${member}'; not retrying further: ${healErr.message}`);
873
+ return { ok: false, alreadyExists: false, prUrl: null, error: `HTTP ${status ?? '(unknown)'}: ${errorText}`, authFailure: true };
874
+ }
875
+ log(`${logPrefix}: PR auth self-heal completed for member '${member}'; retrying PR creation once.`);
876
+ continue;
877
+ }
878
+
879
+ return { ok: false, alreadyExists: false, prUrl: null, error: `HTTP ${status ?? '(unknown)'}: ${errorText}`, authFailure: isPrAuthFailure(status, errorText) };
880
+ }
881
+ }
882
+
883
+ /**
884
+ * apra-fleet-417.7: builds the `resolveMemberProvider(member)` callback
885
+ * threaded through syncMemberBefore/syncMemberAfter/finalizeAbort into
886
+ * runGitStep, so classifyGitFailure() classifies a git failure via the
887
+ * member's OWN resolved VCS provider chain (VCSModule.resolveProvider())
888
+ * instead of always falling back to the default 'github' chain -- this is
889
+ * what makes azure-devops.mjs's TF401019 -> AUTH_DENIED and bitbucket.mjs's
890
+ * app-password -> AUTH_EXPIRED rules reachable at runtime, not just from a
891
+ * caller that names the provider directly against classifyFailure().
892
+ *
893
+ * The resolution is cached per member for the lifetime of the returned
894
+ * callback (a member's registered VCS provider does not change mid-sprint),
895
+ * so a member whose provider fails to resolve (fleet unreachable, no
896
+ * registered provider) is not re-queried on every subsequent git failure --
897
+ * it fails closed to `undefined` (today's default chain) exactly once per
898
+ * member, then reuses that cached `undefined`.
899
+ *
900
+ * `callTool` is injected (the caller's MCP client), so this stays
901
+ * transport-agnostic and unit-testable without a live fleet server.
902
+ *
903
+ * @param {{ callTool: (name: string, args: object) => Promise<any>, log?: Function }} opts
904
+ * @returns {(member: string) => Promise<string|undefined>}
905
+ */
906
+ export function createMemberVcsProviderResolver(opts = {}) {
907
+ const { callTool, log = () => {} } = opts;
908
+ const fleetApi = new ApraFleet({ callTool });
909
+ /** @type {Map<string, string|undefined>} member -> resolved provider (or undefined if unresolvable). */
910
+ const cache = new Map();
911
+
912
+ return async function resolveMemberProvider(member) {
913
+ if (cache.has(member)) return cache.get(member);
914
+ try {
915
+ const { provider } = await resolveProvider(member, { fleetApi });
916
+ cache.set(member, provider);
917
+ return provider;
918
+ } catch (err) {
919
+ log(`[Sync] 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}`);
920
+ cache.set(member, undefined);
921
+ return undefined;
922
+ }
923
+ };
924
+ }
925
+
926
+ /**
927
+ * Builds the REACTIVE `onAuthFailure` self-heal callback runGitStep and
928
+ * runDoltStep invoke on an 'auth' classification: re-provisions the failing
929
+ * member's VCS credentials via provisionVcsAuthForMember (whose owner/repo is
930
+ * derived from the member's own git remote, never hardcoded). Logs both the
931
+ * attempt and its outcome, so a self-heal is never silent. Any failure
932
+ * propagates as a thrown error, which is how runGitStep/runDoltStep recognize
933
+ * "self-heal failed" and stop retrying.
934
+ *
935
+ * `callTool` is injected (the caller's MCP client), so this stays
936
+ * transport-agnostic and unit-testable without a live fleet server.
937
+ *
938
+ * @param {{ callTool: (name: string, args: object) => Promise<any>, command: Function, log?: Function }} opts
939
+ * @returns {(info: { member: string, label: string, cmd?: string, error: string, kind: 'git'|'dolt' }) => Promise<void>}
940
+ */
941
+ export function createVcsAuthSelfHealCallback(opts = {}) {
942
+ const { callTool, command, log = () => {}, azdevopsPatSecretName } = opts;
943
+ const fleetApi = new ApraFleet({ callTool });
944
+
945
+ return async function onAuthFailure({ member, label, error }) {
946
+ log(`[Sync] self-heal: auth failure detected for member '${member}' (${label}); calling provision_vcs_auth to re-provision credentials: ${error}`);
947
+
948
+ // apra-fleet-5co8.4.2: some providers (e.g. Azure DevOps PATs) can
949
+ // never be fixed by this reactive re-provisioning call alone -- it
950
+ // only redeploys the SAME stored secret, it never mints a new one.
951
+ // Print that provider's own remedy hint via the generic
952
+ // `authRemedy` descriptor field (no provider-name conditional here,
953
+ // see vcs-providers/index.mjs) BEFORE attempting the self-heal below,
954
+ // so the operator has the real remedy even if that attempt also
955
+ // fails. A provider that declares no `authRemedy` (or
956
+ // `serverSideReMintable: true`, e.g. GitHub's App-minted token) prints
957
+ // nothing extra here -- unchanged from before this task.
958
+ // apra-fleet-5co8.13: resolve the provider ONCE here and thread it into
959
+ // provisionVcsAuthForMember below via `resolvedProvider`, so a single
960
+ // self-heal attempt makes exactly one member_detail round trip instead
961
+ // of two. A resolution failure here must NOT short-circuit the
962
+ // self-heal attempt -- `resolved` simply stays undefined and
963
+ // provisionVcsAuthForMember falls back to its own lookup.
964
+ let resolved;
965
+ try {
966
+ resolved = await resolveProvider(member, { fleetApi });
967
+ const { provider } = resolved;
968
+ const impl = getVcsProvider(provider);
969
+ if (impl && impl.authRemedy && impl.authRemedy.serverSideReMintable === false) {
970
+ log(`[Sync] self-heal: member '${member}' (${label}) uses '${provider}', whose credentials cannot be re-minted server-side. ${impl.authRemedy.hint}`);
971
+ }
972
+ } catch (resolveErr) {
973
+ log(`[Sync] self-heal: could not resolve member '${member}' (${label})'s VCS provider to check for an auth remedy hint (continuing with the self-heal attempt): ${resolveErr.message}`);
974
+ }
975
+
976
+ await provisionVcsAuthForMember({ fleetApi, command, member, log, logPrefix: '[Sync] self-heal', azdevopsPatSecretName, resolvedProvider: resolved });
977
+
978
+ log(`[Sync] self-heal: provision_vcs_auth succeeded for member '${member}' (${label}); the failed command will be retried once.`);
979
+ };
980
+ }
981
+
982
+ // How far ahead of a credential's known expiry the preflight treats it as
983
+ // "expiring soon" and re-provisions early, rather than letting it lapse
984
+ // mid-dispatch. Mirrors the server's own EXPIRY_WARNING_MS threshold
985
+ // (checkVcsTokenExpiry) so the two "about to expire?" judgments never
986
+ // disagree.
987
+ const VCS_AUTH_EXPIRY_PREFLIGHT_MS = 10 * 60 * 1000; // 10 minutes
988
+
989
+ /**
990
+ * Proactive VCS-auth PREFLIGHT. Unlike createVcsAuthSelfHealCallback above,
991
+ * which is REACTIVE (it fires only after a git/dolt command has already failed
992
+ * with an 'auth' classification), this runs BEFORE a dispatch's git commands
993
+ * and calls provision_vcs_auth only when this member's last-known credential
994
+ * is missing, unknown, or expiring within VCS_AUTH_EXPIRY_PREFLIGHT_MS. It
995
+ * closes the gap a reactive self-heal alone leaves: a credential that lapses
996
+ * BETWEEN dispatches is refreshed before the next dispatch instead of after a
997
+ * command fails.
998
+ *
999
+ * The freshness cache is scoped to the callback instance returned here, so
1000
+ * each member's first call always provisions (no cache entry yet) and later
1001
+ * calls are skipped until the cached expiry approaches. A response carrying no
1002
+ * expiry (PAT mode, which never expires) is cached as "known-good, never needs
1003
+ * refresh".
1004
+ *
1005
+ * NEVER throws: a preflight failure (fleet unreachable, provision_vcs_auth
1006
+ * itself failing) is logged and swallowed so it can never abort a dispatch
1007
+ * that would have succeeded on its still-valid existing credential. The
1008
+ * reactive self-heal remains the actual safety net if the credential is
1009
+ * genuinely stale.
1010
+ *
1011
+ * @param {{ callTool: (name: string, args: object) => Promise<any>, command: Function, log?: Function, now?: () => number }} opts
1012
+ * @returns {(member: string) => Promise<void>}
1013
+ */
1014
+ export function createVcsAuthPreflightCallback(opts = {}) {
1015
+ const { callTool, command, log = () => {}, now = () => Date.now(), azdevopsPatSecretName } = opts;
1016
+ const fleetApi = new ApraFleet({ callTool });
1017
+ /** @type {Map<string, Date|null>} member -> last-known expiresAt (null = no expiry tracked, e.g. PAT mode). */
1018
+ const knownGoodUntil = new Map();
1019
+
1020
+ return async function ensureVcsAuthFresh(member) {
1021
+ if (knownGoodUntil.has(member)) {
1022
+ const expiresAt = knownGoodUntil.get(member);
1023
+ if (expiresAt === null || expiresAt.getTime() - now() > VCS_AUTH_EXPIRY_PREFLIGHT_MS) {
1024
+ // Still fresh (or a no-expiry credential type) -- skip, so
1025
+ // this is not an unconditional provisioning call on every
1026
+ // dispatch.
1027
+ return;
1028
+ }
1029
+ }
1030
+ log(`[Sync] preflight: ensuring member '${member}' has a fresh VCS credential before dispatch; calling provision_vcs_auth.`);
1031
+ try {
1032
+ const { expiresAt } = await provisionVcsAuthForMember({ fleetApi, command, member, log, logPrefix: '[Sync] preflight', azdevopsPatSecretName });
1033
+ knownGoodUntil.set(member, expiresAt);
1034
+ log(`[Sync] preflight: provision_vcs_auth succeeded for member '${member}'${expiresAt ? ` (expires ${expiresAt.toISOString()})` : ''}.`);
1035
+ } catch (err) {
1036
+ log(`[Sync] preflight: provision_vcs_auth failed for member '${member}' (continuing -- the existing credential may still be valid; the reactive self-heal will fire if a git/dolt command actually fails): ${err.message}`);
1037
+ }
1038
+ };
1039
+ }
1040
+
1041
+ /**
1042
+ * Sync-step "will this push be rejected for missing the 'workflows'
1043
+ * permission?" preflight (apra-fleet-2wdc.6). Distinct from
1044
+ * createVcsAuthPreflightCallback above: that one keeps a member's credential
1045
+ * FRESH; this one warns, BEFORE dispatch, when the credential that preflight
1046
+ * ensures is fresh was never going to carry a permission this specific push
1047
+ * needs -- so an operator sees a clear, named referral instead of a raw
1048
+ * GitHub 422 (or a misclassified rejection) surfacing mid-dispatch. See the
1049
+ * parent bug apra-fleet-2wdc: the App installation grants 'workflows', but a
1050
+ * minted token that never REQUESTED it gets rejected pushing any
1051
+ * .github/workflows/** change, on every git_access level that lacks it.
1052
+ *
1053
+ * NEVER mints a token to find out: resolves the member's VCS provider via the
1054
+ * same read-only resolveProvider() lookup provisionVcsAuthForMember itself
1055
+ * uses, then reads the access level that member is actually REGISTERED at off
1056
+ * the same tool (readRegisteredGitAccess below) -- both read-only member_detail
1057
+ * calls, no POST /access_tokens -- and checks that level against
1058
+ * accessLevelGrantsWorkflowsPermission()'s local table.
1059
+ *
1060
+ * WHICH level is checked matters, and is the whole point of apra-fleet-rp7a.4.
1061
+ * This used to test `gitAccess` -- an option no caller ever passes, defaulting
1062
+ * to DEFAULT_SYNC_GIT_ACCESS ('push'), which apra-fleet-2wdc.1 made a level
1063
+ * that DOES carry 'workflows'. That made the check a constant `true` and the
1064
+ * referral unreachable in every configuration the engine can produce: inert
1065
+ * defence, not working defence. The level now comes from the member registry
1066
+ * (member_detail's `gitAccess`, set by register_member/update_member's
1067
+ * git_access), so the members genuinely at risk -- registered 'read' or
1068
+ * 'issues', or holding a credential minted before apra-fleet-2wdc.1 and not
1069
+ * yet re-provisioned -- are the ones that get warned. `opts.gitAccess` is kept
1070
+ * ONLY as the fallback for a member whose record carries no explicit level, in
1071
+ * which case the provisioning default really is what will be requested.
1072
+ *
1073
+ * Cost/safety:
1074
+ * - Reads resolve per MEMBER, not per dispatch: any outcome that
1075
+ * proves this member can never produce a warning (non-GitHub, PAT mode, or
1076
+ * a level that carries 'workflows') is cached in `silentMembers` and the
1077
+ * member is skipped outright from then on -- so the steady state for a
1078
+ * healthy fleet is zero reads. The provider lookup also short-circuits
1079
+ * before the level read for any non-GitHub-App member, so no member ever
1080
+ * pays for a level it cannot be judged on. An AT-RISK outcome is
1081
+ * deliberately NOT cached -- re-provisioning the member at a carrying
1082
+ * level is exactly the remediation the referral asks for, and a cached
1083
+ * verdict would keep crying wolf after the operator did it.
1084
+ * - The diff check, when reached, is purely LOCAL: `git rev-list --count`
1085
+ * then `git diff --name-only`, both against refs already present on
1086
+ * `member`'s checkout (the sprint branch `syncMemberBefore` just synced,
1087
+ * and `origin/<baseBranch>` from this sprint's own branch setup) -- no
1088
+ * extra `git fetch`, so no added per-round remote round trip.
1089
+ * - Skipped entirely (no diff command run at all) when `branch` has no
1090
+ * commits ahead of `baseBranch`.
1091
+ * - NEVER throws: any failure (git command error, provider-resolution
1092
+ * failure, malformed output) is logged and swallowed, exactly like
1093
+ * createVcsAuthPreflightCallback above -- a preflight hiccup must never
1094
+ * abort a dispatch that would otherwise succeed.
1095
+ * - Non-GitHub providers are silently skipped -- never warn.
1096
+ *
1097
+ * @param {{ callTool: (name: string, args: object) => Promise<any>, command: Function, log?: Function, gitAccess?: string }} opts
1098
+ * @returns {(member: string, branch: string, baseBranch: string) => Promise<void>}
1099
+ */
1100
+ /**
1101
+ * The git access level `member` is REGISTERED at, straight off member_detail
1102
+ * (register_member/update_member's git_access, surfaced as `gitAccess` --
1103
+ * src/tools/member-detail.ts). Returns null when the member record names no
1104
+ * level, or when the response is anything this cannot read as JSON.
1105
+ *
1106
+ * Deliberately a separate read from resolveProvider()'s, even though both come
1107
+ * off the same tool: resolveProvider()'s return shape is a pinned contract
1108
+ * several suites assert field-for-field, and widening it to carry a field only
1109
+ * this preflight wants would make every one of those callers pay for a
1110
+ * concern none of them have. The cost is one extra member_detail call per
1111
+ * GitHub-App member per sprint (the caller caches its verdict; see
1112
+ * createWorkflowsPermissionPreflightCallback's silentMembers).
1113
+ *
1114
+ * Best-effort by design -- an absent/unparseable level is NOT an error here,
1115
+ * it just means the caller falls back to its provisioning default. A genuinely
1116
+ * failing memberDetail() call still rejects, and the caller's catch turns that
1117
+ * into the same swallowed degraded-check log as any other preflight hiccup.
1118
+ *
1119
+ * @param {string} member
1120
+ * @param {{ memberDetail: (opts: { member_name: string, format?: string }) => Promise<any> }} fleetApi
1121
+ * @returns {Promise<string|null>}
1122
+ */
1123
+ async function readRegisteredGitAccess(member, fleetApi) {
1124
+ const res = await fleetApi.memberDetail({ member_name: member, format: 'json' });
1125
+ let parsed;
1126
+ try {
1127
+ parsed = JSON.parse(resultText(res));
1128
+ } catch {
1129
+ // member_detail answers with plain prose (not JSON) when the member
1130
+ // cannot be resolved at all -- but that case has already surfaced as a
1131
+ // typed throw from resolveProvider() before this is ever reached, so
1132
+ // there is nothing left to report here.
1133
+ return null;
1134
+ }
1135
+ const level = parsed && typeof parsed.gitAccess === 'string' ? parsed.gitAccess.trim() : '';
1136
+ return level || null;
1137
+ }
1138
+
1139
+ export function createWorkflowsPermissionPreflightCallback(opts = {}) {
1140
+ const { callTool, command, log = () => {}, gitAccess: fallbackGitAccess = DEFAULT_SYNC_GIT_ACCESS } = opts;
1141
+ const fleetApi = new ApraFleet({ callTool });
1142
+
1143
+ /**
1144
+ * Members already proven incapable of producing this warning (wrong
1145
+ * provider, wrong auth mode, or an access level that carries 'workflows').
1146
+ * Skipping them avoids re-reading member_detail on every single dispatch;
1147
+ * see the cost note above for why at-risk members are NOT cached here.
1148
+ * @type {Set<string>}
1149
+ */
1150
+ const silentMembers = new Set();
1151
+
1152
+ return async function warnIfWorkflowsPermissionMissing(member, branch, baseBranch) {
1153
+ try {
1154
+ if (!branch || !baseBranch || branch === baseBranch) return;
1155
+ if (silentMembers.has(member)) return;
1156
+
1157
+ const { provider, authMode } = await resolveProvider(member, { fleetApi });
1158
+ if (provider !== 'github') {
1159
+ silentMembers.add(member);
1160
+ return;
1161
+ }
1162
+ if (authMode !== 'github-app') {
1163
+ // PAT mode, DELIBERATELY out of scope (apra-fleet-rp7a.4 item
1164
+ // 3 -- recorded here rather than left silent). A PAT missing
1165
+ // the 'workflow' scope is rejected by exactly the same GitHub
1166
+ // rule, so the failure mode is real; what is missing is any
1167
+ // way to PREDICT it from here. A PAT's granted scopes are not
1168
+ // derivable from anything the fleet registry holds: `git_access`
1169
+ // is a GitHub-App-only mapping onto installation-token
1170
+ // permissions (src/services/github-app.ts mapAccessLevel), and
1171
+ // the PAT itself is an opaque operator-supplied secret whose
1172
+ // scopes are only observable by calling GitHub with it and
1173
+ // reading the X-OAuth-Scopes response header -- a network call
1174
+ // this advisory, never-throwing, never-blocking preflight must
1175
+ // not make on every dispatch, and which would need the secret
1176
+ // VALUE, which the engine never handles. Warning off the
1177
+ // registered level anyway would be a fabricated verdict (the
1178
+ // level says nothing about a PAT), and warning unconditionally
1179
+ // would cry wolf at every correctly-scoped PAT member. So: no
1180
+ // warning. PAT members find out from the push rejection, which
1181
+ // classifyFailure() already recognizes and reports. Revisit
1182
+ // only if the registry ever records a PAT's scopes at
1183
+ // provisioning time -- then check them here the same way.
1184
+ silentMembers.add(member);
1185
+ return;
1186
+ }
1187
+
1188
+ // The level this member's credential is ACTUALLY minted at, per the
1189
+ // registry; the caller-supplied default applies only when the
1190
+ // member record names no level of its own.
1191
+ const registeredGitAccess = await readRegisteredGitAccess(member, fleetApi);
1192
+ const effectiveGitAccess = registeredGitAccess || fallbackGitAccess;
1193
+ const levelSource = registeredGitAccess ? 'registered' : 'default';
1194
+ if (accessLevelGrantsWorkflowsPermission(effectiveGitAccess)) {
1195
+ silentMembers.add(member);
1196
+ return;
1197
+ }
1198
+
1199
+ const countRes = await command(`git rev-list --count origin/${baseBranch}..${branch}`, { member_name: member, silent: true, failSoft: true });
1200
+ const aheadCount = countRes && countRes.ok ? parseInt(String(countRes.output || '').trim(), 10) : NaN;
1201
+ if (!Number.isFinite(aheadCount) || aheadCount <= 0) return;
1202
+
1203
+ const diffRes = await command(`git diff --name-only origin/${baseBranch}...${branch} -- .github/workflows`, { member_name: member, silent: true, failSoft: true });
1204
+ if (!diffRes || !diffRes.ok) return;
1205
+ const touchedPaths = String(diffRes.output || '').split('\n').map((line) => line.trim()).filter(Boolean);
1206
+ if (touchedPaths.length === 0) return;
1207
+
1208
+ log(
1209
+ `[Sync] OPERATOR REFERRAL: branch '${branch}' touches workflow file(s) [${touchedPaths.join(', ')}] but member ` +
1210
+ `'${member}''s minted credential (git_access '${effectiveGitAccess}', ${levelSource}) was not requested with the 'workflows' permission -- ` +
1211
+ `GitHub WILL reject this push ("refusing to allow a GitHub App to create or update workflow ... without ` +
1212
+ `workflows permission"). Re-provision '${member}' with an access level that carries 'workflows' ` +
1213
+ // Listed from the table itself, never spelled out again by
1214
+ // hand: a remedy naming levels that no longer carry the
1215
+ // permission is worse than no remedy at all.
1216
+ `(${[...GITHUB_ACCESS_LEVELS_WITH_WORKFLOWS].join(', ')}) before this dispatch publishes.`,
1217
+ );
1218
+ } catch (err) {
1219
+ log(`[Sync] preflight: workflows-permission check failed for member '${member}' on branch '${branch}' (continuing -- advisory only, never blocks dispatch): ${err.message}`);
1220
+ }
1221
+ };
1222
+ }
1223
+
1224
+ /**
1225
+ * LLM-auth counterpart to createVcsAuthSelfHealCallback, invoked by a
1226
+ * dispatch-site catch handler on an auth dispatch error: re-provisions LLM
1227
+ * credentials for the failing member via provision_llm_auth, after which the
1228
+ * caller retries its own dispatch once. Never throws -- every failure path
1229
+ * returns false ("do not retry"). A local member returns false without
1230
+ * retrying, because provision_llm_auth is a no-op for local members: they
1231
+ * share the operator's host credentials, and only an interactive `/login` on
1232
+ * that machine can fix an expired local session.
1233
+ *
1234
+ * @param {{ callTool: (name: string, args: object) => Promise<any>, log?: Function }} opts
1235
+ * @returns {(info: { member: string, label: string, error: string }) => Promise<boolean>} resolves true if healed (retry), false if not (do not retry)
1236
+ */
1237
+ export function createLlmAuthSelfHealCallback(opts = {}) {
1238
+ const { callTool, log = () => {} } = opts;
1239
+ const fleetApi = new ApraFleet({ callTool });
1240
+
1241
+ return async function onLlmAuthFailure({ member, label, error }) {
1242
+ log(`[Dispatch] self-heal: LLM auth failure detected for member '${member}' (${label}); calling provision_llm_auth to re-provision credentials: ${error}`);
1243
+
1244
+ let provisionRes;
1245
+ try {
1246
+ provisionRes = await fleetApi.provisionLlmAuth({ member_name: member });
1247
+ } catch (callErr) {
1248
+ log(`[Dispatch] self-heal: provision_llm_auth call failed for member '${member}': ${callErr.message}. Not retrying -- fix credentials manually and re-run.`);
1249
+ return false;
1250
+ }
1251
+
1252
+ const text = resultText(provisionRes).trim();
1253
+ const outcome = provisionOutcome(provisionRes, text);
1254
+
1255
+ // apra-fleet-3swo.13: src/tools/provision-auth.ts's OK_REASONS
1256
+ // classifies 'skipped_local_member' as ok:true (it IS a well-formed,
1257
+ // non-erroring outcome), so this check must run BEFORE the generic
1258
+ // ok/fail branch below -- otherwise a local member's skip would be
1259
+ // misread as a genuine credential refresh and the (pointless) retry
1260
+ // would fire anyway. The 'outcome.reason === null' half of the OR
1261
+ // only matters for the legacy prose fallback (no structuredContent
1262
+ // on the result at all), where the skip marker must still be read
1263
+ // off the text since there is no structured reason to check.
1264
+ if (outcome.reason === 'skipped_local_member' || (outcome.reason === null && /^\[SKIP\]/.test(text))) {
1265
+ // Skip marker (local member): provision_llm_auth is a no-op here,
1266
+ // so retrying would just reproduce the same failure.
1267
+ log(`[Dispatch] self-heal: provision_llm_auth skipped for local member '${member}': ${text || '(no detail)'}. This member's credentials can only be refreshed via an interactive /login on this machine.`);
1268
+ return false;
1269
+ }
1270
+
1271
+ if (!outcome.ok) {
1272
+ log(`[Dispatch] self-heal: provision_llm_auth failed for member '${member}': ${text || '(no detail)'}. Not retrying.`);
1273
+ return false;
1274
+ }
1275
+
1276
+ log(`[Dispatch] self-heal: provision_llm_auth succeeded for member '${member}' (${label}); the failed dispatch will be retried once.`);
1277
+ return true;
1278
+ };
1279
+ }