@apralabs/apra-fleet 0.4.2 → 0.4.4

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 (997) hide show
  1. package/README.md +103 -34
  2. package/dist/agents/backlog-groomer.md +87 -14
  3. package/dist/agents/ci-watcher.md +35 -9
  4. package/dist/agents/deployer.md +63 -11
  5. package/dist/agents/doer.md +99 -41
  6. package/dist/agents/harvester.md +47 -27
  7. package/dist/agents/integ-test-runner.md +38 -10
  8. package/dist/agents/kb-reconciler.md +37 -7
  9. package/dist/agents/plan-reviewer.md +145 -32
  10. package/dist/agents/planner.md +180 -69
  11. package/dist/agents/regression-test-runner.md +98 -64
  12. package/dist/agents/reviewer.md +117 -45
  13. package/dist/agents/schemas/backlog-groomer-output.json +1 -1
  14. package/dist/agents/schemas/doer-output.json +32 -0
  15. package/dist/agents/schemas/harvester-input.json +1 -5
  16. package/dist/agents/schemas/plan-reviewer-output.json +37 -0
  17. package/dist/agents/schemas/planner-output.json +1 -1
  18. package/dist/agents/schemas/regression-test-runner-output.json +41 -7
  19. package/dist/agents/schemas/reviewer-output.json +62 -3
  20. package/dist/cli/agent-transform.d.ts +90 -2
  21. package/dist/cli/agent-transform.js +310 -20
  22. package/dist/cli/auth.d.ts +1 -0
  23. package/dist/cli/auth.js +66 -17
  24. package/dist/cli/beads-install.d.ts +35 -0
  25. package/dist/cli/beads-install.js +125 -0
  26. package/dist/cli/beads-pin.d.ts +5 -0
  27. package/dist/cli/beads-pin.js +27 -0
  28. package/dist/cli/call.d.ts +27 -0
  29. package/dist/cli/call.js +177 -0
  30. package/dist/cli/config.d.ts +31 -6
  31. package/dist/cli/config.js +113 -36
  32. package/dist/cli/dolt-install.d.ts +18 -2
  33. package/dist/cli/dolt-install.js +46 -15
  34. package/dist/cli/fleet-se-guard.d.ts +51 -0
  35. package/dist/cli/fleet-se-guard.js +215 -0
  36. package/dist/cli/install-guard.d.ts +54 -0
  37. package/dist/cli/install-guard.js +132 -4
  38. package/dist/cli/install.d.ts +100 -11
  39. package/dist/cli/install.js +864 -139
  40. package/dist/cli/kb-commit.d.ts +2 -1
  41. package/dist/cli/kb-commit.js +1 -1
  42. package/dist/cli/kb-directives.js +2 -1
  43. package/dist/cli/kb-import.d.ts +2 -1
  44. package/dist/cli/kb-import.js +1 -1
  45. package/dist/cli/register-member.js +26 -5
  46. package/dist/cli/remove-member.d.ts +4 -0
  47. package/dist/cli/remove-member.js +63 -0
  48. package/dist/cli/secret.js +9 -0
  49. package/dist/cli/start.js +59 -4
  50. package/dist/cli/status.d.ts +3 -0
  51. package/dist/cli/status.js +45 -12
  52. package/dist/cli/stop.js +64 -9
  53. package/dist/cli/uninstall.js +101 -15
  54. package/dist/cli/update.js +33 -2
  55. package/dist/cli/watch.js +1 -1
  56. package/dist/cli/workflow.js +3 -2
  57. package/dist/commands/kb-server.d.ts +3 -0
  58. package/dist/commands/kb-server.js +52 -5
  59. package/dist/hub-service/http-server.d.ts +5 -1
  60. package/dist/hub-service/http-server.js +55 -5
  61. package/dist/index.js +158 -11
  62. package/dist/os/child-env-bound.d.ts +77 -0
  63. package/dist/os/child-env-bound.js +171 -0
  64. package/dist/os/linux.d.ts +13 -2
  65. package/dist/os/linux.js +75 -16
  66. package/dist/os/macos.d.ts +1 -1
  67. package/dist/os/macos.js +2 -11
  68. package/dist/os/os-commands.d.ts +78 -4
  69. package/dist/os/windows-gitbash.d.ts +6 -0
  70. package/dist/os/windows-gitbash.js +32 -3
  71. package/dist/os/windows-wrapper.d.ts +0 -4
  72. package/dist/os/windows-wrapper.js +2 -1
  73. package/dist/os/windows.d.ts +11 -2
  74. package/dist/os/windows.js +121 -32
  75. package/dist/paths.d.ts +21 -0
  76. package/dist/paths.js +35 -0
  77. package/dist/providers/agy.d.ts +120 -7
  78. package/dist/providers/agy.js +741 -86
  79. package/dist/providers/claude-permission-denial.d.ts +7 -0
  80. package/dist/providers/claude-permission-denial.js +137 -0
  81. package/dist/providers/claude.d.ts +132 -6
  82. package/dist/providers/claude.js +644 -48
  83. package/dist/providers/codex.d.ts +4 -2
  84. package/dist/providers/codex.js +23 -2
  85. package/dist/providers/copilot.d.ts +4 -2
  86. package/dist/providers/copilot.js +24 -2
  87. package/dist/providers/none.d.ts +4 -2
  88. package/dist/providers/none.js +17 -2
  89. package/dist/providers/opencode.d.ts +12 -2
  90. package/dist/providers/opencode.js +135 -54
  91. package/dist/providers/provider.d.ts +368 -35
  92. package/dist/providers/provider.js +219 -2
  93. package/dist/services/agent-provisioner.d.ts +29 -0
  94. package/dist/services/agent-provisioner.js +107 -0
  95. package/dist/services/agent-shadow.d.ts +96 -0
  96. package/dist/services/agent-shadow.js +479 -0
  97. package/dist/services/agy-project.d.ts +103 -0
  98. package/dist/services/agy-project.js +354 -0
  99. package/dist/services/auth-socket.d.ts +25 -0
  100. package/dist/services/auth-socket.js +72 -27
  101. package/dist/services/auth-web.js +2 -2
  102. package/dist/services/budget-awareness.d.ts +11 -11
  103. package/dist/services/budget-awareness.js +15 -3
  104. package/dist/services/claude-local-scope-mcp.d.ts +19 -0
  105. package/dist/services/claude-local-scope-mcp.js +91 -0
  106. package/dist/services/cloud/aws.js +2 -1
  107. package/dist/services/cloud/lifecycle.js +52 -6
  108. package/dist/services/cloud/task-wrapper.d.ts +0 -9
  109. package/dist/services/cloud/task-wrapper.js +15 -6
  110. package/dist/services/credential-cleanup.js +35 -17
  111. package/dist/services/event-loop-watchdog.d.ts +32 -0
  112. package/dist/services/event-loop-watchdog.js +140 -0
  113. package/dist/services/exit-drain.d.ts +44 -0
  114. package/dist/services/exit-drain.js +52 -0
  115. package/dist/services/github-app.js +32 -4
  116. package/dist/services/http-transport.d.ts +50 -1
  117. package/dist/services/http-transport.js +238 -25
  118. package/dist/services/in-flight-agents.d.ts +2 -0
  119. package/dist/services/in-flight-agents.js +4 -0
  120. package/dist/services/knowledge/bible-basis-filter.d.ts +53 -0
  121. package/dist/services/knowledge/bible-basis-filter.js +134 -0
  122. package/dist/services/knowledge/bible-blob-id.d.ts +44 -0
  123. package/dist/services/knowledge/bible-blob-id.js +113 -0
  124. package/dist/services/knowledge/bible-import.d.ts +65 -0
  125. package/dist/services/knowledge/bible-import.js +211 -0
  126. package/dist/services/knowledge/file-hash.d.ts +31 -0
  127. package/dist/services/knowledge/file-hash.js +153 -23
  128. package/dist/services/knowledge/http-provider.d.ts +4 -3
  129. package/dist/services/knowledge/http-provider.js +17 -5
  130. package/dist/services/knowledge/kb-config.d.ts +42 -0
  131. package/dist/services/knowledge/kb-config.js +54 -0
  132. package/dist/services/knowledge/kb-maintainer-grant.d.ts +15 -0
  133. package/dist/services/knowledge/kb-maintainer-grant.js +34 -0
  134. package/dist/services/knowledge/kb-providers.d.ts +11 -1
  135. package/dist/services/knowledge/kb-providers.js +199 -17
  136. package/dist/services/knowledge/kb-removed-scope-keys.d.ts +28 -0
  137. package/dist/services/knowledge/kb-removed-scope-keys.js +59 -0
  138. package/dist/services/knowledge/kb-scopes.d.ts +14 -0
  139. package/dist/services/knowledge/kb-scopes.js +47 -0
  140. package/dist/services/knowledge/kb-self.d.ts +91 -0
  141. package/dist/services/knowledge/kb-self.js +198 -0
  142. package/dist/services/knowledge/member-bible-view.d.ts +21 -0
  143. package/dist/services/knowledge/member-bible-view.js +194 -0
  144. package/dist/services/knowledge/pre-init.js +1 -0
  145. package/dist/services/knowledge/project-slug.js +2 -2
  146. package/dist/services/knowledge/require-sqlite-project.d.ts +32 -0
  147. package/dist/services/knowledge/require-sqlite-project.js +38 -0
  148. package/dist/services/knowledge/sqlite-provider.d.ts +64 -11
  149. package/dist/services/knowledge/sqlite-provider.js +303 -41
  150. package/dist/services/knowledge/types.d.ts +45 -2
  151. package/dist/services/member-access-secret.d.ts +70 -0
  152. package/dist/services/member-access-secret.js +195 -0
  153. package/dist/services/member-call-counts.d.ts +24 -0
  154. package/dist/services/member-call-counts.js +58 -0
  155. package/dist/services/member-config-io.d.ts +192 -0
  156. package/dist/services/member-config-io.js +443 -0
  157. package/dist/services/member-fleet-install.d.ts +710 -0
  158. package/dist/services/member-fleet-install.js +1895 -0
  159. package/dist/services/member-secret-env.d.ts +42 -0
  160. package/dist/services/member-secret-env.js +68 -0
  161. package/dist/services/member-tool-allowlist.d.ts +49 -0
  162. package/dist/services/member-tool-allowlist.js +111 -0
  163. package/dist/services/model-pricing.d.ts +19 -0
  164. package/dist/services/model-pricing.js +60 -10
  165. package/dist/services/port-holder.d.ts +86 -0
  166. package/dist/services/port-holder.js +351 -0
  167. package/dist/services/preflight-check.js +2 -0
  168. package/dist/services/registry.d.ts +13 -2
  169. package/dist/services/registry.js +27 -1
  170. package/dist/services/relay-strategy.d.ts +2 -0
  171. package/dist/services/relay-strategy.js +8 -0
  172. package/dist/services/secret-token.d.ts +38 -0
  173. package/dist/services/secret-token.js +51 -0
  174. package/dist/services/server-lifecycle.d.ts +26 -0
  175. package/dist/services/server-lifecycle.js +85 -0
  176. package/dist/services/service-manager/index.d.ts +7 -1
  177. package/dist/services/service-manager/index.js +17 -4
  178. package/dist/services/service-manager/linux.d.ts +1 -1
  179. package/dist/services/service-manager/linux.js +15 -7
  180. package/dist/services/service-manager/macos.d.ts +11 -1
  181. package/dist/services/service-manager/macos.js +45 -7
  182. package/dist/services/service-manager/service-path.d.ts +24 -0
  183. package/dist/services/service-manager/service-path.js +55 -0
  184. package/dist/services/service-manager/types.d.ts +39 -2
  185. package/dist/services/service-manager/types.js +29 -0
  186. package/dist/services/service-manager/windows.d.ts +194 -3
  187. package/dist/services/service-manager/windows.js +705 -30
  188. package/dist/services/service-notice.d.ts +14 -0
  189. package/dist/services/service-notice.js +62 -0
  190. package/dist/services/service-start-guard.d.ts +20 -0
  191. package/dist/services/service-start-guard.js +86 -0
  192. package/dist/services/session-cost.d.ts +24 -0
  193. package/dist/services/session-cost.js +105 -0
  194. package/dist/services/session-mcp-config.d.ts +83 -0
  195. package/dist/services/session-mcp-config.js +211 -0
  196. package/dist/services/sftp.d.ts +34 -0
  197. package/dist/services/sftp.js +304 -76
  198. package/dist/services/shell-probe.d.ts +0 -24
  199. package/dist/services/shell-probe.js +28 -3
  200. package/dist/services/singleton.d.ts +68 -2
  201. package/dist/services/singleton.js +168 -11
  202. package/dist/services/sprint-coordination.js +9 -3
  203. package/dist/services/ssh.d.ts +27 -0
  204. package/dist/services/ssh.js +287 -40
  205. package/dist/services/stall/find-log-file.js +12 -5
  206. package/dist/services/stall/index.d.ts +1 -1
  207. package/dist/services/stall/read-log-tail.d.ts +23 -0
  208. package/dist/services/stall/read-log-tail.js +53 -12
  209. package/dist/services/stall/stall-detector.d.ts +78 -5
  210. package/dist/services/stall/stall-detector.js +296 -39
  211. package/dist/services/stall/stall-poller.d.ts +16 -0
  212. package/dist/services/stall/stall-poller.js +50 -6
  213. package/dist/services/stopped-marker.d.ts +16 -0
  214. package/dist/services/stopped-marker.js +55 -0
  215. package/dist/services/strategy.d.ts +33 -1
  216. package/dist/services/strategy.js +165 -19
  217. package/dist/services/substitution-engine.js +2 -2
  218. package/dist/services/supervisor-service-cleanup.d.ts +52 -0
  219. package/dist/services/supervisor-service-cleanup.js +332 -0
  220. package/dist/services/tool-registry.d.ts +8 -1
  221. package/dist/services/tool-registry.js +164 -61
  222. package/dist/services/tool-scope.d.ts +58 -0
  223. package/dist/services/tool-scope.js +99 -0
  224. package/dist/services/vcs/azure-devops.d.ts +66 -1
  225. package/dist/services/vcs/azure-devops.js +192 -21
  226. package/dist/services/vcs/types.d.ts +1 -1
  227. package/dist/services/watch/project-resolver.js +1 -0
  228. package/dist/skills/auto-sprint-args/SKILL.md +2 -2
  229. package/dist/skills/fleet-sprint-cli/SKILL.md +48 -6
  230. package/dist/skills/pm/SKILL.md +4 -4
  231. package/dist/skills/pm/cost.md +0 -3
  232. package/dist/skills/pm/fleet-addendum.md +2 -2
  233. package/dist/skills/pm/index.md +4 -2
  234. package/dist/skills/pm/kb-reconcile.md +29 -14
  235. package/dist/skills/pm/kb-review.md +1 -0
  236. package/dist/skills/pm/sprint.md +5 -5
  237. package/dist/tools/check-status.d.ts +60 -9
  238. package/dist/tools/check-status.js +211 -52
  239. package/dist/tools/child-id-allocator.d.ts +2 -2
  240. package/dist/tools/child-id-allocator.js +1 -1
  241. package/dist/tools/code-index-heal.d.ts +8 -0
  242. package/dist/tools/code-index-heal.js +21 -0
  243. package/dist/tools/code-index-state.d.ts +45 -0
  244. package/dist/tools/code-index-state.js +115 -0
  245. package/dist/tools/code-intelligence-codebase-memory.js +6 -33
  246. package/dist/tools/code-intelligence-freshness.js +1 -1
  247. package/dist/tools/code-intelligence-gitnexus.d.ts +30 -0
  248. package/dist/tools/code-intelligence-gitnexus.js +333 -57
  249. package/dist/tools/code-intelligence-kb-enrich.js +7 -6
  250. package/dist/tools/code-intelligence-readiness.d.ts +99 -0
  251. package/dist/tools/code-intelligence-readiness.js +206 -0
  252. package/dist/tools/code-intelligence-reindex.d.ts +195 -0
  253. package/dist/tools/code-intelligence-reindex.js +530 -50
  254. package/dist/tools/code-intelligence-telemetry.d.ts +6 -1
  255. package/dist/tools/code-intelligence-telemetry.js +12 -3
  256. package/dist/tools/code-intelligence.d.ts +81 -31
  257. package/dist/tools/code-intelligence.js +156 -52
  258. package/dist/tools/compose-permissions.d.ts +63 -2
  259. package/dist/tools/compose-permissions.js +673 -72
  260. package/dist/tools/credential-store-set.js +1 -1
  261. package/dist/tools/execute-command.d.ts +11 -0
  262. package/dist/tools/execute-command.js +111 -32
  263. package/dist/tools/execute-prompt.d.ts +69 -12
  264. package/dist/tools/execute-prompt.js +1610 -895
  265. package/dist/tools/kb-bible-commit.d.ts +65 -0
  266. package/dist/tools/kb-bible-commit.js +239 -0
  267. package/dist/tools/kb-capture.d.ts +15 -11
  268. package/dist/tools/kb-capture.js +71 -16
  269. package/dist/tools/kb-context.d.ts +27 -7
  270. package/dist/tools/kb-context.js +60 -9
  271. package/dist/tools/kb-export.d.ts +98 -9
  272. package/dist/tools/kb-export.js +230 -92
  273. package/dist/tools/kb-feedback.d.ts +13 -9
  274. package/dist/tools/kb-feedback.js +16 -8
  275. package/dist/tools/kb-freshness-sweep.d.ts +11 -7
  276. package/dist/tools/kb-freshness-sweep.js +10 -8
  277. package/dist/tools/kb-harvest.d.ts +11 -7
  278. package/dist/tools/kb-harvest.js +7 -7
  279. package/dist/tools/kb-import.d.ts +26 -10
  280. package/dist/tools/kb-import.js +170 -159
  281. package/dist/tools/kb-invalidate.d.ts +17 -10
  282. package/dist/tools/kb-invalidate.js +41 -8
  283. package/dist/tools/kb-list.d.ts +14 -10
  284. package/dist/tools/kb-list.js +33 -11
  285. package/dist/tools/kb-promote.d.ts +11 -7
  286. package/dist/tools/kb-promote.js +14 -8
  287. package/dist/tools/kb-query.d.ts +21 -11
  288. package/dist/tools/kb-query.js +76 -13
  289. package/dist/tools/kb-reconcile-prefilter.d.ts +11 -7
  290. package/dist/tools/kb-reconcile-prefilter.js +13 -9
  291. package/dist/tools/kb-resolve-contradiction.d.ts +11 -7
  292. package/dist/tools/kb-resolve-contradiction.js +10 -8
  293. package/dist/tools/kb-session-prime.d.ts +14 -7
  294. package/dist/tools/kb-session-prime.js +44 -44
  295. package/dist/tools/kb-setup.d.ts +11 -4
  296. package/dist/tools/kb-setup.js +146 -27
  297. package/dist/tools/kb-stats.d.ts +11 -10
  298. package/dist/tools/kb-stats.js +84 -82
  299. package/dist/tools/list-members.d.ts +2 -2
  300. package/dist/tools/list-members.js +6 -2
  301. package/dist/tools/member-detail.d.ts +5 -2
  302. package/dist/tools/member-detail.js +105 -17
  303. package/dist/tools/member-reservation.d.ts +60 -3
  304. package/dist/tools/member-reservation.js +61 -20
  305. package/dist/tools/provision-auth.d.ts +118 -1
  306. package/dist/tools/provision-auth.js +402 -92
  307. package/dist/tools/provision-vcs-auth.d.ts +93 -3
  308. package/dist/tools/provision-vcs-auth.js +209 -49
  309. package/dist/tools/receive-files.js +3 -1
  310. package/dist/tools/register-member.d.ts +44 -15
  311. package/dist/tools/register-member.js +175 -70
  312. package/dist/tools/remove-member.js +118 -15
  313. package/dist/tools/send-email.d.ts +2 -2
  314. package/dist/tools/send-files.js +6 -4
  315. package/dist/tools/session-stats.d.ts +17 -0
  316. package/dist/tools/session-stats.js +27 -0
  317. package/dist/tools/setup-git-app.js +11 -7
  318. package/dist/tools/shutdown-server.d.ts +2 -0
  319. package/dist/tools/shutdown-server.js +28 -1
  320. package/dist/tools/update-agent-cli.d.ts +19 -0
  321. package/dist/tools/update-agent-cli.js +59 -2
  322. package/dist/tools/update-member.d.ts +23 -17
  323. package/dist/tools/update-member.js +181 -18
  324. package/dist/tools/vcs-credential-exec.d.ts +127 -0
  325. package/dist/tools/vcs-credential-exec.js +203 -0
  326. package/dist/types.d.ts +111 -1
  327. package/dist/utils/agent-helpers.js +2 -0
  328. package/dist/utils/auth-env.d.ts +15 -4
  329. package/dist/utils/auth-env.js +52 -23
  330. package/dist/utils/find-on-path.d.ts +37 -0
  331. package/dist/utils/find-on-path.js +85 -0
  332. package/dist/utils/log-helpers.d.ts +37 -0
  333. package/dist/utils/log-helpers.js +108 -22
  334. package/dist/utils/owner-only-fs.d.ts +56 -0
  335. package/dist/utils/owner-only-fs.js +98 -0
  336. package/dist/utils/process-utils.d.ts +28 -0
  337. package/dist/utils/process-utils.js +68 -0
  338. package/dist/utils/prompt-errors.js +11 -2
  339. package/dist/utils/session-caller.d.ts +4 -2
  340. package/dist/utils/session-caller.js +3 -2
  341. package/dist/utils/shell-escape.d.ts +58 -3
  342. package/dist/utils/shell-escape.js +91 -5
  343. package/dist/utils/ssh-error-messages.js +3 -0
  344. package/dist/utils/vcs-provider-detect.d.ts +65 -0
  345. package/dist/utils/vcs-provider-detect.js +109 -0
  346. package/dist/utils/workspace-trust.d.ts +26 -0
  347. package/dist/utils/workspace-trust.js +91 -1
  348. package/dist/workflows/auto-sprint.js +397 -56
  349. package/package.json +15 -10
  350. package/packages/apra-fleet-client/package.json +2 -2
  351. package/packages/apra-fleet-client/src/client/api.mjs +864 -31
  352. package/packages/apra-fleet-client/src/client/auto-start.mjs +434 -0
  353. package/packages/apra-fleet-client/src/client/client.mjs +9 -0
  354. package/packages/apra-fleet-client/src/client/errors.mjs +6 -2
  355. package/packages/apra-fleet-client/src/client/factory.mjs +23 -4
  356. package/packages/apra-fleet-client/src/client/reconnecting-transport.mjs +137 -0
  357. package/packages/apra-fleet-client/src/client/server-resolution.mjs +267 -30
  358. package/packages/apra-fleet-client/src/client/transport.mjs +37 -3
  359. package/packages/apra-fleet-se/apra-pm/agents/_shared/GRAPH-SEMANTICS.md +10 -2
  360. package/packages/apra-fleet-se/apra-pm/agents/backlog-groomer.md +87 -14
  361. package/packages/apra-fleet-se/apra-pm/agents/ci-watcher.md +35 -9
  362. package/packages/apra-fleet-se/apra-pm/agents/deployer.md +63 -11
  363. package/packages/apra-fleet-se/apra-pm/agents/doer.md +99 -41
  364. package/packages/apra-fleet-se/apra-pm/agents/harvester.md +47 -27
  365. package/packages/apra-fleet-se/apra-pm/agents/integ-test-runner.md +38 -10
  366. package/packages/apra-fleet-se/apra-pm/agents/kb-reconciler.md +37 -7
  367. package/packages/apra-fleet-se/apra-pm/agents/plan-reviewer.md +145 -32
  368. package/packages/apra-fleet-se/apra-pm/agents/planner.md +180 -69
  369. package/packages/apra-fleet-se/apra-pm/agents/regression-test-runner.md +98 -64
  370. package/packages/apra-fleet-se/apra-pm/agents/reviewer.md +117 -45
  371. package/packages/apra-fleet-se/apra-pm/agents/schemas/backlog-groomer-output.json +1 -1
  372. package/packages/apra-fleet-se/apra-pm/agents/schemas/doer-output.json +32 -0
  373. package/packages/apra-fleet-se/apra-pm/agents/schemas/harvester-input.json +1 -5
  374. package/packages/apra-fleet-se/apra-pm/agents/schemas/plan-reviewer-output.json +37 -0
  375. package/packages/apra-fleet-se/apra-pm/agents/schemas/planner-output.json +1 -1
  376. package/packages/apra-fleet-se/apra-pm/agents/schemas/regression-test-runner-output.json +41 -7
  377. package/packages/apra-fleet-se/apra-pm/agents/schemas/reviewer-output.json +62 -3
  378. package/packages/apra-fleet-se/apra-pm/skills/pm/SKILL.md +4 -4
  379. package/packages/apra-fleet-se/apra-pm/skills/pm/cost.md +0 -3
  380. package/packages/apra-fleet-se/apra-pm/skills/pm/fleet-addendum.md +2 -2
  381. package/packages/apra-fleet-se/apra-pm/skills/pm/index.md +4 -2
  382. package/packages/apra-fleet-se/apra-pm/skills/pm/kb-reconcile.md +29 -14
  383. package/packages/apra-fleet-se/apra-pm/skills/pm/kb-review.md +1 -0
  384. package/packages/apra-fleet-se/apra-pm/skills/pm/sprint.md +5 -5
  385. package/packages/apra-fleet-se/bin/cli.mjs +326 -48
  386. package/packages/apra-fleet-se/bin/serve.mjs +218 -11
  387. package/packages/apra-fleet-se/fleet-sprint/abort.mjs +517 -0
  388. package/packages/apra-fleet-se/fleet-sprint/backlog-role.mjs +93 -0
  389. package/packages/apra-fleet-se/fleet-sprint/beads-children.mjs +646 -0
  390. package/packages/apra-fleet-se/fleet-sprint/beads-identity-check.mjs +825 -0
  391. package/packages/apra-fleet-se/fleet-sprint/beads-identity.mjs +217 -0
  392. package/packages/apra-fleet-se/fleet-sprint/beads-memory-hygiene.mjs +201 -0
  393. package/packages/apra-fleet-se/fleet-sprint/beads-scope.mjs +745 -0
  394. package/packages/apra-fleet-se/fleet-sprint/beads-transitions.mjs +447 -0
  395. package/packages/apra-fleet-se/fleet-sprint/branch-ensure.mjs +96 -0
  396. package/packages/apra-fleet-se/fleet-sprint/ci-gate.mjs +353 -0
  397. package/packages/apra-fleet-se/fleet-sprint/conflict-ladder.mjs +20 -0
  398. package/packages/apra-fleet-se/fleet-sprint/contracts.mjs +121 -15
  399. package/packages/apra-fleet-se/fleet-sprint/coordination.mjs +539 -0
  400. package/packages/apra-fleet-se/fleet-sprint/dispatch-accounting.mjs +270 -0
  401. package/packages/apra-fleet-se/fleet-sprint/dispatch-failure.mjs +204 -0
  402. package/packages/apra-fleet-se/fleet-sprint/dispatch-role.mjs +1310 -0
  403. package/packages/apra-fleet-se/fleet-sprint/dispatch-safety-guard.mjs +216 -4
  404. package/packages/apra-fleet-se/fleet-sprint/docs/README.md +53 -15
  405. package/packages/apra-fleet-se/fleet-sprint/docs/dolt-sync-redesign.md +281 -0
  406. package/packages/apra-fleet-se/fleet-sprint/docs/escalate-to-llm-design.md +1 -1
  407. package/packages/apra-fleet-se/fleet-sprint/docs/fleet-sprint-diagram.md +3 -3
  408. package/packages/apra-fleet-se/fleet-sprint/docs/run-sprint-cycle-prelude-decision.md +215 -0
  409. package/packages/apra-fleet-se/fleet-sprint/dolt-literal-guard.mjs +56 -1
  410. package/packages/apra-fleet-se/fleet-sprint/dolt-sync.mjs +1327 -44
  411. package/packages/apra-fleet-se/fleet-sprint/errors.mjs +470 -4
  412. package/packages/apra-fleet-se/fleet-sprint/explicit-id-create-guard.mjs +501 -0
  413. package/packages/apra-fleet-se/fleet-sprint/fatal-diagnostics.mjs +134 -0
  414. package/packages/apra-fleet-se/fleet-sprint/full-db-fetch-guard.mjs +102 -0
  415. package/packages/apra-fleet-se/fleet-sprint/git-sync.mjs +747 -0
  416. package/packages/apra-fleet-se/fleet-sprint/git-topology.mjs +543 -0
  417. package/packages/apra-fleet-se/fleet-sprint/guarded-modules.mjs +613 -0
  418. package/packages/apra-fleet-se/fleet-sprint/inline-ladder-guard.mjs +216 -0
  419. package/packages/apra-fleet-se/fleet-sprint/kb-hints.mjs +181 -0
  420. package/packages/apra-fleet-se/fleet-sprint/kb-injection.mjs +64 -0
  421. package/packages/apra-fleet-se/fleet-sprint/kb-maintainer.mjs +298 -0
  422. package/packages/apra-fleet-se/fleet-sprint/kb.mjs +1684 -0
  423. package/packages/apra-fleet-se/fleet-sprint/lower-quality.mjs +39 -0
  424. package/packages/apra-fleet-se/fleet-sprint/mcp-result.mjs +75 -0
  425. package/packages/apra-fleet-se/fleet-sprint/member-align.mjs +391 -0
  426. package/packages/apra-fleet-se/fleet-sprint/member-call.mjs +374 -0
  427. package/packages/apra-fleet-se/fleet-sprint/member-init-probe.mjs +644 -0
  428. package/packages/apra-fleet-se/fleet-sprint/member-provisioning.mjs +699 -0
  429. package/packages/apra-fleet-se/fleet-sprint/member-sync.mjs +802 -0
  430. package/packages/apra-fleet-se/fleet-sprint/member-target.mjs +93 -0
  431. package/packages/apra-fleet-se/fleet-sprint/newtask-text.mjs +266 -0
  432. package/packages/apra-fleet-se/fleet-sprint/orphan-reclaim.mjs +153 -0
  433. package/packages/apra-fleet-se/fleet-sprint/parent-notes-staleness.mjs +201 -0
  434. package/packages/apra-fleet-se/fleet-sprint/phases/deploy.mjs +218 -0
  435. package/packages/apra-fleet-se/fleet-sprint/phases/develop.mjs +869 -0
  436. package/packages/apra-fleet-se/fleet-sprint/phases/ensure-sprint-branch.mjs +295 -0
  437. package/packages/apra-fleet-se/fleet-sprint/phases/final-review.mjs +466 -0
  438. package/packages/apra-fleet-se/fleet-sprint/phases/harvest.mjs +212 -0
  439. package/packages/apra-fleet-se/fleet-sprint/phases/integ-test.mjs +358 -0
  440. package/packages/apra-fleet-se/fleet-sprint/phases/plan.mjs +395 -0
  441. package/packages/apra-fleet-se/fleet-sprint/phases/publish-pr.mjs +345 -0
  442. package/packages/apra-fleet-se/fleet-sprint/phases/re-review.mjs +264 -0
  443. package/packages/apra-fleet-se/fleet-sprint/phases/regression-test.mjs +179 -0
  444. package/packages/apra-fleet-se/fleet-sprint/phases/replan.mjs +230 -0
  445. package/packages/apra-fleet-se/fleet-sprint/phases/review.mjs +365 -0
  446. package/packages/apra-fleet-se/fleet-sprint/pr-body.mjs +259 -0
  447. package/packages/apra-fleet-se/fleet-sprint/prompts.mjs +617 -0
  448. package/packages/apra-fleet-se/fleet-sprint/role-policies.mjs +1434 -0
  449. package/packages/apra-fleet-se/fleet-sprint/round-session.mjs +100 -0
  450. package/packages/apra-fleet-se/fleet-sprint/runner.js +2289 -9928
  451. package/packages/apra-fleet-se/fleet-sprint/se-os-commands.mjs +24 -0
  452. package/packages/apra-fleet-se/fleet-sprint/se-posix.mjs +147 -12
  453. package/packages/apra-fleet-se/fleet-sprint/se-windows.mjs +111 -0
  454. package/packages/apra-fleet-se/fleet-sprint/shell-command-guard.mjs +347 -0
  455. package/packages/apra-fleet-se/fleet-sprint/skills/fleet-sprint-cli/SKILL.md +48 -6
  456. package/packages/apra-fleet-se/fleet-sprint/skills/fleet-supervisor/SKILL.md +98 -25
  457. package/packages/apra-fleet-se/fleet-sprint/sprint-args.mjs +590 -0
  458. package/packages/apra-fleet-se/fleet-sprint/sprint-report.mjs +339 -0
  459. package/packages/apra-fleet-se/fleet-sprint/sprint-state.mjs +185 -0
  460. package/packages/apra-fleet-se/fleet-sprint/unbracketed-push-guard.mjs +234 -0
  461. package/packages/apra-fleet-se/fleet-sprint/usage-limit-controller.mjs +218 -0
  462. package/packages/apra-fleet-se/fleet-sprint/vcs-auth.mjs +1445 -0
  463. package/packages/apra-fleet-se/fleet-sprint/vcs-module.mjs +284 -23
  464. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/azure-devops.mjs +170 -21
  465. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/bitbucket.mjs +28 -0
  466. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/github.mjs +354 -0
  467. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/index.mjs +189 -16
  468. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/shell-helpers.mjs +9 -4
  469. package/packages/apra-fleet-se/fleet-sprint/verify-block.mjs +152 -0
  470. package/packages/apra-fleet-se/fleet-sprint/viewer-extensions.mjs +311 -22
  471. package/packages/apra-fleet-se/fleet-sprint/worklists.mjs +559 -0
  472. package/packages/apra-fleet-se/package.json +2 -2
  473. package/packages/apra-fleet-se/src/supervisor/api.mjs +919 -0
  474. package/packages/apra-fleet-se/src/supervisor/backlog-member.mjs +332 -0
  475. package/packages/apra-fleet-se/src/supervisor/backlog.mjs +982 -0
  476. package/packages/apra-fleet-se/src/supervisor/beads-identity.mjs +246 -0
  477. package/packages/apra-fleet-se/src/supervisor/beads-view.mjs +438 -0
  478. package/packages/apra-fleet-se/src/supervisor/child-port.mjs +36 -0
  479. package/packages/apra-fleet-se/src/supervisor/dashboard.mjs +1659 -0
  480. package/packages/apra-fleet-se/src/supervisor/dolt-mutex.mjs +350 -0
  481. package/packages/apra-fleet-se/src/supervisor/dolt-orphan-sweep.mjs +338 -0
  482. package/packages/apra-fleet-se/src/supervisor/fleet-members.mjs +279 -0
  483. package/packages/apra-fleet-se/src/supervisor/history-view.mjs +276 -0
  484. package/packages/apra-fleet-se/src/supervisor/history.mjs +328 -0
  485. package/packages/apra-fleet-se/src/supervisor/id-allocator.mjs +521 -0
  486. package/packages/apra-fleet-se/src/supervisor/launch-form.mjs +444 -0
  487. package/packages/apra-fleet-se/src/supervisor/ledger.mjs +629 -0
  488. package/packages/apra-fleet-se/src/supervisor/lib/exec-bd.mjs +303 -0
  489. package/packages/apra-fleet-se/src/supervisor/log-timestamp.mjs +51 -0
  490. package/packages/apra-fleet-se/src/supervisor/log-view.mjs +159 -0
  491. package/packages/apra-fleet-se/src/supervisor/proxy.mjs +474 -0
  492. package/packages/apra-fleet-se/src/supervisor/readopt.mjs +136 -0
  493. package/packages/apra-fleet-se/src/supervisor/reconcile.mjs +263 -0
  494. package/packages/apra-fleet-se/src/supervisor/rename-with-retry.mjs +87 -0
  495. package/packages/apra-fleet-se/src/supervisor/scope-overlap.mjs +327 -0
  496. package/packages/apra-fleet-se/src/supervisor/self-log.mjs +133 -0
  497. package/packages/apra-fleet-se/src/supervisor/server.mjs +399 -0
  498. package/packages/apra-fleet-se/src/supervisor/spawner.mjs +542 -0
  499. package/packages/apra-fleet-se/src/supervisor/sprint-identity.mjs +96 -0
  500. package/packages/apra-fleet-se/src/supervisor/watchdog.mjs +987 -0
  501. package/packages/apra-fleet-workflow/package.json +1 -1
  502. package/packages/apra-fleet-workflow/src/viewer/index.mjs +81 -15
  503. package/packages/apra-fleet-workflow/src/viewer/run-summary.mjs +127 -0
  504. package/packages/apra-fleet-workflow/src/workflow/index.mjs +118 -10
  505. package/packages/apra-fleet-workflow/src/workflow/pricing.mjs +75 -25
  506. package/skills/fleet/SKILL.md +8 -8
  507. package/skills/fleet/auth-azdevops.md +14 -3
  508. package/skills/fleet/auth-bitbucket.md +2 -2
  509. package/skills/fleet/auth-github.md +5 -4
  510. package/skills/fleet/onboarding.md +3 -3
  511. package/skills/fleet/permissions.md +14 -1
  512. package/skills/fleet/profiles/node.json +1 -1
  513. package/skills/fleet/profiles/tag-kb-reconciler.json +2 -6
  514. package/skills/fleet/troubleshooting.md +3 -3
  515. package/version.json +1 -1
  516. package/dist/cli/agent-transform.d.ts.map +0 -1
  517. package/dist/cli/agent-transform.js.map +0 -1
  518. package/dist/cli/auth.d.ts.map +0 -1
  519. package/dist/cli/auth.js.map +0 -1
  520. package/dist/cli/config.d.ts.map +0 -1
  521. package/dist/cli/config.js.map +0 -1
  522. package/dist/cli/dolt-install.d.ts.map +0 -1
  523. package/dist/cli/dolt-install.js.map +0 -1
  524. package/dist/cli/install-guard.d.ts.map +0 -1
  525. package/dist/cli/install-guard.js.map +0 -1
  526. package/dist/cli/install.d.ts.map +0 -1
  527. package/dist/cli/install.js.map +0 -1
  528. package/dist/cli/join.d.ts.map +0 -1
  529. package/dist/cli/join.js.map +0 -1
  530. package/dist/cli/kb-commit.d.ts.map +0 -1
  531. package/dist/cli/kb-commit.js.map +0 -1
  532. package/dist/cli/kb-directives.d.ts.map +0 -1
  533. package/dist/cli/kb-directives.js.map +0 -1
  534. package/dist/cli/kb-import.d.ts.map +0 -1
  535. package/dist/cli/kb-import.js.map +0 -1
  536. package/dist/cli/register-member.d.ts.map +0 -1
  537. package/dist/cli/register-member.js.map +0 -1
  538. package/dist/cli/restart.d.ts.map +0 -1
  539. package/dist/cli/restart.js.map +0 -1
  540. package/dist/cli/secret.d.ts.map +0 -1
  541. package/dist/cli/secret.js.map +0 -1
  542. package/dist/cli/spoke.d.ts.map +0 -1
  543. package/dist/cli/spoke.js.map +0 -1
  544. package/dist/cli/start.d.ts.map +0 -1
  545. package/dist/cli/start.js.map +0 -1
  546. package/dist/cli/status.d.ts.map +0 -1
  547. package/dist/cli/status.js.map +0 -1
  548. package/dist/cli/stop.d.ts.map +0 -1
  549. package/dist/cli/stop.js.map +0 -1
  550. package/dist/cli/uninstall.d.ts.map +0 -1
  551. package/dist/cli/uninstall.js.map +0 -1
  552. package/dist/cli/update.d.ts.map +0 -1
  553. package/dist/cli/update.js.map +0 -1
  554. package/dist/cli/watch.d.ts.map +0 -1
  555. package/dist/cli/watch.js.map +0 -1
  556. package/dist/cli/workflow-assets.d.ts.map +0 -1
  557. package/dist/cli/workflow-assets.js.map +0 -1
  558. package/dist/cli/workflow.d.ts.map +0 -1
  559. package/dist/cli/workflow.js.map +0 -1
  560. package/dist/commands/kb-server.d.ts.map +0 -1
  561. package/dist/commands/kb-server.js.map +0 -1
  562. package/dist/delivery-mode.d.ts.map +0 -1
  563. package/dist/delivery-mode.js.map +0 -1
  564. package/dist/hub-service/activity.d.ts.map +0 -1
  565. package/dist/hub-service/activity.js.map +0 -1
  566. package/dist/hub-service/audit-log.d.ts.map +0 -1
  567. package/dist/hub-service/audit-log.js.map +0 -1
  568. package/dist/hub-service/db/pool.d.ts.map +0 -1
  569. package/dist/hub-service/db/pool.js.map +0 -1
  570. package/dist/hub-service/enrollment.d.ts.map +0 -1
  571. package/dist/hub-service/enrollment.js.map +0 -1
  572. package/dist/hub-service/envelope-routes.d.ts.map +0 -1
  573. package/dist/hub-service/envelope-routes.js.map +0 -1
  574. package/dist/hub-service/handlers/installers.d.ts.map +0 -1
  575. package/dist/hub-service/handlers/installers.js.map +0 -1
  576. package/dist/hub-service/http-server.d.ts.map +0 -1
  577. package/dist/hub-service/http-server.js.map +0 -1
  578. package/dist/hub-service/hub-jwt.d.ts.map +0 -1
  579. package/dist/hub-service/hub-jwt.js.map +0 -1
  580. package/dist/hub-service/jwt-revocation.d.ts.map +0 -1
  581. package/dist/hub-service/jwt-revocation.js.map +0 -1
  582. package/dist/hub-service/machines.d.ts.map +0 -1
  583. package/dist/hub-service/machines.js.map +0 -1
  584. package/dist/hub-service/main.d.ts.map +0 -1
  585. package/dist/hub-service/main.js.map +0 -1
  586. package/dist/hub-service/member-tokens.d.ts.map +0 -1
  587. package/dist/hub-service/member-tokens.js.map +0 -1
  588. package/dist/hub-service/member-view.d.ts.map +0 -1
  589. package/dist/hub-service/member-view.js.map +0 -1
  590. package/dist/hub-service/members.d.ts.map +0 -1
  591. package/dist/hub-service/members.js.map +0 -1
  592. package/dist/hub-service/presence.d.ts.map +0 -1
  593. package/dist/hub-service/presence.js.map +0 -1
  594. package/dist/hub-service/project-view.d.ts.map +0 -1
  595. package/dist/hub-service/project-view.js.map +0 -1
  596. package/dist/hub-service/projects.d.ts.map +0 -1
  597. package/dist/hub-service/projects.js.map +0 -1
  598. package/dist/hub-service/relay-queue.d.ts.map +0 -1
  599. package/dist/hub-service/relay-queue.js.map +0 -1
  600. package/dist/hub-service/session-jwt.d.ts.map +0 -1
  601. package/dist/hub-service/session-jwt.js.map +0 -1
  602. package/dist/hub-service/usage.d.ts.map +0 -1
  603. package/dist/hub-service/usage.js.map +0 -1
  604. package/dist/hub-service/users.d.ts.map +0 -1
  605. package/dist/hub-service/users.js.map +0 -1
  606. package/dist/hub-service/workspaces.d.ts.map +0 -1
  607. package/dist/hub-service/workspaces.js.map +0 -1
  608. package/dist/index.d.ts.map +0 -1
  609. package/dist/index.js.map +0 -1
  610. package/dist/onboarding/text.d.ts.map +0 -1
  611. package/dist/onboarding/text.js.map +0 -1
  612. package/dist/os/git-bash-candidates.d.ts.map +0 -1
  613. package/dist/os/git-bash-candidates.js.map +0 -1
  614. package/dist/os/index.d.ts.map +0 -1
  615. package/dist/os/index.js.map +0 -1
  616. package/dist/os/linux.d.ts.map +0 -1
  617. package/dist/os/linux.js.map +0 -1
  618. package/dist/os/macos.d.ts.map +0 -1
  619. package/dist/os/macos.js.map +0 -1
  620. package/dist/os/os-commands.d.ts.map +0 -1
  621. package/dist/os/os-commands.js.map +0 -1
  622. package/dist/os/windows-gitbash.d.ts.map +0 -1
  623. package/dist/os/windows-gitbash.js.map +0 -1
  624. package/dist/os/windows-wrapper.d.ts.map +0 -1
  625. package/dist/os/windows-wrapper.js.map +0 -1
  626. package/dist/os/windows.d.ts.map +0 -1
  627. package/dist/os/windows.js.map +0 -1
  628. package/dist/paths.d.ts.map +0 -1
  629. package/dist/paths.js.map +0 -1
  630. package/dist/providers/agy.d.ts.map +0 -1
  631. package/dist/providers/agy.js.map +0 -1
  632. package/dist/providers/claude.d.ts.map +0 -1
  633. package/dist/providers/claude.js.map +0 -1
  634. package/dist/providers/codex.d.ts.map +0 -1
  635. package/dist/providers/codex.js.map +0 -1
  636. package/dist/providers/copilot.d.ts.map +0 -1
  637. package/dist/providers/copilot.js.map +0 -1
  638. package/dist/providers/email/headers.d.ts.map +0 -1
  639. package/dist/providers/email/headers.js.map +0 -1
  640. package/dist/providers/email/index.d.ts.map +0 -1
  641. package/dist/providers/email/index.js.map +0 -1
  642. package/dist/providers/email/provider.d.ts.map +0 -1
  643. package/dist/providers/email/provider.js.map +0 -1
  644. package/dist/providers/email/sendgrid.d.ts.map +0 -1
  645. package/dist/providers/email/sendgrid.js.map +0 -1
  646. package/dist/providers/email/smtp.d.ts.map +0 -1
  647. package/dist/providers/email/smtp.js.map +0 -1
  648. package/dist/providers/index.d.ts.map +0 -1
  649. package/dist/providers/index.js.map +0 -1
  650. package/dist/providers/none.d.ts.map +0 -1
  651. package/dist/providers/none.js.map +0 -1
  652. package/dist/providers/opencode.d.ts.map +0 -1
  653. package/dist/providers/opencode.js.map +0 -1
  654. package/dist/providers/provider.d.ts.map +0 -1
  655. package/dist/providers/provider.js.map +0 -1
  656. package/dist/services/agent-provisioner.d.ts.map +0 -1
  657. package/dist/services/agent-provisioner.js.map +0 -1
  658. package/dist/services/auth-socket.d.ts.map +0 -1
  659. package/dist/services/auth-socket.js.map +0 -1
  660. package/dist/services/auth-web.d.ts.map +0 -1
  661. package/dist/services/auth-web.js.map +0 -1
  662. package/dist/services/budget-awareness.d.ts.map +0 -1
  663. package/dist/services/budget-awareness.js.map +0 -1
  664. package/dist/services/cloud/activity.d.ts.map +0 -1
  665. package/dist/services/cloud/activity.js.map +0 -1
  666. package/dist/services/cloud/aws.d.ts.map +0 -1
  667. package/dist/services/cloud/aws.js.map +0 -1
  668. package/dist/services/cloud/cost.d.ts.map +0 -1
  669. package/dist/services/cloud/cost.js.map +0 -1
  670. package/dist/services/cloud/idle-manager.d.ts.map +0 -1
  671. package/dist/services/cloud/idle-manager.js.map +0 -1
  672. package/dist/services/cloud/lifecycle.d.ts.map +0 -1
  673. package/dist/services/cloud/lifecycle.js.map +0 -1
  674. package/dist/services/cloud/task-wrapper.d.ts.map +0 -1
  675. package/dist/services/cloud/task-wrapper.js.map +0 -1
  676. package/dist/services/cloud/types.d.ts.map +0 -1
  677. package/dist/services/cloud/types.js.map +0 -1
  678. package/dist/services/cloud-sync.d.ts.map +0 -1
  679. package/dist/services/cloud-sync.js.map +0 -1
  680. package/dist/services/context-admission.d.ts.map +0 -1
  681. package/dist/services/context-admission.js.map +0 -1
  682. package/dist/services/credential-cleanup.d.ts.map +0 -1
  683. package/dist/services/credential-cleanup.js.map +0 -1
  684. package/dist/services/credential-store.d.ts.map +0 -1
  685. package/dist/services/credential-store.js.map +0 -1
  686. package/dist/services/event-bus.d.ts.map +0 -1
  687. package/dist/services/event-bus.js.map +0 -1
  688. package/dist/services/file-chunker.d.ts.map +0 -1
  689. package/dist/services/file-chunker.js.map +0 -1
  690. package/dist/services/file-transfer-relay.d.ts.map +0 -1
  691. package/dist/services/file-transfer-relay.js.map +0 -1
  692. package/dist/services/file-transfer.d.ts.map +0 -1
  693. package/dist/services/file-transfer.js.map +0 -1
  694. package/dist/services/git-config.d.ts.map +0 -1
  695. package/dist/services/git-config.js.map +0 -1
  696. package/dist/services/github-app.d.ts.map +0 -1
  697. package/dist/services/github-app.js.map +0 -1
  698. package/dist/services/http-transport.d.ts.map +0 -1
  699. package/dist/services/http-transport.js.map +0 -1
  700. package/dist/services/hub-client.d.ts.map +0 -1
  701. package/dist/services/hub-client.js.map +0 -1
  702. package/dist/services/icons.d.ts.map +0 -1
  703. package/dist/services/icons.js.map +0 -1
  704. package/dist/services/jwt.d.ts.map +0 -1
  705. package/dist/services/jwt.js.map +0 -1
  706. package/dist/services/knowledge/audn.d.ts.map +0 -1
  707. package/dist/services/knowledge/audn.js.map +0 -1
  708. package/dist/services/knowledge/file-hash.d.ts.map +0 -1
  709. package/dist/services/knowledge/file-hash.js.map +0 -1
  710. package/dist/services/knowledge/http-provider.d.ts.map +0 -1
  711. package/dist/services/knowledge/http-provider.js.map +0 -1
  712. package/dist/services/knowledge/kb-providers.d.ts.map +0 -1
  713. package/dist/services/knowledge/kb-providers.js.map +0 -1
  714. package/dist/services/knowledge/kb-scope-input.d.ts +0 -5
  715. package/dist/services/knowledge/kb-scope-input.d.ts.map +0 -1
  716. package/dist/services/knowledge/kb-scope-input.js +0 -11
  717. package/dist/services/knowledge/kb-scope-input.js.map +0 -1
  718. package/dist/services/knowledge/kb-service.d.ts.map +0 -1
  719. package/dist/services/knowledge/kb-service.js.map +0 -1
  720. package/dist/services/knowledge/path-validation.d.ts.map +0 -1
  721. package/dist/services/knowledge/path-validation.js.map +0 -1
  722. package/dist/services/knowledge/pre-init.d.ts.map +0 -1
  723. package/dist/services/knowledge/pre-init.js.map +0 -1
  724. package/dist/services/knowledge/project-slug.d.ts.map +0 -1
  725. package/dist/services/knowledge/project-slug.js.map +0 -1
  726. package/dist/services/knowledge/sqlite-provider.d.ts.map +0 -1
  727. package/dist/services/knowledge/sqlite-provider.js.map +0 -1
  728. package/dist/services/knowledge/types.d.ts.map +0 -1
  729. package/dist/services/knowledge/types.js.map +0 -1
  730. package/dist/services/known-hosts.d.ts.map +0 -1
  731. package/dist/services/known-hosts.js.map +0 -1
  732. package/dist/services/known-sessions.d.ts.map +0 -1
  733. package/dist/services/known-sessions.js.map +0 -1
  734. package/dist/services/member-home.d.ts.map +0 -1
  735. package/dist/services/member-home.js.map +0 -1
  736. package/dist/services/member-remote-url.d.ts.map +0 -1
  737. package/dist/services/member-remote-url.js.map +0 -1
  738. package/dist/services/model-pricing.d.ts.map +0 -1
  739. package/dist/services/model-pricing.js.map +0 -1
  740. package/dist/services/onboarding.d.ts.map +0 -1
  741. package/dist/services/onboarding.js.map +0 -1
  742. package/dist/services/orphan-recovery.d.ts.map +0 -1
  743. package/dist/services/orphan-recovery.js.map +0 -1
  744. package/dist/services/pending-responses.d.ts.map +0 -1
  745. package/dist/services/pending-responses.js.map +0 -1
  746. package/dist/services/preflight-check.d.ts.map +0 -1
  747. package/dist/services/preflight-check.js.map +0 -1
  748. package/dist/services/registry.d.ts.map +0 -1
  749. package/dist/services/registry.js.map +0 -1
  750. package/dist/services/relay-context.d.ts.map +0 -1
  751. package/dist/services/relay-context.js.map +0 -1
  752. package/dist/services/relay-executor.d.ts.map +0 -1
  753. package/dist/services/relay-executor.js.map +0 -1
  754. package/dist/services/relay-request.d.ts.map +0 -1
  755. package/dist/services/relay-request.js.map +0 -1
  756. package/dist/services/relay-strategy.d.ts.map +0 -1
  757. package/dist/services/relay-strategy.js.map +0 -1
  758. package/dist/services/service-manager/index.d.ts.map +0 -1
  759. package/dist/services/service-manager/index.js.map +0 -1
  760. package/dist/services/service-manager/linux.d.ts.map +0 -1
  761. package/dist/services/service-manager/linux.js.map +0 -1
  762. package/dist/services/service-manager/macos.d.ts.map +0 -1
  763. package/dist/services/service-manager/macos.js.map +0 -1
  764. package/dist/services/service-manager/types.d.ts.map +0 -1
  765. package/dist/services/service-manager/types.js.map +0 -1
  766. package/dist/services/service-manager/windows.d.ts.map +0 -1
  767. package/dist/services/service-manager/windows.js.map +0 -1
  768. package/dist/services/session-registry.d.ts.map +0 -1
  769. package/dist/services/session-registry.js.map +0 -1
  770. package/dist/services/sftp.d.ts.map +0 -1
  771. package/dist/services/sftp.js.map +0 -1
  772. package/dist/services/shell-probe.d.ts.map +0 -1
  773. package/dist/services/shell-probe.js.map +0 -1
  774. package/dist/services/singleton.d.ts.map +0 -1
  775. package/dist/services/singleton.js.map +0 -1
  776. package/dist/services/sprint-coordination.d.ts.map +0 -1
  777. package/dist/services/sprint-coordination.js.map +0 -1
  778. package/dist/services/ssh.d.ts.map +0 -1
  779. package/dist/services/ssh.js.map +0 -1
  780. package/dist/services/stall/find-log-file.d.ts.map +0 -1
  781. package/dist/services/stall/find-log-file.js.map +0 -1
  782. package/dist/services/stall/index.d.ts.map +0 -1
  783. package/dist/services/stall/index.js.map +0 -1
  784. package/dist/services/stall/log-path-resolver.d.ts.map +0 -1
  785. package/dist/services/stall/log-path-resolver.js.map +0 -1
  786. package/dist/services/stall/read-log-tail.d.ts.map +0 -1
  787. package/dist/services/stall/read-log-tail.js.map +0 -1
  788. package/dist/services/stall/stall-detector.d.ts.map +0 -1
  789. package/dist/services/stall/stall-detector.js.map +0 -1
  790. package/dist/services/stall/stall-poller.d.ts.map +0 -1
  791. package/dist/services/stall/stall-poller.js.map +0 -1
  792. package/dist/services/stall/time-utils.d.ts.map +0 -1
  793. package/dist/services/stall/time-utils.js.map +0 -1
  794. package/dist/services/statusline.d.ts.map +0 -1
  795. package/dist/services/statusline.js.map +0 -1
  796. package/dist/services/strategy.d.ts.map +0 -1
  797. package/dist/services/strategy.js.map +0 -1
  798. package/dist/services/substitution-engine.d.ts.map +0 -1
  799. package/dist/services/substitution-engine.js.map +0 -1
  800. package/dist/services/task-cleanup.d.ts.map +0 -1
  801. package/dist/services/task-cleanup.js.map +0 -1
  802. package/dist/services/token-issuer.d.ts.map +0 -1
  803. package/dist/services/token-issuer.js.map +0 -1
  804. package/dist/services/tool-registry.d.ts.map +0 -1
  805. package/dist/services/tool-registry.js.map +0 -1
  806. package/dist/services/update-check.d.ts.map +0 -1
  807. package/dist/services/update-check.js.map +0 -1
  808. package/dist/services/user-config.d.ts.map +0 -1
  809. package/dist/services/user-config.js.map +0 -1
  810. package/dist/services/vcs/azure-devops.d.ts.map +0 -1
  811. package/dist/services/vcs/azure-devops.js.map +0 -1
  812. package/dist/services/vcs/bitbucket.d.ts.map +0 -1
  813. package/dist/services/vcs/bitbucket.js.map +0 -1
  814. package/dist/services/vcs/constants.d.ts.map +0 -1
  815. package/dist/services/vcs/constants.js.map +0 -1
  816. package/dist/services/vcs/github.d.ts.map +0 -1
  817. package/dist/services/vcs/github.js.map +0 -1
  818. package/dist/services/vcs/types.d.ts.map +0 -1
  819. package/dist/services/vcs/types.js.map +0 -1
  820. package/dist/services/version-check.d.ts.map +0 -1
  821. package/dist/services/version-check.js.map +0 -1
  822. package/dist/services/watch/fleet-log.d.ts.map +0 -1
  823. package/dist/services/watch/fleet-log.js.map +0 -1
  824. package/dist/services/watch/project-resolver.d.ts.map +0 -1
  825. package/dist/services/watch/project-resolver.js.map +0 -1
  826. package/dist/services/watch/transcript-formatter.d.ts.map +0 -1
  827. package/dist/services/watch/transcript-formatter.js.map +0 -1
  828. package/dist/smoke-test.d.ts.map +0 -1
  829. package/dist/smoke-test.js.map +0 -1
  830. package/dist/tools/check-status.d.ts.map +0 -1
  831. package/dist/tools/check-status.js.map +0 -1
  832. package/dist/tools/child-id-allocator.d.ts.map +0 -1
  833. package/dist/tools/child-id-allocator.js.map +0 -1
  834. package/dist/tools/cloud-control.d.ts.map +0 -1
  835. package/dist/tools/cloud-control.js.map +0 -1
  836. package/dist/tools/code-intelligence-codebase-memory.d.ts.map +0 -1
  837. package/dist/tools/code-intelligence-codebase-memory.js.map +0 -1
  838. package/dist/tools/code-intelligence-freshness.d.ts.map +0 -1
  839. package/dist/tools/code-intelligence-freshness.js.map +0 -1
  840. package/dist/tools/code-intelligence-gitnexus.d.ts.map +0 -1
  841. package/dist/tools/code-intelligence-gitnexus.js.map +0 -1
  842. package/dist/tools/code-intelligence-kb-enrich.d.ts.map +0 -1
  843. package/dist/tools/code-intelligence-kb-enrich.js.map +0 -1
  844. package/dist/tools/code-intelligence-reindex.d.ts.map +0 -1
  845. package/dist/tools/code-intelligence-reindex.js.map +0 -1
  846. package/dist/tools/code-intelligence-telemetry.d.ts.map +0 -1
  847. package/dist/tools/code-intelligence-telemetry.js.map +0 -1
  848. package/dist/tools/code-intelligence-tests.d.ts.map +0 -1
  849. package/dist/tools/code-intelligence-tests.js.map +0 -1
  850. package/dist/tools/code-intelligence.d.ts.map +0 -1
  851. package/dist/tools/code-intelligence.js.map +0 -1
  852. package/dist/tools/compose-permissions.d.ts.map +0 -1
  853. package/dist/tools/compose-permissions.js.map +0 -1
  854. package/dist/tools/credential-store-delete.d.ts.map +0 -1
  855. package/dist/tools/credential-store-delete.js.map +0 -1
  856. package/dist/tools/credential-store-list.d.ts.map +0 -1
  857. package/dist/tools/credential-store-list.js.map +0 -1
  858. package/dist/tools/credential-store-set.d.ts.map +0 -1
  859. package/dist/tools/credential-store-set.js.map +0 -1
  860. package/dist/tools/credential-store-update.d.ts.map +0 -1
  861. package/dist/tools/credential-store-update.js.map +0 -1
  862. package/dist/tools/dolt-push-mutex.d.ts.map +0 -1
  863. package/dist/tools/dolt-push-mutex.js.map +0 -1
  864. package/dist/tools/execute-command.d.ts.map +0 -1
  865. package/dist/tools/execute-command.js.map +0 -1
  866. package/dist/tools/execute-prompt.d.ts.map +0 -1
  867. package/dist/tools/execute-prompt.js.map +0 -1
  868. package/dist/tools/get-member-model-pricing.d.ts.map +0 -1
  869. package/dist/tools/get-member-model-pricing.js.map +0 -1
  870. package/dist/tools/kb-capture.d.ts.map +0 -1
  871. package/dist/tools/kb-capture.js.map +0 -1
  872. package/dist/tools/kb-context.d.ts.map +0 -1
  873. package/dist/tools/kb-context.js.map +0 -1
  874. package/dist/tools/kb-export.d.ts.map +0 -1
  875. package/dist/tools/kb-export.js.map +0 -1
  876. package/dist/tools/kb-feedback.d.ts.map +0 -1
  877. package/dist/tools/kb-feedback.js.map +0 -1
  878. package/dist/tools/kb-freshness-sweep.d.ts.map +0 -1
  879. package/dist/tools/kb-freshness-sweep.js.map +0 -1
  880. package/dist/tools/kb-harvest.d.ts.map +0 -1
  881. package/dist/tools/kb-harvest.js.map +0 -1
  882. package/dist/tools/kb-import.d.ts.map +0 -1
  883. package/dist/tools/kb-import.js.map +0 -1
  884. package/dist/tools/kb-invalidate.d.ts.map +0 -1
  885. package/dist/tools/kb-invalidate.js.map +0 -1
  886. package/dist/tools/kb-list.d.ts.map +0 -1
  887. package/dist/tools/kb-list.js.map +0 -1
  888. package/dist/tools/kb-promote.d.ts.map +0 -1
  889. package/dist/tools/kb-promote.js.map +0 -1
  890. package/dist/tools/kb-query.d.ts.map +0 -1
  891. package/dist/tools/kb-query.js.map +0 -1
  892. package/dist/tools/kb-reconcile-prefilter.d.ts.map +0 -1
  893. package/dist/tools/kb-reconcile-prefilter.js.map +0 -1
  894. package/dist/tools/kb-resolve-contradiction.d.ts.map +0 -1
  895. package/dist/tools/kb-resolve-contradiction.js.map +0 -1
  896. package/dist/tools/kb-session-prime.d.ts.map +0 -1
  897. package/dist/tools/kb-session-prime.js.map +0 -1
  898. package/dist/tools/kb-setup.d.ts.map +0 -1
  899. package/dist/tools/kb-setup.js.map +0 -1
  900. package/dist/tools/kb-stats.d.ts.map +0 -1
  901. package/dist/tools/kb-stats.js.map +0 -1
  902. package/dist/tools/list-members.d.ts.map +0 -1
  903. package/dist/tools/list-members.js.map +0 -1
  904. package/dist/tools/member-detail.d.ts.map +0 -1
  905. package/dist/tools/member-detail.js.map +0 -1
  906. package/dist/tools/member-reservation.d.ts.map +0 -1
  907. package/dist/tools/member-reservation.js.map +0 -1
  908. package/dist/tools/monitor-task.d.ts.map +0 -1
  909. package/dist/tools/monitor-task.js.map +0 -1
  910. package/dist/tools/provision-auth.d.ts.map +0 -1
  911. package/dist/tools/provision-auth.js.map +0 -1
  912. package/dist/tools/provision-vcs-auth.d.ts.map +0 -1
  913. package/dist/tools/provision-vcs-auth.js.map +0 -1
  914. package/dist/tools/receive-files.d.ts.map +0 -1
  915. package/dist/tools/receive-files.js.map +0 -1
  916. package/dist/tools/register-member.d.ts.map +0 -1
  917. package/dist/tools/register-member.js.map +0 -1
  918. package/dist/tools/remove-member.d.ts.map +0 -1
  919. package/dist/tools/remove-member.js.map +0 -1
  920. package/dist/tools/report-status.d.ts.map +0 -1
  921. package/dist/tools/report-status.js.map +0 -1
  922. package/dist/tools/respond-to-message.d.ts.map +0 -1
  923. package/dist/tools/respond-to-message.js.map +0 -1
  924. package/dist/tools/revoke-vcs-auth.d.ts.map +0 -1
  925. package/dist/tools/revoke-vcs-auth.js.map +0 -1
  926. package/dist/tools/send-email.d.ts.map +0 -1
  927. package/dist/tools/send-email.js.map +0 -1
  928. package/dist/tools/send-files.d.ts.map +0 -1
  929. package/dist/tools/send-files.js.map +0 -1
  930. package/dist/tools/send-message.d.ts.map +0 -1
  931. package/dist/tools/send-message.js.map +0 -1
  932. package/dist/tools/setup-git-app.d.ts.map +0 -1
  933. package/dist/tools/setup-git-app.js.map +0 -1
  934. package/dist/tools/setup-ssh-key.d.ts.map +0 -1
  935. package/dist/tools/setup-ssh-key.js.map +0 -1
  936. package/dist/tools/shutdown-server.d.ts.map +0 -1
  937. package/dist/tools/shutdown-server.js.map +0 -1
  938. package/dist/tools/stop-prompt.d.ts.map +0 -1
  939. package/dist/tools/stop-prompt.js.map +0 -1
  940. package/dist/tools/update-agent-cli.d.ts.map +0 -1
  941. package/dist/tools/update-agent-cli.js.map +0 -1
  942. package/dist/tools/update-member.d.ts.map +0 -1
  943. package/dist/tools/update-member.js.map +0 -1
  944. package/dist/tools/version.d.ts.map +0 -1
  945. package/dist/tools/version.js.map +0 -1
  946. package/dist/types.d.ts.map +0 -1
  947. package/dist/types.js.map +0 -1
  948. package/dist/utils/agent-helpers.d.ts.map +0 -1
  949. package/dist/utils/agent-helpers.js.map +0 -1
  950. package/dist/utils/ansi.d.ts.map +0 -1
  951. package/dist/utils/ansi.js.map +0 -1
  952. package/dist/utils/auth-env.d.ts.map +0 -1
  953. package/dist/utils/auth-env.js.map +0 -1
  954. package/dist/utils/collect-secret.d.ts.map +0 -1
  955. package/dist/utils/collect-secret.js.map +0 -1
  956. package/dist/utils/credential-validation.d.ts.map +0 -1
  957. package/dist/utils/credential-validation.js.map +0 -1
  958. package/dist/utils/crypto.d.ts.map +0 -1
  959. package/dist/utils/crypto.js.map +0 -1
  960. package/dist/utils/deep-merge.d.ts.map +0 -1
  961. package/dist/utils/deep-merge.js.map +0 -1
  962. package/dist/utils/file-permissions.d.ts.map +0 -1
  963. package/dist/utils/file-permissions.js.map +0 -1
  964. package/dist/utils/gpu-parser.d.ts.map +0 -1
  965. package/dist/utils/gpu-parser.js.map +0 -1
  966. package/dist/utils/log-helpers.d.ts.map +0 -1
  967. package/dist/utils/log-helpers.js.map +0 -1
  968. package/dist/utils/oob-timeout.d.ts.map +0 -1
  969. package/dist/utils/oob-timeout.js.map +0 -1
  970. package/dist/utils/opencode-model-validation.d.ts.map +0 -1
  971. package/dist/utils/opencode-model-validation.js.map +0 -1
  972. package/dist/utils/pid-helpers.d.ts.map +0 -1
  973. package/dist/utils/pid-helpers.js.map +0 -1
  974. package/dist/utils/platform.d.ts.map +0 -1
  975. package/dist/utils/platform.js.map +0 -1
  976. package/dist/utils/process-utils.d.ts.map +0 -1
  977. package/dist/utils/process-utils.js.map +0 -1
  978. package/dist/utils/prompt-errors.d.ts.map +0 -1
  979. package/dist/utils/prompt-errors.js.map +0 -1
  980. package/dist/utils/resolve-member.d.ts.map +0 -1
  981. package/dist/utils/resolve-member.js.map +0 -1
  982. package/dist/utils/secure-input.d.ts.map +0 -1
  983. package/dist/utils/secure-input.js.map +0 -1
  984. package/dist/utils/session-caller.d.ts.map +0 -1
  985. package/dist/utils/session-caller.js.map +0 -1
  986. package/dist/utils/shell-escape.d.ts.map +0 -1
  987. package/dist/utils/shell-escape.js.map +0 -1
  988. package/dist/utils/skill-matrix.d.ts.map +0 -1
  989. package/dist/utils/skill-matrix.js.map +0 -1
  990. package/dist/utils/ssh-error-messages.d.ts.map +0 -1
  991. package/dist/utils/ssh-error-messages.js.map +0 -1
  992. package/dist/utils/work-folder-validation.d.ts.map +0 -1
  993. package/dist/utils/work-folder-validation.js.map +0 -1
  994. package/dist/utils/workspace-trust.d.ts.map +0 -1
  995. package/dist/utils/workspace-trust.js.map +0 -1
  996. package/dist/version.d.ts.map +0 -1
  997. package/dist/version.js.map +0 -1
@@ -0,0 +1,1445 @@
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, buildFindPrCommand, buildUpdatePrCommand, 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 backlogMember 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
+ export 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
+ // EXISTING-PR UPDATE (optional `updateExisting`). A sprint relaunched on a
663
+ // branch that already has a PR must not leave the old run's verdict in the
664
+ // title/body. When the caller passes `updateExisting(old) -> { title, body }`
665
+ // and creation reports already-exists, this finds the open PR for
666
+ // head -> base (provider 'find-pull-request' builder -- the create response
667
+ // carries neither the PR id nor its current body), hands the old title/body
668
+ // to `updateExisting`, and PATCHes the result ('update-pull-request'
669
+ // builder), with the same placeholder handoff, body cap and one-shot auth
670
+ // self-heal as creation. It never throws: any failure (including a provider
671
+ // with no such builder) comes back as `updated: false` + `updateError` for
672
+ // the caller to log as a WARNING, leaving the PR as it was. Without
673
+ // `updateExisting` the returned shape is exactly the historical one.
674
+ /**
675
+ * @param {{ fleetApi: object, command: Function, member: string, base: string, head: string, title: string, body?: string, log?: Function, logPrefix: string, updateExisting?: Function }} opts
676
+ * @returns {Promise<{ ok: boolean, alreadyExists: boolean, prUrl: string|null, error: string|null, authFailure: boolean, updated?: boolean, updateError?: string|null }>}
677
+ */
678
+ export async function raiseVcsPrForMember({ fleetApi, command, member, base, head, title, body, log = () => {}, logPrefix, remoteUrlOverride, updateExisting }) {
679
+ let repo;
680
+ try {
681
+ ({ repo } = await provisionPrCapableAuthForMember({ fleetApi, command, member, log, logPrefix, remoteUrlOverride }));
682
+ } catch (provisionErr) {
683
+ // apra-fleet-5co8.15: provisionPrCapableAuthForMember has no failSoft
684
+ // of its own (by design -- see its doc comment above), so a
685
+ // provisioning failure that happens BEFORE any PR-creation attempt
686
+ // (e.g. a missing Azure DevOps PAT credential-store entry) used to
687
+ // escape here as the raw provision_vcs_auth failure text and abort
688
+ // the whole sprint. Degrade it the same way the reactive
689
+ // auth-self-heal retry below already degrades a mid-retry failure:
690
+ // log the provider's own authRemedy hint (never a wording duplicated
691
+ // here) and return authFailure:true instead of throwing, so a caller
692
+ // (Publish PR, finalizeAbort) can report clean, actionable guidance
693
+ // and keep going rather than aborting on this condition.
694
+ let remedyHint = null;
695
+ try {
696
+ const { provider } = await resolveProvider(member, { fleetApi });
697
+ const impl = getVcsProvider(provider);
698
+ if (impl && impl.authRemedy && impl.authRemedy.hint) remedyHint = impl.authRemedy.hint;
699
+ } catch (resolveErr) {
700
+ 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}`);
701
+ }
702
+ // The provider's remedy text is generic ("PATs cannot be re-minted
703
+ // server-side ..."); on its own it hid WHY provisioning failed --
704
+ // an unreadable remote, a missing credential-store entry and a dead
705
+ // PAT all printed the same paragraph. Keep the hint, but lead with
706
+ // the actual cause so the operator fixes the right thing.
707
+ const message = remedyHint
708
+ ? `Could not provision a push+pr credential for member '${member}': ${provisionErr.message} -- ${remedyHint}`
709
+ : provisionErr.message;
710
+ log(`${logPrefix}: PR-capable credential provisioning failed for member '${member}'; degrading (not throwing): ${message}`);
711
+ return { ok: false, alreadyExists: false, prUrl: null, error: message, authFailure: true };
712
+ }
713
+ if (!repo) {
714
+ const remoteSource = remoteUrlOverride ? 'the supplied remote URL' : `member '${member}' git remote`;
715
+ throw new Error(`Could not derive an owner/repo from ${remoteSource} -- cannot build a VCSModule create-pull-request command without one.`);
716
+ }
717
+ // apra-fleet-lzfv.5: resolve the member's OWN registered VCS provider
718
+ // (VCSModule.resolveProvider(), never a hardcoded 'github' literal --
719
+ // same rule provisionVcsAuthForMember already follows) so
720
+ // buildCreatePrCommand dispatches to the right REST dialect for a
721
+ // dev.azure.com (or any other) remote, not just GitHub.
722
+ //
723
+ // Resolved BEFORE the handoff below because the credential is keyed
724
+ // by provider too: provision_vcs_auth deploys the credential helper
725
+ // under `label = input.label ?? input.provider`
726
+ // (src/tools/provision-vcs-auth.ts), and neither the shared
727
+ // GitHub-App-shaped arguments nor a provider's buildProvisionArgs hook
728
+ // sends an explicit label -- so the credential the handoff must read is
729
+ // the one under $HOME/.fleet-git-credential-<provider>. Passing the
730
+ // 'github' label unconditionally (the pre-fix default this path once
731
+ // carried, back when it read the token itself) made every Azure DevOps
732
+ // member's PR raise fail with "Failed to read VCS credential token ...
733
+ // from '$HOME/.fleet-git-credential-github'" (or, worse, silently reuse a
734
+ // stale GitHub token left over from an earlier provider and send it to
735
+ // dev.azure.com). `credentialLabel` is threaded into every
736
+ // vcsCredentialExec() call below for exactly that reason.
737
+ const { provider } = await resolveProvider(member, { fleetApi });
738
+ const credentialLabel = vcsCredentialLabelForProvider(provider);
739
+
740
+ // apra-fleet-3swo.7.6: the orchestrator never learns the token at all now.
741
+ // It passes the INLINE placeholder as the `token` parameter, so each
742
+ // provider's builder emits its existing shQuote()'d shape with the
743
+ // placeholder sitting inside its OWN quotes (github.mjs still emits
744
+ // -H 'Authorization: Bearer {{vcs_token_inline}}', azure-devops.mjs still
745
+ // emits -u ':{{vcs_token_inline}}' -- the authentication MECHANISM is
746
+ // unchanged, only the substituted word), and the SERVER substitutes it
747
+ // during the vcs_credential_exec dispatch below, escaped for the interior
748
+ // of those quotes with no quotes of its own (VCS_TOKEN_INLINE_PLACEHOLDER,
749
+ // src/tools/vcs-credential-exec.ts). Deliberately inlined here rather than
750
+ // hoisted to a module constant: the facade suite enumerates this module's
751
+ // top-level declarations symbol-for-symbol and a new const desyncs that
752
+ // census.
753
+ const token = '{{vcs_token_inline}}';
754
+ // Both os AND shell feed the command builder: os picks the curl binary
755
+ // token (curl.exe vs curl), shell picks the quoting dialect. A Windows
756
+ // member whose registered shell is gitbash needs POSIX quoting, not
757
+ // PowerShell doubled-quote escaping -- resolving only the OS here fed
758
+ // shell-less params to shQuote and corrupted the curl -d JSON payload
759
+ // (observed live: GitHub 400 "Problems parsing JSON" on the create-PR
760
+ // endpoint for a windows+gitbash member).
761
+ const { os, shell } = await resolveMemberTarget({ fleetApi, member, log });
762
+
763
+ // The provider's own coordinate shape (e.g. Azure DevOps' org/project/repo
764
+ // -- see VCSModule.parseProviderRepoRef()/that provider's parseRepoRef
765
+ // hook) when one exists; null for a provider with no such hook (GitHub),
766
+ // which keeps using the two-part `repo` string above unchanged. Only ONE
767
+ // of `repo`/`repoRef` is ever sent below: passing both would let the
768
+ // (possibly provider-specific, e.g. 3-part) canonical `repo` string
769
+ // silently override repoRef's own coordinates and mis-encode the request
770
+ // URL (see azure-devops.mjs's assertRepoCoords doc comment). Both real
771
+ // call sites (Publish PR, [ABORTED] PR) already resolve and pass
772
+ // `remoteUrlOverride` themselves (see their own comments), so this never
773
+ // needs a git-remote read of its own; a caller that omits it simply gets
774
+ // no repoRef (falls back to `repo`, unchanged from before this task).
775
+ const providerRef = remoteUrlOverride ? parseProviderRepoRef(remoteUrlOverride) : null;
776
+ if (providerRef && providerRef.error) {
777
+ throw new Error(providerRef.error);
778
+ }
779
+ const repoRef = providerRef ? providerRef.ref : null;
780
+
781
+ // One REST round trip for the existing-PR update path (see the header
782
+ // note): placeholder handoff, 2xx check, one-shot auth self-heal. Returns
783
+ // { ok, built, body } or { ok: false, error } -- never throws on an HTTP
784
+ // or handoff failure.
785
+ const runUpdatePathCall = async (buildFn, what) => {
786
+ let healed = false;
787
+ // eslint-disable-next-line no-constant-condition
788
+ while (true) {
789
+ const b = buildFn();
790
+ const res = await fleetApi.vcsCredentialExec({ member_name: member, label: credentialLabel, command: b.command });
791
+ const h = (res && res.structuredContent) || {};
792
+ if (!h.ok || (typeof h.exitCode === 'number' && h.exitCode !== 0)) {
793
+ return { ok: false, error: `${what} dispatch failed (${h.reason || 'nonzero exit'}): ${h.stderr || resultText(res) || '(no detail)'}` };
794
+ }
795
+ const parsed = parseVcsCurlOutput(h.stdout);
796
+ const [lo, hi] = b.interpret.successStatusRange;
797
+ if (parsed.status !== null && parsed.status >= lo && parsed.status <= hi) return { ok: true, built: b, body: parsed.body };
798
+ const msg = (parsed.body && typeof parsed.body.message === 'string') ? parsed.body.message : (parsed.bodyText || '');
799
+ if (isPrAuthFailure(parsed.status, msg) && !healed) {
800
+ healed = true;
801
+ log(`${logPrefix}: ${what} returned an auth-classified failure (HTTP ${parsed.status ?? '(unknown)'}) for member '${member}'; re-provisioning a push+pr credential and retrying once (command: ${b.logSafeCommand}): ${msg}`);
802
+ try {
803
+ const reprov = await provisionPrCapableAuthForMember({ fleetApi, command, member, log, logPrefix, remoteUrlOverride });
804
+ if (reprov.repo) repo = reprov.repo;
805
+ } catch (healErr) {
806
+ return { ok: false, error: `${what} auth self-heal failed: ${healErr.message}` };
807
+ }
808
+ continue;
809
+ }
810
+ return { ok: false, error: `${what} failed: HTTP ${parsed.status ?? '(unknown)'}: ${msg}` };
811
+ }
812
+ };
813
+ const updateExistingPr = async () => {
814
+ try {
815
+ const coords = () => ({ provider, ...(repoRef ? { repoRef } : { repo }), token, os, shell });
816
+ const found = await runUpdatePathCall(() => buildFindPrCommand({ ...coords(), base, head }), 'find-pull-request');
817
+ if (!found.ok) return { updated: false, updateError: found.error, prUrl: null };
818
+ const prs = found.built.mapResponse(found.body);
819
+ if (!prs.length) {
820
+ return { updated: false, updateError: `no open pull request found for '${head}' -> '${base}'`, prUrl: null };
821
+ }
822
+ const pr = prs[0];
823
+ const next = updateExisting({ title: pr.title, body: pr.body }) || {};
824
+ let warned = false;
825
+ const upd = await runUpdatePathCall(() => {
826
+ const b = buildUpdatePrCommand({
827
+ ...coords(),
828
+ pull_request_id: pr.id,
829
+ title: next.title || title,
830
+ body: next.body !== undefined ? next.body : body,
831
+ });
832
+ if (b.descriptionTruncated && !warned) {
833
+ warned = true;
834
+ log(`${logPrefix}: WARNING: updated PR description for member '${member}' was ${b.descriptionTruncated.originalLength} chars, exceeding the ${b.descriptionTruncated.maxLength}-char limit; truncated.`);
835
+ }
836
+ return b;
837
+ }, 'update-pull-request');
838
+ if (!upd.ok) return { updated: false, updateError: upd.error, prUrl: pr.url };
839
+ return { updated: true, updateError: null, prUrl: pr.url };
840
+ } catch (err) {
841
+ return { updated: false, updateError: (err && err.message) ? err.message : String(err), prUrl: null };
842
+ }
843
+ };
844
+
845
+ let authHealAttempted = false;
846
+ // apra-fleet PR-body length fix: buildCreatePrCommand deterministically
847
+ // truncates `body` to PR_DESCRIPTION_MAX_LENGTH and reports it back via
848
+ // `descriptionTruncated` (see vcs-module.mjs -- that module stays pure/
849
+ // I/O-free, so the warning is logged here). Guarded so a retry of the
850
+ // SAME (already-truncated) body after an auth self-heal never re-logs it.
851
+ let truncationWarned = false;
852
+ // eslint-disable-next-line no-constant-condition
853
+ while (true) {
854
+ const built = buildCreatePrCommand({
855
+ provider,
856
+ ...(repoRef ? { repoRef } : { repo }),
857
+ base, head, title, body, token, os, shell,
858
+ });
859
+
860
+ if (built.descriptionTruncated && !truncationWarned) {
861
+ truncationWarned = true;
862
+ const { originalLength, maxLength } = built.descriptionTruncated;
863
+ 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.`);
864
+ }
865
+
866
+ // The server-side credential handoff, NOT command(): the placeholder
867
+ // built into `built.command` above is substituted INSIDE the server,
868
+ // the substituted command is dispatched from there, and the credential
869
+ // is redacted out of the stdout/stderr this process reads back. No
870
+ // plaintext token ever transits the orchestrator, so there is nothing
871
+ // here for a captured result, a log line or a written file to leak.
872
+ if (!fleetApi || typeof fleetApi.vcsCredentialExec !== 'function') {
873
+ throw new Error(
874
+ `Cannot raise a PR for member '${member}': this fleet client exposes no vcs_credential_exec tool, `
875
+ + 'and the orchestrator no longer reads VCS credential tokens itself. Upgrade the fleet server/client '
876
+ + 'to a version that provides the vcs_credential_exec tool.',
877
+ );
878
+ }
879
+ const execRes = await fleetApi.vcsCredentialExec({
880
+ member_name: member,
881
+ label: credentialLabel,
882
+ command: built.command,
883
+ });
884
+ const handoff = (execRes && execRes.structuredContent) || {};
885
+ const handoffText = resultText(execRes);
886
+ // A credential-side failure HARD-FAILS, exactly as reading the token
887
+ // ourselves used to throw -- never an advisory warning that lets the
888
+ // sprint carry on with no credential. 'dispatch_failed' is the one
889
+ // non-ok reason that is a COMMAND failure rather than a credential
890
+ // failure, so it degrades the same way a failed command() dispatch
891
+ // did: returned, not thrown.
892
+ if (!handoff.ok && handoff.reason !== 'dispatch_failed') {
893
+ throw new Error(
894
+ `Failed to read VCS credential token for member '${member}' from the `
895
+ + `'${credentialLabel}'-labelled credential helper via vcs_credential_exec `
896
+ + `(reason: ${handoff.reason || '(none)'}): ${handoffText || '(no detail)'}`,
897
+ );
898
+ }
899
+ if (!handoff.ok || (typeof handoff.exitCode === 'number' && handoff.exitCode !== 0)) {
900
+ const failText = handoff.stderr || handoffText || 'vcs_credential_exec failed';
901
+ return { ok: false, alreadyExists: false, prUrl: null, error: failText, authFailure: false };
902
+ }
903
+
904
+ const { status, body: respBody, bodyText } = parseVcsCurlOutput(handoff.stdout);
905
+ const [lo, hi] = built.interpret.successStatusRange;
906
+ if (status !== null && status >= lo && status <= hi) {
907
+ // apra-fleet-lzfv.5: read the created PR's id/url through the
908
+ // provider's OWN pullRequestResponse.map hook (declared on its
909
+ // descriptor -- see vcs-providers/github.mjs and
910
+ // vcs-providers/azure-devops.mjs) instead of a GitHub-dialect
911
+ // `html_url` field literal here. A provider with no mapping
912
+ // (should not happen for an auth-backend provider, but never
913
+ // throws) yields prUrl: null rather than crashing on an
914
+ // otherwise-successful PR.
915
+ const impl = getVcsProvider(provider);
916
+ const mapped = (impl && impl.pullRequestResponse && typeof impl.pullRequestResponse.map === 'function')
917
+ ? impl.pullRequestResponse.map(respBody, repoRef ? { repoRef } : { repo })
918
+ : { id: null, url: null };
919
+ return { ok: true, alreadyExists: false, prUrl: mapped.url, error: null, authFailure: false };
920
+ }
921
+
922
+ const errorMessages = [];
923
+ if (respBody && typeof respBody.message === 'string') errorMessages.push(respBody.message);
924
+ if (respBody && Array.isArray(respBody.errors)) {
925
+ for (const e of respBody.errors) {
926
+ if (e && typeof e.message === 'string') errorMessages.push(e.message);
927
+ }
928
+ }
929
+ const errorText = errorMessages.join('; ') || bodyText || `HTTP ${status ?? '(unknown)'}`;
930
+
931
+ if (status === built.interpret.alreadyExistsStatus && new RegExp(built.interpret.alreadyExistsPattern, 'i').test(errorText)) {
932
+ const urlMatch = /https?:\/\/\S+/.exec(errorText);
933
+ const existingUrl = urlMatch ? urlMatch[0].replace(/[.,)]+$/, '') : null;
934
+ const existing = { ok: true, alreadyExists: true, prUrl: existingUrl, error: null, authFailure: false };
935
+ if (typeof updateExisting !== 'function') return existing;
936
+ const upd = await updateExistingPr();
937
+ return { ...existing, prUrl: upd.prUrl || existingUrl, updated: upd.updated, updateError: upd.updateError };
938
+ }
939
+
940
+ if (isPrAuthFailure(status, errorText) && !authHealAttempted) {
941
+ authHealAttempted = true;
942
+ 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}`);
943
+ try {
944
+ const reprov = await provisionPrCapableAuthForMember({ fleetApi, command, member, log, logPrefix, remoteUrlOverride });
945
+ if (reprov.repo) repo = reprov.repo;
946
+ // No token re-read here any more: `built.command` still
947
+ // carries the placeholder, so the retry's own
948
+ // vcs_credential_exec dispatch re-reads the FRESHLY
949
+ // re-provisioned credential server-side, once per call. The
950
+ // bounded one-shot retry semantics are unchanged.
951
+ } catch (healErr) {
952
+ log(`${logPrefix}: PR auth self-heal failed for member '${member}'; not retrying further: ${healErr.message}`);
953
+ return { ok: false, alreadyExists: false, prUrl: null, error: `HTTP ${status ?? '(unknown)'}: ${errorText}`, authFailure: true };
954
+ }
955
+ log(`${logPrefix}: PR auth self-heal completed for member '${member}'; retrying PR creation once.`);
956
+ continue;
957
+ }
958
+
959
+ return { ok: false, alreadyExists: false, prUrl: null, error: `HTTP ${status ?? '(unknown)'}: ${errorText}`, authFailure: isPrAuthFailure(status, errorText) };
960
+ }
961
+ }
962
+
963
+ /**
964
+ * apra-fleet-417.7: builds the `resolveMemberProvider(member)` callback
965
+ * threaded through syncMemberBefore/syncMemberAfter/finalizeAbort into
966
+ * runGitStep, so classifyGitFailure() classifies a git failure via the
967
+ * member's OWN resolved VCS provider chain (VCSModule.resolveProvider())
968
+ * instead of always falling back to the default 'github' chain -- this is
969
+ * what makes azure-devops.mjs's TF401019 -> AUTH_DENIED and bitbucket.mjs's
970
+ * app-password -> AUTH_EXPIRED rules reachable at runtime, not just from a
971
+ * caller that names the provider directly against classifyFailure().
972
+ *
973
+ * The resolution is cached per member for the lifetime of the returned
974
+ * callback (a member's registered VCS provider does not change mid-sprint),
975
+ * so a member whose provider fails to resolve (fleet unreachable, no
976
+ * registered provider) is not re-queried on every subsequent git failure --
977
+ * it fails closed to `undefined` (today's default chain) exactly once per
978
+ * member, then reuses that cached `undefined`.
979
+ *
980
+ * `callTool` is injected (the caller's MCP client), so this stays
981
+ * transport-agnostic and unit-testable without a live fleet server.
982
+ *
983
+ * @param {{ callTool: (name: string, args: object) => Promise<any>, log?: Function }} opts
984
+ * @returns {(member: string) => Promise<string|undefined>}
985
+ */
986
+ export function createMemberVcsProviderResolver(opts = {}) {
987
+ const { callTool, log = () => {} } = opts;
988
+ const fleetApi = new ApraFleet({ callTool });
989
+ /** @type {Map<string, string|undefined>} member -> resolved provider (or undefined if unresolvable). */
990
+ const cache = new Map();
991
+
992
+ return async function resolveMemberProvider(member) {
993
+ if (cache.has(member)) return cache.get(member);
994
+ try {
995
+ const { provider } = await resolveProvider(member, { fleetApi });
996
+ cache.set(member, provider);
997
+ return provider;
998
+ } catch (err) {
999
+ 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}`);
1000
+ cache.set(member, undefined);
1001
+ return undefined;
1002
+ }
1003
+ };
1004
+ }
1005
+
1006
+ /**
1007
+ * Builds the REACTIVE `onAuthFailure` self-heal callback runGitStep and
1008
+ * runDoltStep invoke on an 'auth' classification: re-provisions the failing
1009
+ * member's VCS credentials via provisionVcsAuthForMember (whose owner/repo is
1010
+ * derived from the member's own git remote, never hardcoded). Logs both the
1011
+ * attempt and its outcome, so a self-heal is never silent. Any failure
1012
+ * propagates as a thrown error, which is how runGitStep/runDoltStep recognize
1013
+ * "self-heal failed" and stop retrying.
1014
+ *
1015
+ * `callTool` is injected (the caller's MCP client), so this stays
1016
+ * transport-agnostic and unit-testable without a live fleet server.
1017
+ *
1018
+ * @param {{ callTool: (name: string, args: object) => Promise<any>, command: Function, log?: Function }} opts
1019
+ * @returns {((info: { member: string, label: string, cmd?: string, error: string, source?: 'git'|'dolt', failureKind?: string }) => Promise<void>) & { recordHealOutcome: (info: { member: string, label: string, error: string, recovered: boolean }) => Promise<void> }}
1020
+ */
1021
+ export function createVcsAuthSelfHealCallback(opts = {}) {
1022
+ const { callTool, command, log = () => {}, azdevopsPatSecretName, now = () => Date.now(), futileHealTtlMs = FUTILE_HEAL_TTL_MS } = opts;
1023
+ const fleetApi = new ApraFleet({ callTool });
1024
+ // GitHub #616: last-resort heals of UNCLASSIFIED failures that ran and did
1025
+ // NOT recover, keyed by member + normalised error, so the same futile
1026
+ // re-provisioning is not repeated on every D-pull. Only 'unknown' failures
1027
+ // are remembered -- a genuine auth failure is always healed -- and each
1028
+ // entry expires after futileHealTtlMs, so a later, different cause behind
1029
+ // the same text still gets a heal.
1030
+ /** @type {Map<string, { label: string, at: number }>} */
1031
+ const futileHeals = new Map();
1032
+
1033
+ function rememberedFutileHeal(key) {
1034
+ const entry = futileHeals.get(key);
1035
+ if (!entry) return null;
1036
+ if (now() - entry.at >= futileHealTtlMs) {
1037
+ futileHeals.delete(key);
1038
+ return null;
1039
+ }
1040
+ return entry;
1041
+ }
1042
+
1043
+ async function onAuthFailure({ member, label, error, source, failureKind }) {
1044
+ if (failureKind === 'unknown') {
1045
+ const entry = rememberedFutileHeal(selfHealMemoryKey(member, error));
1046
+ if (entry) {
1047
+ throw new Error(
1048
+ `skipping self-heal for member '${member}' (${label}): re-provisioning credentials already failed to recover ` +
1049
+ `this same unclassified failure earlier in this run (${entry.label}); fix the cause on the member instead.`,
1050
+ );
1051
+ }
1052
+ }
1053
+ const isAuth = failureKind === undefined || failureKind === 'auth';
1054
+ log(isAuth
1055
+ ? `[Sync] self-heal: auth failure detected for member '${member}' (${label}${source ? `, ${source}` : ''}); calling provision_vcs_auth to re-provision credentials: ${error}`
1056
+ : `[Sync] self-heal: unclassified failure for member '${member}' (${label}${source ? `, ${source}` : ''}); re-provisioning credentials as a last resort via provision_vcs_auth: ${error}`);
1057
+
1058
+ // apra-fleet-5co8.4.2: some providers (e.g. Azure DevOps PATs) can
1059
+ // never be fixed by this reactive re-provisioning call alone -- it
1060
+ // only redeploys the SAME stored secret, it never mints a new one.
1061
+ // Print that provider's own remedy hint via the generic
1062
+ // `authRemedy` descriptor field (no provider-name conditional here,
1063
+ // see vcs-providers/index.mjs) BEFORE attempting the self-heal below,
1064
+ // so the operator has the real remedy even if that attempt also
1065
+ // fails. A provider that declares no `authRemedy` (or
1066
+ // `serverSideReMintable: true`, e.g. GitHub's App-minted token) prints
1067
+ // nothing extra here -- unchanged from before this task.
1068
+ // apra-fleet-5co8.13: resolve the provider ONCE here and thread it into
1069
+ // provisionVcsAuthForMember below via `resolvedProvider`, so a single
1070
+ // self-heal attempt makes exactly one member_detail round trip instead
1071
+ // of two. A resolution failure here must NOT short-circuit the
1072
+ // self-heal attempt -- `resolved` simply stays undefined and
1073
+ // provisionVcsAuthForMember falls back to its own lookup.
1074
+ let resolved;
1075
+ try {
1076
+ resolved = await resolveProvider(member, { fleetApi });
1077
+ const { provider } = resolved;
1078
+ const impl = getVcsProvider(provider);
1079
+ if (impl && impl.authRemedy && impl.authRemedy.serverSideReMintable === false) {
1080
+ log(`[Sync] self-heal: member '${member}' (${label}) uses '${provider}', whose credentials cannot be re-minted server-side. ${impl.authRemedy.hint}`);
1081
+ }
1082
+ } catch (resolveErr) {
1083
+ 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}`);
1084
+ }
1085
+
1086
+ await provisionVcsAuthForMember({ fleetApi, command, member, log, logPrefix: '[Sync] self-heal', azdevopsPatSecretName, resolvedProvider: resolved });
1087
+
1088
+ log(`[Sync] self-heal: credentials re-provisioned for member '${member}' (${label}); the failed command will be retried once.`);
1089
+ }
1090
+
1091
+ /**
1092
+ * Called by runGitStep/runDoltStep after the post-heal retry; a heal that
1093
+ * did not recover is remembered so it is not attempted again this run.
1094
+ * @param {{ member: string, label: string, error: string, recovered: boolean, failureKind?: string }} info
1095
+ */
1096
+ onAuthFailure.recordHealOutcome = async function recordHealOutcome({ member, label, error, recovered, failureKind }) {
1097
+ if (recovered || failureKind !== 'unknown') return;
1098
+ futileHeals.set(selfHealMemoryKey(member, error), { label, at: now() });
1099
+ };
1100
+
1101
+ return onAuthFailure;
1102
+ }
1103
+
1104
+ /** How long a futile unclassified self-heal is remembered (30 minutes). */
1105
+ export const FUTILE_HEAL_TTL_MS = 30 * 60 * 1000;
1106
+
1107
+ /**
1108
+ * Key for remembering a futile self-heal: the member plus the failure's
1109
+ * DISTINGUISHING text. Warning/hint lines (shell-profile noise, git hints) are
1110
+ * dropped and the fatal/error lines kept (else the TAIL of what remains), so
1111
+ * two failures sharing a long common prefix never collapse into one key. The
1112
+ * run-varying parts (pids, counts, hex ids, whitespace runs) are normalised
1113
+ * away, but the number after "exit code"/"exit status" is kept, so distinct
1114
+ * exit codes stay distinct.
1115
+ * @param {string} member
1116
+ * @param {string} error
1117
+ * @returns {string}
1118
+ */
1119
+ export function selfHealMemoryKey(member, error) {
1120
+ const lines = String(error || '').split(/\r?\n/).map((l) => l.trim()).filter(Boolean)
1121
+ .filter((l) => !/^(?:remote:\s*)?(?:warning|hint)\b/i.test(l));
1122
+ const decisive = lines.filter((l) => /\b(?:fatal|error)\b/i.test(l));
1123
+ let text = (decisive.length > 0 ? decisive : lines).join(' ');
1124
+ text = text.replace(/(\bexit (?:code|status)\s*:?\s*)(\d+)|\b[0-9a-f]{7,}\b|\d+/gi,
1125
+ (m, prefix, code) => (prefix ? `${prefix}${code}` : (/^\d+$/.test(m) ? '<n>' : '<hex>')));
1126
+ text = text.toLowerCase().replace(/\s+/g, ' ').trim();
1127
+ if (text.length > 500) text = text.slice(-500);
1128
+ return `${member}|${text}`;
1129
+ }
1130
+
1131
+ // How far ahead of a credential's known expiry the preflight treats it as
1132
+ // "expiring soon" and re-provisions early, rather than letting it lapse
1133
+ // mid-dispatch. Mirrors the server's own EXPIRY_WARNING_MS threshold
1134
+ // (checkVcsTokenExpiry) so the two "about to expire?" judgments never
1135
+ // disagree.
1136
+ const VCS_AUTH_EXPIRY_PREFLIGHT_MS = 10 * 60 * 1000; // 10 minutes
1137
+
1138
+ /**
1139
+ * Proactive VCS-auth PREFLIGHT. Unlike createVcsAuthSelfHealCallback above,
1140
+ * which is REACTIVE (it fires only after a git/dolt command has already failed
1141
+ * with an 'auth' classification), this runs BEFORE a dispatch's git commands
1142
+ * and calls provision_vcs_auth only when this member's last-known credential
1143
+ * is missing, unknown, or expiring within VCS_AUTH_EXPIRY_PREFLIGHT_MS. It
1144
+ * closes the gap a reactive self-heal alone leaves: a credential that lapses
1145
+ * BETWEEN dispatches is refreshed before the next dispatch instead of after a
1146
+ * command fails.
1147
+ *
1148
+ * The freshness cache is scoped to the callback instance returned here, so
1149
+ * each member's first call always provisions (no cache entry yet) and later
1150
+ * calls are skipped until the cached expiry approaches. A response carrying no
1151
+ * expiry (PAT mode, which never expires) is cached as "known-good, never needs
1152
+ * refresh".
1153
+ *
1154
+ * NEVER throws: a preflight failure (fleet unreachable, provision_vcs_auth
1155
+ * itself failing) is logged and swallowed so it can never abort a dispatch
1156
+ * that would have succeeded on its still-valid existing credential. The
1157
+ * reactive self-heal remains the actual safety net if the credential is
1158
+ * genuinely stale.
1159
+ *
1160
+ * @param {{ callTool: (name: string, args: object) => Promise<any>, command: Function, log?: Function, now?: () => number }} opts
1161
+ * @returns {(member: string) => Promise<void>}
1162
+ */
1163
+ export function createVcsAuthPreflightCallback(opts = {}) {
1164
+ const { callTool, command, log = () => {}, now = () => Date.now(), azdevopsPatSecretName } = opts;
1165
+ const fleetApi = new ApraFleet({ callTool });
1166
+ /** @type {Map<string, Date|null>} member -> last-known expiresAt (null = no expiry tracked, e.g. PAT mode). */
1167
+ const knownGoodUntil = new Map();
1168
+
1169
+ return async function ensureVcsAuthFresh(member) {
1170
+ if (knownGoodUntil.has(member)) {
1171
+ const expiresAt = knownGoodUntil.get(member);
1172
+ if (expiresAt === null || expiresAt.getTime() - now() > VCS_AUTH_EXPIRY_PREFLIGHT_MS) {
1173
+ // Still fresh (or a no-expiry credential type) -- skip, so
1174
+ // this is not an unconditional provisioning call on every
1175
+ // dispatch. Still state WHY nothing was provisioned, so the
1176
+ // "needs a fresh VCS credential" line is never left dangling.
1177
+ log(expiresAt === null
1178
+ ? `[Sync] preflight: provision_vcs_auth skipped for member '${member}': PAT mode, credential has no expiry.`
1179
+ : `[Sync] preflight: provision_vcs_auth skipped for member '${member}': cached credential fresh until ${expiresAt.toISOString()}.`);
1180
+ return;
1181
+ }
1182
+ }
1183
+ log(`[Sync] preflight: ensuring member '${member}' has a fresh VCS credential before dispatch; calling provision_vcs_auth.`);
1184
+ try {
1185
+ const { expiresAt } = await provisionVcsAuthForMember({ fleetApi, command, member, log, logPrefix: '[Sync] preflight', azdevopsPatSecretName });
1186
+ knownGoodUntil.set(member, expiresAt);
1187
+ log(`[Sync] preflight: provision_vcs_auth succeeded for member '${member}'${expiresAt ? ` (expires ${expiresAt.toISOString()})` : ''}.`);
1188
+ } catch (err) {
1189
+ 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}`);
1190
+ }
1191
+ };
1192
+ }
1193
+
1194
+ /**
1195
+ * Sync-step "will this push be rejected for missing the 'workflows'
1196
+ * permission?" preflight (apra-fleet-2wdc.6). Distinct from
1197
+ * createVcsAuthPreflightCallback above: that one keeps a member's credential
1198
+ * FRESH; this one warns, BEFORE dispatch, when the credential that preflight
1199
+ * ensures is fresh was never going to carry a permission this specific push
1200
+ * needs -- so an operator sees a clear, named referral instead of a raw
1201
+ * GitHub 422 (or a misclassified rejection) surfacing mid-dispatch. See the
1202
+ * parent bug apra-fleet-2wdc: the App installation grants 'workflows', but a
1203
+ * minted token that never REQUESTED it gets rejected pushing any
1204
+ * .github/workflows/** change, on every git_access level that lacks it.
1205
+ *
1206
+ * NEVER mints a token to find out: resolves the member's VCS provider via the
1207
+ * same read-only resolveProvider() lookup provisionVcsAuthForMember itself
1208
+ * uses, then reads the access level that member is actually REGISTERED at off
1209
+ * the same tool (readRegisteredGitAccess below) -- both read-only member_detail
1210
+ * calls, no POST /access_tokens -- and checks that level against
1211
+ * accessLevelGrantsWorkflowsPermission()'s local table.
1212
+ *
1213
+ * WHICH level is checked matters, and is the whole point of apra-fleet-rp7a.4.
1214
+ * This used to test `gitAccess` -- an option no caller ever passes, defaulting
1215
+ * to DEFAULT_SYNC_GIT_ACCESS ('push'), which apra-fleet-2wdc.1 made a level
1216
+ * that DOES carry 'workflows'. That made the check a constant `true` and the
1217
+ * referral unreachable in every configuration the engine can produce: inert
1218
+ * defence, not working defence. The level now comes from the member registry
1219
+ * (member_detail's `gitAccess`, set by register_member/update_member's
1220
+ * git_access), so the members genuinely at risk -- registered 'read' or
1221
+ * 'issues', or holding a credential minted before apra-fleet-2wdc.1 and not
1222
+ * yet re-provisioned -- are the ones that get warned. `opts.gitAccess` is kept
1223
+ * ONLY as the fallback for a member whose record carries no explicit level, in
1224
+ * which case the provisioning default really is what will be requested.
1225
+ *
1226
+ * Cost/safety:
1227
+ * - Reads resolve per MEMBER, not per dispatch: any outcome that
1228
+ * proves this member can never produce a warning (non-GitHub, PAT mode, or
1229
+ * a level that carries 'workflows') is cached in `silentMembers` and the
1230
+ * member is skipped outright from then on -- so the steady state for a
1231
+ * healthy fleet is zero reads. The provider lookup also short-circuits
1232
+ * before the level read for any non-GitHub-App member, so no member ever
1233
+ * pays for a level it cannot be judged on. An AT-RISK outcome is
1234
+ * deliberately NOT cached -- re-provisioning the member at a carrying
1235
+ * level is exactly the remediation the referral asks for, and a cached
1236
+ * verdict would keep crying wolf after the operator did it.
1237
+ * - The diff check, when reached, is purely LOCAL: `git rev-list --count`
1238
+ * then `git diff --name-only`, both against refs already present on
1239
+ * `member`'s checkout (the sprint branch `syncMemberBefore` just synced,
1240
+ * and `origin/<baseBranch>` from this sprint's own branch setup) -- no
1241
+ * extra `git fetch`, so no added per-round remote round trip.
1242
+ * - Skipped entirely (no diff command run at all) when `branch` has no
1243
+ * commits ahead of `baseBranch`.
1244
+ * - NEVER throws: any failure (git command error, provider-resolution
1245
+ * failure, malformed output) is logged and swallowed, exactly like
1246
+ * createVcsAuthPreflightCallback above -- a preflight hiccup must never
1247
+ * abort a dispatch that would otherwise succeed.
1248
+ * - Non-GitHub providers are silently skipped -- never warn.
1249
+ *
1250
+ * @param {{ callTool: (name: string, args: object) => Promise<any>, command: Function, log?: Function, gitAccess?: string }} opts
1251
+ * @returns {(member: string, branch: string, baseBranch: string) => Promise<void>}
1252
+ */
1253
+ /**
1254
+ * The git access level `member` is REGISTERED at, straight off member_detail
1255
+ * (register_member/update_member's git_access, surfaced as `gitAccess` --
1256
+ * src/tools/member-detail.ts). Returns null when the member record names no
1257
+ * level, or when the response is anything this cannot read as JSON.
1258
+ *
1259
+ * Deliberately a separate read from resolveProvider()'s, even though both come
1260
+ * off the same tool: resolveProvider()'s return shape is a pinned contract
1261
+ * several suites assert field-for-field, and widening it to carry a field only
1262
+ * this preflight wants would make every one of those callers pay for a
1263
+ * concern none of them have. The cost is one extra member_detail call per
1264
+ * GitHub-App member per sprint (the caller caches its verdict; see
1265
+ * createWorkflowsPermissionPreflightCallback's silentMembers).
1266
+ *
1267
+ * Best-effort by design -- an absent/unparseable level is NOT an error here,
1268
+ * it just means the caller falls back to its provisioning default. A genuinely
1269
+ * failing memberDetail() call still rejects, and the caller's catch turns that
1270
+ * into the same swallowed degraded-check log as any other preflight hiccup.
1271
+ *
1272
+ * @param {string} member
1273
+ * @param {{ memberDetail: (opts: { member_name: string, format?: string }) => Promise<any> }} fleetApi
1274
+ * @returns {Promise<string|null>}
1275
+ */
1276
+ async function readRegisteredGitAccess(member, fleetApi) {
1277
+ const res = await fleetApi.memberDetail({ member_name: member, format: 'json' });
1278
+ let parsed;
1279
+ try {
1280
+ parsed = JSON.parse(resultText(res));
1281
+ } catch {
1282
+ // member_detail answers with plain prose (not JSON) when the member
1283
+ // cannot be resolved at all -- but that case has already surfaced as a
1284
+ // typed throw from resolveProvider() before this is ever reached, so
1285
+ // there is nothing left to report here.
1286
+ return null;
1287
+ }
1288
+ const level = parsed && typeof parsed.gitAccess === 'string' ? parsed.gitAccess.trim() : '';
1289
+ return level || null;
1290
+ }
1291
+
1292
+ export function createWorkflowsPermissionPreflightCallback(opts = {}) {
1293
+ const { callTool, command, log = () => {}, gitAccess: fallbackGitAccess = DEFAULT_SYNC_GIT_ACCESS } = opts;
1294
+ const fleetApi = new ApraFleet({ callTool });
1295
+
1296
+ /**
1297
+ * Members already proven incapable of producing this warning (wrong
1298
+ * provider, wrong auth mode, or an access level that carries 'workflows').
1299
+ * Skipping them avoids re-reading member_detail on every single dispatch;
1300
+ * see the cost note above for why at-risk members are NOT cached here.
1301
+ * @type {Set<string>}
1302
+ */
1303
+ const silentMembers = new Set();
1304
+
1305
+ return async function warnIfWorkflowsPermissionMissing(member, branch, baseBranch) {
1306
+ try {
1307
+ // branch === baseBranch is rejected at launch (sprint-args.mjs
1308
+ // validateBranchPair), so it is no longer tolerated as a silent no-op
1309
+ // here: a same-named pair falls through to the ahead-count check,
1310
+ // which still returns early when nothing is ahead of origin.
1311
+ if (!branch || !baseBranch) return;
1312
+ if (silentMembers.has(member)) return;
1313
+
1314
+ const { provider, authMode } = await resolveProvider(member, { fleetApi });
1315
+ if (provider !== 'github') {
1316
+ silentMembers.add(member);
1317
+ return;
1318
+ }
1319
+ if (authMode !== 'github-app') {
1320
+ // PAT mode, DELIBERATELY out of scope (apra-fleet-rp7a.4 item
1321
+ // 3 -- recorded here rather than left silent). A PAT missing
1322
+ // the 'workflow' scope is rejected by exactly the same GitHub
1323
+ // rule, so the failure mode is real; what is missing is any
1324
+ // way to PREDICT it from here. A PAT's granted scopes are not
1325
+ // derivable from anything the fleet registry holds: `git_access`
1326
+ // is a GitHub-App-only mapping onto installation-token
1327
+ // permissions (src/services/github-app.ts mapAccessLevel), and
1328
+ // the PAT itself is an opaque operator-supplied secret whose
1329
+ // scopes are only observable by calling GitHub with it and
1330
+ // reading the X-OAuth-Scopes response header -- a network call
1331
+ // this advisory, never-throwing, never-blocking preflight must
1332
+ // not make on every dispatch, and which would need the secret
1333
+ // VALUE, which the engine never handles. Warning off the
1334
+ // registered level anyway would be a fabricated verdict (the
1335
+ // level says nothing about a PAT), and warning unconditionally
1336
+ // would cry wolf at every correctly-scoped PAT member. So: no
1337
+ // warning. PAT members find out from the push rejection, which
1338
+ // classifyFailure() already recognizes and reports. Revisit
1339
+ // only if the registry ever records a PAT's scopes at
1340
+ // provisioning time -- then check them here the same way.
1341
+ silentMembers.add(member);
1342
+ return;
1343
+ }
1344
+
1345
+ // The level this member's credential is ACTUALLY minted at, per the
1346
+ // registry; the caller-supplied default applies only when the
1347
+ // member record names no level of its own.
1348
+ const registeredGitAccess = await readRegisteredGitAccess(member, fleetApi);
1349
+ const effectiveGitAccess = registeredGitAccess || fallbackGitAccess;
1350
+ const levelSource = registeredGitAccess ? 'registered' : 'default';
1351
+ if (accessLevelGrantsWorkflowsPermission(effectiveGitAccess)) {
1352
+ silentMembers.add(member);
1353
+ return;
1354
+ }
1355
+
1356
+ const countRes = await command(`git rev-list --count origin/${baseBranch}..${branch}`, { member_name: member, silent: true, failSoft: true });
1357
+ const aheadCount = countRes && countRes.ok ? parseInt(String(countRes.output || '').trim(), 10) : NaN;
1358
+ if (!Number.isFinite(aheadCount) || aheadCount <= 0) return;
1359
+
1360
+ const diffRes = await command(`git diff --name-only origin/${baseBranch}...${branch} -- .github/workflows`, { member_name: member, silent: true, failSoft: true });
1361
+ if (!diffRes || !diffRes.ok) return;
1362
+ const touchedPaths = String(diffRes.output || '').split('\n').map((line) => line.trim()).filter(Boolean);
1363
+ if (touchedPaths.length === 0) return;
1364
+
1365
+ log(
1366
+ `[Sync] OPERATOR REFERRAL: branch '${branch}' touches workflow file(s) [${touchedPaths.join(', ')}] but member ` +
1367
+ `'${member}''s minted credential (git_access '${effectiveGitAccess}', ${levelSource}) was not requested with the 'workflows' permission -- ` +
1368
+ `GitHub WILL reject this push ("refusing to allow a GitHub App to create or update workflow ... without ` +
1369
+ `workflows permission"). Re-provision '${member}' with an access level that carries 'workflows' ` +
1370
+ // Listed from the table itself, never spelled out again by
1371
+ // hand: a remedy naming levels that no longer carry the
1372
+ // permission is worse than no remedy at all.
1373
+ `(${[...GITHUB_ACCESS_LEVELS_WITH_WORKFLOWS].join(', ')}) before this dispatch publishes.`,
1374
+ );
1375
+ } catch (err) {
1376
+ log(`[Sync] preflight: workflows-permission check failed for member '${member}' on branch '${branch}' (continuing -- advisory only, never blocks dispatch): ${err.message}`);
1377
+ }
1378
+ };
1379
+ }
1380
+
1381
+ /**
1382
+ * LLM-auth counterpart to createVcsAuthSelfHealCallback, invoked by a
1383
+ * dispatch-site catch handler on an auth dispatch error: re-provisions LLM
1384
+ * credentials for the failing member via provision_llm_auth, after which the
1385
+ * caller retries its own dispatch once. Never throws -- every failure path
1386
+ * returns false ("do not retry"). A local member returns false without
1387
+ * retrying, because provision_llm_auth is a no-op for local members: they
1388
+ * share the operator's host credentials, and only an interactive `/login` on
1389
+ * that machine can fix an expired local session.
1390
+ *
1391
+ * @param {{ callTool: (name: string, args: object) => Promise<any>, log?: Function }} opts
1392
+ * @returns {(info: { member: string, label: string, error: string }) => Promise<boolean>} resolves true if healed (retry), false if not (do not retry)
1393
+ */
1394
+ export function createLlmAuthSelfHealCallback(opts = {}) {
1395
+ const { callTool, log = () => {} } = opts;
1396
+ const fleetApi = new ApraFleet({ callTool });
1397
+
1398
+ return async function onLlmAuthFailure({ member, label, error }) {
1399
+ log(`[Dispatch] self-heal: LLM auth failure detected for member '${member}' (${label}); calling provision_llm_auth to re-provision credentials: ${error}`);
1400
+
1401
+ let provisionRes;
1402
+ try {
1403
+ provisionRes = await fleetApi.provisionLlmAuth({ member_name: member });
1404
+ } catch (callErr) {
1405
+ log(`[Dispatch] self-heal: provision_llm_auth call failed for member '${member}': ${callErr.message}. Not retrying -- fix credentials manually and re-run.`);
1406
+ return false;
1407
+ }
1408
+
1409
+ const text = resultText(provisionRes).trim();
1410
+ const outcome = provisionOutcome(provisionRes, text);
1411
+
1412
+ // apra-fleet-3swo.13: src/tools/provision-auth.ts's OK_REASONS
1413
+ // classifies 'skipped_local_member' as ok:true (it IS a well-formed,
1414
+ // non-erroring outcome), so this check must run BEFORE the generic
1415
+ // ok/fail branch below -- otherwise a local member's skip would be
1416
+ // misread as a genuine credential refresh and the (pointless) retry
1417
+ // would fire anyway. The 'outcome.reason === null' half of the OR
1418
+ // only matters for the legacy prose fallback (no structuredContent
1419
+ // on the result at all), where the skip marker must still be read
1420
+ // off the text since there is no structured reason to check.
1421
+ if (outcome.reason === 'skipped_local_member' || (outcome.reason === null && /^\[SKIP\]/.test(text))) {
1422
+ // Skip marker (local member): provision_llm_auth is a no-op here,
1423
+ // so retrying would just reproduce the same failure.
1424
+ 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.`);
1425
+ return false;
1426
+ }
1427
+
1428
+ if (!outcome.ok) {
1429
+ log(`[Dispatch] self-heal: provision_llm_auth failed for member '${member}': ${text || '(no detail)'}. Not retrying.`);
1430
+ return false;
1431
+ }
1432
+
1433
+ if (outcome.reason === 'deployed_unverified') {
1434
+ // Credentials were deployed but the server's post-deploy auth test
1435
+ // did not confirm them: surface its error line and the explicit
1436
+ // switch, then still retry once (the test can be stricter than a real dispatch).
1437
+ const authLine = (text.split('\n').find((l) => /Auth test/i.test(l)) || '').trim();
1438
+ log(`[Dispatch] self-heal: provision_llm_auth deployed credentials for member '${member}' (${label}) but could not verify them${authLine ? `: ${authLine}` : ''}. If the member's stored credential is stale, re-run provision_llm_auth with a fresh api_key, or with force_oauth_copy: true to use your local login. Retrying the failed dispatch once.`);
1439
+ return true;
1440
+ }
1441
+
1442
+ log(`[Dispatch] self-heal: provision_llm_auth succeeded for member '${member}' (${label}); the failed dispatch will be retried once.`);
1443
+ return true;
1444
+ };
1445
+ }