@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
@@ -14,6 +14,7 @@
14
14
  // GET /api/sprints/:id LIVE child state proxied from the child's /state
15
15
  // when running, else the historical record
16
16
  // POST /api/sprints/:id/stop proxy the child's own cooperative /stop endpoint
17
+ // POST /api/sprints/:id/decisions/:decisionId answer a pending operator decision (proxied to the child)
17
18
  //
18
19
  // SINGLE SOURCE OF TRUTH FOR VALIDATION (acceptance criterion): request
19
20
  // validation REUSES the exported runner.js helpers validateIssueId /
@@ -42,11 +43,12 @@ import { statSync } from 'node:fs';
42
43
  import { fileURLToPath } from 'node:url';
43
44
 
44
45
  import { readJsonBody, sendJson } from './server.mjs';
46
+ import { validateDecisionNotify } from '../../fleet-sprint/decision-notify.mjs';
45
47
  import { validateIssueId, validateBranchName, validateBranchPair } from '../../fleet-sprint/runner.js';
46
48
  import { resolveRoleMap } from '../../bin/cli.mjs';
47
49
  import { resolveBacklogRoleAlias, ROLE_BACKLOG } from '../../fleet-sprint/backlog-role.mjs';
48
50
  import { normalizeRole } from '../../fleet-sprint/contracts.mjs';
49
- import { isDeterministicTerminalReason } from './history.mjs';
51
+ import { isDeterministicTerminalReason, HISTORY_EVENTS } from './history.mjs';
50
52
  import { defaultHasTerminalState } from './watchdog.mjs';
51
53
  import { toBeadsSummary } from './beads-identity.mjs';
52
54
  import { fleetMembersUnavailableReason, fleetMembersStoppedByUserReason } from './fleet-members.mjs';
@@ -295,16 +297,67 @@ export function proxyChildStop(port, opts = {}) {
295
297
  const host = opts.host ?? '127.0.0.1';
296
298
  const timeoutMs = Number.isInteger(opts.timeoutMs) ? opts.timeoutMs : 2000;
297
299
  return new Promise((resolve, reject) => {
298
- const req = http.request({ host, port, path: '/stop', method: 'POST', timeout: timeoutMs }, (res) => {
300
+ // The child viewer's POST routes require a JSON content type
301
+ // (request-guard.mjs), so send an empty JSON object.
302
+ const data = Buffer.from('{}', 'utf-8');
303
+ const req = http.request({
304
+ host, port, path: '/stop', method: 'POST', timeout: timeoutMs,
305
+ headers: { 'content-type': 'application/json', 'content-length': data.length },
306
+ }, (res) => {
299
307
  res.resume();
300
308
  res.on('end', () => resolve({ statusCode: res.statusCode }));
301
309
  });
302
310
  req.on('timeout', () => { req.destroy(new Error('child /stop timed out')); });
303
311
  req.on('error', reject);
304
- req.end();
312
+ req.end(data);
305
313
  });
306
314
  }
307
315
 
316
+ /**
317
+ * Default child HTTP proxy: POST a JSON body to the child viewer's generic
318
+ * extension action route (`/extensions/:extId/actions/:actionId`) and return
319
+ * { statusCode, body } (body parsed when JSON).
320
+ */
321
+ export function proxyChildAction(port, extId, actionId, payload, opts = {}) {
322
+ const host = opts.host ?? '127.0.0.1';
323
+ const timeoutMs = Number.isInteger(opts.timeoutMs) ? opts.timeoutMs : 30000;
324
+ const data = Buffer.from(JSON.stringify(payload ?? {}), 'utf-8');
325
+ return new Promise((resolve, reject) => {
326
+ const req = http.request({
327
+ host, port, method: 'POST', timeout: timeoutMs,
328
+ path: `/extensions/${encodeURIComponent(extId)}/actions/${encodeURIComponent(actionId)}`,
329
+ headers: { 'content-type': 'application/json', 'content-length': data.length },
330
+ }, (res) => {
331
+ const chunks = [];
332
+ res.on('data', (c) => chunks.push(c));
333
+ res.on('end', () => {
334
+ const text = Buffer.concat(chunks).toString('utf-8');
335
+ let body = null;
336
+ try { body = text ? JSON.parse(text) : null; } catch { body = { error: text.slice(0, 200) }; }
337
+ resolve({ statusCode: res.statusCode, body });
338
+ });
339
+ });
340
+ req.on('timeout', () => { req.destroy(new Error('child action timed out')); });
341
+ req.on('error', reject);
342
+ req.end(data);
343
+ });
344
+ }
345
+
346
+ /** Longest operator answer the decision-answer route accepts. */
347
+ export const DECISION_ANSWER_MAX_CHARS = 4000;
348
+
349
+ /**
350
+ * Pulls the pending-decision view out of a child /state payload: the decisions
351
+ * extension's summary (never leaned, so the question and options are whole).
352
+ * @param {object|null|undefined} state
353
+ * @returns {{ pendingDecisions: object[], decisionState: string|null }}
354
+ */
355
+ export function decisionsFromChildState(state) {
356
+ const d = state && state.summary && state.summary.extensions && state.summary.extensions.decisions;
357
+ const pendingDecisions = d && Array.isArray(d.pending) ? d.pending : [];
358
+ return { pendingDecisions, decisionState: d && typeof d.state === 'string' ? d.state : null };
359
+ }
360
+
308
361
  /**
309
362
  * apra-fleet-gey.2: default build-version stamp -- this module's own on-disk
310
363
  * mtime. This package runs directly from source (no separate compiled
@@ -403,6 +456,7 @@ export function createSprintController(deps = {}) {
403
456
  const getBacklog = deps.getBacklog ?? (() => ({ tasks: [] }));
404
457
  const proxyState = deps.proxyState ?? proxyChildState;
405
458
  const proxyStop = deps.proxyStop ?? proxyChildStop;
459
+ const proxyAction = deps.proxyAction ?? proxyChildAction;
406
460
  const roleMapResolver = deps.resolveRoleMap ?? resolveRoleMap;
407
461
  const beadsIdentity = deps.beadsIdentity ?? null;
408
462
  const backlogMemberHandle = deps.backlogMember && typeof deps.backlogMember.get === 'function' ? deps.backlogMember : null;
@@ -495,7 +549,28 @@ export function createSprintController(deps = {}) {
495
549
  // buildSprintArgv/cli.mjs's --issue flag expects, and byte-identical
496
550
  // to the input for the single-id case); `issueIds` is the split array
497
551
  // callers use for issueRoots / per-root history lookups.
498
- return { issue: issueIds.join(','), issueIds, branch, base, members, skipRegression };
552
+ // decisionNotify (optional): same JSON shape as the CLI's
553
+ // --decision-notify; validated here so a bad value is a 400 before any
554
+ // spawn. Forwarded to the child as a JSON string; credentials never
555
+ // travel in the body (validateDecisionNotify rejects unknown keys).
556
+ let decisionNotify;
557
+ if (body.decisionNotify !== undefined && body.decisionNotify !== null && body.decisionNotify !== '') {
558
+ try { validateDecisionNotify(body.decisionNotify); }
559
+ catch (err) { throw new ApiError(400, err.message, 'decisionNotify'); }
560
+ decisionNotify = typeof body.decisionNotify === 'string' ? body.decisionNotify : JSON.stringify(body.decisionNotify);
561
+ }
562
+ // kbDemotionLoop (optional): the reviewer KB demotion loop switch, "on"
563
+ // (the engine default) or "off" -- the same values as the CLI's
564
+ // --kb-demotion-loop. Anything else is a 400 before any spawn; omitted
565
+ // means the child is launched without the flag (engine default).
566
+ let kbDemotionLoop;
567
+ if (body.kbDemotionLoop !== undefined) {
568
+ if (body.kbDemotionLoop !== 'on' && body.kbDemotionLoop !== 'off') {
569
+ throw new ApiError(400, `kbDemotionLoop must be "on" or "off", got ${JSON.stringify(body.kbDemotionLoop)}`, 'kbDemotionLoop');
570
+ }
571
+ kbDemotionLoop = body.kbDemotionLoop;
572
+ }
573
+ return { issue: issueIds.join(','), issueIds, branch, base, members, skipRegression, kbDemotionLoop, decisionNotify };
499
574
  }
500
575
 
501
576
  // -- GET /api/members : list_members + live-reservation overlay -----------
@@ -536,7 +611,7 @@ export function createSprintController(deps = {}) {
536
611
 
537
612
  // -- POST /api/sprints : validated, goal-forwarding launch ----------------
538
613
  async function launch(body = {}) {
539
- const { issue, issueIds, branch, base, members, skipRegression } = validateLaunchRequest(body);
614
+ const { issue, issueIds, branch, base, members, skipRegression, kbDemotionLoop, decisionNotify } = validateLaunchRequest(body);
540
615
  // An '@file' roleMap is a CLI-only convenience: over HTTP it would make
541
616
  // the supervisor read an arbitrary server-side path named by the request
542
617
  // body, and the alias warning could not be computed from it. Reject it.
@@ -713,6 +788,8 @@ export function createSprintController(deps = {}) {
713
788
  budget: body.budget,
714
789
  runId: sprintId,
715
790
  skipRegression,
791
+ kbDemotionLoop,
792
+ decisionNotify,
716
793
  };
717
794
  let spawned;
718
795
  try {
@@ -808,18 +885,43 @@ export function createSprintController(deps = {}) {
808
885
  // and surfacing a raw ECONNREFUSED-derived 500.
809
886
  const terminalState = hasTerminalState(id, reservation.branch ?? null);
810
887
  if (terminalState) {
811
- return { sprintId: id, live: false, terminal: true, state: terminalState };
888
+ // Lift the run's own terminal status + warnings (e.g.
889
+ // success-with-warnings when the PR was skipped for an auth
890
+ // failure) so consumers need not dig through state.result.
891
+ const res = terminalState && typeof terminalState === 'object' ? terminalState.result : null;
892
+ const resultStatus = res && typeof res === 'object' && typeof res.status === 'string' ? res.status : null;
893
+ const warnings = res && typeof res === 'object' && Array.isArray(res.warnings) ? res.warnings : [];
894
+ return {
895
+ sprintId: id, live: false, terminal: true, state: terminalState,
896
+ ...(resultStatus ? { resultStatus } : {}),
897
+ ...(warnings.length > 0 ? { warnings } : {}),
898
+ };
812
899
  }
813
900
  const port = resolvePort(reservation.childPid ?? null);
814
901
  if (port != null) {
815
902
  const state = await proxyState(port);
816
- return { sprintId: id, live: true, state };
903
+ // pendingDecisions (full, untruncated) and the run state while
904
+ // paused for a decision, lifted from the child's decisions summary.
905
+ const { pendingDecisions, decisionState } = decisionsFromChildState(state);
906
+ return {
907
+ sprintId: id, live: true, state, pendingDecisions,
908
+ ...(decisionState ? { decisionState } : {}),
909
+ ...(decisionState === 'paused-awaiting-decision' ? { runState: decisionState } : {}),
910
+ };
817
911
  }
818
912
  }
819
913
  // Not live (finished/gone, or port unknown): return the historical record.
820
914
  const latest = history.latestFor(id);
821
915
  if (latest) {
822
- return { sprintId: id, live: false, history: history.forSprint(id), latest };
916
+ // Lift the FINISHED event's resultStatus + warnings (e.g. PR skipped
917
+ // for auth failure) so they stay visible after the reservation release.
918
+ const fin = history.forSprint(id).filter((e) => e.event === HISTORY_EVENTS.FINISHED).pop();
919
+ const warnings = fin && Array.isArray(fin.warnings) ? fin.warnings : [];
920
+ return {
921
+ sprintId: id, live: false, history: history.forSprint(id), latest,
922
+ ...(fin && fin.resultStatus ? { resultStatus: fin.resultStatus } : {}),
923
+ ...(warnings.length > 0 ? { warnings } : {}),
924
+ };
823
925
  }
824
926
  throw new ApiError(404, `no sprint '${id}' is live or in history`);
825
927
  }
@@ -850,8 +952,31 @@ export function createSprintController(deps = {}) {
850
952
  return { sprintId: id, status: 'stopping', child: result ?? null };
851
953
  }
852
954
 
955
+ // -- POST /api/sprints/:id/decisions/:decisionId : answer a decision -------
956
+ async function answerDecision(id, decisionId, body) {
957
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
958
+ throw new ApiError(400, 'request body must be a JSON object', 'body');
959
+ }
960
+ if (typeof body.answer !== 'string' || !body.answer.trim()) {
961
+ throw new ApiError(400, 'answer is required (a non-empty string)', 'answer');
962
+ }
963
+ if (body.answer.length > DECISION_ANSWER_MAX_CHARS) {
964
+ throw new ApiError(400, `answer is longer than ${DECISION_ANSWER_MAX_CHARS} characters`, 'answer');
965
+ }
966
+ const reservation = ledger.get(id);
967
+ if (!reservation) throw new ApiError(404, `no live sprint '${id}'`);
968
+ const port = resolvePort(reservation.childPid ?? null);
969
+ if (port == null) throw new ApiError(409, `sprint '${id}' has no reachable child (port unknown)`);
970
+ const out = await proxyAction(port, 'decisions', 'answer', { decisionId, answer: body.answer });
971
+ if (out.statusCode === 404) throw new ApiError(404, `no pending decision '${decisionId}' in sprint '${id}'`);
972
+ if (out.statusCode === 400) throw new ApiError(400, (out.body && out.body.error) || 'bad decision answer', 'answer');
973
+ if (out.statusCode !== 200) throw new ApiError(409, (out.body && out.body.error) || `decision answer failed (${out.statusCode})`);
974
+ return { sprintId: id, decisionId, status: (out.body && out.body.status) || 'recorded', released: (out.body && out.body.released) || [] };
975
+ }
976
+
853
977
  return {
854
978
  name: 'sprint-controller',
979
+ answerDecision,
855
980
  members,
856
981
  backlog,
857
982
  launch,
@@ -909,6 +1034,21 @@ export function registerSprintRoutes(supervisor, controller) {
909
1034
  }
910
1035
  });
911
1036
 
1037
+ supervisor.route('POST', '/api/sprints/:id/decisions/:decisionId', async (req, res, ctx) => {
1038
+ let body;
1039
+ try {
1040
+ body = (await readJsonBody(req)) ?? {};
1041
+ } catch (err) {
1042
+ sendJson(res, 400, { error: String(err && err.message ? err.message : err), field: 'body' });
1043
+ return;
1044
+ }
1045
+ try {
1046
+ sendJson(res, 200, await controller.answerDecision(ctx.params.id, ctx.params.decisionId, body));
1047
+ } catch (err) {
1048
+ if (!onApiError(res, err)) throw err;
1049
+ }
1050
+ });
1051
+
912
1052
  supervisor.route('POST', '/api/sprints/:id/stop', async (req, res, ctx) => {
913
1053
  try {
914
1054
  sendJson(res, 200, await controller.stopSprint(ctx.params.id));
@@ -705,7 +705,7 @@ const SPRINT_PAUSE_SCRIPT = `
705
705
  var resultEl = document.querySelector('.pause-result[data-sprint-id="' + sprintId + '"]');
706
706
  btn.disabled = true;
707
707
  if (resultEl) { resultEl.style.color = '#a1a1aa'; resultEl.textContent = (action === 'pause' ? 'Pause' : 'Resume') + ' requested...'; }
708
- fetch('/sprints/' + encodeURIComponent(sprintId) + '/live/' + action, { method: 'POST' })
708
+ fetch('/sprints/' + encodeURIComponent(sprintId) + '/live/' + action, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' })
709
709
  .then(function (res) {
710
710
  return res.json().catch(function () { return {}; }).then(function (json) {
711
711
  return { status: res.status, json: json };
@@ -1407,6 +1407,9 @@ export function createDashboard(deps = {}) {
1407
1407
  const eventsIntervalMs = Number.isInteger(deps.eventsIntervalMs) && deps.eventsIntervalMs > 0
1408
1408
  ? deps.eventsIntervalMs
1409
1409
  : DEFAULT_EVENTS_INTERVAL_MS;
1410
+ // Injectable timer fns so a unit test can prove stop() clears the interval.
1411
+ const setIntervalFn = deps.setInterval ?? setInterval;
1412
+ const clearIntervalFn = deps.clearInterval ?? clearInterval;
1410
1413
  let eventsTimer = null;
1411
1414
 
1412
1415
  /**
@@ -1520,11 +1523,11 @@ export function createDashboard(deps = {}) {
1520
1523
  // Idempotent -- a second start() (e.g. a supervisor restart-in-
1521
1524
  // place test) must not leak a second interval.
1522
1525
  if (eventsTimer) return;
1523
- eventsTimer = setInterval(() => changeEmitter.emit('change'), eventsIntervalMs);
1526
+ eventsTimer = setIntervalFn(() => changeEmitter.emit('change'), eventsIntervalMs);
1524
1527
  },
1525
1528
  async stop() {
1526
1529
  if (eventsTimer) {
1527
- clearInterval(eventsTimer);
1530
+ clearIntervalFn(eventsTimer);
1528
1531
  eventsTimer = null;
1529
1532
  }
1530
1533
  },
@@ -52,6 +52,10 @@ export const DEFAULT_LEASE_MS = 60_000;
52
52
  /** Default background sweep interval for reclaiming expired/dead holders. */
53
53
  export const DEFAULT_SWEEP_MS = 5_000;
54
54
 
55
+ /** How often a queued acquire writes a heartbeat byte. Well under the 300s body
56
+ * timeout of the client's fetch, which resets on every chunk. */
57
+ export const DEFAULT_ACQUIRE_HEARTBEAT_MS = 30_000;
58
+
55
59
  let tokenSeq = 0;
56
60
  /** Monotonic, collision-free grant token. */
57
61
  function nextToken(sprintId) {
@@ -265,9 +269,10 @@ export function createDoltMutex(deps = {}) {
265
269
  * Detached sprint children coordinate through these:
266
270
  *
267
271
  * POST /api/dolt-push-mutex/:sprintId/acquire body { pid? }
268
- * Long-polls: the response is deferred until this sprint genuinely owns
269
- * the mutex, then returns 200 { token, expiresAt }. If the client aborts
270
- * the request, its queued waiter is dropped.
272
+ * Long-polls: 200 headers go out at once, a space every heartbeatMs while
273
+ * queued, and the body ends with { status, token, sprintId, expiresAt }
274
+ * when this sprint genuinely owns the mutex, or { error } if the wait
275
+ * failed. If the client aborts the request, its queued waiter is dropped.
271
276
  * POST /api/dolt-push-mutex/:sprintId/release body { token }
272
277
  * Releases; 200 { released: boolean }.
273
278
  * POST /api/dolt-push-mutex/:sprintId/renew body { token }
@@ -276,29 +281,44 @@ export function createDoltMutex(deps = {}) {
276
281
  *
277
282
  * @param {{ route: Function }} supervisor
278
283
  * @param {ReturnType<typeof createDoltMutex>} mutex
279
- * @param {{ readJsonBody: Function, sendJson: Function }} http
284
+ * @param {{ readJsonBody: Function, sendJson: Function, heartbeatMs?: number }} http
280
285
  */
281
286
  export function registerDoltMutexRoutes(supervisor, mutex, http) {
282
287
  const { readJsonBody, sendJson } = http;
288
+ const heartbeatMs = http.heartbeatMs > 0 ? http.heartbeatMs : DEFAULT_ACQUIRE_HEARTBEAT_MS;
283
289
 
284
290
  supervisor.route('POST', '/api/dolt-push-mutex/:sprintId/acquire', async (req, res, ctx) => {
285
291
  const sprintId = ctx?.params?.sprintId;
286
292
  if (!sprintId) { sendJson(res, 400, { error: 'missing sprintId in path' }); return; }
287
293
  const body = (await readJsonBody(req)) ?? {};
294
+ // Headers now, whitespace while queued, the JSON when the wait ends: the
295
+ // client's fetch times out after 300s without headers or a body chunk,
296
+ // and re-POSTing would lose this sprint's FIFO place. JSON.parse ignores
297
+ // the leading whitespace.
298
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
299
+ res.flushHeaders();
300
+ const heartbeat = setInterval(() => { if (!res.destroyed) res.write(' '); }, heartbeatMs);
301
+ heartbeat.unref?.();
288
302
  // If the client hangs up before it is granted, drop its queued waiter so
289
- // it can never later be handed a mutex nobody is waiting on.
290
- req.on('close', () => {
303
+ // it can never later be handed a mutex nobody is waiting on. This has to
304
+ // watch res: req has already closed once its body was read.
305
+ res.on('close', () => {
306
+ clearInterval(heartbeat);
291
307
  if (!res.writableEnded) {
292
308
  mutex.cancelWaiter(sprintId, new Error('acquire request aborted by client'));
293
309
  }
294
310
  });
295
311
  try {
296
312
  const grant = await mutex.acquire(sprintId, { pid: body.pid });
297
- if (res.writableEnded) return; // client already gone
298
- sendJson(res, 200, { status: 'acquired', ...grant });
313
+ // Client already gone: nobody would ever release this grant.
314
+ if (res.destroyed) { mutex.release(grant.token); return; }
315
+ res.end(JSON.stringify({ status: 'acquired', ...grant }));
299
316
  } catch (err) {
300
- if (res.writableEnded) return;
301
- sendJson(res, 503, { error: `acquire failed: ${err.message}` });
317
+ if (res.destroyed) return;
318
+ // The status line is long gone, so the failure travels in the body.
319
+ res.end(JSON.stringify({ error: `acquire failed: ${err.message}` }));
320
+ } finally {
321
+ clearInterval(heartbeat);
302
322
  }
303
323
  });
304
324
 
@@ -130,7 +130,14 @@ export async function listFleetMembers(deps = {}) {
130
130
  const mcpClient = new McpClient(transport);
131
131
  const fleetApi = new ApraFleet(mcpClient);
132
132
  const listRes = await fleetApi.listMembers({ format: 'json' });
133
- const text = listRes && listRes.content && listRes.content[0] ? listRes.content[0].text : JSON.stringify(listRes);
133
+ // The tool-registry wrapper may prepend an <apra-fleet-display> (user-audience)
134
+ // content item; the tool result is the first text item that is not one.
135
+ const items = listRes && Array.isArray(listRes.content) ? listRes.content : [];
136
+ const resultItem = items.find((c) => c && typeof c.text === 'string'
137
+ && !c.text.trimStart().startsWith('<apra-fleet-display')
138
+ && !(c.annotations && Array.isArray(c.annotations.audience)
139
+ && c.annotations.audience.length > 0 && !c.annotations.audience.includes('assistant')));
140
+ const text = resultItem ? resultItem.text : JSON.stringify(listRes);
134
141
  const parsed = JSON.parse(text);
135
142
  if (!parsed || !Array.isArray(parsed.members)) {
136
143
  return markFleetMembersUnavailable({ members: [] }, 'list_members returned no members array');
@@ -140,7 +147,9 @@ export async function listFleetMembers(deps = {}) {
140
147
  logError('[fleet-members] failed to list fleet members:', err);
141
148
  return markFleetMembersUnavailable({ members: [] }, `failed to list fleet members: ${errorText(err)}`);
142
149
  } finally {
143
- try { transport.stop(); } catch { /* best-effort teardown */ }
150
+ // close(), not stop(): stop() only aborts local streams and leaves the
151
+ // server session (and its McpServer) open.
152
+ try { await transport.close(); } catch { /* best-effort teardown */ }
144
153
  }
145
154
  }
146
155
 
@@ -209,7 +218,9 @@ export async function executeFleetCommand(opts = {}) {
209
218
  logError(`[fleet-members] execute_command failed on member '${member}':`, err);
210
219
  return { ok: false, error: err && err.message ? err.message : String(err) };
211
220
  } finally {
212
- try { transport.stop(); } catch { /* best-effort teardown */ }
221
+ // close(), not stop(): stop() only aborts local streams and leaves the
222
+ // server session (and its McpServer) open.
223
+ try { await transport.close(); } catch { /* best-effort teardown */ }
213
224
  }
214
225
  }
215
226
 
@@ -250,7 +261,9 @@ async function callFleetMemberTool(toolName, invoke, { resolveConnection, logger
250
261
  logError(`[fleet-members] ${toolName} failed:`, err);
251
262
  return { ok: false, unavailable: true, error: errorText(err) };
252
263
  } finally {
253
- try { transport.stop(); } catch { /* best-effort teardown */ }
264
+ // close(), not stop(): stop() only aborts local streams and leaves the
265
+ // server session (and its McpServer) open.
266
+ try { await transport.close(); } catch { /* best-effort teardown */ }
254
267
  }
255
268
  }
256
269
 
@@ -147,6 +147,11 @@ function cloneEvent(e) {
147
147
  // same optional/null-default convention as the fields above.
148
148
  terminalReason: e.terminalReason === undefined ? null : e.terminalReason,
149
149
  verdict: e.verdict === undefined ? null : e.verdict,
150
+ // Only meaningful for a FINISHED event: the run's own result status
151
+ // (e.g. 'success-with-warnings' when the PR was skipped for a VCS auth
152
+ // failure) and its warnings, so they survive the reservation release.
153
+ resultStatus: e.resultStatus === undefined ? null : e.resultStatus,
154
+ warnings: Array.isArray(e.warnings) ? [...e.warnings] : [],
150
155
  };
151
156
  }
152
157
 
@@ -233,7 +238,7 @@ export function createHistory(deps = {}) {
233
238
  /**
234
239
  * Append one terminal event and persist atomically. The in-memory log is
235
240
  * committed only after the disk write succeeds.
236
- * @param {{ sprintId: string, event: string, reason?: string, by?: string|null, members?: string[], issueRoots?: string[], at?: string, exitCode?: number|null, signal?: string|null, logPath?: string|null, terminalReason?: string|null, verdict?: string|null }} entry
241
+ * @param {{ sprintId: string, event: string, reason?: string, by?: string|null, members?: string[], issueRoots?: string[], at?: string, exitCode?: number|null, signal?: string|null, logPath?: string|null, terminalReason?: string|null, verdict?: string|null, resultStatus?: string|null, warnings?: string[] }} entry
237
242
  * @returns {Promise<object>} a clone of the stored event
238
243
  */
239
244
  async record(entry) {
@@ -256,6 +261,8 @@ export function createHistory(deps = {}) {
256
261
  logPath: entry.logPath,
257
262
  terminalReason: entry.terminalReason,
258
263
  verdict: entry.verdict,
264
+ resultStatus: entry.resultStatus,
265
+ warnings: entry.warnings,
259
266
  });
260
267
  const run = txChain.then(async () => {
261
268
  const next = [...events, stored];
@@ -82,8 +82,19 @@ function nextToken(parentId) {
82
82
  return `${parentId}#${tokenSeq}#${Date.now().toString(36)}`;
83
83
  }
84
84
 
85
- /** Default per-user data dir shared with the ledger. */
86
- function defaultDataDir() {
85
+ /** Legacy per-user allocator dir (~/.apra-fleet/supervisor); read-only seed source. */
86
+ export function legacyDataDir() {
87
+ return path.join(os.homedir() || os.tmpdir(), '.apra-fleet', 'supervisor');
88
+ }
89
+
90
+ /**
91
+ * Default allocator data dir: FLEET_SE_DATA_DIR when set (same resolution as
92
+ * ledger.mjs, so two supervisors with separate data dirs never share one
93
+ * allocator file), else the legacy per-user ~/.apra-fleet/supervisor. A new
94
+ * allocator file is seeded once from the legacy file (see seedFromLegacy).
95
+ */
96
+ export function defaultDataDir() {
97
+ if (process.env.FLEET_SE_DATA_DIR) return path.resolve(process.env.FLEET_SE_DATA_DIR);
87
98
  return path.join(os.homedir() || os.tmpdir(), '.apra-fleet', 'supervisor');
88
99
  }
89
100
 
@@ -93,6 +104,10 @@ function defaultDataDir() {
93
104
  * @param {{
94
105
  * dataDir?: string,
95
106
  * filePath?: string,
107
+ * legacyFilePath?: string|null,
108
+ * legacy allocator file to seed per-parent high-water marks from ONCE when
109
+ * the configured file is missing. Defaults to the ~/.apra-fleet/supervisor
110
+ * file only when dataDir is the FLEET_SE_DATA_DIR dir; null disables.
96
111
  * leaseMs?: number,
97
112
  * sweepMs?: number,
98
113
  * now?: () => number,
@@ -118,10 +133,20 @@ function defaultDataDir() {
118
133
  * (5 attempts, ~10ms escalating).
119
134
  * }} [deps]
120
135
  */
136
+ /** A legacy allocator file modified this recently is treated as possibly still live. */
137
+ const LEGACY_LIVE_WINDOW_MS = 10 * 60 * 1000;
138
+
121
139
  export function createIdAllocator(deps = {}) {
122
140
  const dataDir = deps.dataDir ?? defaultDataDir();
123
141
  const filePath = deps.filePath ?? path.join(dataDir, ID_ALLOCATOR_FILENAME);
124
142
  const tmpPath = `${filePath}.tmp`;
143
+ const envDir = process.env.FLEET_SE_DATA_DIR ? path.resolve(process.env.FLEET_SE_DATA_DIR) : null;
144
+ const legacyFilePath = deps.legacyFilePath !== undefined
145
+ ? deps.legacyFilePath
146
+ : (!deps.filePath && envDir && path.resolve(dataDir) === envDir
147
+ ? path.join(legacyDataDir(), ID_ALLOCATOR_FILENAME)
148
+ : null);
149
+ let seededFromLegacy = false;
125
150
  const leaseMs = Number.isFinite(deps.leaseMs) && deps.leaseMs > 0 ? deps.leaseMs : DEFAULT_LEASE_MS;
126
151
  const sweepMs = Number.isFinite(deps.sweepMs) && deps.sweepMs > 0 ? deps.sweepMs : DEFAULT_SWEEP_MS;
127
152
  const now = deps.now ?? (() => Date.now());
@@ -205,6 +230,66 @@ export function createIdAllocator(deps = {}) {
205
230
  return run;
206
231
  }
207
232
 
233
+ /**
234
+ * One-time upgrade seed: copy per-parent high-water marks ONLY from the legacy
235
+ * file. The free pool is deliberately NOT copied: reusing legacy holes is the
236
+ * likeliest way to hand out an id a still-running legacy supervisor also
237
+ * hands out. Reservations are not carried over (their seqs lift the
238
+ * high-water mark). The legacy file is only read, never modified. Any
239
+ * failure leaves the allocator empty.
240
+ *
241
+ * Remaining risk: a legacy supervisor (no FLEET_SE_DATA_DIR) still running
242
+ * against the same beads DB keeps minting above the snapshot, so both can
243
+ * mint the same seq. When the legacy file shows a live signal (a
244
+ * reservation whose pid is alive, or an mtime within LEGACY_LIVE_WINDOW_MS)
245
+ * ONE warning is logged naming the remedy. We warn rather than refuse: a
246
+ * stale-but-recent file would otherwise block a legitimate upgrade, and the
247
+ * supervisor must not fail to start.
248
+ */
249
+ async function seedFromLegacy() {
250
+ if (!legacyFilePath || path.resolve(legacyFilePath) === path.resolve(filePath)) return;
251
+ let doc;
252
+ try {
253
+ doc = JSON.parse(await fs.readFile(legacyFilePath, 'utf-8'));
254
+ if (!doc || typeof doc !== 'object' || doc.version !== ID_ALLOCATOR_VERSION || !doc.parents || typeof doc.parents !== 'object') {
255
+ throw new Error('unexpected shape or version');
256
+ }
257
+ } catch (err) {
258
+ if (err && err.code === 'ENOENT') {
259
+ log(`[id-allocator] no legacy allocator file at ${legacyFilePath}; starting empty`);
260
+ } else {
261
+ log(`[id-allocator] cannot seed from legacy allocator file ${legacyFilePath} (${err.message}); starting empty`);
262
+ }
263
+ return;
264
+ }
265
+ let liveSignal = null;
266
+ for (const [parentId, st] of Object.entries(doc.parents)) {
267
+ if (!st || typeof st !== 'object') continue;
268
+ let highWater = Number.isInteger(st.highWater) ? st.highWater : 0;
269
+ // Outstanding reservations are dropped, but their seqs were handed out:
270
+ // keep the high-water above them so they are never re-minted.
271
+ for (const r of Object.values(st.reserved ?? {})) {
272
+ if (Number.isInteger(r?.seq) && r.seq > highWater) highWater = r.seq;
273
+ if (!liveSignal && r?.pid != null && Number.isInteger(r.pid) && probe(r.pid)) liveSignal = `a reservation is held by live pid ${r.pid}`;
274
+ }
275
+ parents.set(parentId, { highWater, free: [], reserved: new Map() });
276
+ }
277
+ if (!liveSignal) {
278
+ try {
279
+ // A just-written file's mtime can be a few ms AHEAD of Date.now()
280
+ // (fractional fs timestamps vs whole-ms clock; Windows clock skew),
281
+ // so a slightly negative age is "just now", not "no signal".
282
+ const age = now() - (await fs.stat(legacyFilePath)).mtimeMs;
283
+ if (Math.abs(age) < LEGACY_LIVE_WINDOW_MS) liveSignal = `the legacy file was modified ${Math.max(0, Math.round(age / 1000))}s ago`;
284
+ } catch { /* no mtime: no signal */ }
285
+ }
286
+ if (liveSignal) {
287
+ log(`[id-allocator] WARNING: a legacy supervisor may still be running against ${legacyFilePath} (${liveSignal}); both allocators can then mint the same child id. Stop the legacy supervisor, or run both with the same FLEET_SE_DATA_DIR.`);
288
+ }
289
+ seededFromLegacy = true;
290
+ log(`[id-allocator] seeded ${parents.size} parent high-water mark(s) from legacy file ${legacyFilePath} into ${filePath}`);
291
+ }
292
+
208
293
  /**
209
294
  * Load allocator state from disk. A missing file yields empty state. A
210
295
  * corrupt/foreign-version file is a hard error -- the supervisor must not
@@ -218,6 +303,7 @@ export function createIdAllocator(deps = {}) {
218
303
  if (err && err.code === 'ENOENT') {
219
304
  parents = new Map();
220
305
  loaded = true;
306
+ await seedFromLegacy();
221
307
  return;
222
308
  }
223
309
  throw err;
@@ -411,6 +497,10 @@ export function createIdAllocator(deps = {}) {
411
497
  // -- seam lifecycle (server.mjs calls start()/stop()) ----------------
412
498
  async start() {
413
499
  if (!loaded) await load();
500
+ if (seededFromLegacy) {
501
+ seededFromLegacy = false;
502
+ await persist();
503
+ }
414
504
  if (sweepTimer) return;
415
505
  sweepTimer = setIntervalFn(() => {
416
506
  if (reclaimExpired() > 0) persist().catch(() => {});
@@ -50,6 +50,7 @@ import http from 'node:http';
50
50
  import fsp from 'node:fs/promises';
51
51
  import { escapeHtml } from '@apralabs/apra-fleet-workflow/viewer/html-utils';
52
52
  import { getTerminalRunStatePath } from '@apralabs/apra-fleet-workflow/viewer/run-state-paths';
53
+ import { ADMITTED_REQUEST_STRIP_HEADERS } from '@apralabs/apra-fleet-workflow/viewer/request-guard';
53
54
  import { withTimestamps } from './log-timestamp.mjs';
54
55
  import { createChildPortResolver } from './child-port.mjs';
55
56
 
@@ -101,10 +102,17 @@ export function rewriteChildHtml(html, prefix) {
101
102
  .split("'/activities/").join("'" + prefix + "/activities/");
102
103
  }
103
104
 
104
- /** Copy request headers for the upstream call, dropping host/encoding/hop-by-hop. */
105
+ /**
106
+ * Copy request headers for the upstream call, dropping host/encoding/hop-by-hop
107
+ * and the browser-origin/token headers: the supervisor's route() guard already
108
+ * admitted this request against the SUPERVISOR's origin, and the child viewer
109
+ * (a different port, same guard) would otherwise read the supervisor's Origin
110
+ * as cross-site and refuse the forwarded POST.
111
+ */
105
112
  function upstreamRequestHeaders(req) {
106
113
  const headers = { ...req.headers };
107
114
  delete headers.host;
115
+ for (const h of ADMITTED_REQUEST_STRIP_HEADERS) delete headers[h];
108
116
  // SSE passthrough must stay uncompressed and unbuffered -- never let the
109
117
  // child gzip a stream we need to flush event-by-event.
110
118
  delete headers['accept-encoding'];
@@ -437,6 +445,21 @@ export function createLiveProxy(deps = {}) {
437
445
  proxyStream({ host, port, childPath, req, res, logError });
438
446
  }
439
447
 
448
+ // The generic extension action route (extension id + action id from the
449
+ // URL), POST with a JSON body: the decisions banner's answer form.
450
+ async function handleExtensionAction(req, res, ctx) {
451
+ const sprintId = ctx?.params?.id;
452
+ if (!sprintId) { sendPlain(res, 400, 'missing sprint id in path'); return; }
453
+ const port = safeResolvePort(sprintId);
454
+ if (!Number.isInteger(port)) {
455
+ sendPlain(res, 404, `sprint '${sprintId}' is no longer live`);
456
+ return;
457
+ }
458
+ const childPath = '/extensions/' + encodeURIComponent(ctx?.params?.extId ?? '')
459
+ + '/actions/' + encodeURIComponent(ctx?.params?.actionId ?? '');
460
+ proxyStream({ host, port, childPath, req, res, logError });
461
+ }
462
+
440
463
  return {
441
464
  name: 'live-proxy',
442
465
  resolvePort: safeResolvePort,
@@ -449,6 +472,7 @@ export function createLiveProxy(deps = {}) {
449
472
  handleResume,
450
473
  handleSaveLogs,
451
474
  handleExtensionDetail,
475
+ handleExtensionAction,
452
476
  handleActivityOutput,
453
477
  };
454
478
  }
@@ -470,5 +494,6 @@ export function registerLiveRoutes(supervisor, proxy) {
470
494
  supervisor.route('POST', '/sprints/:id/live/resume', proxy.handleResume);
471
495
  supervisor.route('POST', '/sprints/:id/live/save_logs', proxy.handleSaveLogs);
472
496
  supervisor.route('GET', '/sprints/:id/live/extensions/:extId/detail/:itemId', proxy.handleExtensionDetail);
497
+ supervisor.route('POST', '/sprints/:id/live/extensions/:extId/actions/:actionId', proxy.handleExtensionAction);
473
498
  supervisor.route('GET', '/sprints/:id/live/activities/:activityId/output', proxy.handleActivityOutput);
474
499
  }