@apralabs/apra-fleet 0.4.4 → 0.4.5

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 (268) hide show
  1. package/README.md +49 -4
  2. package/dist/agents/backlog-groomer.md +5 -0
  3. package/dist/agents/ci-watcher.md +5 -0
  4. package/dist/agents/deployer.md +20 -2
  5. package/dist/agents/doer.md +38 -2
  6. package/dist/agents/harvester.md +12 -9
  7. package/dist/agents/integ-test-runner.md +5 -0
  8. package/dist/agents/kb-reconciler.md +6 -0
  9. package/dist/agents/plan-reviewer.md +5 -0
  10. package/dist/agents/planner.md +5 -0
  11. package/dist/agents/regression-test-runner.md +5 -0
  12. package/dist/agents/reviewer.md +67 -15
  13. package/dist/agents/schemas/deployer-output.json +5 -0
  14. package/dist/agents/schemas/doer-output.json +78 -2
  15. package/dist/agents/schemas/reviewer-output.json +104 -2
  16. package/dist/cli/auth.js +5 -1
  17. package/dist/cli/beads-pin.js +6 -7
  18. package/dist/cli/claude-mod.d.ts +75 -0
  19. package/dist/cli/claude-mod.js +288 -0
  20. package/dist/cli/dolt-install.d.ts +1 -1
  21. package/dist/cli/dolt-install.js +5 -1
  22. package/dist/cli/fleet-se-guard.d.ts +8 -0
  23. package/dist/cli/fleet-se-guard.js +19 -3
  24. package/dist/cli/install-guard.d.ts +9 -0
  25. package/dist/cli/install-guard.js +24 -0
  26. package/dist/cli/install.d.ts +12 -0
  27. package/dist/cli/install.js +180 -20
  28. package/dist/cli/kb-profile.d.ts +16 -0
  29. package/dist/cli/kb-profile.js +81 -0
  30. package/dist/cli/start.js +3 -0
  31. package/dist/cli/uninstall.js +13 -3
  32. package/dist/cli/update.d.ts +4 -0
  33. package/dist/cli/update.js +19 -3
  34. package/dist/commands/kb-server.d.ts +10 -1
  35. package/dist/commands/kb-server.js +285 -11
  36. package/dist/index.js +22 -1
  37. package/dist/os/git-executable.d.ts +57 -0
  38. package/dist/os/git-executable.js +85 -0
  39. package/dist/os/go-concurrency.d.ts +44 -0
  40. package/dist/os/go-concurrency.js +53 -0
  41. package/dist/os/index.d.ts +1 -0
  42. package/dist/os/index.js +1 -0
  43. package/dist/os/linux.d.ts +2 -0
  44. package/dist/os/linux.js +10 -1
  45. package/dist/os/os-commands.d.ts +25 -0
  46. package/dist/os/os-commands.js +2 -0
  47. package/dist/os/windows-executable.d.ts +53 -0
  48. package/dist/os/windows-executable.js +185 -0
  49. package/dist/os/windows-gitbash.d.ts +23 -14
  50. package/dist/os/windows-gitbash.js +40 -16
  51. package/dist/os/windows.d.ts +2 -0
  52. package/dist/os/windows.js +37 -6
  53. package/dist/paths.d.ts +10 -1
  54. package/dist/paths.js +19 -2
  55. package/dist/services/agy-project.d.ts +7 -1
  56. package/dist/services/agy-project.js +7 -2
  57. package/dist/services/auth-socket.d.ts +18 -0
  58. package/dist/services/auth-socket.js +30 -4
  59. package/dist/services/credential-store.d.ts +33 -0
  60. package/dist/services/credential-store.js +79 -2
  61. package/dist/services/http-transport.d.ts +29 -0
  62. package/dist/services/http-transport.js +166 -37
  63. package/dist/services/kb-tool-profile.d.ts +36 -0
  64. package/dist/services/kb-tool-profile.js +88 -0
  65. package/dist/services/knowledge/bible-blob-id.js +10 -1
  66. package/dist/services/knowledge/bible-import.d.ts +108 -0
  67. package/dist/services/knowledge/bible-import.js +137 -4
  68. package/dist/services/knowledge/file-hash.js +6 -5
  69. package/dist/services/knowledge/http-provider.d.ts +303 -20
  70. package/dist/services/knowledge/http-provider.js +795 -125
  71. package/dist/services/knowledge/kb-config.d.ts +65 -1
  72. package/dist/services/knowledge/kb-config.js +143 -3
  73. package/dist/services/knowledge/kb-http-auth-state.d.ts +26 -0
  74. package/dist/services/knowledge/kb-http-auth-state.js +40 -0
  75. package/dist/services/knowledge/kb-providers.d.ts +9 -2
  76. package/dist/services/knowledge/kb-providers.js +67 -37
  77. package/dist/services/knowledge/kb-removed-scope-keys.js +1 -1
  78. package/dist/services/knowledge/kb-self.d.ts +122 -9
  79. package/dist/services/knowledge/kb-self.js +196 -36
  80. package/dist/services/knowledge/member-bible-view.js +16 -3
  81. package/dist/services/knowledge/path-validation.d.ts +7 -0
  82. package/dist/services/knowledge/path-validation.js +11 -0
  83. package/dist/services/knowledge/project-slug.js +3 -2
  84. package/dist/services/knowledge/repository-header.d.ts +77 -0
  85. package/dist/services/knowledge/repository-header.js +233 -0
  86. package/dist/services/knowledge/require-sqlite-project.d.ts +1 -1
  87. package/dist/services/knowledge/require-sqlite-project.js +1 -1
  88. package/dist/services/knowledge/sqlite-provider.d.ts +169 -0
  89. package/dist/services/knowledge/sqlite-provider.js +416 -4
  90. package/dist/services/knowledge/types.d.ts +15 -2
  91. package/dist/services/member-busy.d.ts +12 -0
  92. package/dist/services/member-busy.js +20 -0
  93. package/dist/services/member-config-io.d.ts +3 -2
  94. package/dist/services/member-config-io.js +7 -4
  95. package/dist/services/member-fleet-install.js +1 -0
  96. package/dist/services/member-tool-allowlist.d.ts +1 -1
  97. package/dist/services/member-tool-allowlist.js +8 -4
  98. package/dist/services/port-holder.js +2 -1
  99. package/dist/services/service-manager/types.d.ts +17 -1
  100. package/dist/services/service-manager/windows.d.ts +7 -2
  101. package/dist/services/service-manager/windows.js +28 -11
  102. package/dist/services/service-notice.d.ts +7 -0
  103. package/dist/services/service-notice.js +19 -0
  104. package/dist/services/session-registry.d.ts +13 -0
  105. package/dist/services/session-registry.js +13 -0
  106. package/dist/services/session-roots.d.ts +67 -0
  107. package/dist/services/session-roots.js +126 -0
  108. package/dist/services/statusline.d.ts +21 -0
  109. package/dist/services/statusline.js +97 -1
  110. package/dist/services/supervisor-service-cleanup.js +2 -1
  111. package/dist/services/tool-registry.js +108 -20
  112. package/dist/services/tool-scope.d.ts +34 -1
  113. package/dist/services/tool-scope.js +27 -2
  114. package/dist/services/vcs/azure-devops.js +10 -0
  115. package/dist/services/vcs/bitbucket.d.ts +22 -1
  116. package/dist/services/vcs/bitbucket.js +163 -17
  117. package/dist/services/vcs/types.d.ts +25 -2
  118. package/dist/services/watch/project-resolver.js +2 -1
  119. package/dist/skills/pm/cost.md +5 -1
  120. package/dist/skills/pm/index.md +9 -9
  121. package/dist/skills/pm/sprint.md +2 -1
  122. package/dist/tools/check-status.d.ts +51 -0
  123. package/dist/tools/check-status.js +124 -12
  124. package/dist/tools/code-intelligence-freshness.js +1 -1
  125. package/dist/tools/code-intelligence-gitnexus.d.ts +19 -0
  126. package/dist/tools/code-intelligence-gitnexus.js +166 -9
  127. package/dist/tools/code-intelligence-readiness.d.ts +58 -1
  128. package/dist/tools/code-intelligence-readiness.js +93 -8
  129. package/dist/tools/code-intelligence-reindex.d.ts +25 -1
  130. package/dist/tools/code-intelligence-reindex.js +76 -4
  131. package/dist/tools/code-intelligence.d.ts +1 -1
  132. package/dist/tools/code-intelligence.js +1 -1
  133. package/dist/tools/execute-command.js +14 -8
  134. package/dist/tools/execute-prompt.js +6 -2
  135. package/dist/tools/fleet-snapshot.d.ts +21 -0
  136. package/dist/tools/fleet-snapshot.js +78 -0
  137. package/dist/tools/kb-bible-commit.d.ts +25 -11
  138. package/dist/tools/kb-bible-commit.js +142 -33
  139. package/dist/tools/kb-capture.d.ts +2 -2
  140. package/dist/tools/kb-context.js +47 -27
  141. package/dist/tools/kb-demote.d.ts +27 -0
  142. package/dist/tools/kb-demote.js +37 -0
  143. package/dist/tools/kb-export.d.ts +35 -3
  144. package/dist/tools/kb-export.js +56 -13
  145. package/dist/tools/kb-feedback.d.ts +2 -0
  146. package/dist/tools/kb-feedback.js +17 -7
  147. package/dist/tools/kb-harvest.js +28 -9
  148. package/dist/tools/kb-import.d.ts +18 -2
  149. package/dist/tools/kb-import.js +24 -9
  150. package/dist/tools/kb-invalidate.d.ts +11 -3
  151. package/dist/tools/kb-invalidate.js +80 -7
  152. package/dist/tools/kb-list.js +38 -10
  153. package/dist/tools/kb-promote.js +6 -4
  154. package/dist/tools/kb-query.d.ts +3 -0
  155. package/dist/tools/kb-query.js +181 -37
  156. package/dist/tools/kb-session-prime.d.ts +4 -4
  157. package/dist/tools/kb-session-prime.js +89 -9
  158. package/dist/tools/kb-setup.d.ts +20 -0
  159. package/dist/tools/kb-setup.js +149 -11
  160. package/dist/tools/list-members.js +1 -1
  161. package/dist/tools/member-detail.js +7 -3
  162. package/dist/tools/provision-vcs-auth.d.ts +28 -3
  163. package/dist/tools/provision-vcs-auth.js +53 -7
  164. package/dist/tools/receive-files.js +7 -4
  165. package/dist/tools/send-files.js +5 -4
  166. package/dist/tools/send-message.d.ts +3 -0
  167. package/dist/tools/send-message.js +15 -2
  168. package/dist/tools/stop-prompt.js +3 -1
  169. package/dist/tools/vcs-credential-exec.d.ts +45 -3
  170. package/dist/tools/vcs-credential-exec.js +90 -11
  171. package/dist/utils/process-utils.js +5 -1
  172. package/dist/utils/redact-known-secrets.d.ts +17 -0
  173. package/dist/utils/redact-known-secrets.js +70 -0
  174. package/dist/utils/skill-matrix.js +1 -1
  175. package/dist/utils/vcs-provider-detect.js +2 -2
  176. package/dist/workflows/auto-sprint.js +245 -9
  177. package/package.json +10 -7
  178. package/packages/apra-fleet-client/package.json +1 -1
  179. package/packages/apra-fleet-client/src/client/api.mjs +172 -19
  180. package/packages/apra-fleet-client/src/client/reconnecting-transport.mjs +35 -2
  181. package/packages/apra-fleet-client/src/client/transport.mjs +6 -0
  182. package/packages/apra-fleet-se/apra-pm/agents/backlog-groomer.md +5 -0
  183. package/packages/apra-fleet-se/apra-pm/agents/ci-watcher.md +5 -0
  184. package/packages/apra-fleet-se/apra-pm/agents/deployer.md +20 -2
  185. package/packages/apra-fleet-se/apra-pm/agents/doer.md +38 -2
  186. package/packages/apra-fleet-se/apra-pm/agents/harvester.md +12 -9
  187. package/packages/apra-fleet-se/apra-pm/agents/integ-test-runner.md +5 -0
  188. package/packages/apra-fleet-se/apra-pm/agents/kb-reconciler.md +6 -0
  189. package/packages/apra-fleet-se/apra-pm/agents/plan-reviewer.md +5 -0
  190. package/packages/apra-fleet-se/apra-pm/agents/planner.md +5 -0
  191. package/packages/apra-fleet-se/apra-pm/agents/regression-test-runner.md +5 -0
  192. package/packages/apra-fleet-se/apra-pm/agents/reviewer.md +67 -15
  193. package/packages/apra-fleet-se/apra-pm/agents/schemas/deployer-output.json +5 -0
  194. package/packages/apra-fleet-se/apra-pm/agents/schemas/doer-output.json +78 -2
  195. package/packages/apra-fleet-se/apra-pm/agents/schemas/reviewer-output.json +104 -2
  196. package/packages/apra-fleet-se/apra-pm/skills/pm/cost.md +5 -1
  197. package/packages/apra-fleet-se/apra-pm/skills/pm/index.md +9 -9
  198. package/packages/apra-fleet-se/apra-pm/skills/pm/sprint.md +2 -1
  199. package/packages/apra-fleet-se/bin/cli.mjs +104 -31
  200. package/packages/apra-fleet-se/bin/serve.mjs +46 -8
  201. package/packages/apra-fleet-se/fleet-sprint/abort.mjs +184 -32
  202. package/packages/apra-fleet-se/fleet-sprint/bd-sync-command.mjs +69 -0
  203. package/packages/apra-fleet-se/fleet-sprint/beads-children.mjs +21 -0
  204. package/packages/apra-fleet-se/fleet-sprint/beads-lock-probe.mjs +176 -0
  205. package/packages/apra-fleet-se/fleet-sprint/beads-reachability.mjs +126 -0
  206. package/packages/apra-fleet-se/fleet-sprint/beads-scope.mjs +158 -1
  207. package/packages/apra-fleet-se/fleet-sprint/contracts.mjs +82 -2
  208. package/packages/apra-fleet-se/fleet-sprint/coordination.mjs +23 -6
  209. package/packages/apra-fleet-se/fleet-sprint/decision-notify.mjs +338 -0
  210. package/packages/apra-fleet-se/fleet-sprint/decision-wait.mjs +731 -0
  211. package/packages/apra-fleet-se/fleet-sprint/decisions.mjs +372 -0
  212. package/packages/apra-fleet-se/fleet-sprint/dispatch-role.mjs +44 -11
  213. package/packages/apra-fleet-se/fleet-sprint/docs/README.md +4 -1
  214. package/packages/apra-fleet-se/fleet-sprint/dolt-settle.mjs +9 -3
  215. package/packages/apra-fleet-se/fleet-sprint/dolt-sync.mjs +314 -19
  216. package/packages/apra-fleet-se/fleet-sprint/errors.mjs +72 -4
  217. package/packages/apra-fleet-se/fleet-sprint/git-sync.mjs +7 -1
  218. package/packages/apra-fleet-se/fleet-sprint/git-topology.mjs +112 -1
  219. package/packages/apra-fleet-se/fleet-sprint/guarded-modules.mjs +36 -2
  220. package/packages/apra-fleet-se/fleet-sprint/kb.mjs +736 -101
  221. package/packages/apra-fleet-se/fleet-sprint/member-init-probe.mjs +1 -1
  222. package/packages/apra-fleet-se/fleet-sprint/member-provisioning.mjs +7 -1
  223. package/packages/apra-fleet-se/fleet-sprint/phases/deploy.mjs +49 -2
  224. package/packages/apra-fleet-se/fleet-sprint/phases/develop.mjs +206 -3
  225. package/packages/apra-fleet-se/fleet-sprint/phases/final-review.mjs +61 -3
  226. package/packages/apra-fleet-se/fleet-sprint/phases/harvest.mjs +81 -31
  227. package/packages/apra-fleet-se/fleet-sprint/phases/plan.mjs +7 -3
  228. package/packages/apra-fleet-se/fleet-sprint/phases/publish-pr.mjs +39 -14
  229. package/packages/apra-fleet-se/fleet-sprint/phases/re-review.mjs +17 -1
  230. package/packages/apra-fleet-se/fleet-sprint/phases/review.mjs +18 -3
  231. package/packages/apra-fleet-se/fleet-sprint/pr-body.mjs +14 -1
  232. package/packages/apra-fleet-se/fleet-sprint/prompts.mjs +32 -5
  233. package/packages/apra-fleet-se/fleet-sprint/runner.js +824 -98
  234. package/packages/apra-fleet-se/fleet-sprint/se-os-commands.mjs +4 -2
  235. package/packages/apra-fleet-se/fleet-sprint/se-posix.mjs +54 -1
  236. package/packages/apra-fleet-se/fleet-sprint/se-windows.mjs +29 -2
  237. package/packages/apra-fleet-se/fleet-sprint/set-aside.mjs +288 -0
  238. package/packages/apra-fleet-se/fleet-sprint/skills/fleet-supervisor/SKILL.md +3 -2
  239. package/packages/apra-fleet-se/fleet-sprint/sprint-args.mjs +20 -0
  240. package/packages/apra-fleet-se/fleet-sprint/sprint-report.mjs +21 -0
  241. package/packages/apra-fleet-se/fleet-sprint/sprint-state.mjs +9 -0
  242. package/packages/apra-fleet-se/fleet-sprint/vcs-auth.mjs +605 -32
  243. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/bitbucket.mjs +811 -17
  244. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/index.mjs +89 -1
  245. package/packages/apra-fleet-se/fleet-sprint/viewer-extensions.mjs +225 -2
  246. package/packages/apra-fleet-se/fleet-sprint/worklists.mjs +59 -3
  247. package/packages/apra-fleet-se/src/supervisor/api.mjs +148 -8
  248. package/packages/apra-fleet-se/src/supervisor/dashboard.mjs +6 -3
  249. package/packages/apra-fleet-se/src/supervisor/dolt-mutex.mjs +30 -10
  250. package/packages/apra-fleet-se/src/supervisor/fleet-members.mjs +17 -4
  251. package/packages/apra-fleet-se/src/supervisor/history.mjs +8 -1
  252. package/packages/apra-fleet-se/src/supervisor/id-allocator.mjs +92 -2
  253. package/packages/apra-fleet-se/src/supervisor/proxy.mjs +26 -1
  254. package/packages/apra-fleet-se/src/supervisor/server.mjs +151 -8
  255. package/packages/apra-fleet-se/src/supervisor/spawner.mjs +11 -9
  256. package/packages/apra-fleet-se/src/supervisor/watchdog.mjs +7 -1
  257. package/packages/apra-fleet-workflow/package.json +2 -1
  258. package/packages/apra-fleet-workflow/src/viewer/index.mjs +86 -5
  259. package/packages/apra-fleet-workflow/src/viewer/request-guard.mjs +222 -0
  260. package/packages/apra-fleet-workflow/src/workflow/index.mjs +34 -2
  261. package/plugins/claude-code/fleet-status/.claude-plugin/plugin.json +7 -0
  262. package/plugins/claude-code/fleet-status/hooks/hooks.json +1 -0
  263. package/plugins/claude-code/fleet-status/hooks/register.tsx +906 -0
  264. package/plugins/claude-code/fleet-status/types/index.d.ts +88 -0
  265. package/skills/fleet/auth-bitbucket.md +47 -20
  266. package/skills/fleet/onboarding.md +1 -1
  267. package/skills/fleet/skill-matrix.md +3 -3
  268. package/version.json +1 -1
@@ -107,6 +107,18 @@ async function listCredentialStoreNames(fleetApi) {
107
107
  }
108
108
  }
109
109
 
110
+ /**
111
+ * A remote URL safe to quote in a log line: the userinfo of a scheme'd URL
112
+ * (`https://user:TOKEN@host/...` -- git prints an embedded credential
113
+ * verbatim) becomes `***`. scp-like `git@host:path` is left as is: `git` is
114
+ * the login name, not a secret.
115
+ * @param {string} url
116
+ * @returns {string}
117
+ */
118
+ export function redactUrlUserinfo(url) {
119
+ return String(url ?? '').replace(/([a-z][a-z0-9+.-]*:\/\/)[^/@\s]*@/gi, (_m, scheme) => scheme + '***@');
120
+ }
121
+
110
122
  /**
111
123
  * Build the provision_vcs_auth arguments for a member, dispatched through the
112
124
  * resolved provider's OPTIONAL buildProvisionArgs hook (apra-fleet-5co8.2.1).
@@ -125,10 +137,22 @@ async function listCredentialStoreNames(fleetApi) {
125
137
  * advisory the operator should see (e.g. an ssh remote the PAT cannot
126
138
  * serve) that is NOT a failure.
127
139
  *
140
+ * apra-fleet-qeq1.9: a hook may also answer `{ skip: true }` -- "this
141
+ * provider has nothing to provision for THIS request, proceed on the
142
+ * credential already deployed". That is a third answer, distinct from both
143
+ * `args` (dispatch these) and `error` (fail): a provider whose credential is
144
+ * deployed out of band and carries no scope axis has no meaningful
145
+ * just-in-time re-provision to run, and forcing a doomed one would abort the
146
+ * very call it is supposed to enable. Reported to the caller as a `null`
147
+ * return -- no provider ever legitimately produces null `args`, and the
148
+ * no-hook path above returns `base`, so null is unambiguous. The skip is
149
+ * never silent: a hook taking it should also return a `note`, logged below
150
+ * exactly like any other advisory.
151
+ *
128
152
  * @param {{ provider: string, base: object, repoRef: object|null, fleetApi: object,
129
153
  * secretName?: string, remoteUrl?: string, remoteReadError?: string|null,
130
154
  * log?: Function, logPrefix?: string }} ctx
131
- * @returns {Promise<object>} the arguments to send
155
+ * @returns {Promise<object|null>} the arguments to send, or null to skip provisioning entirely
132
156
  */
133
157
  async function buildProvisionArgsForProvider({ provider, base, repoRef, fleetApi, secretName, remoteUrl, remoteReadError, log = () => {}, logPrefix = '' }) {
134
158
  const impl = getVcsProvider(provider);
@@ -137,13 +161,14 @@ async function buildProvisionArgsForProvider({ provider, base, repoRef, fleetApi
137
161
  const availableSecrets = await listCredentialStoreNames(fleetApi);
138
162
  const built = impl.buildProvisionArgs({ base, repoRef, availableSecrets, secretName, remoteUrl, remoteReadError });
139
163
  if (built && typeof built.error === 'string') throw new Error(built.error);
140
- if (!built || !built.args || typeof built.args !== 'object') {
164
+ const skipped = !!(built && built.skip === true);
165
+ if (!built || (!skipped && (!built.args || typeof built.args !== 'object'))) {
141
166
  throw new Error(`ERROR: VCS provider '${provider}' returned no provision arguments for member '${base.member_name}'.`);
142
167
  }
143
168
  if (typeof built.note === 'string' && built.note.trim()) {
144
169
  log(`${logPrefix}: note: ${built.note.trim()}`);
145
170
  }
146
- return built.args;
171
+ return skipped ? null : built.args;
147
172
  }
148
173
 
149
174
  // apra-fleet-3swo.13: provision_vcs_auth / provision_llm_auth used to be
@@ -257,7 +282,7 @@ function detectVcsProviderFromRemote(remoteUrl) {
257
282
  return (impl && impl.name) || null;
258
283
  }
259
284
 
260
- async function provisionVcsAuthForMember({ fleetApi, command, member, log = () => {}, logPrefix, gitAccess = DEFAULT_SYNC_GIT_ACCESS, azdevopsPatSecretName, remoteUrlOverride, resolvedProvider }) {
285
+ async function provisionVcsAuthForMember({ fleetApi, command, member, log = () => {}, logPrefix, gitAccess = DEFAULT_SYNC_GIT_ACCESS, azdevopsPatSecretName, remoteUrlOverride, resolvedProvider, refuseLocalNonReMintable = false }) {
261
286
  let repos;
262
287
  let derivedRepo = null;
263
288
  let derivedRef = null;
@@ -311,7 +336,7 @@ async function provisionVcsAuthForMember({ fleetApi, command, member, log = () =
311
336
  // member/repo than `member` -- see the caller-note above -- so
312
337
  // this log deliberately does not claim the URL is `member`'s own.
313
338
  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.`);
339
+ log(`${logPrefix}: could not derive an owner/repo from ${remoteSource} (raw: '${redactUrlUserinfo(remoteUrl)}'); calling provision_vcs_auth without an explicit repos scope.`);
315
340
  }
316
341
  }
317
342
 
@@ -357,8 +382,26 @@ async function provisionVcsAuthForMember({ fleetApi, command, member, log = () =
357
382
  // that stable code rather than by its message text.
358
383
  let provider;
359
384
  let authMode;
385
+ // PR-raising (push+pr) calls act on the TARGET repo, so the provider whose
386
+ // host serves that remote wins over the member's registered one: a
387
+ // GitHub-registered backlog member publishing a bitbucket.org sprint must
388
+ // use Bitbucket's provider (and its own credential label), never mint a
389
+ // GitHub credential for a Bitbucket repo. Only an anchored auth-provider
390
+ // host match counts (detectVcsProviderFromRemote); anything else keeps
391
+ // the registry answer.
392
+ const hostProvider = (gitAccess === 'push+pr' && !resolvedProvider && !remoteReadFailed && remoteUrl)
393
+ ? detectVcsProviderFromRemote(remoteUrl)
394
+ : null;
395
+ let registeredMismatch = null;
360
396
  try {
361
397
  ({ provider, authMode } = resolvedProvider || await resolveProvider(member, { fleetApi }));
398
+ if (hostProvider && hostProvider !== provider) {
399
+ registeredMismatch = provider;
400
+ provider = hostProvider;
401
+ const impl = getVcsProvider(provider);
402
+ authMode = isAuthBackend(impl) ? impl.defaultAuthMode : null;
403
+ log(`${logPrefix}: member '${member}' is registered for VCS provider '${registeredMismatch}', but the target remote is served by '${provider}'; using '${provider}' for this pull-request call.`);
404
+ }
362
405
  } catch (resolveErr) {
363
406
  if (!resolveErr || resolveErr.code !== VCS_NO_REGISTERED_PROVIDER) throw resolveErr;
364
407
  const detected = (!remoteReadFailed && remoteUrl)
@@ -371,6 +414,12 @@ async function provisionVcsAuthForMember({ fleetApi, command, member, log = () =
371
414
  const remoteSource = remoteUrlOverride ? 'the supplied remote URL' : 'its git remote';
372
415
  log(`${logPrefix}: member '${member}' had no registered VCS provider; detected '${provider}' from ${remoteSource} and will provision it now`);
373
416
  }
417
+ // A caller that could not run its own local-member check (e.g. the
418
+ // self-heal whose provider lookup failed) asks for it here, now that the
419
+ // provider is known. Fails CLOSED -- see assertNotLocalNonReMintable.
420
+ if (refuseLocalNonReMintable) {
421
+ await assertNotLocalNonReMintable({ fleetApi, member, provider });
422
+ }
374
423
  // apra-fleet-5co8.2.1: the argument shape itself is now provider-owned.
375
424
  // What follows is the DEFAULT (GitHub-App) shape; a provider that declares
376
425
  // a buildProvisionArgs hook replaces it wholesale -- see
@@ -392,7 +441,34 @@ async function provisionVcsAuthForMember({ fleetApi, command, member, log = () =
392
441
  log,
393
442
  logPrefix,
394
443
  });
395
- const provisionRes = await fleetApi.provisionVcsAuth(provisionArgs);
444
+ // apra-fleet-qeq1.9: the hook answered "nothing to provision for this
445
+ // request" (see buildProvisionArgsForProvider's own doc for the null
446
+ // contract). Dispatch nothing, claim no new expiry -- the credential in
447
+ // place is whatever it already was -- and still hand back the derived
448
+ // repo, which is the other half of this function's return contract and is
449
+ // what the PR-raising call sites need to build their command.
450
+ //
451
+ // `provider` + `provisionSkipped` are returned too: with no
452
+ // provision_vcs_auth call, a member that had no registered vcsProvider
453
+ // (detected from its remote above) is never persisted, so a caller's
454
+ // later resolveProvider() would throw VCS_NO_REGISTERED_PROVIDER. And a
455
+ // skipped provision means the credential exists only if an operator
456
+ // deployed it, so its absence is an operator fix, not an internal fault.
457
+ if (provisionArgs === null) {
458
+ log(`${logPrefix}: provider '${provider}' has nothing to re-provision for member '${member}'; continuing on its already-deployed credential without calling provision_vcs_auth.`);
459
+ return { expiresAt: null, repo: derivedRepo, provider, provisionSkipped: true };
460
+ }
461
+ // A member holds one VCS credential: provisioning the host's provider
462
+ // here would revoke the credential of the provider it is registered for
463
+ // (provision_vcs_auth swaps labels) and break that provider's sprints.
464
+ // Refuse with a typed error instead; the PR callers degrade on it.
465
+ if (registeredMismatch) {
466
+ throw new Error(`member '${member}' is registered for VCS provider '${registeredMismatch}', which does not serve this '${provider}' remote; not provisioning '${provider}' on it, because that would revoke the member's '${registeredMismatch}' credential. Use a backlog member dedicated to '${provider}' for this repository.`);
467
+ }
468
+ // apra-fleet-d1pk.3: fleet-sprint runs unattended, so it never lets
469
+ // provision_vcs_auth fall into its out-of-band secret prompt -- a missing
470
+ // secret comes back as reason credential_missing instead.
471
+ const provisionRes = await fleetApi.provisionVcsAuth({ ...provisionArgs, non_interactive: true });
396
472
  const provisionText = resultText(provisionRes);
397
473
  // provision_vcs_auth NEVER throws on failure -- it reports failure via
398
474
  // structuredContent.ok === false (apra-fleet-3swo.13; see
@@ -591,12 +667,33 @@ export function buildCredentialReadCommand(target, label) {
591
667
  // Splits a VCSModule create-pull-request curl result's captured stdout into
592
668
  // its HTTP status code and JSON body. VCSModule's buildCreatePrCommand always
593
669
  // appends `-w '\n%{http_code}'`, so curl's own stdout is "<json body>\n<status>".
670
+ // A builder may also pass curl `-D -` (bitbucket.mjs does), which puts the
671
+ // RESPONSE header block(s) first: "HTTP/x NNN\r\nName: v\r\n\r\n<body>\n<status>".
672
+ // Each leading block is consumed into `headers` (lowercased names; a later
673
+ // block -- after a 100 Continue -- replaces an earlier one), and the rest
674
+ // parses exactly as before, so output without headers is unaffected.
675
+ // Cookie-bearing and auth headers are dropped, never returned: callers quote
676
+ // header values into log lines.
594
677
  /**
595
678
  * @param {string} output
596
- * @returns {{ status: number|null, body: unknown }}
679
+ * @returns {{ status: number|null, body: unknown, bodyText: string, headers: Record<string, string> }}
597
680
  */
598
681
  function parseVcsCurlOutput(output) {
599
- const text = String(output || '');
682
+ let text = String(output || '');
683
+ const headers = {};
684
+ while (/^HTTP\/\d(?:\.\d)? \d{3}/.test(text)) {
685
+ const end = /\r?\n\r?\n/.exec(text);
686
+ const block = end ? text.slice(0, end.index) : text;
687
+ text = end ? text.slice(end.index + end[0].length) : '';
688
+ for (const k of Object.keys(headers)) delete headers[k];
689
+ for (const line of block.split(/\r?\n/).slice(1)) {
690
+ const colon = line.indexOf(':');
691
+ if (colon <= 0) continue;
692
+ const name = line.slice(0, colon).trim().toLowerCase();
693
+ if (/^(?:set-cookie|cookie|authorization|proxy-authorization|www-authenticate|proxy-authenticate)$/.test(name)) continue;
694
+ headers[name] = line.slice(colon + 1).trim();
695
+ }
696
+ }
600
697
  const lines = text.split('\n');
601
698
  const statusLine = lines.length ? lines[lines.length - 1].trim() : '';
602
699
  const status = /^\d+$/.test(statusLine) ? parseInt(statusLine, 10) : null;
@@ -609,7 +706,7 @@ function parseVcsCurlOutput(output) {
609
706
  body = null;
610
707
  }
611
708
  }
612
- return { status, body, bodyText };
709
+ return { status, body, bodyText, headers };
613
710
  }
614
711
 
615
712
  const PR_AUTH_404_TEXT_RE = /not accessible by (this )?(integration|token|personal access token)|requires (authentication|additional scopes?)|insufficient (scope|permission)/i;
@@ -677,8 +774,13 @@ function isPrAuthFailure(status, errorText) {
677
774
  */
678
775
  export async function raiseVcsPrForMember({ fleetApi, command, member, base, head, title, body, log = () => {}, logPrefix, remoteUrlOverride, updateExisting }) {
679
776
  let repo;
777
+ // Set when the provider's buildProvisionArgs hook answered `skip` (its
778
+ // credential is deployed out of band only -- see provisionVcsAuthForMember).
779
+ let skippedProvider = null;
680
780
  try {
681
- ({ repo } = await provisionPrCapableAuthForMember({ fleetApi, command, member, log, logPrefix, remoteUrlOverride }));
781
+ const provisioned = await provisionPrCapableAuthForMember({ fleetApi, command, member, log, logPrefix, remoteUrlOverride });
782
+ repo = provisioned.repo;
783
+ if (provisioned.provisionSkipped && provisioned.provider) skippedProvider = provisioned.provider;
682
784
  } catch (provisionErr) {
683
785
  // apra-fleet-5co8.15: provisionPrCapableAuthForMember has no failSoft
684
786
  // of its own (by design -- see its doc comment above), so a
@@ -693,8 +795,21 @@ export async function raiseVcsPrForMember({ fleetApi, command, member, base, hea
693
795
  // and keep going rather than aborting on this condition.
694
796
  let remedyHint = null;
695
797
  try {
696
- const { provider } = await resolveProvider(member, { fleetApi });
697
- const impl = getVcsProvider(provider);
798
+ // The TARGET remote's provider wins over the member's registered
799
+ // one (same rule provisionVcsAuthForMember applies at push+pr): a
800
+ // GitHub-registered member publishing to bitbucket.org must be
801
+ // told the Bitbucket remedy, not the registered provider's.
802
+ let remedyProvider = null;
803
+ try {
804
+ let remote = remoteUrlOverride ? String(remoteUrlOverride).trim() : '';
805
+ if (!remote) {
806
+ const r = await command('git remote get-url origin', { member_name: member, silent: true, failSoft: true });
807
+ remote = r && r.ok ? String(r.output || '').trim() : '';
808
+ }
809
+ if (remote) remedyProvider = detectVcsProviderFromRemote(remote);
810
+ } catch { /* fall back to the registered provider below */ }
811
+ if (!remedyProvider) ({ provider: remedyProvider } = await resolveProvider(member, { fleetApi }));
812
+ const impl = getVcsProvider(remedyProvider);
698
813
  if (impl && impl.authRemedy && impl.authRemedy.hint) remedyHint = impl.authRemedy.hint;
699
814
  } catch (resolveErr) {
700
815
  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}`);
@@ -734,8 +849,49 @@ export async function raiseVcsPrForMember({ fleetApi, command, member, base, hea
734
849
  // stale GitHub token left over from an earlier provider and send it to
735
850
  // dev.azure.com). `credentialLabel` is threaded into every
736
851
  // vcsCredentialExec() call below for exactly that reason.
737
- const { provider } = await resolveProvider(member, { fleetApi });
852
+ //
853
+ // A skipped provision never persisted a vcsProvider, so a member that had
854
+ // none registered (provider detected from its remote) would make
855
+ // resolveProvider() throw here -- use the provider the skip named instead.
856
+ const { provider } = skippedProvider ? { provider: skippedProvider } : await resolveProvider(member, { fleetApi });
738
857
  const credentialLabel = vcsCredentialLabelForProvider(provider);
858
+ // The provider's operator-facing remedy, appended to every degraded
859
+ // (authFailure) outcome below when the credential is out-of-band only.
860
+ const skippedRemedy = () => {
861
+ const impl = getVcsProvider(provider);
862
+ return impl && impl.authRemedy && impl.authRemedy.hint ? ` -- ${impl.authRemedy.hint}` : '';
863
+ };
864
+ // Provider-owned explanation of an HTTP failure (e.g. Bitbucket 410/403),
865
+ // appended to failure messages. The hook gets the whole parsed response
866
+ // ({ status, body, headers }) plus what this caller knows (credential
867
+ // store names, member, repo coordinates), so it can name the credential
868
+ // type and scopes the server reported instead of guessing from the
869
+ // status. It answers a string (legacy: diagnosis only) or
870
+ // { hint, remedy }; a non-empty `remedy` REPLACES the provider's generic
871
+ // authRemedy.hint for this failure (see vcs-providers/index.mjs).
872
+ // Returns { hint: ' -- ...'|'', remedy: ' -- ...'|null }.
873
+ let storeNames;
874
+ const statusHint = async (parsed) => {
875
+ const impl = getVcsProvider(provider);
876
+ if (!impl || typeof impl.httpFailureHint !== 'function') return { hint: '', remedy: null };
877
+ const { status } = parsed;
878
+ if (storeNames === undefined && typeof status === 'number' && status >= 400 && status < 500) {
879
+ storeNames = await listCredentialStoreNames(fleetApi);
880
+ }
881
+ const out = impl.httpFailureHint({
882
+ status,
883
+ body: parsed.body,
884
+ headers: parsed.headers || {},
885
+ availableSecrets: storeNames === undefined ? null : storeNames,
886
+ memberName: member,
887
+ repoRef,
888
+ repo,
889
+ });
890
+ if (typeof out === 'string') return { hint: out ? ` -- ${out}` : '', remedy: null };
891
+ const hint = out && typeof out.hint === 'string' && out.hint ? ` -- ${out.hint}` : '';
892
+ const remedy = out && typeof out.remedy === 'string' && out.remedy ? ` -- ${out.remedy}` : null;
893
+ return { hint, remedy };
894
+ };
739
895
 
740
896
  // apra-fleet-3swo.7.6: the orchestrator never learns the token at all now.
741
897
  // It passes the INLINE placeholder as the `token` parameter, so each
@@ -751,6 +907,8 @@ export async function raiseVcsPrForMember({ fleetApi, command, member, base, hea
751
907
  // top-level declarations symbol-for-symbol and a new const desyncs that
752
908
  // census.
753
909
  const token = '{{vcs_token_inline}}';
910
+ // Bitbucket REST authenticates with a Bearer token (the same inline
911
+ // token placeholder as above); no username is sent for any provider.
754
912
  // Both os AND shell feed the command builder: os picks the curl binary
755
913
  // token (curl.exe vs curl), shell picks the quoting dialect. A Windows
756
914
  // member whose registered shell is gitbash needs POSIX quoting, not
@@ -795,8 +953,11 @@ export async function raiseVcsPrForMember({ fleetApi, command, member, base, hea
795
953
  const parsed = parseVcsCurlOutput(h.stdout);
796
954
  const [lo, hi] = b.interpret.successStatusRange;
797
955
  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) {
956
+ // Bitbucket nests its error text at error.message.
957
+ const msg = (parsed.body && typeof parsed.body.message === 'string') ? parsed.body.message
958
+ : (parsed.body && parsed.body.error && typeof parsed.body.error.message === 'string') ? parsed.body.error.message
959
+ : (parsed.bodyText || '');
960
+ if (isPrAuthFailure(parsed.status, msg) && !healed && !skippedProvider) {
800
961
  healed = true;
801
962
  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
963
  try {
@@ -807,19 +968,34 @@ export async function raiseVcsPrForMember({ fleetApi, command, member, base, hea
807
968
  }
808
969
  continue;
809
970
  }
810
- return { ok: false, error: `${what} failed: HTTP ${parsed.status ?? '(unknown)'}: ${msg}` };
971
+ const why = await statusHint(parsed);
972
+ return { ok: false, error: `${what} failed: HTTP ${parsed.status ?? '(unknown)'}: ${msg}${why.hint}${skippedProvider && isPrAuthFailure(parsed.status, msg) ? (why.remedy ?? skippedRemedy()) : ''}` };
811
973
  }
812
974
  };
813
- const updateExistingPr = async () => {
975
+ const coords = () => ({ provider, ...(repoRef ? { repoRef } : { repo }), token, os, shell });
976
+ // Open PRs for head -> base: { ok: true, prs } or { ok: false, error }.
977
+ // Never throws (a missing builder comes back as { ok: false }).
978
+ const findOpenPrs = async () => {
814
979
  try {
815
- const coords = () => ({ provider, ...(repoRef ? { repoRef } : { repo }), token, os, shell });
816
980
  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 };
981
+ if (!found.ok) return found;
982
+ return { ok: true, prs: found.built.mapResponse(found.body) };
983
+ } catch (err) {
984
+ return { ok: false, error: (err && err.message) ? err.message : String(err) };
985
+ }
986
+ };
987
+ // `knownPr` skips the lookup when the caller already found the PR.
988
+ const updateExistingPr = async (knownPr = null) => {
989
+ try {
990
+ let pr = knownPr;
991
+ if (!pr) {
992
+ const found = await findOpenPrs();
993
+ if (!found.ok) return { updated: false, updateError: found.error, prUrl: null };
994
+ if (!found.prs.length) {
995
+ return { updated: false, updateError: `no open pull request found for '${head}' -> '${base}'`, prUrl: null };
996
+ }
997
+ pr = found.prs[0];
821
998
  }
822
- const pr = prs[0];
823
999
  const next = updateExisting({ title: pr.title, body: pr.body }) || {};
824
1000
  let warned = false;
825
1001
  const upd = await runUpdatePathCall(() => {
@@ -842,6 +1018,28 @@ export async function raiseVcsPrForMember({ fleetApi, command, member, base, hea
842
1018
  }
843
1019
  };
844
1020
 
1021
+ // Providers whose create is not an upsert (and whose duplicate-PR
1022
+ // response is unverified) declare `findBeforeCreate`: look up the open PR
1023
+ // for head -> base FIRST and update it in place (preserving the run
1024
+ // history block) instead of POSTing a second PR. A failed lookup falls
1025
+ // through to the normal create path.
1026
+ if (typeof updateExisting === 'function') {
1027
+ const preImpl = getVcsProvider(provider);
1028
+ if (preImpl && preImpl.findBeforeCreate === true) {
1029
+ const pre = await findOpenPrs();
1030
+ if (pre.ok && pre.prs.length) {
1031
+ const pr = pre.prs[0];
1032
+ const upd = await updateExistingPr(pr);
1033
+ const updUrl = upd.prUrl || pr.url;
1034
+ if (updUrl) log(`${logPrefix}: updated PR URL for member '${member}': ${updUrl}`);
1035
+ return { ok: true, alreadyExists: true, prUrl: updUrl, error: null, authFailure: false, updated: upd.updated, updateError: upd.updateError };
1036
+ }
1037
+ if (!pre.ok) {
1038
+ log(`${logPrefix}: could not check for an existing open PR before creating (${pre.error}); creating a new one.`);
1039
+ }
1040
+ }
1041
+ }
1042
+
845
1043
  let authHealAttempted = false;
846
1044
  // apra-fleet PR-body length fix: buildCreatePrCommand deterministically
847
1045
  // truncates `body` to PR_DESCRIPTION_MAX_LENGTH and reports it back via
@@ -890,6 +1088,30 @@ export async function raiseVcsPrForMember({ fleetApi, command, member, base, hea
890
1088
  // failure, so it degrades the same way a failed command() dispatch
891
1089
  // did: returned, not thrown.
892
1090
  if (!handoff.ok && handoff.reason !== 'dispatch_failed') {
1091
+ // Out-of-band-only credential (provision skipped) that is absent:
1092
+ // the operator has not deployed it yet. Degrade to a skipped PR
1093
+ // naming the fix instead of failing the sprint. A just-in-time
1094
+ // minted credential that cannot be read is still a hard failure.
1095
+ // credential_read_failed WITHOUT an exitCode means the read itself
1096
+ // threw (dispatch/connection error): the credential may well be
1097
+ // deployed, so report the read failure and never take the
1098
+ // credentialAbsent path that closes targets without a PR.
1099
+ const transientRead = handoff.reason === 'credential_read_failed' && typeof handoff.exitCode !== 'number';
1100
+ if (skippedProvider && transientRead) {
1101
+ const message = `Could not read the '${credentialLabel}' VCS credential on member '${member}' `
1102
+ + `(transient read failure, vcs_credential_exec reason: ${handoff.reason}): ${handoffText || '(no detail)'}`;
1103
+ log(`${logPrefix}: ${message}`);
1104
+ return { ok: false, alreadyExists: false, prUrl: null, error: message, authFailure: false, credentialReadFailed: true };
1105
+ }
1106
+ if (skippedProvider && ['credential_read_failed', 'credential_empty', 'username_empty'].includes(handoff.reason)) {
1107
+ const message = `No usable '${credentialLabel}' VCS credential is deployed on member '${member}' `
1108
+ + `(vcs_credential_exec reason: ${handoff.reason})${skippedRemedy()}`;
1109
+ log(`${logPrefix}: ${message}`);
1110
+ // credentialAbsent: no PR was possible at all (nothing is
1111
+ // deployed), as opposed to a deployed credential that failed.
1112
+ // Publish PR keeps the pre-PR-support behaviour for it.
1113
+ return { ok: false, alreadyExists: false, prUrl: null, error: message, authFailure: true, credentialAbsent: true };
1114
+ }
893
1115
  throw new Error(
894
1116
  `Failed to read VCS credential token for member '${member}' from the `
895
1117
  + `'${credentialLabel}'-labelled credential helper via vcs_credential_exec `
@@ -901,7 +1123,8 @@ export async function raiseVcsPrForMember({ fleetApi, command, member, base, hea
901
1123
  return { ok: false, alreadyExists: false, prUrl: null, error: failText, authFailure: false };
902
1124
  }
903
1125
 
904
- const { status, body: respBody, bodyText } = parseVcsCurlOutput(handoff.stdout);
1126
+ const parsedResponse = parseVcsCurlOutput(handoff.stdout);
1127
+ const { status, body: respBody, bodyText } = parsedResponse;
905
1128
  const [lo, hi] = built.interpret.successStatusRange;
906
1129
  if (status !== null && status >= lo && status <= hi) {
907
1130
  // apra-fleet-lzfv.5: read the created PR's id/url through the
@@ -916,11 +1139,13 @@ export async function raiseVcsPrForMember({ fleetApi, command, member, base, hea
916
1139
  const mapped = (impl && impl.pullRequestResponse && typeof impl.pullRequestResponse.map === 'function')
917
1140
  ? impl.pullRequestResponse.map(respBody, repoRef ? { repoRef } : { repo })
918
1141
  : { id: null, url: null };
1142
+ if (mapped.url) log(`${logPrefix}: opened PR URL for member '${member}': ${mapped.url}`);
919
1143
  return { ok: true, alreadyExists: false, prUrl: mapped.url, error: null, authFailure: false };
920
1144
  }
921
1145
 
922
1146
  const errorMessages = [];
923
1147
  if (respBody && typeof respBody.message === 'string') errorMessages.push(respBody.message);
1148
+ if (respBody && respBody.error && typeof respBody.error.message === 'string') errorMessages.push(respBody.error.message);
924
1149
  if (respBody && Array.isArray(respBody.errors)) {
925
1150
  for (const e of respBody.errors) {
926
1151
  if (e && typeof e.message === 'string') errorMessages.push(e.message);
@@ -928,7 +1153,7 @@ export async function raiseVcsPrForMember({ fleetApi, command, member, base, hea
928
1153
  }
929
1154
  const errorText = errorMessages.join('; ') || bodyText || `HTTP ${status ?? '(unknown)'}`;
930
1155
 
931
- if (status === built.interpret.alreadyExistsStatus && new RegExp(built.interpret.alreadyExistsPattern, 'i').test(errorText)) {
1156
+ if (built.interpret.alreadyExistsStatus != null && built.interpret.alreadyExistsPattern && status === built.interpret.alreadyExistsStatus && new RegExp(built.interpret.alreadyExistsPattern, 'i').test(errorText)) {
932
1157
  const urlMatch = /https?:\/\/\S+/.exec(errorText);
933
1158
  const existingUrl = urlMatch ? urlMatch[0].replace(/[.,)]+$/, '') : null;
934
1159
  const existing = { ok: true, alreadyExists: true, prUrl: existingUrl, error: null, authFailure: false };
@@ -937,12 +1162,47 @@ export async function raiseVcsPrForMember({ fleetApi, command, member, base, hea
937
1162
  return { ...existing, prUrl: upd.prUrl || existingUrl, updated: upd.updated, updateError: upd.updateError };
938
1163
  }
939
1164
 
940
- if (isPrAuthFailure(status, errorText) && !authHealAttempted) {
1165
+ const authFailed = isPrAuthFailure(status, errorText);
1166
+ if (authFailed && skippedProvider) {
1167
+ // Nothing to re-provision (the provider skipped it), so a retry
1168
+ // would resend the same credential: report it with the remedy.
1169
+ const why = await statusHint(parsedResponse);
1170
+ return { ok: false, alreadyExists: false, prUrl: null, error: `HTTP ${status ?? '(unknown)'}: ${errorText}${why.hint}${why.remedy ?? skippedRemedy()}`, authFailure: true };
1171
+ }
1172
+
1173
+ // A provider whose duplicate-PR response is unverified declares
1174
+ // `probeExistingOnFailure` instead of an alreadyExists dialect: on any
1175
+ // other non-2xx create failure, look for an open PR for head -> base,
1176
+ // and treat a hit as already-exists (then update it like above).
1177
+ if (!authFailed && built.interpret.probeExistingOnFailure) {
1178
+ const found = await findOpenPrs();
1179
+ if (found.ok && found.prs.length) {
1180
+ const pr = found.prs[0];
1181
+ log(`${logPrefix}: PR creation for '${head}' -> '${base}' failed (HTTP ${status ?? '(unknown)'}: ${errorText}) but an open PR already exists for it${pr.url ? `: ${pr.url}` : ''} -- treating as already-exists.`);
1182
+ const existing = { ok: true, alreadyExists: true, prUrl: pr.url, error: null, authFailure: false };
1183
+ if (typeof updateExisting !== 'function') return existing;
1184
+ const upd = await updateExistingPr(pr);
1185
+ return { ...existing, prUrl: upd.prUrl || pr.url, updated: upd.updated, updateError: upd.updateError };
1186
+ }
1187
+ if (!found.ok) {
1188
+ log(`${logPrefix}: could not check for an existing open PR after the create failure (${found.error}); reporting the create failure.`);
1189
+ }
1190
+ }
1191
+
1192
+ if (authFailed && !authHealAttempted) {
941
1193
  authHealAttempted = true;
942
1194
  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
1195
  try {
944
1196
  const reprov = await provisionPrCapableAuthForMember({ fleetApi, command, member, log, logPrefix, remoteUrlOverride });
945
1197
  if (reprov.repo) repo = reprov.repo;
1198
+ if (reprov.provisionSkipped) {
1199
+ // The provider deploys its credential out of band, so the
1200
+ // re-provision ran nothing: no heal happened and a retry
1201
+ // would resend a byte-identical command.
1202
+ log(`${logPrefix}: no PR auth self-heal ran for member '${member}' (provider '${reprov.provider || provider}' skipped re-provisioning); not retrying.`);
1203
+ const why = await statusHint(parsedResponse);
1204
+ return { ok: false, alreadyExists: false, prUrl: null, error: `HTTP ${status ?? '(unknown)'}: ${errorText}${why.hint}${why.remedy ?? skippedRemedy()}`, authFailure: true };
1205
+ }
946
1206
  // No token re-read here any more: `built.command` still
947
1207
  // carries the placeholder, so the retry's own
948
1208
  // vcs_credential_exec dispatch re-reads the FRESHLY
@@ -956,7 +1216,7 @@ export async function raiseVcsPrForMember({ fleetApi, command, member, base, hea
956
1216
  continue;
957
1217
  }
958
1218
 
959
- return { ok: false, alreadyExists: false, prUrl: null, error: `HTTP ${status ?? '(unknown)'}: ${errorText}`, authFailure: isPrAuthFailure(status, errorText) };
1219
+ return { ok: false, alreadyExists: false, prUrl: null, error: `HTTP ${status ?? '(unknown)'}: ${errorText}${(await statusHint(parsedResponse)).hint}`, authFailure: isPrAuthFailure(status, errorText) };
960
1220
  }
961
1221
  }
962
1222
 
@@ -1074,16 +1334,25 @@ export function createVcsAuthSelfHealCallback(opts = {}) {
1074
1334
  let resolved;
1075
1335
  try {
1076
1336
  resolved = await resolveProvider(member, { fleetApi });
1337
+ } catch (resolveErr) {
1338
+ 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}`);
1339
+ }
1340
+ if (resolved) {
1077
1341
  const { provider } = resolved;
1078
1342
  const impl = getVcsProvider(provider);
1079
1343
  if (impl && impl.authRemedy && impl.authRemedy.serverSideReMintable === false) {
1080
1344
  log(`[Sync] self-heal: member '${member}' (${label}) uses '${provider}', whose credentials cannot be re-minted server-side. ${impl.authRemedy.hint}`);
1345
+ // apra-fleet-d1pk.3: re-provisioning a LOCAL member of such a
1346
+ // provider rewrites the host's own credential helper and
1347
+ // cannot mint anything new, so the self-heal refuses it --
1348
+ // and refuses too when the lookup fails (fail closed, F4).
1349
+ await assertNotLocalNonReMintable({ fleetApi, member, provider });
1081
1350
  }
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
1351
  }
1085
-
1086
- await provisionVcsAuthForMember({ fleetApi, command, member, log, logPrefix: '[Sync] self-heal', azdevopsPatSecretName, resolvedProvider: resolved });
1352
+ // When the provider could not be resolved above, the local check has
1353
+ // not run yet: provisionVcsAuthForMember runs it once its own lookup
1354
+ // has named the provider.
1355
+ await provisionVcsAuthForMember({ fleetApi, command, member, log, logPrefix: '[Sync] self-heal', azdevopsPatSecretName, resolvedProvider: resolved, refuseLocalNonReMintable: !resolved });
1087
1356
 
1088
1357
  log(`[Sync] self-heal: credentials re-provisioned for member '${member}' (${label}); the failed command will be retried once.`);
1089
1358
  }
@@ -1128,6 +1397,74 @@ export function selfHealMemoryKey(member, error) {
1128
1397
  return `${member}|${text}`;
1129
1398
  }
1130
1399
 
1400
+ /**
1401
+ * Typed error code the VCS preflight logs (once per member per run) when a
1402
+ * non-re-mintable member's existing credential fails its probe and cannot be
1403
+ * fixed by the fleet. Stable, so log readers and tests match it, not prose.
1404
+ */
1405
+ export const VCS_CREDENTIAL_PROBE_FAILED = 'vcs_credential_probe_failed';
1406
+
1407
+ /**
1408
+ * Typed error code for the local-member guard failing CLOSED: member_detail
1409
+ * could not say whether a member is local, so a credential the fleet cannot
1410
+ * mint is NOT provisioned (on a local member it would overwrite the host's own
1411
+ * credential helper). Stable, so log readers and tests match it, not prose.
1412
+ */
1413
+ export const VCS_MEMBER_LOOKUP_FAILED = 'vcs_member_lookup_failed';
1414
+
1415
+ /**
1416
+ * Throw unless `member` is known NOT to be a local member, when `provider` is
1417
+ * one whose credential the fleet cannot mint (authRemedy.serverSideReMintable
1418
+ * === false). Re-provisioning a local member of such a provider rewrites the
1419
+ * host's own credential helper, so: a local record -> refuse; a member_detail
1420
+ * failure or non-record answer -> refuse with VCS_MEMBER_LOOKUP_FAILED (fail
1421
+ * closed, never provision on an unknown member type). Any other provider is a
1422
+ * no-op. Messages are ASCII-only.
1423
+ * @param {{ fleetApi: object, member: string, provider: string }} opts
1424
+ */
1425
+ async function assertNotLocalNonReMintable({ fleetApi, member, provider }) {
1426
+ const impl = getVcsProvider(provider);
1427
+ if (!impl || !impl.authRemedy || impl.authRemedy.serverSideReMintable !== false) return;
1428
+ let record = null;
1429
+ let why = 'member_detail did not return a member record';
1430
+ try {
1431
+ record = await readMemberRecord(member, fleetApi);
1432
+ } catch (err) {
1433
+ why = `member_detail failed: ${err && err.message ? err.message : String(err)}`;
1434
+ }
1435
+ if (!record) {
1436
+ const err = new Error(
1437
+ `ERROR ${VCS_MEMBER_LOOKUP_FAILED}: could not confirm member '${member}' is not a local member (${why}); `
1438
+ + `not provisioning its '${provider}' credential, which on a local member would overwrite the host's own credential. `
1439
+ + 'Retry once the fleet server answers member_detail for this member.',
1440
+ );
1441
+ err.message = err.message.replace(/[^\x20-\x7e]+/g, ' ');
1442
+ err.code = VCS_MEMBER_LOOKUP_FAILED;
1443
+ throw err;
1444
+ }
1445
+ if (record.type === 'local') {
1446
+ throw new Error(`member '${member}' is a local member on '${provider}': not re-provisioning it, which would overwrite the host's own credential; fix the host's credential instead.`);
1447
+ }
1448
+ }
1449
+
1450
+ /**
1451
+ * Parsed member_detail JSON for `member` (type, os, shell, vcsProvider, ...),
1452
+ * or null when the response is not JSON (e.g. an unknown member's plain-text
1453
+ * answer). A failing memberDetail() call rejects; callers decide.
1454
+ * @param {string} member
1455
+ * @param {{ memberDetail: Function }} fleetApi
1456
+ * @returns {Promise<object|null>}
1457
+ */
1458
+ async function readMemberRecord(member, fleetApi) {
1459
+ const res = await fleetApi.memberDetail({ member_name: member, format: 'json' });
1460
+ try {
1461
+ const parsed = JSON.parse(resultText(res));
1462
+ return parsed && typeof parsed === 'object' ? parsed : null;
1463
+ } catch {
1464
+ return null;
1465
+ }
1466
+ }
1467
+
1131
1468
  // How far ahead of a credential's known expiry the preflight treats it as
1132
1469
  // "expiring soon" and re-provisions early, rather than letting it lapse
1133
1470
  // mid-dispatch. Mirrors the server's own EXPIRY_WARNING_MS threshold
@@ -1165,8 +1502,244 @@ export function createVcsAuthPreflightCallback(opts = {}) {
1165
1502
  const fleetApi = new ApraFleet({ callTool });
1166
1503
  /** @type {Map<string, Date|null>} member -> last-known expiresAt (null = no expiry tracked, e.g. PAT mode). */
1167
1504
  const knownGoodUntil = new Map();
1505
+ // apra-fleet-d1pk.3: PROBE-FIRST branch for members whose credential the
1506
+ // fleet cannot mint (provider authRemedy.serverSideReMintable === false,
1507
+ // e.g. Bitbucket API tokens, Azure DevOps PATs). Provisioning such a
1508
+ // member just redeploys a stored secret -- and on a LOCAL member it
1509
+ // rewrites the host's own git credential helper -- so the preflight first
1510
+ // asks whether the credential ALREADY in place works (a non-interactive
1511
+ // `git ls-remote origin HEAD`, see getSeCommands().gitLsRemoteProbe()),
1512
+ // and decides once per member per run:
1513
+ // 'ok' -- probe passed, or a remote member was provisioned after a
1514
+ // failed probe: never probe or provision again this run.
1515
+ // 'failed' -- one typed ERROR line naming the provider remedy was
1516
+ // logged; never re-probed, re-provisioned or re-logged.
1517
+ // A GitHub-App (server-side re-mintable) member never enters this branch
1518
+ // and keeps the expiry-based refresh below exactly as before.
1519
+ /** @type {Map<string, { probe: boolean, provider?: string, impl?: object, local?: boolean, target?: { os: string, shell: string } }>} */
1520
+ const plans = new Map();
1521
+ /** @type {Map<string, 'ok'|'failed'>} */
1522
+ const probeVerdicts = new Map();
1523
+
1524
+ async function planFor(member) {
1525
+ if (plans.has(member)) return plans.get(member);
1526
+ let plan = { probe: false };
1527
+ const record = await readMemberRecord(member, fleetApi);
1528
+ if (record) {
1529
+ let provider = typeof record.vcsProvider === 'string' && getVcsProvider(record.vcsProvider) ? record.vcsProvider : null;
1530
+ if (!provider) {
1531
+ // No registered provider: detect it from the member's own
1532
+ // remote with the same anchored auth-host match the
1533
+ // provisioning path's LAYER 2 fallback uses, so an
1534
+ // unregistered local Bitbucket member is never provisioned.
1535
+ const remoteRes = await command('git remote get-url origin', { member_name: member, silent: true, failSoft: true });
1536
+ const remoteUrl = remoteRes && remoteRes.ok ? String(remoteRes.output || '').trim() : '';
1537
+ provider = remoteUrl ? detectVcsProviderFromRemote(remoteUrl) : null;
1538
+ }
1539
+ const impl = provider ? getVcsProvider(provider) : null;
1540
+ if (impl && impl.authRemedy && impl.authRemedy.serverSideReMintable === false) {
1541
+ plan = {
1542
+ probe: true,
1543
+ provider,
1544
+ impl,
1545
+ local: record.type === 'local',
1546
+ target: { os: typeof record.os === 'string' ? record.os : '', shell: typeof record.shell === 'string' ? record.shell : '' },
1547
+ };
1548
+ }
1549
+ }
1550
+ plans.set(member, plan);
1551
+ return plan;
1552
+ }
1553
+
1554
+ // `remedy` (when given) replaces the provider's generic authRemedy.hint:
1555
+ // a credentialProbe provider words its own member-specific fix.
1556
+ // `noPr` appends the consequence for the labelled PR credential.
1557
+ function logProbeFailure(member, plan, why, { remedy = null, noPr = false } = {}) {
1558
+ const where = plan.local ? 'local member' : 'member';
1559
+ const consequence = noPr
1560
+ ? ` No PR will be opened this sprint for member '${member}': Publish PR reads this same '${vcsCredentialLabelForProvider(plan.provider)}' credential (the sprint continues and the skipped PR is reported in its final status).`
1561
+ : '';
1562
+ const line = `[Sync] preflight: ERROR ${VCS_CREDENTIAL_PROBE_FAILED}: ${where} '${member}' (provider '${plan.provider}') cannot reach its origin with the credential already in place: ${why}. ${remedy || plan.impl.authRemedy.hint}${consequence}`;
1563
+ // ASCII only, whatever git or the member shell printed.
1564
+ log(line.replace(/[^\x20-\x7e]+/g, ' '));
1565
+ }
1566
+
1567
+ // The provider's credentialProbe (see vcs-providers/index.mjs) checks the
1568
+ // credential Publish PR will actually read -- the provider-labelled
1569
+ // fleet helper -- instead of trusting git ls-remote, which goes through
1570
+ // the host's whole credential helper chain where ANOTHER helper (a
1571
+ // system credential manager, a global store) can answer for a broken
1572
+ // fleet helper. Two checks, both on that labelled credential:
1573
+ // 1. the provider's REST probe through vcs_credential_exec with the
1574
+ // provider label and the {{vcs_token_inline}} placeholder -- the
1575
+ // same server-side handoff as the PR path, so the token never
1576
+ // reaches this process;
1577
+ // 2. the helper's username= line (read member-side, filtered there so
1578
+ // the token line never leaves the member) against the provider's
1579
+ // expectedUsername; an unresolved {{...}} placeholder literal is
1580
+ // named as such, any other value is NOT printed.
1581
+ // Returns { ok, reasons: string[], remedy: string|null }. Never throws.
1582
+ let storeNames;
1583
+ async function checkLabelledCredential(member, plan) {
1584
+ const probe = plan.impl.credentialProbe;
1585
+ const label = vcsCredentialLabelForProvider(plan.provider);
1586
+ const reasons = [];
1587
+ let remedy = null;
1588
+ if (storeNames === undefined) storeNames = await listCredentialStoreNames(fleetApi);
1589
+ const availableSecrets = storeNames;
1590
+
1591
+ const remoteRes = await command('git remote get-url origin', { member_name: member, silent: true, failSoft: true });
1592
+ const remoteUrl = remoteRes && remoteRes.ok ? String(remoteRes.output || '').trim() : '';
1593
+ const repoRef = remoteUrl && typeof plan.impl.parseRepoRef === 'function' ? plan.impl.parseRepoRef(remoteUrl) : null;
1594
+ const remedyCtx = { availableSecrets, memberName: member, repoRef, local: plan.local };
1595
+
1596
+ if (!repoRef) {
1597
+ // The raw origin may embed a credential (https://user:TOKEN@host/...,
1598
+ // which git prints verbatim): quote it with the userinfo masked.
1599
+ const shown = remoteUrl ? ` '${redactUrlUserinfo(remoteUrl)}'` : ' (unreadable)';
1600
+ reasons.push(`the REST credential probe could not run: no ${plan.provider} repository could be derived from the member's origin remote${shown}`);
1601
+ } else if (!fleetApi || typeof fleetApi.vcsCredentialExec !== 'function') {
1602
+ reasons.push('the REST credential probe could not run: this fleet client exposes no vcs_credential_exec tool');
1603
+ } else {
1604
+ const built = probe.build({ repoRef, token: '{{vcs_token_inline}}', os: plan.target.os, shell: plan.target.shell });
1605
+ let handoff = {};
1606
+ try {
1607
+ const execRes = await fleetApi.vcsCredentialExec({ member_name: member, label, command: built.command });
1608
+ handoff = (execRes && execRes.structuredContent) || {};
1609
+ } catch (err) {
1610
+ handoff = { ok: false, reason: 'dispatch_failed', stderr: err && err.message ? err.message : String(err) };
1611
+ }
1612
+ if (!handoff.ok) {
1613
+ reasons.push(`the '${label}' fleet credential helper could not be used for the REST probe (vcs_credential_exec reason: ${handoff.reason || 'unknown'})`);
1614
+ } else {
1615
+ const parsed = parseVcsCurlOutput(handoff.stdout);
1616
+ const [lo, hi] = built.interpret.successStatusRange;
1617
+ if (!(typeof handoff.exitCode !== 'number' || handoff.exitCode === 0) || parsed.status === null) {
1618
+ reasons.push(`the REST credential probe (${built.logSafeCommand}) did not complete (exit ${handoff.exitCode ?? 'unknown'}${handoff.stderr ? `: ${String(handoff.stderr).trim().slice(0, 200)}` : ''})`);
1619
+ } else if (parsed.status < lo || parsed.status > hi) {
1620
+ const out = typeof plan.impl.httpFailureHint === 'function'
1621
+ ? plan.impl.httpFailureHint({ status: parsed.status, body: parsed.body, headers: parsed.headers, ...remedyCtx })
1622
+ : '';
1623
+ const hint = typeof out === 'string' ? out : (out && out.hint) || '';
1624
+ if (out && typeof out === 'object' && out.remedy) remedy = out.remedy;
1625
+ reasons.push(`the '${label}' fleet credential Publish PR uses was refused by the REST probe with HTTP ${parsed.status}${hint ? `: ${hint}` : ''}`);
1626
+ }
1627
+ }
1628
+ }
1629
+
1630
+ if (typeof probe.expectedUsername === 'string') {
1631
+ const read = getSeCommands(plan.target).readCredentialHelperUsername(label);
1632
+ let userRes;
1633
+ try {
1634
+ userRes = await command(read.command, { member_name: member, silent: true, failSoft: true });
1635
+ } catch (err) {
1636
+ userRes = { ok: false, output: '' };
1637
+ }
1638
+ // Only the username= line is ever looked at, even if a broken
1639
+ // member-side filter let more through.
1640
+ const m = /^username=(.*)$/m.exec(String((userRes && userRes.output) || ''));
1641
+ const username = m ? m[1].trim() : '';
1642
+ if (!m) {
1643
+ reasons.push(`the '${label}' fleet credential helper (${read.descriptor}) printed no username= line (missing helper, or written without a username)`);
1644
+ } else if (username !== probe.expectedUsername) {
1645
+ reasons.push(/^\{\{\s*[A-Za-z]+\.[A-Za-z0-9_.-]+\s*\}\}$/.test(username)
1646
+ ? `the '${label}' fleet credential helper's username line is the unresolved placeholder literal ${username}, not ${probe.expectedUsername} (it was written without placeholder resolution)`
1647
+ : `the '${label}' fleet credential helper's username line is not ${probe.expectedUsername} (it was written by something other than provision_vcs_auth for this provider)`);
1648
+ }
1649
+ }
1650
+
1651
+ if (!remedy && reasons.length && typeof probe.remedy === 'function') remedy = probe.remedy(remedyCtx);
1652
+ return { ok: reasons.length === 0, reasons, remedy };
1653
+ }
1654
+
1655
+ async function probeFirst(member, plan) {
1656
+ const verdict = probeVerdicts.get(member);
1657
+ if (verdict) {
1658
+ log(verdict === 'ok'
1659
+ ? `[Sync] preflight: provision_vcs_auth skipped for member '${member}': its '${plan.provider}' credential already passed this run's probe.`
1660
+ : `[Sync] preflight: provision_vcs_auth skipped for member '${member}': its '${plan.provider}' credential probe already failed this run (reported once above).`);
1661
+ return;
1662
+ }
1663
+ const restProbe = !!(plan.impl.credentialProbe && typeof plan.impl.credentialProbe.build === 'function');
1664
+ const restNote = restProbe ? `, plus a REST probe of the '${vcsCredentialLabelForProvider(plan.provider)}' credential Publish PR uses` : '';
1665
+ log(`[Sync] preflight: probing member '${member}''s existing '${plan.provider}' credential (git ls-remote origin, non-interactive${restNote}) instead of provisioning.`);
1666
+ let res;
1667
+ try {
1668
+ res = await command(getSeCommands(plan.target).gitLsRemoteProbe(), { member_name: member, silent: true, failSoft: true });
1669
+ } catch (err) {
1670
+ res = { ok: false, error: err && err.message ? err.message : String(err) };
1671
+ }
1672
+ const gitOk = !!(res && res.ok);
1673
+ const detail = gitOk ? '' : String((res && (res.error || res.output)) || 'git ls-remote origin failed').trim().split(/\r?\n/).filter(Boolean).slice(-2).join(' / ').slice(0, 300);
1674
+ // Both must pass for a credentialProbe provider: ls-remote alone can
1675
+ // be answered by another host helper while the labelled one is dead.
1676
+ const cred = restProbe ? await checkLabelledCredential(member, plan) : { ok: true, reasons: [], remedy: null };
1677
+ if (gitOk && cred.ok) {
1678
+ probeVerdicts.set(member, 'ok');
1679
+ log(`[Sync] preflight: member '${member}''s existing '${plan.provider}' credential works; provision_vcs_auth skipped for this run.`);
1680
+ return;
1681
+ }
1682
+ const why = [gitOk ? '' : (restProbe ? `git ls-remote origin failed: ${detail}` : detail), ...cred.reasons].filter(Boolean).join('; ');
1683
+ if (plan.local) {
1684
+ // Never provision a LOCAL non-re-mintable member: it would
1685
+ // rewrite the host operator's own credential helper.
1686
+ //
1687
+ // DECISION (documented in docs/fleet-sprint-getting-started.md):
1688
+ // a failed labelled-credential probe on a local member does NOT
1689
+ // stop the sprint. It is reported once, here, at preflight time
1690
+ // with the exact by-hand fix; the sprint keeps going, Publish PR
1691
+ // skips the PR (its credential is this same dead one) and the
1692
+ // final status surfaces the skipped PR. Stopping the launch would
1693
+ // throw away a whole sprint over a PR that the operator can open
1694
+ // by hand after fixing the helper.
1695
+ probeVerdicts.set(member, 'failed');
1696
+ logProbeFailure(member, plan, `${why}; not provisioning a local member, which would overwrite the host's own credential`, { remedy: cred.remedy, noPr: !cred.ok });
1697
+ return;
1698
+ }
1699
+ // A remote member gets exactly ONE non-interactive provision attempt;
1700
+ // for a credentialProbe provider the labelled credential is re-probed
1701
+ // after it and that re-probe decides the verdict.
1702
+ try {
1703
+ const { expiresAt } = await provisionVcsAuthForMember({ fleetApi, command, member, log, logPrefix: '[Sync] preflight', azdevopsPatSecretName, refuseLocalNonReMintable: true });
1704
+ knownGoodUntil.set(member, expiresAt);
1705
+ } catch (err) {
1706
+ probeVerdicts.set(member, 'failed');
1707
+ logProbeFailure(member, plan, `${why}; provision_vcs_auth also failed: ${err.message}`, { remedy: cred.remedy, noPr: !cred.ok });
1708
+ return;
1709
+ }
1710
+ if (restProbe) {
1711
+ const again = await checkLabelledCredential(member, plan);
1712
+ if (!again.ok) {
1713
+ probeVerdicts.set(member, 'failed');
1714
+ logProbeFailure(member, plan, `${why}; provision_vcs_auth ran once, but the re-probe still fails: ${again.reasons.join('; ')}`, { remedy: again.remedy, noPr: true });
1715
+ return;
1716
+ }
1717
+ }
1718
+ probeVerdicts.set(member, 'ok');
1719
+ log(`[Sync] preflight: provision_vcs_auth succeeded for member '${member}' after its credential probe failed.`);
1720
+ }
1168
1721
 
1169
1722
  return async function ensureVcsAuthFresh(member) {
1723
+ let plan;
1724
+ try {
1725
+ plan = await planFor(member);
1726
+ } catch (err) {
1727
+ // Fail CLOSED: without the record this cannot tell a local member
1728
+ // (whose host credential must never be overwritten) from a remote
1729
+ // one, so nothing is provisioned. Not cached: the next call
1730
+ // retries the lookup. Still never throws (see above).
1731
+ const line = `[Sync] preflight: ERROR ${VCS_MEMBER_LOOKUP_FAILED}: could not read member '${member}''s record (member_detail) to choose probe vs provision; provision_vcs_auth skipped for member '${member}' (fail closed, a local member's host credential must not be overwritten): ${err && err.message ? err.message : String(err)}`;
1732
+ log(line.replace(/[^\x20-\x7e]+/g, ' '));
1733
+ return;
1734
+ }
1735
+ if (plan.probe) {
1736
+ try {
1737
+ await probeFirst(member, plan);
1738
+ } catch (err) {
1739
+ log(`[Sync] preflight: credential probe for member '${member}' failed unexpectedly (continuing): ${err.message}`);
1740
+ }
1741
+ return;
1742
+ }
1170
1743
  if (knownGoodUntil.has(member)) {
1171
1744
  const expiresAt = knownGoodUntil.get(member);
1172
1745
  if (expiresAt === null || expiresAt.getTime() - now() > VCS_AUTH_EXPIRY_PREFLIGHT_MS) {
@@ -1182,7 +1755,7 @@ export function createVcsAuthPreflightCallback(opts = {}) {
1182
1755
  }
1183
1756
  log(`[Sync] preflight: ensuring member '${member}' has a fresh VCS credential before dispatch; calling provision_vcs_auth.`);
1184
1757
  try {
1185
- const { expiresAt } = await provisionVcsAuthForMember({ fleetApi, command, member, log, logPrefix: '[Sync] preflight', azdevopsPatSecretName });
1758
+ const { expiresAt } = await provisionVcsAuthForMember({ fleetApi, command, member, log, logPrefix: '[Sync] preflight', azdevopsPatSecretName, refuseLocalNonReMintable: true });
1186
1759
  knownGoodUntil.set(member, expiresAt);
1187
1760
  log(`[Sync] preflight: provision_vcs_auth succeeded for member '${member}'${expiresAt ? ` (expires ${expiresAt.toISOString()})` : ''}.`);
1188
1761
  } catch (err) {