@apralabs/apra-fleet 0.4.2 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (997) hide show
  1. package/README.md +103 -34
  2. package/dist/agents/backlog-groomer.md +87 -14
  3. package/dist/agents/ci-watcher.md +35 -9
  4. package/dist/agents/deployer.md +63 -11
  5. package/dist/agents/doer.md +99 -41
  6. package/dist/agents/harvester.md +47 -27
  7. package/dist/agents/integ-test-runner.md +38 -10
  8. package/dist/agents/kb-reconciler.md +37 -7
  9. package/dist/agents/plan-reviewer.md +145 -32
  10. package/dist/agents/planner.md +180 -69
  11. package/dist/agents/regression-test-runner.md +98 -64
  12. package/dist/agents/reviewer.md +117 -45
  13. package/dist/agents/schemas/backlog-groomer-output.json +1 -1
  14. package/dist/agents/schemas/doer-output.json +32 -0
  15. package/dist/agents/schemas/harvester-input.json +1 -5
  16. package/dist/agents/schemas/plan-reviewer-output.json +37 -0
  17. package/dist/agents/schemas/planner-output.json +1 -1
  18. package/dist/agents/schemas/regression-test-runner-output.json +41 -7
  19. package/dist/agents/schemas/reviewer-output.json +62 -3
  20. package/dist/cli/agent-transform.d.ts +90 -2
  21. package/dist/cli/agent-transform.js +310 -20
  22. package/dist/cli/auth.d.ts +1 -0
  23. package/dist/cli/auth.js +66 -17
  24. package/dist/cli/beads-install.d.ts +35 -0
  25. package/dist/cli/beads-install.js +125 -0
  26. package/dist/cli/beads-pin.d.ts +5 -0
  27. package/dist/cli/beads-pin.js +27 -0
  28. package/dist/cli/call.d.ts +27 -0
  29. package/dist/cli/call.js +177 -0
  30. package/dist/cli/config.d.ts +31 -6
  31. package/dist/cli/config.js +113 -36
  32. package/dist/cli/dolt-install.d.ts +18 -2
  33. package/dist/cli/dolt-install.js +46 -15
  34. package/dist/cli/fleet-se-guard.d.ts +51 -0
  35. package/dist/cli/fleet-se-guard.js +215 -0
  36. package/dist/cli/install-guard.d.ts +54 -0
  37. package/dist/cli/install-guard.js +132 -4
  38. package/dist/cli/install.d.ts +100 -11
  39. package/dist/cli/install.js +864 -139
  40. package/dist/cli/kb-commit.d.ts +2 -1
  41. package/dist/cli/kb-commit.js +1 -1
  42. package/dist/cli/kb-directives.js +2 -1
  43. package/dist/cli/kb-import.d.ts +2 -1
  44. package/dist/cli/kb-import.js +1 -1
  45. package/dist/cli/register-member.js +26 -5
  46. package/dist/cli/remove-member.d.ts +4 -0
  47. package/dist/cli/remove-member.js +63 -0
  48. package/dist/cli/secret.js +9 -0
  49. package/dist/cli/start.js +59 -4
  50. package/dist/cli/status.d.ts +3 -0
  51. package/dist/cli/status.js +45 -12
  52. package/dist/cli/stop.js +64 -9
  53. package/dist/cli/uninstall.js +101 -15
  54. package/dist/cli/update.js +33 -2
  55. package/dist/cli/watch.js +1 -1
  56. package/dist/cli/workflow.js +3 -2
  57. package/dist/commands/kb-server.d.ts +3 -0
  58. package/dist/commands/kb-server.js +52 -5
  59. package/dist/hub-service/http-server.d.ts +5 -1
  60. package/dist/hub-service/http-server.js +55 -5
  61. package/dist/index.js +158 -11
  62. package/dist/os/child-env-bound.d.ts +77 -0
  63. package/dist/os/child-env-bound.js +171 -0
  64. package/dist/os/linux.d.ts +13 -2
  65. package/dist/os/linux.js +75 -16
  66. package/dist/os/macos.d.ts +1 -1
  67. package/dist/os/macos.js +2 -11
  68. package/dist/os/os-commands.d.ts +78 -4
  69. package/dist/os/windows-gitbash.d.ts +6 -0
  70. package/dist/os/windows-gitbash.js +32 -3
  71. package/dist/os/windows-wrapper.d.ts +0 -4
  72. package/dist/os/windows-wrapper.js +2 -1
  73. package/dist/os/windows.d.ts +11 -2
  74. package/dist/os/windows.js +121 -32
  75. package/dist/paths.d.ts +21 -0
  76. package/dist/paths.js +35 -0
  77. package/dist/providers/agy.d.ts +120 -7
  78. package/dist/providers/agy.js +741 -86
  79. package/dist/providers/claude-permission-denial.d.ts +7 -0
  80. package/dist/providers/claude-permission-denial.js +137 -0
  81. package/dist/providers/claude.d.ts +132 -6
  82. package/dist/providers/claude.js +644 -48
  83. package/dist/providers/codex.d.ts +4 -2
  84. package/dist/providers/codex.js +23 -2
  85. package/dist/providers/copilot.d.ts +4 -2
  86. package/dist/providers/copilot.js +24 -2
  87. package/dist/providers/none.d.ts +4 -2
  88. package/dist/providers/none.js +17 -2
  89. package/dist/providers/opencode.d.ts +12 -2
  90. package/dist/providers/opencode.js +135 -54
  91. package/dist/providers/provider.d.ts +368 -35
  92. package/dist/providers/provider.js +219 -2
  93. package/dist/services/agent-provisioner.d.ts +29 -0
  94. package/dist/services/agent-provisioner.js +107 -0
  95. package/dist/services/agent-shadow.d.ts +96 -0
  96. package/dist/services/agent-shadow.js +479 -0
  97. package/dist/services/agy-project.d.ts +103 -0
  98. package/dist/services/agy-project.js +354 -0
  99. package/dist/services/auth-socket.d.ts +25 -0
  100. package/dist/services/auth-socket.js +72 -27
  101. package/dist/services/auth-web.js +2 -2
  102. package/dist/services/budget-awareness.d.ts +11 -11
  103. package/dist/services/budget-awareness.js +15 -3
  104. package/dist/services/claude-local-scope-mcp.d.ts +19 -0
  105. package/dist/services/claude-local-scope-mcp.js +91 -0
  106. package/dist/services/cloud/aws.js +2 -1
  107. package/dist/services/cloud/lifecycle.js +52 -6
  108. package/dist/services/cloud/task-wrapper.d.ts +0 -9
  109. package/dist/services/cloud/task-wrapper.js +15 -6
  110. package/dist/services/credential-cleanup.js +35 -17
  111. package/dist/services/event-loop-watchdog.d.ts +32 -0
  112. package/dist/services/event-loop-watchdog.js +140 -0
  113. package/dist/services/exit-drain.d.ts +44 -0
  114. package/dist/services/exit-drain.js +52 -0
  115. package/dist/services/github-app.js +32 -4
  116. package/dist/services/http-transport.d.ts +50 -1
  117. package/dist/services/http-transport.js +238 -25
  118. package/dist/services/in-flight-agents.d.ts +2 -0
  119. package/dist/services/in-flight-agents.js +4 -0
  120. package/dist/services/knowledge/bible-basis-filter.d.ts +53 -0
  121. package/dist/services/knowledge/bible-basis-filter.js +134 -0
  122. package/dist/services/knowledge/bible-blob-id.d.ts +44 -0
  123. package/dist/services/knowledge/bible-blob-id.js +113 -0
  124. package/dist/services/knowledge/bible-import.d.ts +65 -0
  125. package/dist/services/knowledge/bible-import.js +211 -0
  126. package/dist/services/knowledge/file-hash.d.ts +31 -0
  127. package/dist/services/knowledge/file-hash.js +153 -23
  128. package/dist/services/knowledge/http-provider.d.ts +4 -3
  129. package/dist/services/knowledge/http-provider.js +17 -5
  130. package/dist/services/knowledge/kb-config.d.ts +42 -0
  131. package/dist/services/knowledge/kb-config.js +54 -0
  132. package/dist/services/knowledge/kb-maintainer-grant.d.ts +15 -0
  133. package/dist/services/knowledge/kb-maintainer-grant.js +34 -0
  134. package/dist/services/knowledge/kb-providers.d.ts +11 -1
  135. package/dist/services/knowledge/kb-providers.js +199 -17
  136. package/dist/services/knowledge/kb-removed-scope-keys.d.ts +28 -0
  137. package/dist/services/knowledge/kb-removed-scope-keys.js +59 -0
  138. package/dist/services/knowledge/kb-scopes.d.ts +14 -0
  139. package/dist/services/knowledge/kb-scopes.js +47 -0
  140. package/dist/services/knowledge/kb-self.d.ts +91 -0
  141. package/dist/services/knowledge/kb-self.js +198 -0
  142. package/dist/services/knowledge/member-bible-view.d.ts +21 -0
  143. package/dist/services/knowledge/member-bible-view.js +194 -0
  144. package/dist/services/knowledge/pre-init.js +1 -0
  145. package/dist/services/knowledge/project-slug.js +2 -2
  146. package/dist/services/knowledge/require-sqlite-project.d.ts +32 -0
  147. package/dist/services/knowledge/require-sqlite-project.js +38 -0
  148. package/dist/services/knowledge/sqlite-provider.d.ts +64 -11
  149. package/dist/services/knowledge/sqlite-provider.js +303 -41
  150. package/dist/services/knowledge/types.d.ts +45 -2
  151. package/dist/services/member-access-secret.d.ts +70 -0
  152. package/dist/services/member-access-secret.js +195 -0
  153. package/dist/services/member-call-counts.d.ts +24 -0
  154. package/dist/services/member-call-counts.js +58 -0
  155. package/dist/services/member-config-io.d.ts +192 -0
  156. package/dist/services/member-config-io.js +443 -0
  157. package/dist/services/member-fleet-install.d.ts +710 -0
  158. package/dist/services/member-fleet-install.js +1895 -0
  159. package/dist/services/member-secret-env.d.ts +42 -0
  160. package/dist/services/member-secret-env.js +68 -0
  161. package/dist/services/member-tool-allowlist.d.ts +49 -0
  162. package/dist/services/member-tool-allowlist.js +111 -0
  163. package/dist/services/model-pricing.d.ts +19 -0
  164. package/dist/services/model-pricing.js +60 -10
  165. package/dist/services/port-holder.d.ts +86 -0
  166. package/dist/services/port-holder.js +351 -0
  167. package/dist/services/preflight-check.js +2 -0
  168. package/dist/services/registry.d.ts +13 -2
  169. package/dist/services/registry.js +27 -1
  170. package/dist/services/relay-strategy.d.ts +2 -0
  171. package/dist/services/relay-strategy.js +8 -0
  172. package/dist/services/secret-token.d.ts +38 -0
  173. package/dist/services/secret-token.js +51 -0
  174. package/dist/services/server-lifecycle.d.ts +26 -0
  175. package/dist/services/server-lifecycle.js +85 -0
  176. package/dist/services/service-manager/index.d.ts +7 -1
  177. package/dist/services/service-manager/index.js +17 -4
  178. package/dist/services/service-manager/linux.d.ts +1 -1
  179. package/dist/services/service-manager/linux.js +15 -7
  180. package/dist/services/service-manager/macos.d.ts +11 -1
  181. package/dist/services/service-manager/macos.js +45 -7
  182. package/dist/services/service-manager/service-path.d.ts +24 -0
  183. package/dist/services/service-manager/service-path.js +55 -0
  184. package/dist/services/service-manager/types.d.ts +39 -2
  185. package/dist/services/service-manager/types.js +29 -0
  186. package/dist/services/service-manager/windows.d.ts +194 -3
  187. package/dist/services/service-manager/windows.js +705 -30
  188. package/dist/services/service-notice.d.ts +14 -0
  189. package/dist/services/service-notice.js +62 -0
  190. package/dist/services/service-start-guard.d.ts +20 -0
  191. package/dist/services/service-start-guard.js +86 -0
  192. package/dist/services/session-cost.d.ts +24 -0
  193. package/dist/services/session-cost.js +105 -0
  194. package/dist/services/session-mcp-config.d.ts +83 -0
  195. package/dist/services/session-mcp-config.js +211 -0
  196. package/dist/services/sftp.d.ts +34 -0
  197. package/dist/services/sftp.js +304 -76
  198. package/dist/services/shell-probe.d.ts +0 -24
  199. package/dist/services/shell-probe.js +28 -3
  200. package/dist/services/singleton.d.ts +68 -2
  201. package/dist/services/singleton.js +168 -11
  202. package/dist/services/sprint-coordination.js +9 -3
  203. package/dist/services/ssh.d.ts +27 -0
  204. package/dist/services/ssh.js +287 -40
  205. package/dist/services/stall/find-log-file.js +12 -5
  206. package/dist/services/stall/index.d.ts +1 -1
  207. package/dist/services/stall/read-log-tail.d.ts +23 -0
  208. package/dist/services/stall/read-log-tail.js +53 -12
  209. package/dist/services/stall/stall-detector.d.ts +78 -5
  210. package/dist/services/stall/stall-detector.js +296 -39
  211. package/dist/services/stall/stall-poller.d.ts +16 -0
  212. package/dist/services/stall/stall-poller.js +50 -6
  213. package/dist/services/stopped-marker.d.ts +16 -0
  214. package/dist/services/stopped-marker.js +55 -0
  215. package/dist/services/strategy.d.ts +33 -1
  216. package/dist/services/strategy.js +165 -19
  217. package/dist/services/substitution-engine.js +2 -2
  218. package/dist/services/supervisor-service-cleanup.d.ts +52 -0
  219. package/dist/services/supervisor-service-cleanup.js +332 -0
  220. package/dist/services/tool-registry.d.ts +8 -1
  221. package/dist/services/tool-registry.js +164 -61
  222. package/dist/services/tool-scope.d.ts +58 -0
  223. package/dist/services/tool-scope.js +99 -0
  224. package/dist/services/vcs/azure-devops.d.ts +66 -1
  225. package/dist/services/vcs/azure-devops.js +192 -21
  226. package/dist/services/vcs/types.d.ts +1 -1
  227. package/dist/services/watch/project-resolver.js +1 -0
  228. package/dist/skills/auto-sprint-args/SKILL.md +2 -2
  229. package/dist/skills/fleet-sprint-cli/SKILL.md +48 -6
  230. package/dist/skills/pm/SKILL.md +4 -4
  231. package/dist/skills/pm/cost.md +0 -3
  232. package/dist/skills/pm/fleet-addendum.md +2 -2
  233. package/dist/skills/pm/index.md +4 -2
  234. package/dist/skills/pm/kb-reconcile.md +29 -14
  235. package/dist/skills/pm/kb-review.md +1 -0
  236. package/dist/skills/pm/sprint.md +5 -5
  237. package/dist/tools/check-status.d.ts +60 -9
  238. package/dist/tools/check-status.js +211 -52
  239. package/dist/tools/child-id-allocator.d.ts +2 -2
  240. package/dist/tools/child-id-allocator.js +1 -1
  241. package/dist/tools/code-index-heal.d.ts +8 -0
  242. package/dist/tools/code-index-heal.js +21 -0
  243. package/dist/tools/code-index-state.d.ts +45 -0
  244. package/dist/tools/code-index-state.js +115 -0
  245. package/dist/tools/code-intelligence-codebase-memory.js +6 -33
  246. package/dist/tools/code-intelligence-freshness.js +1 -1
  247. package/dist/tools/code-intelligence-gitnexus.d.ts +30 -0
  248. package/dist/tools/code-intelligence-gitnexus.js +333 -57
  249. package/dist/tools/code-intelligence-kb-enrich.js +7 -6
  250. package/dist/tools/code-intelligence-readiness.d.ts +99 -0
  251. package/dist/tools/code-intelligence-readiness.js +206 -0
  252. package/dist/tools/code-intelligence-reindex.d.ts +195 -0
  253. package/dist/tools/code-intelligence-reindex.js +530 -50
  254. package/dist/tools/code-intelligence-telemetry.d.ts +6 -1
  255. package/dist/tools/code-intelligence-telemetry.js +12 -3
  256. package/dist/tools/code-intelligence.d.ts +81 -31
  257. package/dist/tools/code-intelligence.js +156 -52
  258. package/dist/tools/compose-permissions.d.ts +63 -2
  259. package/dist/tools/compose-permissions.js +673 -72
  260. package/dist/tools/credential-store-set.js +1 -1
  261. package/dist/tools/execute-command.d.ts +11 -0
  262. package/dist/tools/execute-command.js +111 -32
  263. package/dist/tools/execute-prompt.d.ts +69 -12
  264. package/dist/tools/execute-prompt.js +1610 -895
  265. package/dist/tools/kb-bible-commit.d.ts +65 -0
  266. package/dist/tools/kb-bible-commit.js +239 -0
  267. package/dist/tools/kb-capture.d.ts +15 -11
  268. package/dist/tools/kb-capture.js +71 -16
  269. package/dist/tools/kb-context.d.ts +27 -7
  270. package/dist/tools/kb-context.js +60 -9
  271. package/dist/tools/kb-export.d.ts +98 -9
  272. package/dist/tools/kb-export.js +230 -92
  273. package/dist/tools/kb-feedback.d.ts +13 -9
  274. package/dist/tools/kb-feedback.js +16 -8
  275. package/dist/tools/kb-freshness-sweep.d.ts +11 -7
  276. package/dist/tools/kb-freshness-sweep.js +10 -8
  277. package/dist/tools/kb-harvest.d.ts +11 -7
  278. package/dist/tools/kb-harvest.js +7 -7
  279. package/dist/tools/kb-import.d.ts +26 -10
  280. package/dist/tools/kb-import.js +170 -159
  281. package/dist/tools/kb-invalidate.d.ts +17 -10
  282. package/dist/tools/kb-invalidate.js +41 -8
  283. package/dist/tools/kb-list.d.ts +14 -10
  284. package/dist/tools/kb-list.js +33 -11
  285. package/dist/tools/kb-promote.d.ts +11 -7
  286. package/dist/tools/kb-promote.js +14 -8
  287. package/dist/tools/kb-query.d.ts +21 -11
  288. package/dist/tools/kb-query.js +76 -13
  289. package/dist/tools/kb-reconcile-prefilter.d.ts +11 -7
  290. package/dist/tools/kb-reconcile-prefilter.js +13 -9
  291. package/dist/tools/kb-resolve-contradiction.d.ts +11 -7
  292. package/dist/tools/kb-resolve-contradiction.js +10 -8
  293. package/dist/tools/kb-session-prime.d.ts +14 -7
  294. package/dist/tools/kb-session-prime.js +44 -44
  295. package/dist/tools/kb-setup.d.ts +11 -4
  296. package/dist/tools/kb-setup.js +146 -27
  297. package/dist/tools/kb-stats.d.ts +11 -10
  298. package/dist/tools/kb-stats.js +84 -82
  299. package/dist/tools/list-members.d.ts +2 -2
  300. package/dist/tools/list-members.js +6 -2
  301. package/dist/tools/member-detail.d.ts +5 -2
  302. package/dist/tools/member-detail.js +105 -17
  303. package/dist/tools/member-reservation.d.ts +60 -3
  304. package/dist/tools/member-reservation.js +61 -20
  305. package/dist/tools/provision-auth.d.ts +118 -1
  306. package/dist/tools/provision-auth.js +402 -92
  307. package/dist/tools/provision-vcs-auth.d.ts +93 -3
  308. package/dist/tools/provision-vcs-auth.js +209 -49
  309. package/dist/tools/receive-files.js +3 -1
  310. package/dist/tools/register-member.d.ts +44 -15
  311. package/dist/tools/register-member.js +175 -70
  312. package/dist/tools/remove-member.js +118 -15
  313. package/dist/tools/send-email.d.ts +2 -2
  314. package/dist/tools/send-files.js +6 -4
  315. package/dist/tools/session-stats.d.ts +17 -0
  316. package/dist/tools/session-stats.js +27 -0
  317. package/dist/tools/setup-git-app.js +11 -7
  318. package/dist/tools/shutdown-server.d.ts +2 -0
  319. package/dist/tools/shutdown-server.js +28 -1
  320. package/dist/tools/update-agent-cli.d.ts +19 -0
  321. package/dist/tools/update-agent-cli.js +59 -2
  322. package/dist/tools/update-member.d.ts +23 -17
  323. package/dist/tools/update-member.js +181 -18
  324. package/dist/tools/vcs-credential-exec.d.ts +127 -0
  325. package/dist/tools/vcs-credential-exec.js +203 -0
  326. package/dist/types.d.ts +111 -1
  327. package/dist/utils/agent-helpers.js +2 -0
  328. package/dist/utils/auth-env.d.ts +15 -4
  329. package/dist/utils/auth-env.js +52 -23
  330. package/dist/utils/find-on-path.d.ts +37 -0
  331. package/dist/utils/find-on-path.js +85 -0
  332. package/dist/utils/log-helpers.d.ts +37 -0
  333. package/dist/utils/log-helpers.js +108 -22
  334. package/dist/utils/owner-only-fs.d.ts +56 -0
  335. package/dist/utils/owner-only-fs.js +98 -0
  336. package/dist/utils/process-utils.d.ts +28 -0
  337. package/dist/utils/process-utils.js +68 -0
  338. package/dist/utils/prompt-errors.js +11 -2
  339. package/dist/utils/session-caller.d.ts +4 -2
  340. package/dist/utils/session-caller.js +3 -2
  341. package/dist/utils/shell-escape.d.ts +58 -3
  342. package/dist/utils/shell-escape.js +91 -5
  343. package/dist/utils/ssh-error-messages.js +3 -0
  344. package/dist/utils/vcs-provider-detect.d.ts +65 -0
  345. package/dist/utils/vcs-provider-detect.js +109 -0
  346. package/dist/utils/workspace-trust.d.ts +26 -0
  347. package/dist/utils/workspace-trust.js +91 -1
  348. package/dist/workflows/auto-sprint.js +397 -56
  349. package/package.json +15 -10
  350. package/packages/apra-fleet-client/package.json +2 -2
  351. package/packages/apra-fleet-client/src/client/api.mjs +864 -31
  352. package/packages/apra-fleet-client/src/client/auto-start.mjs +434 -0
  353. package/packages/apra-fleet-client/src/client/client.mjs +9 -0
  354. package/packages/apra-fleet-client/src/client/errors.mjs +6 -2
  355. package/packages/apra-fleet-client/src/client/factory.mjs +23 -4
  356. package/packages/apra-fleet-client/src/client/reconnecting-transport.mjs +137 -0
  357. package/packages/apra-fleet-client/src/client/server-resolution.mjs +267 -30
  358. package/packages/apra-fleet-client/src/client/transport.mjs +37 -3
  359. package/packages/apra-fleet-se/apra-pm/agents/_shared/GRAPH-SEMANTICS.md +10 -2
  360. package/packages/apra-fleet-se/apra-pm/agents/backlog-groomer.md +87 -14
  361. package/packages/apra-fleet-se/apra-pm/agents/ci-watcher.md +35 -9
  362. package/packages/apra-fleet-se/apra-pm/agents/deployer.md +63 -11
  363. package/packages/apra-fleet-se/apra-pm/agents/doer.md +99 -41
  364. package/packages/apra-fleet-se/apra-pm/agents/harvester.md +47 -27
  365. package/packages/apra-fleet-se/apra-pm/agents/integ-test-runner.md +38 -10
  366. package/packages/apra-fleet-se/apra-pm/agents/kb-reconciler.md +37 -7
  367. package/packages/apra-fleet-se/apra-pm/agents/plan-reviewer.md +145 -32
  368. package/packages/apra-fleet-se/apra-pm/agents/planner.md +180 -69
  369. package/packages/apra-fleet-se/apra-pm/agents/regression-test-runner.md +98 -64
  370. package/packages/apra-fleet-se/apra-pm/agents/reviewer.md +117 -45
  371. package/packages/apra-fleet-se/apra-pm/agents/schemas/backlog-groomer-output.json +1 -1
  372. package/packages/apra-fleet-se/apra-pm/agents/schemas/doer-output.json +32 -0
  373. package/packages/apra-fleet-se/apra-pm/agents/schemas/harvester-input.json +1 -5
  374. package/packages/apra-fleet-se/apra-pm/agents/schemas/plan-reviewer-output.json +37 -0
  375. package/packages/apra-fleet-se/apra-pm/agents/schemas/planner-output.json +1 -1
  376. package/packages/apra-fleet-se/apra-pm/agents/schemas/regression-test-runner-output.json +41 -7
  377. package/packages/apra-fleet-se/apra-pm/agents/schemas/reviewer-output.json +62 -3
  378. package/packages/apra-fleet-se/apra-pm/skills/pm/SKILL.md +4 -4
  379. package/packages/apra-fleet-se/apra-pm/skills/pm/cost.md +0 -3
  380. package/packages/apra-fleet-se/apra-pm/skills/pm/fleet-addendum.md +2 -2
  381. package/packages/apra-fleet-se/apra-pm/skills/pm/index.md +4 -2
  382. package/packages/apra-fleet-se/apra-pm/skills/pm/kb-reconcile.md +29 -14
  383. package/packages/apra-fleet-se/apra-pm/skills/pm/kb-review.md +1 -0
  384. package/packages/apra-fleet-se/apra-pm/skills/pm/sprint.md +5 -5
  385. package/packages/apra-fleet-se/bin/cli.mjs +326 -48
  386. package/packages/apra-fleet-se/bin/serve.mjs +218 -11
  387. package/packages/apra-fleet-se/fleet-sprint/abort.mjs +517 -0
  388. package/packages/apra-fleet-se/fleet-sprint/backlog-role.mjs +93 -0
  389. package/packages/apra-fleet-se/fleet-sprint/beads-children.mjs +646 -0
  390. package/packages/apra-fleet-se/fleet-sprint/beads-identity-check.mjs +825 -0
  391. package/packages/apra-fleet-se/fleet-sprint/beads-identity.mjs +217 -0
  392. package/packages/apra-fleet-se/fleet-sprint/beads-memory-hygiene.mjs +201 -0
  393. package/packages/apra-fleet-se/fleet-sprint/beads-scope.mjs +745 -0
  394. package/packages/apra-fleet-se/fleet-sprint/beads-transitions.mjs +447 -0
  395. package/packages/apra-fleet-se/fleet-sprint/branch-ensure.mjs +96 -0
  396. package/packages/apra-fleet-se/fleet-sprint/ci-gate.mjs +353 -0
  397. package/packages/apra-fleet-se/fleet-sprint/conflict-ladder.mjs +20 -0
  398. package/packages/apra-fleet-se/fleet-sprint/contracts.mjs +121 -15
  399. package/packages/apra-fleet-se/fleet-sprint/coordination.mjs +539 -0
  400. package/packages/apra-fleet-se/fleet-sprint/dispatch-accounting.mjs +270 -0
  401. package/packages/apra-fleet-se/fleet-sprint/dispatch-failure.mjs +204 -0
  402. package/packages/apra-fleet-se/fleet-sprint/dispatch-role.mjs +1310 -0
  403. package/packages/apra-fleet-se/fleet-sprint/dispatch-safety-guard.mjs +216 -4
  404. package/packages/apra-fleet-se/fleet-sprint/docs/README.md +53 -15
  405. package/packages/apra-fleet-se/fleet-sprint/docs/dolt-sync-redesign.md +281 -0
  406. package/packages/apra-fleet-se/fleet-sprint/docs/escalate-to-llm-design.md +1 -1
  407. package/packages/apra-fleet-se/fleet-sprint/docs/fleet-sprint-diagram.md +3 -3
  408. package/packages/apra-fleet-se/fleet-sprint/docs/run-sprint-cycle-prelude-decision.md +215 -0
  409. package/packages/apra-fleet-se/fleet-sprint/dolt-literal-guard.mjs +56 -1
  410. package/packages/apra-fleet-se/fleet-sprint/dolt-sync.mjs +1327 -44
  411. package/packages/apra-fleet-se/fleet-sprint/errors.mjs +470 -4
  412. package/packages/apra-fleet-se/fleet-sprint/explicit-id-create-guard.mjs +501 -0
  413. package/packages/apra-fleet-se/fleet-sprint/fatal-diagnostics.mjs +134 -0
  414. package/packages/apra-fleet-se/fleet-sprint/full-db-fetch-guard.mjs +102 -0
  415. package/packages/apra-fleet-se/fleet-sprint/git-sync.mjs +747 -0
  416. package/packages/apra-fleet-se/fleet-sprint/git-topology.mjs +543 -0
  417. package/packages/apra-fleet-se/fleet-sprint/guarded-modules.mjs +613 -0
  418. package/packages/apra-fleet-se/fleet-sprint/inline-ladder-guard.mjs +216 -0
  419. package/packages/apra-fleet-se/fleet-sprint/kb-hints.mjs +181 -0
  420. package/packages/apra-fleet-se/fleet-sprint/kb-injection.mjs +64 -0
  421. package/packages/apra-fleet-se/fleet-sprint/kb-maintainer.mjs +298 -0
  422. package/packages/apra-fleet-se/fleet-sprint/kb.mjs +1684 -0
  423. package/packages/apra-fleet-se/fleet-sprint/lower-quality.mjs +39 -0
  424. package/packages/apra-fleet-se/fleet-sprint/mcp-result.mjs +75 -0
  425. package/packages/apra-fleet-se/fleet-sprint/member-align.mjs +391 -0
  426. package/packages/apra-fleet-se/fleet-sprint/member-call.mjs +374 -0
  427. package/packages/apra-fleet-se/fleet-sprint/member-init-probe.mjs +644 -0
  428. package/packages/apra-fleet-se/fleet-sprint/member-provisioning.mjs +699 -0
  429. package/packages/apra-fleet-se/fleet-sprint/member-sync.mjs +802 -0
  430. package/packages/apra-fleet-se/fleet-sprint/member-target.mjs +93 -0
  431. package/packages/apra-fleet-se/fleet-sprint/newtask-text.mjs +266 -0
  432. package/packages/apra-fleet-se/fleet-sprint/orphan-reclaim.mjs +153 -0
  433. package/packages/apra-fleet-se/fleet-sprint/parent-notes-staleness.mjs +201 -0
  434. package/packages/apra-fleet-se/fleet-sprint/phases/deploy.mjs +218 -0
  435. package/packages/apra-fleet-se/fleet-sprint/phases/develop.mjs +869 -0
  436. package/packages/apra-fleet-se/fleet-sprint/phases/ensure-sprint-branch.mjs +295 -0
  437. package/packages/apra-fleet-se/fleet-sprint/phases/final-review.mjs +466 -0
  438. package/packages/apra-fleet-se/fleet-sprint/phases/harvest.mjs +212 -0
  439. package/packages/apra-fleet-se/fleet-sprint/phases/integ-test.mjs +358 -0
  440. package/packages/apra-fleet-se/fleet-sprint/phases/plan.mjs +395 -0
  441. package/packages/apra-fleet-se/fleet-sprint/phases/publish-pr.mjs +345 -0
  442. package/packages/apra-fleet-se/fleet-sprint/phases/re-review.mjs +264 -0
  443. package/packages/apra-fleet-se/fleet-sprint/phases/regression-test.mjs +179 -0
  444. package/packages/apra-fleet-se/fleet-sprint/phases/replan.mjs +230 -0
  445. package/packages/apra-fleet-se/fleet-sprint/phases/review.mjs +365 -0
  446. package/packages/apra-fleet-se/fleet-sprint/pr-body.mjs +259 -0
  447. package/packages/apra-fleet-se/fleet-sprint/prompts.mjs +617 -0
  448. package/packages/apra-fleet-se/fleet-sprint/role-policies.mjs +1434 -0
  449. package/packages/apra-fleet-se/fleet-sprint/round-session.mjs +100 -0
  450. package/packages/apra-fleet-se/fleet-sprint/runner.js +2289 -9928
  451. package/packages/apra-fleet-se/fleet-sprint/se-os-commands.mjs +24 -0
  452. package/packages/apra-fleet-se/fleet-sprint/se-posix.mjs +147 -12
  453. package/packages/apra-fleet-se/fleet-sprint/se-windows.mjs +111 -0
  454. package/packages/apra-fleet-se/fleet-sprint/shell-command-guard.mjs +347 -0
  455. package/packages/apra-fleet-se/fleet-sprint/skills/fleet-sprint-cli/SKILL.md +48 -6
  456. package/packages/apra-fleet-se/fleet-sprint/skills/fleet-supervisor/SKILL.md +98 -25
  457. package/packages/apra-fleet-se/fleet-sprint/sprint-args.mjs +590 -0
  458. package/packages/apra-fleet-se/fleet-sprint/sprint-report.mjs +339 -0
  459. package/packages/apra-fleet-se/fleet-sprint/sprint-state.mjs +185 -0
  460. package/packages/apra-fleet-se/fleet-sprint/unbracketed-push-guard.mjs +234 -0
  461. package/packages/apra-fleet-se/fleet-sprint/usage-limit-controller.mjs +218 -0
  462. package/packages/apra-fleet-se/fleet-sprint/vcs-auth.mjs +1445 -0
  463. package/packages/apra-fleet-se/fleet-sprint/vcs-module.mjs +284 -23
  464. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/azure-devops.mjs +170 -21
  465. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/bitbucket.mjs +28 -0
  466. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/github.mjs +354 -0
  467. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/index.mjs +189 -16
  468. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/shell-helpers.mjs +9 -4
  469. package/packages/apra-fleet-se/fleet-sprint/verify-block.mjs +152 -0
  470. package/packages/apra-fleet-se/fleet-sprint/viewer-extensions.mjs +311 -22
  471. package/packages/apra-fleet-se/fleet-sprint/worklists.mjs +559 -0
  472. package/packages/apra-fleet-se/package.json +2 -2
  473. package/packages/apra-fleet-se/src/supervisor/api.mjs +919 -0
  474. package/packages/apra-fleet-se/src/supervisor/backlog-member.mjs +332 -0
  475. package/packages/apra-fleet-se/src/supervisor/backlog.mjs +982 -0
  476. package/packages/apra-fleet-se/src/supervisor/beads-identity.mjs +246 -0
  477. package/packages/apra-fleet-se/src/supervisor/beads-view.mjs +438 -0
  478. package/packages/apra-fleet-se/src/supervisor/child-port.mjs +36 -0
  479. package/packages/apra-fleet-se/src/supervisor/dashboard.mjs +1659 -0
  480. package/packages/apra-fleet-se/src/supervisor/dolt-mutex.mjs +350 -0
  481. package/packages/apra-fleet-se/src/supervisor/dolt-orphan-sweep.mjs +338 -0
  482. package/packages/apra-fleet-se/src/supervisor/fleet-members.mjs +279 -0
  483. package/packages/apra-fleet-se/src/supervisor/history-view.mjs +276 -0
  484. package/packages/apra-fleet-se/src/supervisor/history.mjs +328 -0
  485. package/packages/apra-fleet-se/src/supervisor/id-allocator.mjs +521 -0
  486. package/packages/apra-fleet-se/src/supervisor/launch-form.mjs +444 -0
  487. package/packages/apra-fleet-se/src/supervisor/ledger.mjs +629 -0
  488. package/packages/apra-fleet-se/src/supervisor/lib/exec-bd.mjs +303 -0
  489. package/packages/apra-fleet-se/src/supervisor/log-timestamp.mjs +51 -0
  490. package/packages/apra-fleet-se/src/supervisor/log-view.mjs +159 -0
  491. package/packages/apra-fleet-se/src/supervisor/proxy.mjs +474 -0
  492. package/packages/apra-fleet-se/src/supervisor/readopt.mjs +136 -0
  493. package/packages/apra-fleet-se/src/supervisor/reconcile.mjs +263 -0
  494. package/packages/apra-fleet-se/src/supervisor/rename-with-retry.mjs +87 -0
  495. package/packages/apra-fleet-se/src/supervisor/scope-overlap.mjs +327 -0
  496. package/packages/apra-fleet-se/src/supervisor/self-log.mjs +133 -0
  497. package/packages/apra-fleet-se/src/supervisor/server.mjs +399 -0
  498. package/packages/apra-fleet-se/src/supervisor/spawner.mjs +542 -0
  499. package/packages/apra-fleet-se/src/supervisor/sprint-identity.mjs +96 -0
  500. package/packages/apra-fleet-se/src/supervisor/watchdog.mjs +987 -0
  501. package/packages/apra-fleet-workflow/package.json +1 -1
  502. package/packages/apra-fleet-workflow/src/viewer/index.mjs +81 -15
  503. package/packages/apra-fleet-workflow/src/viewer/run-summary.mjs +127 -0
  504. package/packages/apra-fleet-workflow/src/workflow/index.mjs +118 -10
  505. package/packages/apra-fleet-workflow/src/workflow/pricing.mjs +75 -25
  506. package/skills/fleet/SKILL.md +8 -8
  507. package/skills/fleet/auth-azdevops.md +14 -3
  508. package/skills/fleet/auth-bitbucket.md +2 -2
  509. package/skills/fleet/auth-github.md +5 -4
  510. package/skills/fleet/onboarding.md +3 -3
  511. package/skills/fleet/permissions.md +14 -1
  512. package/skills/fleet/profiles/node.json +1 -1
  513. package/skills/fleet/profiles/tag-kb-reconciler.json +2 -6
  514. package/skills/fleet/troubleshooting.md +3 -3
  515. package/version.json +1 -1
  516. package/dist/cli/agent-transform.d.ts.map +0 -1
  517. package/dist/cli/agent-transform.js.map +0 -1
  518. package/dist/cli/auth.d.ts.map +0 -1
  519. package/dist/cli/auth.js.map +0 -1
  520. package/dist/cli/config.d.ts.map +0 -1
  521. package/dist/cli/config.js.map +0 -1
  522. package/dist/cli/dolt-install.d.ts.map +0 -1
  523. package/dist/cli/dolt-install.js.map +0 -1
  524. package/dist/cli/install-guard.d.ts.map +0 -1
  525. package/dist/cli/install-guard.js.map +0 -1
  526. package/dist/cli/install.d.ts.map +0 -1
  527. package/dist/cli/install.js.map +0 -1
  528. package/dist/cli/join.d.ts.map +0 -1
  529. package/dist/cli/join.js.map +0 -1
  530. package/dist/cli/kb-commit.d.ts.map +0 -1
  531. package/dist/cli/kb-commit.js.map +0 -1
  532. package/dist/cli/kb-directives.d.ts.map +0 -1
  533. package/dist/cli/kb-directives.js.map +0 -1
  534. package/dist/cli/kb-import.d.ts.map +0 -1
  535. package/dist/cli/kb-import.js.map +0 -1
  536. package/dist/cli/register-member.d.ts.map +0 -1
  537. package/dist/cli/register-member.js.map +0 -1
  538. package/dist/cli/restart.d.ts.map +0 -1
  539. package/dist/cli/restart.js.map +0 -1
  540. package/dist/cli/secret.d.ts.map +0 -1
  541. package/dist/cli/secret.js.map +0 -1
  542. package/dist/cli/spoke.d.ts.map +0 -1
  543. package/dist/cli/spoke.js.map +0 -1
  544. package/dist/cli/start.d.ts.map +0 -1
  545. package/dist/cli/start.js.map +0 -1
  546. package/dist/cli/status.d.ts.map +0 -1
  547. package/dist/cli/status.js.map +0 -1
  548. package/dist/cli/stop.d.ts.map +0 -1
  549. package/dist/cli/stop.js.map +0 -1
  550. package/dist/cli/uninstall.d.ts.map +0 -1
  551. package/dist/cli/uninstall.js.map +0 -1
  552. package/dist/cli/update.d.ts.map +0 -1
  553. package/dist/cli/update.js.map +0 -1
  554. package/dist/cli/watch.d.ts.map +0 -1
  555. package/dist/cli/watch.js.map +0 -1
  556. package/dist/cli/workflow-assets.d.ts.map +0 -1
  557. package/dist/cli/workflow-assets.js.map +0 -1
  558. package/dist/cli/workflow.d.ts.map +0 -1
  559. package/dist/cli/workflow.js.map +0 -1
  560. package/dist/commands/kb-server.d.ts.map +0 -1
  561. package/dist/commands/kb-server.js.map +0 -1
  562. package/dist/delivery-mode.d.ts.map +0 -1
  563. package/dist/delivery-mode.js.map +0 -1
  564. package/dist/hub-service/activity.d.ts.map +0 -1
  565. package/dist/hub-service/activity.js.map +0 -1
  566. package/dist/hub-service/audit-log.d.ts.map +0 -1
  567. package/dist/hub-service/audit-log.js.map +0 -1
  568. package/dist/hub-service/db/pool.d.ts.map +0 -1
  569. package/dist/hub-service/db/pool.js.map +0 -1
  570. package/dist/hub-service/enrollment.d.ts.map +0 -1
  571. package/dist/hub-service/enrollment.js.map +0 -1
  572. package/dist/hub-service/envelope-routes.d.ts.map +0 -1
  573. package/dist/hub-service/envelope-routes.js.map +0 -1
  574. package/dist/hub-service/handlers/installers.d.ts.map +0 -1
  575. package/dist/hub-service/handlers/installers.js.map +0 -1
  576. package/dist/hub-service/http-server.d.ts.map +0 -1
  577. package/dist/hub-service/http-server.js.map +0 -1
  578. package/dist/hub-service/hub-jwt.d.ts.map +0 -1
  579. package/dist/hub-service/hub-jwt.js.map +0 -1
  580. package/dist/hub-service/jwt-revocation.d.ts.map +0 -1
  581. package/dist/hub-service/jwt-revocation.js.map +0 -1
  582. package/dist/hub-service/machines.d.ts.map +0 -1
  583. package/dist/hub-service/machines.js.map +0 -1
  584. package/dist/hub-service/main.d.ts.map +0 -1
  585. package/dist/hub-service/main.js.map +0 -1
  586. package/dist/hub-service/member-tokens.d.ts.map +0 -1
  587. package/dist/hub-service/member-tokens.js.map +0 -1
  588. package/dist/hub-service/member-view.d.ts.map +0 -1
  589. package/dist/hub-service/member-view.js.map +0 -1
  590. package/dist/hub-service/members.d.ts.map +0 -1
  591. package/dist/hub-service/members.js.map +0 -1
  592. package/dist/hub-service/presence.d.ts.map +0 -1
  593. package/dist/hub-service/presence.js.map +0 -1
  594. package/dist/hub-service/project-view.d.ts.map +0 -1
  595. package/dist/hub-service/project-view.js.map +0 -1
  596. package/dist/hub-service/projects.d.ts.map +0 -1
  597. package/dist/hub-service/projects.js.map +0 -1
  598. package/dist/hub-service/relay-queue.d.ts.map +0 -1
  599. package/dist/hub-service/relay-queue.js.map +0 -1
  600. package/dist/hub-service/session-jwt.d.ts.map +0 -1
  601. package/dist/hub-service/session-jwt.js.map +0 -1
  602. package/dist/hub-service/usage.d.ts.map +0 -1
  603. package/dist/hub-service/usage.js.map +0 -1
  604. package/dist/hub-service/users.d.ts.map +0 -1
  605. package/dist/hub-service/users.js.map +0 -1
  606. package/dist/hub-service/workspaces.d.ts.map +0 -1
  607. package/dist/hub-service/workspaces.js.map +0 -1
  608. package/dist/index.d.ts.map +0 -1
  609. package/dist/index.js.map +0 -1
  610. package/dist/onboarding/text.d.ts.map +0 -1
  611. package/dist/onboarding/text.js.map +0 -1
  612. package/dist/os/git-bash-candidates.d.ts.map +0 -1
  613. package/dist/os/git-bash-candidates.js.map +0 -1
  614. package/dist/os/index.d.ts.map +0 -1
  615. package/dist/os/index.js.map +0 -1
  616. package/dist/os/linux.d.ts.map +0 -1
  617. package/dist/os/linux.js.map +0 -1
  618. package/dist/os/macos.d.ts.map +0 -1
  619. package/dist/os/macos.js.map +0 -1
  620. package/dist/os/os-commands.d.ts.map +0 -1
  621. package/dist/os/os-commands.js.map +0 -1
  622. package/dist/os/windows-gitbash.d.ts.map +0 -1
  623. package/dist/os/windows-gitbash.js.map +0 -1
  624. package/dist/os/windows-wrapper.d.ts.map +0 -1
  625. package/dist/os/windows-wrapper.js.map +0 -1
  626. package/dist/os/windows.d.ts.map +0 -1
  627. package/dist/os/windows.js.map +0 -1
  628. package/dist/paths.d.ts.map +0 -1
  629. package/dist/paths.js.map +0 -1
  630. package/dist/providers/agy.d.ts.map +0 -1
  631. package/dist/providers/agy.js.map +0 -1
  632. package/dist/providers/claude.d.ts.map +0 -1
  633. package/dist/providers/claude.js.map +0 -1
  634. package/dist/providers/codex.d.ts.map +0 -1
  635. package/dist/providers/codex.js.map +0 -1
  636. package/dist/providers/copilot.d.ts.map +0 -1
  637. package/dist/providers/copilot.js.map +0 -1
  638. package/dist/providers/email/headers.d.ts.map +0 -1
  639. package/dist/providers/email/headers.js.map +0 -1
  640. package/dist/providers/email/index.d.ts.map +0 -1
  641. package/dist/providers/email/index.js.map +0 -1
  642. package/dist/providers/email/provider.d.ts.map +0 -1
  643. package/dist/providers/email/provider.js.map +0 -1
  644. package/dist/providers/email/sendgrid.d.ts.map +0 -1
  645. package/dist/providers/email/sendgrid.js.map +0 -1
  646. package/dist/providers/email/smtp.d.ts.map +0 -1
  647. package/dist/providers/email/smtp.js.map +0 -1
  648. package/dist/providers/index.d.ts.map +0 -1
  649. package/dist/providers/index.js.map +0 -1
  650. package/dist/providers/none.d.ts.map +0 -1
  651. package/dist/providers/none.js.map +0 -1
  652. package/dist/providers/opencode.d.ts.map +0 -1
  653. package/dist/providers/opencode.js.map +0 -1
  654. package/dist/providers/provider.d.ts.map +0 -1
  655. package/dist/providers/provider.js.map +0 -1
  656. package/dist/services/agent-provisioner.d.ts.map +0 -1
  657. package/dist/services/agent-provisioner.js.map +0 -1
  658. package/dist/services/auth-socket.d.ts.map +0 -1
  659. package/dist/services/auth-socket.js.map +0 -1
  660. package/dist/services/auth-web.d.ts.map +0 -1
  661. package/dist/services/auth-web.js.map +0 -1
  662. package/dist/services/budget-awareness.d.ts.map +0 -1
  663. package/dist/services/budget-awareness.js.map +0 -1
  664. package/dist/services/cloud/activity.d.ts.map +0 -1
  665. package/dist/services/cloud/activity.js.map +0 -1
  666. package/dist/services/cloud/aws.d.ts.map +0 -1
  667. package/dist/services/cloud/aws.js.map +0 -1
  668. package/dist/services/cloud/cost.d.ts.map +0 -1
  669. package/dist/services/cloud/cost.js.map +0 -1
  670. package/dist/services/cloud/idle-manager.d.ts.map +0 -1
  671. package/dist/services/cloud/idle-manager.js.map +0 -1
  672. package/dist/services/cloud/lifecycle.d.ts.map +0 -1
  673. package/dist/services/cloud/lifecycle.js.map +0 -1
  674. package/dist/services/cloud/task-wrapper.d.ts.map +0 -1
  675. package/dist/services/cloud/task-wrapper.js.map +0 -1
  676. package/dist/services/cloud/types.d.ts.map +0 -1
  677. package/dist/services/cloud/types.js.map +0 -1
  678. package/dist/services/cloud-sync.d.ts.map +0 -1
  679. package/dist/services/cloud-sync.js.map +0 -1
  680. package/dist/services/context-admission.d.ts.map +0 -1
  681. package/dist/services/context-admission.js.map +0 -1
  682. package/dist/services/credential-cleanup.d.ts.map +0 -1
  683. package/dist/services/credential-cleanup.js.map +0 -1
  684. package/dist/services/credential-store.d.ts.map +0 -1
  685. package/dist/services/credential-store.js.map +0 -1
  686. package/dist/services/event-bus.d.ts.map +0 -1
  687. package/dist/services/event-bus.js.map +0 -1
  688. package/dist/services/file-chunker.d.ts.map +0 -1
  689. package/dist/services/file-chunker.js.map +0 -1
  690. package/dist/services/file-transfer-relay.d.ts.map +0 -1
  691. package/dist/services/file-transfer-relay.js.map +0 -1
  692. package/dist/services/file-transfer.d.ts.map +0 -1
  693. package/dist/services/file-transfer.js.map +0 -1
  694. package/dist/services/git-config.d.ts.map +0 -1
  695. package/dist/services/git-config.js.map +0 -1
  696. package/dist/services/github-app.d.ts.map +0 -1
  697. package/dist/services/github-app.js.map +0 -1
  698. package/dist/services/http-transport.d.ts.map +0 -1
  699. package/dist/services/http-transport.js.map +0 -1
  700. package/dist/services/hub-client.d.ts.map +0 -1
  701. package/dist/services/hub-client.js.map +0 -1
  702. package/dist/services/icons.d.ts.map +0 -1
  703. package/dist/services/icons.js.map +0 -1
  704. package/dist/services/jwt.d.ts.map +0 -1
  705. package/dist/services/jwt.js.map +0 -1
  706. package/dist/services/knowledge/audn.d.ts.map +0 -1
  707. package/dist/services/knowledge/audn.js.map +0 -1
  708. package/dist/services/knowledge/file-hash.d.ts.map +0 -1
  709. package/dist/services/knowledge/file-hash.js.map +0 -1
  710. package/dist/services/knowledge/http-provider.d.ts.map +0 -1
  711. package/dist/services/knowledge/http-provider.js.map +0 -1
  712. package/dist/services/knowledge/kb-providers.d.ts.map +0 -1
  713. package/dist/services/knowledge/kb-providers.js.map +0 -1
  714. package/dist/services/knowledge/kb-scope-input.d.ts +0 -5
  715. package/dist/services/knowledge/kb-scope-input.d.ts.map +0 -1
  716. package/dist/services/knowledge/kb-scope-input.js +0 -11
  717. package/dist/services/knowledge/kb-scope-input.js.map +0 -1
  718. package/dist/services/knowledge/kb-service.d.ts.map +0 -1
  719. package/dist/services/knowledge/kb-service.js.map +0 -1
  720. package/dist/services/knowledge/path-validation.d.ts.map +0 -1
  721. package/dist/services/knowledge/path-validation.js.map +0 -1
  722. package/dist/services/knowledge/pre-init.d.ts.map +0 -1
  723. package/dist/services/knowledge/pre-init.js.map +0 -1
  724. package/dist/services/knowledge/project-slug.d.ts.map +0 -1
  725. package/dist/services/knowledge/project-slug.js.map +0 -1
  726. package/dist/services/knowledge/sqlite-provider.d.ts.map +0 -1
  727. package/dist/services/knowledge/sqlite-provider.js.map +0 -1
  728. package/dist/services/knowledge/types.d.ts.map +0 -1
  729. package/dist/services/knowledge/types.js.map +0 -1
  730. package/dist/services/known-hosts.d.ts.map +0 -1
  731. package/dist/services/known-hosts.js.map +0 -1
  732. package/dist/services/known-sessions.d.ts.map +0 -1
  733. package/dist/services/known-sessions.js.map +0 -1
  734. package/dist/services/member-home.d.ts.map +0 -1
  735. package/dist/services/member-home.js.map +0 -1
  736. package/dist/services/member-remote-url.d.ts.map +0 -1
  737. package/dist/services/member-remote-url.js.map +0 -1
  738. package/dist/services/model-pricing.d.ts.map +0 -1
  739. package/dist/services/model-pricing.js.map +0 -1
  740. package/dist/services/onboarding.d.ts.map +0 -1
  741. package/dist/services/onboarding.js.map +0 -1
  742. package/dist/services/orphan-recovery.d.ts.map +0 -1
  743. package/dist/services/orphan-recovery.js.map +0 -1
  744. package/dist/services/pending-responses.d.ts.map +0 -1
  745. package/dist/services/pending-responses.js.map +0 -1
  746. package/dist/services/preflight-check.d.ts.map +0 -1
  747. package/dist/services/preflight-check.js.map +0 -1
  748. package/dist/services/registry.d.ts.map +0 -1
  749. package/dist/services/registry.js.map +0 -1
  750. package/dist/services/relay-context.d.ts.map +0 -1
  751. package/dist/services/relay-context.js.map +0 -1
  752. package/dist/services/relay-executor.d.ts.map +0 -1
  753. package/dist/services/relay-executor.js.map +0 -1
  754. package/dist/services/relay-request.d.ts.map +0 -1
  755. package/dist/services/relay-request.js.map +0 -1
  756. package/dist/services/relay-strategy.d.ts.map +0 -1
  757. package/dist/services/relay-strategy.js.map +0 -1
  758. package/dist/services/service-manager/index.d.ts.map +0 -1
  759. package/dist/services/service-manager/index.js.map +0 -1
  760. package/dist/services/service-manager/linux.d.ts.map +0 -1
  761. package/dist/services/service-manager/linux.js.map +0 -1
  762. package/dist/services/service-manager/macos.d.ts.map +0 -1
  763. package/dist/services/service-manager/macos.js.map +0 -1
  764. package/dist/services/service-manager/types.d.ts.map +0 -1
  765. package/dist/services/service-manager/types.js.map +0 -1
  766. package/dist/services/service-manager/windows.d.ts.map +0 -1
  767. package/dist/services/service-manager/windows.js.map +0 -1
  768. package/dist/services/session-registry.d.ts.map +0 -1
  769. package/dist/services/session-registry.js.map +0 -1
  770. package/dist/services/sftp.d.ts.map +0 -1
  771. package/dist/services/sftp.js.map +0 -1
  772. package/dist/services/shell-probe.d.ts.map +0 -1
  773. package/dist/services/shell-probe.js.map +0 -1
  774. package/dist/services/singleton.d.ts.map +0 -1
  775. package/dist/services/singleton.js.map +0 -1
  776. package/dist/services/sprint-coordination.d.ts.map +0 -1
  777. package/dist/services/sprint-coordination.js.map +0 -1
  778. package/dist/services/ssh.d.ts.map +0 -1
  779. package/dist/services/ssh.js.map +0 -1
  780. package/dist/services/stall/find-log-file.d.ts.map +0 -1
  781. package/dist/services/stall/find-log-file.js.map +0 -1
  782. package/dist/services/stall/index.d.ts.map +0 -1
  783. package/dist/services/stall/index.js.map +0 -1
  784. package/dist/services/stall/log-path-resolver.d.ts.map +0 -1
  785. package/dist/services/stall/log-path-resolver.js.map +0 -1
  786. package/dist/services/stall/read-log-tail.d.ts.map +0 -1
  787. package/dist/services/stall/read-log-tail.js.map +0 -1
  788. package/dist/services/stall/stall-detector.d.ts.map +0 -1
  789. package/dist/services/stall/stall-detector.js.map +0 -1
  790. package/dist/services/stall/stall-poller.d.ts.map +0 -1
  791. package/dist/services/stall/stall-poller.js.map +0 -1
  792. package/dist/services/stall/time-utils.d.ts.map +0 -1
  793. package/dist/services/stall/time-utils.js.map +0 -1
  794. package/dist/services/statusline.d.ts.map +0 -1
  795. package/dist/services/statusline.js.map +0 -1
  796. package/dist/services/strategy.d.ts.map +0 -1
  797. package/dist/services/strategy.js.map +0 -1
  798. package/dist/services/substitution-engine.d.ts.map +0 -1
  799. package/dist/services/substitution-engine.js.map +0 -1
  800. package/dist/services/task-cleanup.d.ts.map +0 -1
  801. package/dist/services/task-cleanup.js.map +0 -1
  802. package/dist/services/token-issuer.d.ts.map +0 -1
  803. package/dist/services/token-issuer.js.map +0 -1
  804. package/dist/services/tool-registry.d.ts.map +0 -1
  805. package/dist/services/tool-registry.js.map +0 -1
  806. package/dist/services/update-check.d.ts.map +0 -1
  807. package/dist/services/update-check.js.map +0 -1
  808. package/dist/services/user-config.d.ts.map +0 -1
  809. package/dist/services/user-config.js.map +0 -1
  810. package/dist/services/vcs/azure-devops.d.ts.map +0 -1
  811. package/dist/services/vcs/azure-devops.js.map +0 -1
  812. package/dist/services/vcs/bitbucket.d.ts.map +0 -1
  813. package/dist/services/vcs/bitbucket.js.map +0 -1
  814. package/dist/services/vcs/constants.d.ts.map +0 -1
  815. package/dist/services/vcs/constants.js.map +0 -1
  816. package/dist/services/vcs/github.d.ts.map +0 -1
  817. package/dist/services/vcs/github.js.map +0 -1
  818. package/dist/services/vcs/types.d.ts.map +0 -1
  819. package/dist/services/vcs/types.js.map +0 -1
  820. package/dist/services/version-check.d.ts.map +0 -1
  821. package/dist/services/version-check.js.map +0 -1
  822. package/dist/services/watch/fleet-log.d.ts.map +0 -1
  823. package/dist/services/watch/fleet-log.js.map +0 -1
  824. package/dist/services/watch/project-resolver.d.ts.map +0 -1
  825. package/dist/services/watch/project-resolver.js.map +0 -1
  826. package/dist/services/watch/transcript-formatter.d.ts.map +0 -1
  827. package/dist/services/watch/transcript-formatter.js.map +0 -1
  828. package/dist/smoke-test.d.ts.map +0 -1
  829. package/dist/smoke-test.js.map +0 -1
  830. package/dist/tools/check-status.d.ts.map +0 -1
  831. package/dist/tools/check-status.js.map +0 -1
  832. package/dist/tools/child-id-allocator.d.ts.map +0 -1
  833. package/dist/tools/child-id-allocator.js.map +0 -1
  834. package/dist/tools/cloud-control.d.ts.map +0 -1
  835. package/dist/tools/cloud-control.js.map +0 -1
  836. package/dist/tools/code-intelligence-codebase-memory.d.ts.map +0 -1
  837. package/dist/tools/code-intelligence-codebase-memory.js.map +0 -1
  838. package/dist/tools/code-intelligence-freshness.d.ts.map +0 -1
  839. package/dist/tools/code-intelligence-freshness.js.map +0 -1
  840. package/dist/tools/code-intelligence-gitnexus.d.ts.map +0 -1
  841. package/dist/tools/code-intelligence-gitnexus.js.map +0 -1
  842. package/dist/tools/code-intelligence-kb-enrich.d.ts.map +0 -1
  843. package/dist/tools/code-intelligence-kb-enrich.js.map +0 -1
  844. package/dist/tools/code-intelligence-reindex.d.ts.map +0 -1
  845. package/dist/tools/code-intelligence-reindex.js.map +0 -1
  846. package/dist/tools/code-intelligence-telemetry.d.ts.map +0 -1
  847. package/dist/tools/code-intelligence-telemetry.js.map +0 -1
  848. package/dist/tools/code-intelligence-tests.d.ts.map +0 -1
  849. package/dist/tools/code-intelligence-tests.js.map +0 -1
  850. package/dist/tools/code-intelligence.d.ts.map +0 -1
  851. package/dist/tools/code-intelligence.js.map +0 -1
  852. package/dist/tools/compose-permissions.d.ts.map +0 -1
  853. package/dist/tools/compose-permissions.js.map +0 -1
  854. package/dist/tools/credential-store-delete.d.ts.map +0 -1
  855. package/dist/tools/credential-store-delete.js.map +0 -1
  856. package/dist/tools/credential-store-list.d.ts.map +0 -1
  857. package/dist/tools/credential-store-list.js.map +0 -1
  858. package/dist/tools/credential-store-set.d.ts.map +0 -1
  859. package/dist/tools/credential-store-set.js.map +0 -1
  860. package/dist/tools/credential-store-update.d.ts.map +0 -1
  861. package/dist/tools/credential-store-update.js.map +0 -1
  862. package/dist/tools/dolt-push-mutex.d.ts.map +0 -1
  863. package/dist/tools/dolt-push-mutex.js.map +0 -1
  864. package/dist/tools/execute-command.d.ts.map +0 -1
  865. package/dist/tools/execute-command.js.map +0 -1
  866. package/dist/tools/execute-prompt.d.ts.map +0 -1
  867. package/dist/tools/execute-prompt.js.map +0 -1
  868. package/dist/tools/get-member-model-pricing.d.ts.map +0 -1
  869. package/dist/tools/get-member-model-pricing.js.map +0 -1
  870. package/dist/tools/kb-capture.d.ts.map +0 -1
  871. package/dist/tools/kb-capture.js.map +0 -1
  872. package/dist/tools/kb-context.d.ts.map +0 -1
  873. package/dist/tools/kb-context.js.map +0 -1
  874. package/dist/tools/kb-export.d.ts.map +0 -1
  875. package/dist/tools/kb-export.js.map +0 -1
  876. package/dist/tools/kb-feedback.d.ts.map +0 -1
  877. package/dist/tools/kb-feedback.js.map +0 -1
  878. package/dist/tools/kb-freshness-sweep.d.ts.map +0 -1
  879. package/dist/tools/kb-freshness-sweep.js.map +0 -1
  880. package/dist/tools/kb-harvest.d.ts.map +0 -1
  881. package/dist/tools/kb-harvest.js.map +0 -1
  882. package/dist/tools/kb-import.d.ts.map +0 -1
  883. package/dist/tools/kb-import.js.map +0 -1
  884. package/dist/tools/kb-invalidate.d.ts.map +0 -1
  885. package/dist/tools/kb-invalidate.js.map +0 -1
  886. package/dist/tools/kb-list.d.ts.map +0 -1
  887. package/dist/tools/kb-list.js.map +0 -1
  888. package/dist/tools/kb-promote.d.ts.map +0 -1
  889. package/dist/tools/kb-promote.js.map +0 -1
  890. package/dist/tools/kb-query.d.ts.map +0 -1
  891. package/dist/tools/kb-query.js.map +0 -1
  892. package/dist/tools/kb-reconcile-prefilter.d.ts.map +0 -1
  893. package/dist/tools/kb-reconcile-prefilter.js.map +0 -1
  894. package/dist/tools/kb-resolve-contradiction.d.ts.map +0 -1
  895. package/dist/tools/kb-resolve-contradiction.js.map +0 -1
  896. package/dist/tools/kb-session-prime.d.ts.map +0 -1
  897. package/dist/tools/kb-session-prime.js.map +0 -1
  898. package/dist/tools/kb-setup.d.ts.map +0 -1
  899. package/dist/tools/kb-setup.js.map +0 -1
  900. package/dist/tools/kb-stats.d.ts.map +0 -1
  901. package/dist/tools/kb-stats.js.map +0 -1
  902. package/dist/tools/list-members.d.ts.map +0 -1
  903. package/dist/tools/list-members.js.map +0 -1
  904. package/dist/tools/member-detail.d.ts.map +0 -1
  905. package/dist/tools/member-detail.js.map +0 -1
  906. package/dist/tools/member-reservation.d.ts.map +0 -1
  907. package/dist/tools/member-reservation.js.map +0 -1
  908. package/dist/tools/monitor-task.d.ts.map +0 -1
  909. package/dist/tools/monitor-task.js.map +0 -1
  910. package/dist/tools/provision-auth.d.ts.map +0 -1
  911. package/dist/tools/provision-auth.js.map +0 -1
  912. package/dist/tools/provision-vcs-auth.d.ts.map +0 -1
  913. package/dist/tools/provision-vcs-auth.js.map +0 -1
  914. package/dist/tools/receive-files.d.ts.map +0 -1
  915. package/dist/tools/receive-files.js.map +0 -1
  916. package/dist/tools/register-member.d.ts.map +0 -1
  917. package/dist/tools/register-member.js.map +0 -1
  918. package/dist/tools/remove-member.d.ts.map +0 -1
  919. package/dist/tools/remove-member.js.map +0 -1
  920. package/dist/tools/report-status.d.ts.map +0 -1
  921. package/dist/tools/report-status.js.map +0 -1
  922. package/dist/tools/respond-to-message.d.ts.map +0 -1
  923. package/dist/tools/respond-to-message.js.map +0 -1
  924. package/dist/tools/revoke-vcs-auth.d.ts.map +0 -1
  925. package/dist/tools/revoke-vcs-auth.js.map +0 -1
  926. package/dist/tools/send-email.d.ts.map +0 -1
  927. package/dist/tools/send-email.js.map +0 -1
  928. package/dist/tools/send-files.d.ts.map +0 -1
  929. package/dist/tools/send-files.js.map +0 -1
  930. package/dist/tools/send-message.d.ts.map +0 -1
  931. package/dist/tools/send-message.js.map +0 -1
  932. package/dist/tools/setup-git-app.d.ts.map +0 -1
  933. package/dist/tools/setup-git-app.js.map +0 -1
  934. package/dist/tools/setup-ssh-key.d.ts.map +0 -1
  935. package/dist/tools/setup-ssh-key.js.map +0 -1
  936. package/dist/tools/shutdown-server.d.ts.map +0 -1
  937. package/dist/tools/shutdown-server.js.map +0 -1
  938. package/dist/tools/stop-prompt.d.ts.map +0 -1
  939. package/dist/tools/stop-prompt.js.map +0 -1
  940. package/dist/tools/update-agent-cli.d.ts.map +0 -1
  941. package/dist/tools/update-agent-cli.js.map +0 -1
  942. package/dist/tools/update-member.d.ts.map +0 -1
  943. package/dist/tools/update-member.js.map +0 -1
  944. package/dist/tools/version.d.ts.map +0 -1
  945. package/dist/tools/version.js.map +0 -1
  946. package/dist/types.d.ts.map +0 -1
  947. package/dist/types.js.map +0 -1
  948. package/dist/utils/agent-helpers.d.ts.map +0 -1
  949. package/dist/utils/agent-helpers.js.map +0 -1
  950. package/dist/utils/ansi.d.ts.map +0 -1
  951. package/dist/utils/ansi.js.map +0 -1
  952. package/dist/utils/auth-env.d.ts.map +0 -1
  953. package/dist/utils/auth-env.js.map +0 -1
  954. package/dist/utils/collect-secret.d.ts.map +0 -1
  955. package/dist/utils/collect-secret.js.map +0 -1
  956. package/dist/utils/credential-validation.d.ts.map +0 -1
  957. package/dist/utils/credential-validation.js.map +0 -1
  958. package/dist/utils/crypto.d.ts.map +0 -1
  959. package/dist/utils/crypto.js.map +0 -1
  960. package/dist/utils/deep-merge.d.ts.map +0 -1
  961. package/dist/utils/deep-merge.js.map +0 -1
  962. package/dist/utils/file-permissions.d.ts.map +0 -1
  963. package/dist/utils/file-permissions.js.map +0 -1
  964. package/dist/utils/gpu-parser.d.ts.map +0 -1
  965. package/dist/utils/gpu-parser.js.map +0 -1
  966. package/dist/utils/log-helpers.d.ts.map +0 -1
  967. package/dist/utils/log-helpers.js.map +0 -1
  968. package/dist/utils/oob-timeout.d.ts.map +0 -1
  969. package/dist/utils/oob-timeout.js.map +0 -1
  970. package/dist/utils/opencode-model-validation.d.ts.map +0 -1
  971. package/dist/utils/opencode-model-validation.js.map +0 -1
  972. package/dist/utils/pid-helpers.d.ts.map +0 -1
  973. package/dist/utils/pid-helpers.js.map +0 -1
  974. package/dist/utils/platform.d.ts.map +0 -1
  975. package/dist/utils/platform.js.map +0 -1
  976. package/dist/utils/process-utils.d.ts.map +0 -1
  977. package/dist/utils/process-utils.js.map +0 -1
  978. package/dist/utils/prompt-errors.d.ts.map +0 -1
  979. package/dist/utils/prompt-errors.js.map +0 -1
  980. package/dist/utils/resolve-member.d.ts.map +0 -1
  981. package/dist/utils/resolve-member.js.map +0 -1
  982. package/dist/utils/secure-input.d.ts.map +0 -1
  983. package/dist/utils/secure-input.js.map +0 -1
  984. package/dist/utils/session-caller.d.ts.map +0 -1
  985. package/dist/utils/session-caller.js.map +0 -1
  986. package/dist/utils/shell-escape.d.ts.map +0 -1
  987. package/dist/utils/shell-escape.js.map +0 -1
  988. package/dist/utils/skill-matrix.d.ts.map +0 -1
  989. package/dist/utils/skill-matrix.js.map +0 -1
  990. package/dist/utils/ssh-error-messages.d.ts.map +0 -1
  991. package/dist/utils/ssh-error-messages.js.map +0 -1
  992. package/dist/utils/work-folder-validation.d.ts.map +0 -1
  993. package/dist/utils/work-folder-validation.js.map +0 -1
  994. package/dist/utils/workspace-trust.d.ts.map +0 -1
  995. package/dist/utils/workspace-trust.js.map +0 -1
  996. package/dist/version.d.ts.map +0 -1
  997. package/dist/version.js.map +0 -1
@@ -0,0 +1,1659 @@
1
+ // =============================================================================
2
+ // fleet-sprint supervisor -- sprint-stack index dashboard (apra-fleet-eft.6.1,
3
+ // Plan Part 2.3)
4
+ // =============================================================================
5
+ //
6
+ // Supervisor serves exactly ONE page at `GET /`. This module renders that
7
+ // page's sprint-stack section: one <section> per RUNNING sprint, showing its
8
+ // branch, goal, four-status classifier badge (apra-fleet-eft.4.3), claimed
9
+ // scope (bead count), claimed members (with roles where known), and an
10
+ // open-live-view link. Finished sprints (per the watchdog classifier) are
11
+ // excluded from the stack entirely -- they belong in the process-free
12
+ // History view (apra-fleet-eft.6.5), not here.
13
+ //
14
+ // DATA AVAILABILITY NOTE: as of apra-fleet-3i3.2 the reservation ledger
15
+ // (eft.5.1, src/supervisor/ledger.mjs) also durably persists `branch`,
16
+ // `base`, and `goal` at claim() time (alongside the `members`/`issueRoots`
17
+ // axes it always stored) -- a pre-existing on-disk entry written before those
18
+ // fields existed simply reads back as null for them, never an error. This
19
+ // module still does NOT reach into the ledger's on-disk schema directly for
20
+ // `branch`/`goal`: it sources them (and any per-member role map, which the
21
+ // ledger still does not persist) from an INJECTED `getSprintMeta(sprintId)`
22
+ // collaborator, defaulting to one that reads `branch`/`goal` straight off the
23
+ // ledger entry (see createDashboard() below) when the caller does not inject
24
+ // its own. Every field the page needs still renders (with an explicit
25
+ // "unknown" fallback, never a blank/throw) even when nothing is injected and
26
+ // the ledger entry itself predates these fields.
27
+ //
28
+ // Claimed scope's bead count answers the SAME "how many beads does this
29
+ // sprint currently claim" question eft.5.3's expandScope() (./scope-
30
+ // overlap.mjs) answers for the launch-time overlap guard -- but, as of
31
+ // apra-fleet-c4s.1, computed purely IN-MEMORY off the single bulk
32
+ // `listAllBeads()` fetch this render already makes below, via
33
+ // `expandScopeInMemory()`/`buildChildIndex()` (backlog.mjs), the SAME
34
+ // migration backlog.mjs's own buildClaimedBy() already made for this same
35
+ // "one `bd` subprocess per discovered node" bug. `deps.expandScope` remains
36
+ // the injectable test seam (and, if a caller still supplies it, the actual
37
+ // expansion path used verbatim) -- production wiring (bin/serve.mjs) injects
38
+ // nothing, so it always takes the in-memory path.
39
+ // =============================================================================
40
+
41
+ import { execFile } from 'node:child_process';
42
+ import { promisify } from 'node:util';
43
+ import { EventEmitter } from 'node:events';
44
+ import http from 'node:http';
45
+ import { escapeHtml } from '@apralabs/apra-fleet-workflow/viewer/html-utils';
46
+ import { WATCHDOG_STATUS } from './watchdog.mjs';
47
+ import { renderLaunchFormHtml, formatLaunchError } from './launch-form.mjs';
48
+ import { renderBacklogPanelHtml, normalizeBead, expandScopeInMemory, buildChildIndex } from './backlog.mjs';
49
+ // apra-fleet-72o0 (dashboard follow-up): the claimed-scope count needs CLOSED
50
+ // beads present in the bulk fetch -- a closed intermediate parent must still
51
+ // surface its open descendants to expandScopeInMemory(), same correctness
52
+ // requirement scope-overlap.mjs's launch guard already has. backlog.mjs's own
53
+ // bdListAllBeads()/bdListAllBeadsRaw() deliberately omit `--all` (that fetch
54
+ // feeds the visible backlog BOARD, which intentionally shows open work only)
55
+ // -- reusing it here would repeat the closed-parent-hides-subtree hole. Use
56
+ // scope-overlap.mjs's `--all` fetcher instead; it is the one
57
+ // correctness-appropriate default.
58
+ import { bdListAllBeadsWithClosed } from './scope-overlap.mjs';
59
+ // The progress bar markup is shared with the fleet-sprint viewer; its
60
+ // NUMBERS come from each child's own published summary (GET
61
+ // /state?summary=1, see fetchChildSummary()/classifyChildSummary() below),
62
+ // never from a supervisor-side recompute over the supervisor's beads clone
63
+ // (vre7: that clone can be stale relative to the child's, rendering 0/N for
64
+ // a sprint that has in fact closed work).
65
+ import { renderProgressBarHtml } from '../../fleet-sprint/viewer-extensions.mjs';
66
+ import { toBeadsSummary } from './beads-identity.mjs';
67
+ import { createChildPortResolver } from './child-port.mjs';
68
+
69
+ const execFileAsync = promisify(execFile);
70
+
71
+ /**
72
+ * (apra-fleet-p2to.3.1) Base-drift indicator: how many commits the sprint's
73
+ * base branch (e.g. `main`) has picked up that are NOT yet reachable from the
74
+ * sprint's own branch -- `git rev-list --count <branch>..<base>` -- i.e. how
75
+ * far the sprint has fallen behind its base since it forked. Returns `null`
76
+ * (NEVER throws) when either ref is unknown, the local git checkout has no
77
+ * knowledge of one of them (a remote branch never fetched into this
78
+ * checkout, a sprint whose worktree lives elsewhere), or the git invocation
79
+ * otherwise fails -- "cannot determine drift" is always rendered distinctly
80
+ * from "zero drift" (renderSprintSection below), never conflated as 0.
81
+ * @param {string|null|undefined} branch
82
+ * @param {string|null|undefined} base
83
+ * @param {{ cwd?: string, exec?: (cmd: string, args: string[], opts: object) => Promise<{ stdout: string }> }} [opts]
84
+ * @returns {Promise<number|null>}
85
+ */
86
+ export async function computeBaseDrift(branch, base, opts = {}) {
87
+ if (typeof branch !== 'string' || branch.length === 0) return null;
88
+ if (typeof base !== 'string' || base.length === 0) return null;
89
+ const cwd = opts.cwd ?? process.cwd();
90
+ const exec = opts.exec ?? execFileAsync;
91
+ try {
92
+ const { stdout } = await exec('git', ['rev-list', '--count', `${branch}..${base}`], { cwd, encoding: 'utf-8', windowsHide: true });
93
+ const n = parseInt(String(stdout).trim(), 10);
94
+ return Number.isFinite(n) && n >= 0 ? n : null;
95
+ } catch {
96
+ return null;
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Renders the base-drift indicator for one row. `driftCount === null` means
102
+ * "unknown" (base/branch missing, or the git check failed/could not
103
+ * resolve either ref locally) -- rendered distinctly from a confirmed-zero
104
+ * drift, never silently coerced to either extreme.
105
+ * @param {number|null} driftCount
106
+ * @param {string|null} base
107
+ * @returns {string}
108
+ */
109
+ function baseDriftIndicator(driftCount, base) {
110
+ const baseLabel = base ? escapeHtml(base) : 'base';
111
+ if (typeof driftCount !== 'number') {
112
+ return '<span style="color:#71717a; font-size:11px; font-style:italic;">Base drift: unknown</span>';
113
+ }
114
+ if (driftCount === 0) {
115
+ return '<span style="color:var(--success); font-size:11px;">Up to date with ' + baseLabel + '</span>';
116
+ }
117
+ return '<span style="color:var(--warning); font-size:11px;" title="commits on ' + baseLabel +
118
+ ' not yet merged into this branch">Base drift: ' + driftCount + ' commit(s) behind ' + baseLabel + '</span>';
119
+ }
120
+
121
+ /**
122
+ * Badge color per classifier status value; unknown values fall back to
123
+ * grey. Uses the same `var(--success)`/`var(--warning)`/`var(--danger)`
124
+ * tokens DASHBOARD_CSS defines below (and fleet-sprint's renderBeadsHtml
125
+ * badges already reference) rather than independent hardcoded hex, so a live
126
+ * sprint's health badge and its beads-tree status badges read as one system.
127
+ */
128
+ const STATUS_BADGE_COLORS = Object.freeze({
129
+ [WATCHDOG_STATUS.RUNNING_HEALTHY]: 'var(--success)',
130
+ // (apra-fleet-p2to.3.1) A live, engine-paused run is an intentional,
131
+ // operator-visible state -- not a health problem -- but still worth
132
+ // calling out at a glance, so it shares running-unresponsive's amber
133
+ // rather than success green or danger red.
134
+ [WATCHDOG_STATUS.PAUSED]: 'var(--warning)',
135
+ [WATCHDOG_STATUS.RUNNING_UNRESPONSIVE]: 'var(--warning)',
136
+ [WATCHDOG_STATUS.CRASHED]: 'var(--danger)',
137
+ [WATCHDOG_STATUS.FINISHED]: 'var(--text-muted)',
138
+ });
139
+
140
+ /**
141
+ * Renders a status badge. The label is the classifier's status string
142
+ * VERBATIM (acceptance criterion: "badge text matches the four classifier
143
+ * statuses exactly") -- never relabeled/renamed -- so a caller asserting on
144
+ * the literal text 'running-healthy' / 'running-unresponsive' / 'crashed' /
145
+ * 'finished' always finds it.
146
+ * @param {string} status
147
+ * @returns {string}
148
+ */
149
+ export function statusBadge(status) {
150
+ const safe = escapeHtml(status || 'unknown');
151
+ const color = STATUS_BADGE_COLORS[status] ?? '#a1a1aa';
152
+ return '<span style="color: ' + color + '; font-weight: bold; font-size: 11px; ' +
153
+ 'border: 1px solid ' + color + '; border-radius: 3px; padding: 2px 6px; ' +
154
+ 'white-space: nowrap;">' + safe + '</span>';
155
+ }
156
+
157
+ /**
158
+ * Renders one member's chip: `name` alone, or `name (role)` when a role is
159
+ * known for that member.
160
+ * @param {{ name: string, role?: string|null }} member
161
+ * @returns {string}
162
+ */
163
+ function memberChip(member) {
164
+ const name = escapeHtml(member.name);
165
+ if (member.role) {
166
+ return '<span style="display:inline-block; margin: 0 6px 4px 0; padding: 1px 6px; ' +
167
+ 'border: 1px solid rgba(255,255,255,0.15); border-radius: 3px; font-size: 12px;">' +
168
+ name + ' <span style="color:#a1a1aa;">(' + escapeHtml(member.role) + ')</span></span>';
169
+ }
170
+ return '<span style="display:inline-block; margin: 0 6px 4px 0; padding: 1px 6px; ' +
171
+ 'border: 1px solid rgba(255,255,255,0.15); border-radius: 3px; font-size: 12px;">' +
172
+ name + '</span>';
173
+ }
174
+
175
+ /**
176
+ * Compact "how long ago" label for a pulled summary's computedAt: `12s`,
177
+ * `3m`, `2h`, `1d`. Returns null when the timestamp is missing/unparseable.
178
+ * Self-contained (no module-level references) because it is embedded
179
+ * verbatim into the client live-refresh script via `.toString()`.
180
+ * @param {string|null|undefined} iso
181
+ * @param {number} nowMs
182
+ * @returns {string|null}
183
+ */
184
+ function formatSummaryAge(iso, nowMs) {
185
+ if (typeof iso !== 'string' || iso.length === 0) return null;
186
+ var t = Date.parse(iso);
187
+ if (!Number.isFinite(t)) return null;
188
+ var secs = Math.max(0, Math.floor((nowMs - t) / 1000));
189
+ if (secs < 60) return secs + 's';
190
+ var mins = Math.floor(secs / 60);
191
+ if (mins < 60) return mins + 'm';
192
+ var hours = Math.floor(mins / 60);
193
+ if (hours < 24) return hours + 'h';
194
+ return Math.floor(hours / 24) + 'd';
195
+ }
196
+
197
+ /**
198
+ * The Sprint Stack row's progress markup, driven by the summary view
199
+ * buildSprintViews() pulls from the child (`view.progress`, see
200
+ * classifyChildSummary()):
201
+ * - state 'ok' -> the shared bar + "as of AGE"
202
+ * - state 'unreachable' -> the LAST GOOD bar + "as of AGE" + an
203
+ * "unreachable" marker (only built when a last
204
+ * good summary exists)
205
+ * - state 'no-summary' -> "no summary yet"
206
+ * - anything else (state 'unavailable', null, a legacy shape) -> "status
207
+ * unavailable"
208
+ * Never renders digits/digits for a non-ok state without its last-good
209
+ * marker, and never a 0/N placeholder. Self-contained apart from
210
+ * renderProgressBarHtml/formatSummaryAge/escapeHtml, which the client script
211
+ * embeds alongside it.
212
+ * @param {{ state: string, closed?: number, required?: number, fraction?: number, computedAt?: string|null, rejected?: boolean }|null|undefined} progress
213
+ * @param {number} [nowMs] - pinned "now" for the age label; defaults to Date.now()
214
+ * @returns {string}
215
+ */
216
+ function renderSprintProgressHtml(progress, nowMs) {
217
+ var placeholder = function (text, cls) {
218
+ return '<div class="sprint-progress-status ' + cls + '" style="padding: 8px 0; font-size: 12px; color: #71717a; font-style: italic;">' + text + '</div>';
219
+ };
220
+ var state = progress && typeof progress === 'object' ? progress.state : null;
221
+ var hasNumbers = !!progress && typeof progress.closed === 'number' && Number.isFinite(progress.closed) &&
222
+ typeof progress.required === 'number' && Number.isFinite(progress.required);
223
+ if (state === 'no-summary') {
224
+ return placeholder('no summary yet', 'sprint-progress-no-summary');
225
+ }
226
+ if ((state !== 'ok' && state !== 'unreachable') || !hasNumbers) {
227
+ return placeholder('status unavailable', 'sprint-progress-unavailable');
228
+ }
229
+ var now = typeof nowMs === 'number' && Number.isFinite(nowMs) ? nowMs : Date.now();
230
+ var age = formatSummaryAge(progress.computedAt, now);
231
+ var ageHtml = '<span class="sprint-progress-age" style="color: #a1a1aa; font-size: 12px; white-space: nowrap;">as of ' +
232
+ (age === null ? 'unknown' : age) + '</span>';
233
+ var markerHtml = state === 'unreachable'
234
+ ? '<span class="sprint-progress-unreachable" style="color: #f59e0b; font-size: 12px; white-space: nowrap;">unreachable</span>'
235
+ : '';
236
+ return (
237
+ '<div class="sprint-progress-row" style="display: flex; align-items: center; gap: 8px;">' +
238
+ '<div style="flex: 1;">' +
239
+ renderProgressBarHtml({ closed: progress.closed, required: progress.required, fraction: progress.fraction }) +
240
+ '</div>' +
241
+ ageHtml +
242
+ markerHtml +
243
+ '</div>'
244
+ );
245
+ }
246
+
247
+ /**
248
+ * Renders one running sprint's section.
249
+ * @param {SprintView} view
250
+ * @param {number} [nowMs] - pinned "now" for the progress "as of" label; defaults to Date.now()
251
+ * @returns {string}
252
+ */
253
+ export function renderSprintSection(view, nowMs) {
254
+ const sprintId = escapeHtml(view.sprintId);
255
+ const branch = view.branch ? escapeHtml(view.branch) : 'unknown';
256
+ const base = view.base ? escapeHtml(view.base) : '';
257
+ const goal = view.goal ? escapeHtml(view.goal) : 'unknown';
258
+ const beadCount = Number.isInteger(view.beadCount) ? String(view.beadCount) : 'unknown';
259
+ const progressHtml = renderSprintProgressHtml(view.progress, nowMs);
260
+ const scopeRoots = (view.issueRoots ?? []).map((id) => escapeHtml(id)).join(', ') || 'none';
261
+ const members = (view.members ?? []);
262
+ const membersHtml = members.length > 0
263
+ ? members.map(memberChip).join('')
264
+ : '<span style="color:#71717a; font-style: italic;">no members recorded</span>';
265
+ // Supervisor-relative path ONLY -- never a bare child port (Plan Part 2.3:
266
+ // bare child-port links leak port allocation and break across hosts).
267
+ const liveHref = '/sprints/' + encodeURIComponent(view.sprintId) + '/live';
268
+ // apra-fleet-ou7.2: the raw stdout/stderr log link -- present for EVERY
269
+ // row this stack renders, including a CRASHED sprint (the live SSE
270
+ // viewer above is gone/unresponsive for that status; the raw log is the
271
+ // one remaining way to see what the child actually printed).
272
+ const logHref = '/sprints/' + encodeURIComponent(view.sprintId) + '/log';
273
+
274
+ // (apra-fleet-p2to.3.1) Pause/Resume is only meaningful for a sprint the
275
+ // watchdog currently sees as a LIVE pid (running-healthy/running-
276
+ // unresponsive: Pause may still be attempted against an unresponsive
277
+ // child -- the request itself is what the live proxy forwards, its
278
+ // success is not gated on the watchdog's last HTTP probe) or already
279
+ // PAUSED (Resume). A crashed/finished/launch-failed row has no live
280
+ // child to pause/resume, so neither button renders for it -- unlike
281
+ // Stop/Restart, which remain meaningful (releasing/relaunching a stale
282
+ // reservation) regardless of live-pid state.
283
+ const livePidStatuses = new Set([WATCHDOG_STATUS.RUNNING_HEALTHY, WATCHDOG_STATUS.RUNNING_UNRESPONSIVE]);
284
+ let pauseResumeButton = '';
285
+ if (view.status === WATCHDOG_STATUS.PAUSED) {
286
+ // apra-fleet-p2to.3.1: proxies to the child viewer's OWN POST /resume
287
+ // (apra-fleet-p2to.2.1) via the live-view reverse proxy (proxy.mjs's
288
+ // handleResume, /sprints/:id/live/resume) -- never the kill+force-
289
+ // release route Stop/Restart use.
290
+ pauseResumeButton = '<button type="button" class="btn btn-secondary btn-resume-sprint" data-sprint-id="' + sprintId + '" ' +
291
+ 'style="font-size: 12px;">Resume</button>';
292
+ } else if (livePidStatuses.has(view.status)) {
293
+ // apra-fleet-p2to.3.1: proxies to the child viewer's OWN POST /pause
294
+ // (apra-fleet-p2to.2.1) via the SAME live-view reverse proxy
295
+ // (proxy.mjs's handlePause, /sprints/:id/live/pause) -- a cooperative
296
+ // request the engine may defer, never an immediate kill.
297
+ pauseResumeButton = '<button type="button" class="btn btn-secondary btn-pause-sprint" data-sprint-id="' + sprintId + '" ' +
298
+ 'style="font-size: 12px;">Pause</button>';
299
+ }
300
+
301
+ return (
302
+ '<section data-sprint-id="' + sprintId + '" style="border: 1px solid rgba(255,255,255,0.1); ' +
303
+ 'border-radius: 6px; padding: 12px 14px; margin-bottom: 12px;">' +
304
+ '<div style="display:flex; align-items:center; gap: 10px; flex-wrap: wrap;">' +
305
+ '<strong style="font-size: 14px;">' + sprintId + '</strong>' +
306
+ statusBadge(view.status) +
307
+ '<a href="' + liveHref + '" target="_blank" rel="noopener" style="margin-left:auto; font-size: 12px;">Open live view</a>' +
308
+ '<a href="' + logHref + '" target="_blank" rel="noopener" style="font-size: 12px;">Raw log</a>' +
309
+ // apra-fleet-3i3.1: kills the still-live child AND releases the
310
+ // member+scope reservation in one action (POST /api/reservations/
311
+ // :sprintId/force-release, extended -- see reconcile.mjs). A plain
312
+ // button (not a form submit) wired up by SPRINT_STOP_SCRIPT below via
313
+ // event delegation on data-sprint-id, matching the Launch Sprint
314
+ // form's formatLaunchError() inline-feedback convention.
315
+ '<button type="button" class="btn btn-secondary btn-stop-sprint" data-sprint-id="' + sprintId + '" ' +
316
+ 'style="font-size: 12px;">Stop</button>' +
317
+ pauseResumeButton +
318
+ // apra-fleet-3i3.3: releases the SAME reservation (via the SAME
319
+ // force-release route Stop uses) then re-launches the SAME sprint via
320
+ // POST /api/sprints, without a separate manual Stop first -- see
321
+ // SPRINT_RESTART_SCRIPT below and reconcile.mjs's forceRelease(),
322
+ // which now echoes back branch/base/goal/members/issueRoots for
323
+ // exactly this purpose.
324
+ '<button type="button" class="btn btn-secondary btn-restart-sprint" data-sprint-id="' + sprintId + '" ' +
325
+ 'style="font-size: 12px;">Restart</button>' +
326
+ '</div>' +
327
+ progressHtml +
328
+ '<div style="margin-top: 8px; font-size: 13px; color: #d4d4d8;">' +
329
+ '<div><span style="color:#a1a1aa;">Branch:</span> ' + branch + (base ? ' -> ' + base : '') + '</div>' +
330
+ '<div><span style="color:#a1a1aa;">Goal:</span> ' + goal + '</div>' +
331
+ // apra-fleet-vk0a.3: explicitly labeled 'total in scope' -- distinct
332
+ // from the progress bar's OWN, differently-scoped 'Required: M/N'
333
+ // widget a few lines above (the child's own published summary,
334
+ // goal-filtered). This raw count legitimately GROWS
335
+ // over a sprint's life (planners/reviewers add tasks under an
336
+ // already-claimed root); labeling it distinguishes that from a
337
+ // glitch and from the filtered 'Required' count staying flat.
338
+ '<div><span style="color:#a1a1aa;">Claimed scope:</span> ' + beadCount + ' bead(s) total in scope, unfiltered (roots: ' + scopeRoots + ')</div>' +
339
+ // (apra-fleet-p2to.3.1) base-drift indicator -- see baseDriftIndicator()'s
340
+ // doc comment for the "unknown" vs "0 drift" distinction.
341
+ '<div>' + baseDriftIndicator(view.baseDrift ?? null, view.base ?? null) + '</div>' +
342
+ // The beads prefix the supervisor resolved when it launched this
343
+ // sprint (ledger entry `beads`, see beads-identity.mjs); omitted for
344
+ // a reservation predating that field.
345
+ (view.beadsPrefix
346
+ ? '<div><span style="color:#a1a1aa;">Beads prefix:</span> ' + escapeHtml(view.beadsPrefix) + '</div>'
347
+ : '') +
348
+ '</div>' +
349
+ '<div style="margin-top: 8px;">' +
350
+ '<span style="color:#a1a1aa; font-size: 12px;">Members:</span><br/>' +
351
+ membersHtml +
352
+ '</div>' +
353
+ '<div class="stop-result" data-sprint-id="' + sprintId + '" style="margin-top: 6px; font-size: 12px;"></div>' +
354
+ '<div class="restart-result" data-sprint-id="' + sprintId + '" style="margin-top: 6px; font-size: 12px;"></div>' +
355
+ '<div class="pause-result" data-sprint-id="' + sprintId + '" style="margin-top: 6px; font-size: 12px;"></div>' +
356
+ '</section>'
357
+ );
358
+ }
359
+
360
+ /**
361
+ * Renders the full sprint-stack section: one <section> per running sprint, or
362
+ * an explicit empty-state message when there are none. Never throws on an
363
+ * empty/undefined input -- the page must render correctly with zero running
364
+ * sprints (acceptance criterion).
365
+ * @param {SprintView[]} [views]
366
+ * @returns {string}
367
+ */
368
+ export function renderSprintStackHtml(views) {
369
+ const list = Array.isArray(views) ? views : [];
370
+ if (list.length === 0) {
371
+ return '<p style="color:#71717a; font-style: italic;">No sprints are currently running.</p>';
372
+ }
373
+ // Arrow wrapper: a bare .map(renderSprintSection) would pass the array
374
+ // index as renderSprintSection's optional `nowMs`.
375
+ return list.map((view) => renderSprintSection(view)).join('\n');
376
+ }
377
+
378
+ // apra-fleet supervisor-viewer-parity: the SAME CSS custom-property names and
379
+ // header/tab/panel vocabulary as apra-fleet-workflow's per-sprint dashboard
380
+ // (packages/apra-fleet-workflow/src/viewer/index.mjs's HTML_TEMPLATE) -- one
381
+ // operator moving between "a single sprint's live view" and "the cross-sprint
382
+ // supervisor" should not have to re-learn a second visual language. fleet-
383
+ // sprint's own beads-tree extension (viewer-extensions.mjs's renderBeadsHtml,
384
+ // reused verbatim for the Backlog tab below) already styles its badges via
385
+ // `var(--accent)` / `var(--danger)` etc, so defining the SAME tokens here is
386
+ // what makes that reuse actually look right, not just share markup shape.
387
+ const DASHBOARD_CSS = `
388
+ :root {
389
+ --bg: #09090b; --bg-glass: rgba(24, 24, 27, 0.6); --border: rgba(255, 255, 255, 0.1);
390
+ --text: #e4e4e7; --text-muted: #a1a1aa; --accent: #3b82f6; --accent-glow: rgba(59, 130, 246, 0.2);
391
+ --success: #10b981; --warning: #f59e0b; --danger: #ef4444;
392
+ }
393
+ * { box-sizing: border-box; margin: 0; padding: 0; }
394
+ html, body { height: 100%; }
395
+ body { background: var(--bg); color: var(--text); font-family: sans-serif; height: 100vh; height: 100dvh; overflow: hidden; display: flex; flex-direction: column; }
396
+ a { color: var(--accent); }
397
+ .header { flex-shrink: 0; display: flex; justify-content: space-between; align-items: center; padding: 12px 24px; background: var(--bg-glass); border-bottom: 1px solid var(--border); }
398
+ .header h1 { font-size: 16px; font-weight: 600; margin: 0; }
399
+ .header-actions { display: flex; gap: 12px; align-items: center; }
400
+ .stats-banner { display: flex; gap: 16px; font-size: 12px; color: var(--text-muted); background: rgba(0,0,0,0.3); padding: 4px 12px; border-radius: 12px; border: 1px solid rgba(255,255,255,0.05); }
401
+ .stats-banner span strong { color: var(--text); font-weight: 600; }
402
+
403
+ .btn { padding: 4px 12px; font-size: 12px; border-radius: 4px; border: none; cursor: pointer; font-weight: 600; transition: opacity 0.2s; }
404
+ .btn:hover { opacity: 0.8; }
405
+ .btn-secondary { background: rgba(255,255,255,0.1); color: var(--text); }
406
+
407
+ .main-content { display: flex; flex: 1; overflow: hidden; min-height: 0; }
408
+ .content-area { flex: 1; padding: 20px; display: flex; flex-direction: column; overflow: hidden; min-height: 0; }
409
+ .panel { background: var(--bg-glass); border: 1px solid var(--border); border-radius: 6px; display: flex; flex-direction: column; flex: 1; overflow: hidden; min-height: 0; }
410
+ .panel-header { flex-shrink: 0; padding: 10px 16px; font-size: 12px; font-weight: 600; color: var(--text-muted); border-bottom: 1px solid var(--border); background: rgba(255,255,255,0.02); text-transform: uppercase; letter-spacing: 0.5px; }
411
+ .panel-body { flex: 1; min-height: 0; overflow-y: auto; padding: 14px; }
412
+
413
+ .tab-bar { display: flex; gap: 8px; margin-bottom: 16px; border-bottom: 1px solid rgba(255,255,255,0.1); padding-bottom: 8px; flex-shrink: 0; }
414
+ .tab-btn { background: transparent; color: var(--text-muted); border: none; padding: 6px 12px; cursor: pointer; border-radius: 4px; font-size: 13px; }
415
+ .tab-btn:hover { background: rgba(255,255,255,0.05); }
416
+ .tab-btn.active { color: #fff; background: rgba(255,255,255,0.1); }
417
+ .tab-content { display: none; }
418
+ .tab-content.active { display: flex; min-height: 0; }
419
+
420
+ .bead-row-selected { outline: 2px solid var(--accent); background: var(--accent-glow) !important; }
421
+ table tr:hover { background: rgba(255,255,255,0.03); }
422
+ `;
423
+
424
+ // (apra-fleet-siqi.2.1) How old a tab's last fetch must be, in ms, before
425
+ // activating that tab triggers a fresh one -- rather than just showing
426
+ // whatever markup the last full-page load (or last poll/filter fetch)
427
+ // already produced. Deliberately shorter than SPRINT_STACK_LIVE_SCRIPT's own
428
+ // HEARTBEAT_INTERVAL_MS (7000, above) so a tab switch shortly after that
429
+ // heartbeat's own poll does not double-fetch, but idling on one tab for even
430
+ // a few seconds before switching still gets a genuinely fresh fetch on
431
+ // activation rather than stale data.
432
+ const TAB_ACTIVATION_STALE_MS = 3000;
433
+
434
+ const DASHBOARD_TAB_SCRIPT = `
435
+ var TAB_ACTIVATION_STALE_MS = ${TAB_ACTIVATION_STALE_MS};
436
+ function switchTab(id) {
437
+ document.querySelectorAll('.tab-btn').forEach(function (b) { b.classList.remove('active'); });
438
+ document.querySelectorAll('.tab-content').forEach(function (c) { c.classList.remove('active'); });
439
+ event.currentTarget.classList.add('active');
440
+ document.getElementById('tab-' + id).classList.add('active');
441
+ // apra-fleet-siqi.2.1: activating a tab triggers a fresh fetch of
442
+ // THAT tab's own data through the SAME fetch/poll plumbing each tab
443
+ // already uses elsewhere (SPRINT_STACK_LIVE_SCRIPT's schedulePoll()/
444
+ // poll() for Sprints, backlogPanelClientScript()'s applyFilters() for
445
+ // Backlog) -- never a separate one-off fetch call -- but only when
446
+ // the last such fetch is stale (see TAB_ACTIVATION_STALE_MS above);
447
+ // each tab tracks and refreshes independently of the other.
448
+ if (id === 'sprints' && window.__fleetSeSprintStack && typeof window.__fleetSeSprintStack.refreshIfStale === 'function') {
449
+ window.__fleetSeSprintStack.refreshIfStale(TAB_ACTIVATION_STALE_MS);
450
+ } else if (id === 'backlog' && window.__fleetSeBacklog && typeof window.__fleetSeBacklog.refreshIfStale === 'function') {
451
+ window.__fleetSeBacklog.refreshIfStale(TAB_ACTIVATION_STALE_MS);
452
+ }
453
+ }
454
+ `;
455
+
456
+ /**
457
+ * Renders a POST /api/reservations/:sprintId/force-release error response
458
+ * (reconcile.mjs's ApiError-shaped JSON: `{ error: string }`, e.g. a 404 for
459
+ * an already-gone sprint) as a legible operator-facing message. Mirrors
460
+ * launch-form.mjs's formatLaunchError() pattern exactly (acceptance
461
+ * criterion: "inline success/error feedback consistent with the Launch
462
+ * Sprint form's formatLaunchError() pattern") -- same pure, side-effect-free,
463
+ * `.toString()`-embeddable shape.
464
+ * @param {number} status
465
+ * @param {{ error?: string }|null|undefined} errJson
466
+ * @returns {string}
467
+ */
468
+ export function formatStopError(status, errJson) {
469
+ const message = (errJson && typeof errJson.error === 'string' && errJson.error.length > 0)
470
+ ? errJson.error
471
+ : `Stop failed (HTTP ${status}).`;
472
+ if (status === 404) {
473
+ return `Already gone: ${message}`;
474
+ }
475
+ return message;
476
+ }
477
+
478
+ /**
479
+ * The Sprint Stack's per-row Stop button behavior, as a source string ready
480
+ * to inline into a `<script>` tag (same `.toString()`-embedding pattern as
481
+ * launch-form.mjs's clientScriptSource(), so the exact code under test is the
482
+ * exact code shipped to the browser). Event-delegated on `document` -- as of
483
+ * apra-fleet-siqi.1.2, SPRINT_STACK_LIVE_SCRIPT below DOES periodically
484
+ * rebuild each `<section data-sprint-id>` row (a fresh /state poll may
485
+ * replace this exact button element), but delegation on `document` still
486
+ * catches every click regardless of which concrete button element it landed
487
+ * on, so a single listener wired once at page load remains sufficient -- no
488
+ * re-wiring needed after a live rebuild: a click on any `.btn-stop-sprint`
489
+ * button confirms with the operator, then POSTs
490
+ * POST /api/reservations/:sprintId/force-release (extended by apra-fleet-3i3.1
491
+ * to also kill the child), surfacing success/failure INLINE in that row's
492
+ * `.stop-result` element (never a silent no-op, and every promise chain ends
493
+ * in a `.catch()` so a network failure can never surface as an unhandled
494
+ * browser rejection). On success the whole `<section>` is removed from the
495
+ * DOM so the stopped sprint no longer visually claims to still be running.
496
+ */
497
+ const SPRINT_STOP_SCRIPT = `
498
+ ${formatStopError.toString()}
499
+ document.addEventListener('click', function (ev) {
500
+ var btn = ev.target.closest('.btn-stop-sprint');
501
+ if (!btn) return;
502
+ var sprintId = btn.getAttribute('data-sprint-id');
503
+ if (!sprintId) return;
504
+ if (!confirm('Stop sprint ' + sprintId + '? This kills its process and releases its reservation.')) return;
505
+ var resultEl = document.querySelector('.stop-result[data-sprint-id="' + sprintId + '"]');
506
+ var section = btn.closest('section[data-sprint-id]');
507
+ // apra-fleet-3i3.3: also disable Restart while a Stop is in flight on
508
+ // the SAME row, so the two controls can never race each other into
509
+ // two concurrent force-release calls for the same sprintId.
510
+ var restartBtn = section ? section.querySelector('.btn-restart-sprint') : null;
511
+ btn.disabled = true;
512
+ if (restartBtn) restartBtn.disabled = true;
513
+ if (resultEl) { resultEl.style.color = '#a1a1aa'; resultEl.textContent = 'Stopping...'; }
514
+ fetch('/api/reservations/' + encodeURIComponent(sprintId) + '/force-release', {
515
+ method: 'POST',
516
+ headers: { 'content-type': 'application/json' },
517
+ body: JSON.stringify({ reason: 'stopped via Sprint Stack Stop button' }),
518
+ }).then(function (res) {
519
+ return res.json().catch(function () { return {}; }).then(function (json) {
520
+ return { status: res.status, json: json };
521
+ });
522
+ }).then(function (r) {
523
+ if (r.status === 200) {
524
+ if (resultEl) { resultEl.style.color = '#22c55e'; resultEl.textContent = 'Stopped.'; }
525
+ if (section) section.remove();
526
+ } else {
527
+ btn.disabled = false;
528
+ if (restartBtn) restartBtn.disabled = false;
529
+ if (resultEl) { resultEl.style.color = '#ef4444'; resultEl.textContent = formatStopError(r.status, r.json); }
530
+ }
531
+ }).catch(function (err) {
532
+ btn.disabled = false;
533
+ if (restartBtn) restartBtn.disabled = false;
534
+ if (resultEl) { resultEl.style.color = '#ef4444'; resultEl.textContent = 'Stop request failed: ' + err.message; }
535
+ });
536
+ });
537
+ `;
538
+
539
+ /**
540
+ * The Sprint Stack's per-row Restart button behavior, as a source string
541
+ * ready to inline into a `<script>` tag (same embedding pattern as
542
+ * SPRINT_STOP_SCRIPT above). A click on any `.btn-restart-sprint` button:
543
+ *
544
+ * 1. Confirms with the operator (destructive-ish: discards the old
545
+ * sprint's history, same framing as Stop).
546
+ * 2. POSTs the SAME POST /api/reservations/:sprintId/force-release route
547
+ * Stop uses (apra-fleet-3i3.1) -- releasing the reservation (and killing
548
+ * the child, if still alive) with NO separate manual Stop first
549
+ * (acceptance criterion).
550
+ * 3. Reads branch/base/goal/members/issueRoots off THAT response's `audit`
551
+ * (apra-fleet-3i3.3's reconcile.mjs extension) rather than a second
552
+ * network round-trip. When branch or base -- both server-REQUIRED
553
+ * fields (api.mjs's validateLaunchRequest) -- is null (a pre-3i3.2
554
+ * legacy entry that never persisted it), prompts the operator to enter
555
+ * it; declining aborts the restart (the old reservation is already
556
+ * released either way, matching Stop's own irreversibility). `goal` is
557
+ * optional at launch, so a null goal only offers a prompt the operator
558
+ * may leave blank, never aborts.
559
+ * 4. POSTs the reconstructed request to POST /api/sprints (the SAME
560
+ * validated launch endpoint the Launch Sprint form uses), surfacing a
561
+ * 201 success (with a link to the new sprint's live view) or failure
562
+ * (via launch-form.mjs's OWN formatLaunchError(), consistent with that
563
+ * form's error-surfacing pattern per the acceptance criterion) INLINE in
564
+ * that row's `.restart-result` element.
565
+ *
566
+ * Every promise chain ends in a `.catch()` (never a silent no-op / unhandled
567
+ * browser rejection). Unlike Stop, a successfully force-released row's
568
+ * `<section>` is NOT removed from the DOM on success -- the freshly-launched
569
+ * sprint has no server-rendered view model yet (branch/goal/bead-count/
570
+ * members are all built server-side in buildSprintViews()), so removing it
571
+ * would discard the only place left to show the success message and the new
572
+ * sprint's live-view link; both buttons are left disabled instead, since the
573
+ * old reservation is gone either way and a further click on either would only
574
+ * ever 404.
575
+ */
576
+ const SPRINT_RESTART_SCRIPT = `
577
+ ${formatStopError.toString()}
578
+ ${formatLaunchError.toString()}
579
+ document.addEventListener('click', function (ev) {
580
+ var btn = ev.target.closest('.btn-restart-sprint');
581
+ if (!btn) return;
582
+ var sprintId = btn.getAttribute('data-sprint-id');
583
+ if (!sprintId) return;
584
+ if (!confirm('Restart sprint ' + sprintId + '? This releases its current reservation and relaunches the same scope as a NEW sprint.')) return;
585
+ var resultEl = document.querySelector('.restart-result[data-sprint-id="' + sprintId + '"]');
586
+ var section = btn.closest('section[data-sprint-id]');
587
+ var stopBtn = section ? section.querySelector('.btn-stop-sprint') : null;
588
+ btn.disabled = true;
589
+ if (stopBtn) stopBtn.disabled = true;
590
+ if (resultEl) { resultEl.style.color = '#a1a1aa'; resultEl.textContent = 'Releasing old reservation...'; }
591
+ fetch('/api/reservations/' + encodeURIComponent(sprintId) + '/force-release', {
592
+ method: 'POST',
593
+ headers: { 'content-type': 'application/json' },
594
+ body: JSON.stringify({ reason: 'restarted via Sprint Stack Restart button' }),
595
+ }).then(function (res) {
596
+ return res.json().catch(function () { return {}; }).then(function (json) {
597
+ return { status: res.status, json: json };
598
+ });
599
+ }).then(function (r) {
600
+ if (r.status !== 200) {
601
+ btn.disabled = false;
602
+ if (stopBtn) stopBtn.disabled = false;
603
+ if (resultEl) { resultEl.style.color = '#ef4444'; resultEl.textContent = formatStopError(r.status, r.json); }
604
+ return;
605
+ }
606
+ var audit = (r.json && r.json.audit) || {};
607
+ var issueRoots = Array.isArray(audit.issueRoots) ? audit.issueRoots : [];
608
+ var members = Array.isArray(audit.members) ? audit.members : [];
609
+ var issue = issueRoots.length > 0 ? issueRoots[0] : null;
610
+ var branch = (typeof audit.branch === 'string' && audit.branch) ? audit.branch : null;
611
+ var base = (typeof audit.base === 'string' && audit.base) ? audit.base : null;
612
+ var goal = (typeof audit.goal === 'string' && audit.goal) ? audit.goal : null;
613
+
614
+ if (!issue || members.length === 0) {
615
+ if (resultEl) { resultEl.style.color = '#ef4444'; resultEl.textContent = 'Reservation released, but the original issue/members could not be recovered -- use the Launch Sprint form to relaunch manually.'; }
616
+ return;
617
+ }
618
+ if (!branch) {
619
+ branch = (window.prompt('Branch name is not recoverable for this sprint -- enter it to continue the restart (Cancel aborts; the old reservation is already released):') || '').trim();
620
+ if (!branch) {
621
+ if (resultEl) { resultEl.style.color = '#ef4444'; resultEl.textContent = 'Restart cancelled: branch name is required. The old reservation has already been released -- use the Launch Sprint form to relaunch manually.'; }
622
+ return;
623
+ }
624
+ }
625
+ if (!base) {
626
+ base = (window.prompt('Base branch name is not recoverable for this sprint -- enter it to continue the restart (Cancel aborts; the old reservation is already released):') || '').trim();
627
+ if (!base) {
628
+ if (resultEl) { resultEl.style.color = '#ef4444'; resultEl.textContent = 'Restart cancelled: base branch name is required. The old reservation has already been released -- use the Launch Sprint form to relaunch manually.'; }
629
+ return;
630
+ }
631
+ }
632
+ if (!goal) {
633
+ goal = (window.prompt('Goal (e.g. P1, P1/P2, P1/P2/P3) for the restarted sprint. Leave blank to launch without one:') || '').trim();
634
+ }
635
+
636
+ if (resultEl) { resultEl.style.color = '#a1a1aa'; resultEl.textContent = 'Relaunching...'; }
637
+ var body = { issue: issue, members: members, branch: branch, base: base };
638
+ if (goal) body.goal = goal;
639
+ fetch('/api/sprints', {
640
+ method: 'POST',
641
+ headers: { 'content-type': 'application/json' },
642
+ body: JSON.stringify(body),
643
+ }).then(function (res2) {
644
+ return res2.json().catch(function () { return {}; }).then(function (json2) {
645
+ return { status: res2.status, json: json2 };
646
+ });
647
+ }).then(function (r2) {
648
+ if (r2.status === 201) {
649
+ if (resultEl) {
650
+ resultEl.style.color = '#22c55e';
651
+ resultEl.textContent = 'Restarted as sprint ' + r2.json.sprintId + '. ';
652
+ var link = document.createElement('a');
653
+ link.href = '/sprints/' + encodeURIComponent(r2.json.sprintId) + '/live';
654
+ link.target = '_blank';
655
+ link.rel = 'noopener';
656
+ link.textContent = 'Open live view';
657
+ resultEl.appendChild(link);
658
+ }
659
+ } else {
660
+ btn.disabled = false;
661
+ if (stopBtn) stopBtn.disabled = false;
662
+ if (resultEl) { resultEl.style.color = '#ef4444'; resultEl.textContent = 'Reservation released, but relaunch failed: ' + formatLaunchError(r2.status, r2.json); }
663
+ }
664
+ }).catch(function (err2) {
665
+ btn.disabled = false;
666
+ if (stopBtn) stopBtn.disabled = false;
667
+ if (resultEl) { resultEl.style.color = '#ef4444'; resultEl.textContent = 'Reservation released, but the relaunch request failed: ' + err2.message; }
668
+ });
669
+ }).catch(function (err) {
670
+ btn.disabled = false;
671
+ if (stopBtn) stopBtn.disabled = false;
672
+ if (resultEl) { resultEl.style.color = '#ef4444'; resultEl.textContent = 'Restart request failed: ' + err.message; }
673
+ });
674
+ });
675
+ `;
676
+
677
+ /**
678
+ * (apra-fleet-p2to.3.1) The Sprint Stack's per-row Pause/Resume button
679
+ * behavior, as a source string ready to inline into a `<script>` tag (same
680
+ * `.toString()`-embedding pattern as SPRINT_STOP_SCRIPT/SPRINT_RESTART_SCRIPT
681
+ * above). Event-delegated on `document`, same discipline as those two: a
682
+ * click on `.btn-pause-sprint` POSTs `/sprints/:id/live/pause`, a click on
683
+ * `.btn-resume-sprint` POSTs `/sprints/:id/live/resume` -- BOTH via the
684
+ * live-view reverse proxy (proxy.mjs), which forwards to the child viewer's
685
+ * OWN `/pause`/`/resume` (apra-fleet-p2to.2.1), never the kill+force-release
686
+ * route Stop/Restart use. Unlike Stop, a click here does not remove or
687
+ * relabel the row: the requested transition is COOPERATIVE and may be
688
+ * deferred by the engine (apra-fleet-p2to.1's requestPause()), so the button
689
+ * is only disabled (to prevent a double-submit) and an inline status message
690
+ * is shown -- the row's own Pause/Resume button + status badge only reflect
691
+ * the ACTUAL new state once the watchdog's own `/state`-based pause probe
692
+ * (watchdog.mjs) has observed it. Pre-apra-fleet-siqi.1.2 that meant "on the
693
+ * next full page load"; as of siqi.1.2, SPRINT_STACK_LIVE_SCRIPT's own
694
+ * periodic /state poll rebuilds this row too, so the correct button/badge
695
+ * typically appears within a poll cycle with no manual reload needed -- this
696
+ * script itself still does not attempt to predict or race that outcome, it
697
+ * only reports the request as submitted. Every promise chain ends in a
698
+ * `.catch()`, matching the other two scripts' discipline.
699
+ */
700
+ const SPRINT_PAUSE_SCRIPT = `
701
+ ${formatStopError.toString()}
702
+ function requestPauseResume(btn, action) {
703
+ var sprintId = btn.getAttribute('data-sprint-id');
704
+ if (!sprintId) return;
705
+ var resultEl = document.querySelector('.pause-result[data-sprint-id="' + sprintId + '"]');
706
+ btn.disabled = true;
707
+ if (resultEl) { resultEl.style.color = '#a1a1aa'; resultEl.textContent = (action === 'pause' ? 'Pause' : 'Resume') + ' requested...'; }
708
+ fetch('/sprints/' + encodeURIComponent(sprintId) + '/live/' + action, { method: 'POST' })
709
+ .then(function (res) {
710
+ return res.json().catch(function () { return {}; }).then(function (json) {
711
+ return { status: res.status, json: json };
712
+ });
713
+ }).then(function (r) {
714
+ if (r.status === 200) {
715
+ if (resultEl) {
716
+ resultEl.style.color = '#22c55e';
717
+ resultEl.textContent = (action === 'pause' ? 'Pause' : 'Resume') + ' requested -- reload to see the updated status.';
718
+ }
719
+ // Deliberately left disabled: the cooperative transition may
720
+ // still be in flight (a deferred pause) or has already
721
+ // happened (a resume) -- either way, this row's button/badge
722
+ // are only accurate again after a reload, and re-enabling
723
+ // it here would let an operator fire the SAME request twice
724
+ // before that reload happens.
725
+ } else {
726
+ btn.disabled = false;
727
+ if (resultEl) { resultEl.style.color = '#ef4444'; resultEl.textContent = formatStopError(r.status, r.json); }
728
+ }
729
+ }).catch(function (err) {
730
+ btn.disabled = false;
731
+ if (resultEl) { resultEl.style.color = '#ef4444'; resultEl.textContent = (action === 'pause' ? 'Pause' : 'Resume') + ' request failed: ' + err.message; }
732
+ });
733
+ }
734
+ document.addEventListener('click', function (ev) {
735
+ var pauseBtn = ev.target.closest('.btn-pause-sprint');
736
+ if (pauseBtn) { requestPauseResume(pauseBtn, 'pause'); return; }
737
+ var resumeBtn = ev.target.closest('.btn-resume-sprint');
738
+ if (resumeBtn) { requestPauseResume(resumeBtn, 'resume'); return; }
739
+ });
740
+ `;
741
+
742
+ /**
743
+ * (apra-fleet-siqi.1.2) The Sprint Stack's live-refresh client loop, as a
744
+ * source string ready to inline into a `<script>` tag (same
745
+ * `.toString()`-embedding pattern as the three button scripts above). Mirrors
746
+ * apra-fleet-workflow's per-sprint viewer client loop
747
+ * (packages/apra-fleet-workflow/src/viewer/index.mjs, ~lines 478-504) in
748
+ * shape exactly: a debounced `schedulePoll()` guard (`POLL_COALESCE_MS`), an
749
+ * `EventSource('/events')` whose `onmessage` calls `schedulePoll()` (this
750
+ * dashboard's own GET /events -- apra-fleet-siqi.1.1 -- emits a generic
751
+ * `{ type: 'update' }` signal on every message, so the payload itself is
752
+ * never inspected here, unlike the per-run viewer's namespaced
753
+ * `workflow:state:*` dispatch), and a `setInterval` heartbeat that ALSO calls
754
+ * `schedulePoll()` so a dropped/unavailable EventSource still polls (the
755
+ * SAME `apra-fleet-36l.1` fallback discipline) -- ONE polling mechanism
756
+ * (`schedulePoll()` -> `poll()`), never two independent pollers.
757
+ *
758
+ * `poll()` fetches GET /state (apra-fleet-siqi.1.1's `buildStatePayload()`
759
+ * shape: `{ generatedAt, runningCount, sprints }`) and re-renders the Sprint
760
+ * Stack rows FROM that payload -- never a one-shot server render, and never
761
+ * `location.reload()`. Row rendering itself reuses `renderSprintSection()`
762
+ * (and its own escapeHtml/statusBadge/renderSprintProgressHtml/memberChip/
763
+ * baseDriftIndicator/renderProgressBarHtml dependencies, all embedded
764
+ * verbatim via `.toString()` below, plus WATCHDOG_STATUS/STATUS_BADGE_COLORS
765
+ * as inline JSON) -- the EXACT SAME markup-building function GET / uses for
766
+ * the initial server render, so a live-refreshed row can never visually
767
+ * drift from a freshly-loaded one. Reconciliation against the current DOM is
768
+ * by `data-sprint-id`: an existing `<section>` is replaced in place (its
769
+ * Stop/Restart/Pause buttons come back correctly wired since those three
770
+ * scripts delegate their click handling on `document`, not on the button
771
+ * elements themselves -- see SPRINT_STOP_SCRIPT's doc comment), a newly
772
+ * appeared sprintId is appended, and a row whose sprintId is no longer in
773
+ * the payload (finished/force-released/restarted-away since the last poll)
774
+ * is removed -- falling back to the SAME empty-state message
775
+ * `renderSprintStackHtml()` renders server-side when the list goes to zero.
776
+ */
777
+ const SPRINT_STACK_LIVE_SCRIPT = `
778
+ ${escapeHtml.toString()}
779
+ ${memberChip.toString()}
780
+ ${baseDriftIndicator.toString()}
781
+ var WATCHDOG_STATUS = ${JSON.stringify(WATCHDOG_STATUS)};
782
+ var STATUS_BADGE_COLORS = ${JSON.stringify(STATUS_BADGE_COLORS)};
783
+ ${statusBadge.toString()}
784
+ ${renderProgressBarHtml.toString()}
785
+ ${formatSummaryAge.toString()}
786
+ ${renderSprintProgressHtml.toString()}
787
+ ${renderSprintSection.toString()}
788
+ ${renderBeadsFreshnessHtml.toString()}
789
+
790
+ // Re-renders the "Beads as of" line from GET /state's beadsFreshness.
791
+ function renderBeadsFreshnessFromState(f) {
792
+ var el = document.getElementById('beads-freshness');
793
+ if (!el || !f) return;
794
+ el.outerHTML = renderBeadsFreshnessHtml(f);
795
+ }
796
+
797
+ // Re-renders #sprint-stack's rows from a GET /state 'sprints' array,
798
+ // in place, by data-sprint-id -- see this const's doc comment above.
799
+ function renderSprintStackFromState(sprints) {
800
+ var container = document.getElementById('sprint-stack');
801
+ if (!container) return;
802
+ var list = Array.isArray(sprints) ? sprints : [];
803
+ var existingSections = {};
804
+ Array.prototype.forEach.call(container.querySelectorAll('section[data-sprint-id]'), function (s) {
805
+ existingSections[s.getAttribute('data-sprint-id')] = s;
806
+ });
807
+ if (list.length === 0) {
808
+ container.innerHTML = '<p style="color:#71717a; font-style: italic;">No sprints are currently running.</p>';
809
+ return;
810
+ }
811
+ var seenIds = {};
812
+ list.forEach(function (view) {
813
+ seenIds[view.sprintId] = true;
814
+ var existing = existingSections[view.sprintId];
815
+ var html = renderSprintSection(view);
816
+ if (existing) {
817
+ existing.outerHTML = html;
818
+ } else {
819
+ // First real row ever renders here (not the empty-state
820
+ // placeholder text) -- clear that placeholder, if present,
821
+ // before appending.
822
+ var placeholder = container.querySelector('p');
823
+ if (placeholder && container.querySelectorAll('section[data-sprint-id]').length === 0) {
824
+ container.innerHTML = '';
825
+ }
826
+ container.insertAdjacentHTML('beforeend', html);
827
+ }
828
+ });
829
+ Object.keys(existingSections).forEach(function (id) {
830
+ if (!seenIds[id]) existingSections[id].remove();
831
+ });
832
+ }
833
+
834
+ // apra-fleet-workflow's viewer client loop (index.mjs ~478-504), same
835
+ // shape: debounced schedulePoll() -> poll(), driven by BOTH an
836
+ // EventSource('/events') message and a setInterval heartbeat fallback.
837
+ var POLL_COALESCE_MS = 400;
838
+ var pollTimer = null;
839
+ function schedulePoll() {
840
+ if (pollTimer) return;
841
+ pollTimer = setTimeout(function () { pollTimer = null; poll(); }, POLL_COALESCE_MS);
842
+ }
843
+
844
+ // apra-fleet-siqi.2.1: when this poll was last (attempted to be) run --
845
+ // set up front, not just on success, so a Sprints-tab activation right
846
+ // after a poll was already scheduled/kicked off never piles on a second,
847
+ // redundant one; see window.__fleetSeSprintStack.refreshIfStale() below.
848
+ var lastPollAt = 0;
849
+ async function poll() {
850
+ lastPollAt = Date.now();
851
+ try {
852
+ var res = await fetch('/state?_t=' + Date.now(), { cache: 'no-store' });
853
+ var data = await res.json();
854
+ renderSprintStackFromState(data.sprints);
855
+ renderBeadsFreshnessFromState(data.beadsFreshness);
856
+ } catch (e) {
857
+ console.error('Poll Error:', e);
858
+ }
859
+ }
860
+
861
+ // apra-fleet-siqi.2.1: the Sprints-tab-activation refresh hook
862
+ // (DASHBOARD_TAB_SCRIPT's switchTab()) reaches this SAME
863
+ // schedulePoll()/poll() plumbing through here -- never a separate
864
+ // one-off fetch -- and only when the last poll is stale. Guarded on
865
+ // 'typeof window' (rather than a bare reference) so this script stays
866
+ // runnable in a sandboxed Function-eval harness that never supplies a
867
+ // 'window' global (e.g. supervisor-dashboard-live-refresh.test.mjs's
868
+ // runLiveRefreshScript(), which only passes document/fetch/EventSource)
869
+ // -- a real browser <script> tag always has 'window' defined, so this
870
+ // guard is a no-op true branch there.
871
+ if (typeof window !== 'undefined') {
872
+ window.__fleetSeSprintStack = {
873
+ refreshIfStale: function (maxAgeMs) {
874
+ if (Date.now() - lastPollAt >= maxAgeMs) schedulePoll();
875
+ },
876
+ };
877
+ }
878
+
879
+ if (typeof EventSource !== 'undefined') {
880
+ var source = new EventSource('/events');
881
+ // Every /events message is the same generic 'go poll /state' signal
882
+ // (apra-fleet-siqi.1.1) -- never inspected, just a trigger.
883
+ source.onmessage = function () { schedulePoll(); };
884
+ }
885
+
886
+ // apra-fleet-36l.1-style heartbeat fallback: independent of EventSource
887
+ // state (unavailable, never connected, or silently dropped without an
888
+ // onerror the browser surfaces), this keeps calling the SAME
889
+ // schedulePoll()/poll() path on a fixed cadence so the dashboard can
890
+ // never sit silently stale.
891
+ var HEARTBEAT_INTERVAL_MS = 7000;
892
+ setInterval(function () { schedulePoll(); }, HEARTBEAT_INTERVAL_MS);
893
+
894
+ poll();
895
+ `;
896
+
897
+ /**
898
+ * The single "which .beads is this supervisor running against" line shown
899
+ * above the Sprint Stack: "Beads: <dir> | prefix <p> | <syncRemote>", every
900
+ * field HTML-escaped, styled like the Supervisor-log link line in the header.
901
+ * When the identity is UNKNOWN (no .beads found / probe failed) and
902
+ * `warning` carries the reason, renders an amber "Beads: NOT RESOLVED --
903
+ * <warning>" line instead (the warning text already says what to do).
904
+ * Renders nothing when neither was supplied (tests, inert skeleton).
905
+ * @param {{ dir?: string, prefix?: string, syncRemote?: string }|null|undefined} beads
906
+ * @param {string|null|undefined} [warning]
907
+ * @returns {string}
908
+ */
909
+ export function renderBeadsHeaderHtml(beads, warning) {
910
+ if (!beads || typeof beads !== 'object') {
911
+ if (typeof warning !== 'string' || !warning.trim()) return '';
912
+ return '<div class="beads-identity beads-identity-warning" style="font-size: 12px; color: #f59e0b; padding: 4px 16px;">' +
913
+ '<strong>Beads: NOT RESOLVED</strong> -- ' + escapeHtml(warning) + '</div>\n';
914
+ }
915
+ const dir = escapeHtml(beads.dir || '(unknown)');
916
+ const prefix = escapeHtml(beads.prefix || '?');
917
+ const remote = escapeHtml(beads.syncRemote || '(sync.remote unset)');
918
+ return '<div class="beads-identity" style="font-size: 12px; color: #a1a1aa; padding: 4px 16px;">' +
919
+ 'Beads: <span style="color:#d4d4d8;">' + dir + '</span> | prefix <span style="color:#d4d4d8;">' + prefix + '</span>' +
920
+ ' | <span style="color:#d4d4d8;">' + remote + '</span></div>\n';
921
+ }
922
+
923
+ /**
924
+ * Normalize the cached beads view's snapshot into the wire/render freshness
925
+ * shape. ASCII only. `lastSkip` (a busy/lock round, rows kept) is carried
926
+ * separately from `lastError` (a real failure).
927
+ * @param {object|null} snap - beads-view snapshot()
928
+ * @returns {{ asOf: string|null, lastError: {message:string, at:string}|null, lastSkip: {reason:string, at:string}|null }|null}
929
+ */
930
+ export function toBeadsFreshness(snap) {
931
+ if (!snap || typeof snap !== 'object') return null;
932
+ const iso = (t) => (typeof t === 'number' && Number.isFinite(t) ? new Date(t).toISOString() : null);
933
+ return {
934
+ asOf: iso(snap.asOf),
935
+ lastError: snap.lastError ? { message: String(snap.lastError.message ?? ''), at: iso(snap.lastError.at) } : null,
936
+ lastSkip: snap.lastSkip ? { reason: String(snap.lastSkip.reason ?? ''), at: iso(snap.lastSkip.at) } : null,
937
+ };
938
+ }
939
+
940
+ /**
941
+ * Renders the "Beads as of <time>" line plus a visible failure notice when the
942
+ * view's last refresh failed. A busy-skip renders as a muted note, NOT as an
943
+ * error. Returns '' when no freshness is supplied.
944
+ * @param {ReturnType<typeof toBeadsFreshness>} f
945
+ * @returns {string}
946
+ */
947
+ export function renderBeadsFreshnessHtml(f) {
948
+ if (!f) return '';
949
+ const asOf = f.asOf ? 'Beads as of ' + escapeHtml(f.asOf) : 'Beads as of (not yet synced)';
950
+ let html = '<div id="beads-freshness" class="beads-freshness" style="font-size: 12px; color: #a1a1aa; padding: 4px 16px;">' + asOf;
951
+ if (f.lastSkip && !f.lastError) {
952
+ html += ' <span class="beads-refresh-busy" style="color:#a1a1aa;">(refresh deferred: ' + escapeHtml(f.lastSkip.reason) + '; will retry)</span>';
953
+ }
954
+ if (f.lastError) {
955
+ html += '<div class="beads-refresh-error" style="color: #ef4444;"><strong>Beads refresh failed:</strong> ' + escapeHtml(f.lastError.message) + '</div>';
956
+ }
957
+ return html + '</div>\n';
958
+ }
959
+
960
+ /**
961
+ * Renders the full index page (`GET /` document): a header, then a Sprints
962
+ * tab (Sprint Stack alone) and a separate Backlog tab (eft.6.2's cross-sprint
963
+ * free-set view, followed by the Launch Sprint form -- launching starts from
964
+ * picking rows out of the Backlog, so the two live in the same tab), using
965
+ * the same tab-bar/panel chrome as apra-fleet-workflow's per-sprint viewer
966
+ * (see DASHBOARD_CSS above). `id="sprint-stack"` still renders before
967
+ * `id="backlog"`, which still renders before `id="launch-form"`, in the raw
968
+ * HTML -- callers relying on that ordering (or on `data-bead-id`/`data-
969
+ * sprint-id` markers anywhere in the body) are unaffected by which tab
970
+ * happens to be visually active.
971
+ * @param {SprintView[]} [views]
972
+ * @param {string} [backlogHtml] - pre-rendered Backlog tab content (eft.6.2 / renderBacklogPanelHtml())
973
+ * @param {string} [launchFormHtml] - pre-rendered Launch Sprint form HTML (eft.6.3)
974
+ * @param {{ beads?: { dir?: string, prefix?: string, syncRemote?: string, repoRemote?: string }|null, beadsWarning?: string|null }} [opts]
975
+ * `beads`: the supervisor's resolved .beads identity (beads-identity.mjs's
976
+ * toBeadsSummary()), rendered as one header line above the Sprint Stack;
977
+ * `beadsWarning`: when `beads` is null, why it is unknown (rendered as an
978
+ * amber warning line in its place).
979
+ * @returns {string}
980
+ */
981
+ export function renderIndexPageHtml(views, backlogHtml, launchFormHtml, opts = {}) {
982
+ const backlogSection = typeof backlogHtml === 'string'
983
+ ? backlogHtml
984
+ : '<p style="color:var(--text-muted); font-style: italic;">No unclaimed work in the backlog.</p>';
985
+ const launchFormSection = typeof launchFormHtml === 'string' ? launchFormHtml : renderLaunchFormHtml();
986
+ const runningCount = Array.isArray(views) ? views.length : 0;
987
+ return (
988
+ '<!DOCTYPE html>\n' +
989
+ '<html lang="en">\n' +
990
+ '<head>\n' +
991
+ '<meta charset="utf-8"/>\n' +
992
+ '<meta name="viewport" content="width=device-width,initial-scale=1">\n' +
993
+ '<title>Fleet-Sprint Supervisor</title>\n' +
994
+ '<style>' + DASHBOARD_CSS + '</style>\n' +
995
+ '</head>\n' +
996
+ '<body>\n' +
997
+ '<div class="header">' +
998
+ '<h1>Fleet-Sprint Supervisor</h1>' +
999
+ '<div class="header-actions"><div class="stats-banner"><span><strong>' + runningCount + '</strong> running</span></div>' +
1000
+ '<a href="/supervisor/log" target="_blank" rel="noopener" style="font-size: 12px;">Supervisor log</a></div>' +
1001
+ '</div>\n' +
1002
+ renderBeadsHeaderHtml(opts && opts.beads, opts && opts.beadsWarning) +
1003
+ renderBeadsFreshnessHtml(opts && opts.beadsFreshness) +
1004
+ '<div class="main-content"><div class="content-area">' +
1005
+ '<div class="tab-bar" id="tab-bar">' +
1006
+ '<button class="tab-btn active" onclick="switchTab(\'sprints\')">Sprints</button>' +
1007
+ '<button class="tab-btn" onclick="switchTab(\'backlog\')">Backlog</button>' +
1008
+ '</div>\n' +
1009
+ '<div id="tab-sprints" class="tab-content active panel">' +
1010
+ '<div class="panel-header">Sprint Stack</div>' +
1011
+ '<div id="sprint-stack" class="panel-body">\n' + renderSprintStackHtml(views) + '\n</div>' +
1012
+ '</div>\n' +
1013
+ // Backlog is its own tab (this file's tab restructuring) -- still
1014
+ // ALWAYS rendered after the sprint stack in raw document order (the
1015
+ // original eft.6.2 acceptance criterion), regardless of which tab a
1016
+ // viewer happens to have active. Launch Sprint now lives HERE too
1017
+ // (below the backlog table, in the same tab) -- launching starts
1018
+ // from picking rows out of the Backlog, so the two belong together;
1019
+ // it renders after `id="backlog"` in raw document order.
1020
+ '<div id="tab-backlog" class="tab-content panel">' +
1021
+ '<div class="panel-header">Backlog</div>' +
1022
+ '<div id="backlog" class="panel-body">\n' + backlogSection +
1023
+ '\n<div class="panel-header" style="border-top: 1px solid var(--border); margin: 12px -14px -14px; border-radius: 0 0 6px 6px;">Launch Sprint</div>' +
1024
+ '<div id="launch-form" style="padding-top: 12px;">\n' + launchFormSection + '\n</div>' +
1025
+ '\n</div>' +
1026
+ '</div>\n' +
1027
+ '</div></div>\n' +
1028
+ '<script>' + DASHBOARD_TAB_SCRIPT + '</script>\n' +
1029
+ '<script>' + SPRINT_STOP_SCRIPT + '</script>\n' +
1030
+ '<script>' + SPRINT_RESTART_SCRIPT + '</script>\n' +
1031
+ '<script>' + SPRINT_PAUSE_SCRIPT + '</script>\n' +
1032
+ // (apra-fleet-siqi.1.2) Live-refresh loop -- registered LAST so the
1033
+ // Stop/Restart/Pause scripts' own `document`-level delegated click
1034
+ // listeners (which SPRINT_STACK_LIVE_SCRIPT's poll-driven rebuilds
1035
+ // rely on) are already wired before this script's first poll() can
1036
+ // possibly replace any row.
1037
+ '<script>' + SPRINT_STACK_LIVE_SCRIPT + '</script>\n' +
1038
+ '</body>\n' +
1039
+ '</html>\n'
1040
+ );
1041
+ }
1042
+
1043
+ /**
1044
+ * @typedef {object} SprintView
1045
+ * @property {string} sprintId
1046
+ * @property {string|null} branch
1047
+ * @property {string|null} goal
1048
+ * @property {string} status - one of WATCHDOG_STATUS's six values
1049
+ * @property {string[]} issueRoots
1050
+ * @property {number|null} beadCount
1051
+ * @property {SummaryView|null} progress - the child's pulled summary, classified (see classifyChildSummary())
1052
+ * @property {Array<{ name: string, role: string|null }>} members
1053
+ * @property {string|null} base - (apra-fleet-p2to.3.1) the sprint's launch `--base` branch, as recorded on the ledger entry
1054
+ * @property {number|null} baseDrift - (apra-fleet-p2to.3.1) commits on `base` not yet reachable from `branch`; `null` when unknown (see computeBaseDrift())
1055
+ * @property {string|null} beadsPrefix - the beads prefix recorded on the ledger entry at launch (`beads.prefix`, beads-identity.mjs); null when absent
1056
+ */
1057
+
1058
+ /**
1059
+ * (apra-fleet-siqi.1.1) Lean JSON payload for GET /state -- the SAME
1060
+ * sprint-stack view data `renderSprintStackHtml()`/`renderSprintSection()`
1061
+ * render into HTML above (ids, statuses, claimed-scope/progress counts,
1062
+ * members), but as plain JSON for the dashboard's poll('/state') client path
1063
+ * -- never the full HTML shell `GET /` serves. Mirrors
1064
+ * apra-fleet-workflow/src/viewer/lean-state.mjs's buildListStatePayload() in
1065
+ * spirit (a lean, wire-shaped transform of the same view model a full page
1066
+ * render already computes) without pulling in that module's string-dedup
1067
+ * machinery, which targets a much larger per-activity payload than this
1068
+ * small, per-sprint list ever grows to.
1069
+ * @param {SprintView[]} [views]
1070
+ * @returns {{ generatedAt: string, runningCount: number, sprints: Array<object> }}
1071
+ */
1072
+ export function buildStatePayload(views, opts = {}) {
1073
+ const list = Array.isArray(views) ? views : [];
1074
+ return {
1075
+ generatedAt: new Date().toISOString(),
1076
+ runningCount: list.length,
1077
+ beadsFreshness: (opts && opts.beadsFreshness) ?? null,
1078
+ sprints: list.map((v) => ({
1079
+ sprintId: v.sprintId,
1080
+ branch: v.branch ?? null,
1081
+ goal: v.goal ?? null,
1082
+ status: v.status,
1083
+ issueRoots: v.issueRoots ?? [],
1084
+ beadCount: v.beadCount ?? null,
1085
+ progress: v.progress ?? null,
1086
+ members: v.members ?? [],
1087
+ base: v.base ?? null,
1088
+ baseDrift: v.baseDrift ?? null,
1089
+ beadsPrefix: v.beadsPrefix ?? null,
1090
+ })),
1091
+ };
1092
+ }
1093
+
1094
+ // (apra-fleet-siqi.1.1) Default interval, in ms, at which GET /events emits a
1095
+ // generic "state may have changed, go poll /state" signal to every connected
1096
+ // SSE client -- see createDashboard()'s changeEmitter below. The supervisor
1097
+ // has no single internal event stream the way one workflow run does
1098
+ // (apra-fleet-workflow's viewer broadcasts on its own workflow.on(...)
1099
+ // handlers); its RUNNING-sprint view model instead changes via many disjoint
1100
+ // HTTP routes (POST /api/sprints, force-release, a watchdog reclassification
1101
+ // on the NEXT renderIndexPage()/buildSprintViews() call, etc.). Rather than
1102
+ // threading a notify() call into every one of those call sites (out of scope
1103
+ // for this task -- see the bead's file list), GET /events emits this same
1104
+ // generic signal on a fixed cadence, mirroring the per-sprint viewer's own
1105
+ // client-side heartbeat fallback (apra-fleet-36l.1) -- just server-side,
1106
+ // since the supervisor has no per-mutation push events to relay yet. The
1107
+ // client (apra-fleet-siqi.1.2) treats every signal identically: refetch
1108
+ // /state and re-render, so a period-driven signal here is indistinguishable
1109
+ // from a real per-mutation push from the client's point of view.
1110
+ const DEFAULT_EVENTS_INTERVAL_MS = 5000;
1111
+
1112
+ // Per-row budget for pulling a child's GET /state?summary=1. Rows are pulled
1113
+ // concurrently, so a hung child delays the whole page by at most this much.
1114
+ const DEFAULT_SUMMARY_TIMEOUT_MS = 2000;
1115
+ // A summary is a few hundred bytes; an old child serving its FULL /state on
1116
+ // ?summary=1 can be far larger. Past this cap the body is not worth reading --
1117
+ // it cannot be a summary.
1118
+ const MAX_SUMMARY_BYTES = 1024 * 1024;
1119
+
1120
+ /**
1121
+ * @typedef {object} SummaryView
1122
+ * @property {'ok'|'unreachable'|'no-summary'|'unavailable'} state
1123
+ * @property {number} [closed]
1124
+ * @property {number} [required]
1125
+ * @property {number} [fraction]
1126
+ * @property {string|null} [computedAt] - extensions.beads.computed_at (when the child FETCHED the beads)
1127
+ * @property {boolean} [rejected] - unreachable because the port answered for a different runId
1128
+ */
1129
+
1130
+ /**
1131
+ * Default `fetchSummary` seam: HTTP GET http://127.0.0.1:PORT/state?summary=1.
1132
+ * One overall timer (started before the request) covers connect, headers AND
1133
+ * body, so a child that accepts the connection and then stalls still times
1134
+ * out. `agent: false` -- no pooled keep-alive socket outlives the call.
1135
+ *
1136
+ * Resolves `{ status, json }` for ANY HTTP response (`json` is `undefined`
1137
+ * when the body is not valid JSON or exceeds MAX_SUMMARY_BYTES); rejects on
1138
+ * connection error or timeout (the caller classifies that as unreachable).
1139
+ * @param {number} port
1140
+ * @param {{ timeoutMs?: number, host?: string }} [opts]
1141
+ * @returns {Promise<{ status: number, json: any }>}
1142
+ */
1143
+ export function fetchChildSummary(port, opts = {}) {
1144
+ const timeoutMs = Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0 ? opts.timeoutMs : DEFAULT_SUMMARY_TIMEOUT_MS;
1145
+ const host = opts.host ?? '127.0.0.1';
1146
+ return new Promise((resolve, reject) => {
1147
+ let settled = false;
1148
+ let req = null;
1149
+ let res = null;
1150
+ const finish = (fn, value) => {
1151
+ if (settled) return;
1152
+ settled = true;
1153
+ clearTimeout(timer);
1154
+ fn(value);
1155
+ };
1156
+ const timer = setTimeout(() => {
1157
+ const err = new Error(`child summary request timed out after ${timeoutMs}ms`);
1158
+ err.code = 'ETIMEDOUT';
1159
+ finish(reject, err);
1160
+ try { if (res) res.destroy(); } catch { /* ignore */ }
1161
+ try { if (req) req.destroy(); } catch { /* ignore */ }
1162
+ }, timeoutMs);
1163
+ try {
1164
+ req = http.get({ host, port, path: '/state?summary=1', agent: false, headers: { accept: 'application/json' } }, (response) => {
1165
+ res = response;
1166
+ const chunks = [];
1167
+ let size = 0;
1168
+ let oversize = false;
1169
+ response.on('data', (chunk) => {
1170
+ if (oversize) return;
1171
+ size += chunk.length;
1172
+ if (size > MAX_SUMMARY_BYTES) {
1173
+ oversize = true;
1174
+ chunks.length = 0;
1175
+ finish(resolve, { status: response.statusCode, json: undefined });
1176
+ response.destroy();
1177
+ return;
1178
+ }
1179
+ chunks.push(chunk);
1180
+ });
1181
+ response.on('end', () => {
1182
+ let json;
1183
+ try {
1184
+ json = JSON.parse(Buffer.concat(chunks).toString('utf8'));
1185
+ } catch {
1186
+ json = undefined;
1187
+ }
1188
+ finish(resolve, { status: response.statusCode, json });
1189
+ });
1190
+ response.on('error', (err) => finish(reject, err));
1191
+ });
1192
+ req.on('error', (err) => finish(reject, err));
1193
+ } catch (err) {
1194
+ finish(reject, err);
1195
+ }
1196
+ });
1197
+ }
1198
+
1199
+ /**
1200
+ * Classify one pulled child summary response against the pinned wire shape
1201
+ * (GET /state?summary=1 -> { summaryVersion, runId, ..., extensions: { beads:
1202
+ * { closed, required, fraction, computed_at } } }). Order matters:
1203
+ * 1. non-200 / non-JSON / no summaryVersion (an old child) -> unavailable
1204
+ * 2. runId !== sprintId (the port now belongs to another run) -> rejected,
1205
+ * checked BEFORE beads presence so another run's empty summary never
1206
+ * reads as "no summary yet" for this sprint
1207
+ * 3. no extensions.beads -> no-summary
1208
+ * 4. non-finite closed/required -> unavailable (never 0/N)
1209
+ * 5. otherwise ok
1210
+ * @param {{ status: number, json: any }} response
1211
+ * @param {string} sprintId
1212
+ * @returns {{ kind: 'ok', summary: SummaryView }|{ kind: 'rejected', runId: any }|{ kind: 'no-summary' }|{ kind: 'unavailable' }}
1213
+ */
1214
+ export function classifyChildSummary(response, sprintId) {
1215
+ const json = response ? response.json : undefined;
1216
+ if (!response || response.status !== 200 || !json || typeof json !== 'object' || Array.isArray(json)) {
1217
+ return { kind: 'unavailable' };
1218
+ }
1219
+ if (json.summaryVersion === undefined || json.summaryVersion === null) return { kind: 'unavailable' };
1220
+ if (json.runId !== sprintId) return { kind: 'rejected', runId: json.runId };
1221
+ const ext = json.extensions && typeof json.extensions === 'object' ? json.extensions : null;
1222
+ const beads = ext && ext.beads && typeof ext.beads === 'object' ? ext.beads : null;
1223
+ if (!beads) return { kind: 'no-summary' };
1224
+ const { closed, required } = beads;
1225
+ if (typeof closed !== 'number' || !Number.isFinite(closed) || typeof required !== 'number' || !Number.isFinite(required)) {
1226
+ return { kind: 'unavailable' };
1227
+ }
1228
+ const fraction = typeof beads.fraction === 'number' && Number.isFinite(beads.fraction)
1229
+ ? beads.fraction
1230
+ : (required > 0 ? closed / required : 0);
1231
+ const computedAt = typeof beads.computed_at === 'string' ? beads.computed_at : null;
1232
+ return { kind: 'ok', summary: { state: 'ok', closed, required, fraction, computedAt } };
1233
+ }
1234
+
1235
+ /**
1236
+ * Create the dashboard seam (see src/supervisor/server.mjs's seam docs).
1237
+ * Builds the list of RUNNING (non-finished) sprint view models from the
1238
+ * ledger + watchdog classifier, and renders the index page HTML.
1239
+ *
1240
+ * @param {{
1241
+ * ledger: {
1242
+ * list: () => Array<{ sprintId: string, members: string[], issueRoots: string[], childPid: number|null }>,
1243
+ * get?: (sprintId: string) => { branch?: string|null, goal?: string|null }|undefined,
1244
+ * },
1245
+ * watchdog: { classifySprint: (entry: object) => Promise<{ status: string }> },
1246
+ * expandScope?: (roots: string[]) => Promise<Set<string>>, // test seam only -- production leaves this unset and expands in-memory (apra-fleet-c4s.1)
1247
+ * resolvePort?: (sprintId: string) => number|undefined, // live child viewer port; production injects child-port.mjs's ledger+spawner resolver
1248
+ * spawner?: { getLiveEntry: (pid: number) => { port?: number }|undefined }, // used to build the default resolvePort when none is injected
1249
+ * fetchSummary?: (port: number, opts: { timeoutMs: number, sprintId: string }) => Promise<{ status: number, json: any }>, // test seam; defaults to fetchChildSummary()
1250
+ * summaryTimeoutMs?: number, // per-row summary pull budget; defaults to DEFAULT_SUMMARY_TIMEOUT_MS
1251
+
1252
+ * listAllBeads?: () => Promise<Array<{ id: string, status: string }>>,
1253
+ * beadsView?: { snapshot: () => object }, // cached beads view; supplies the freshness shown on the page and in GET /state
1254
+ * getSprintMeta?: (sprintId: string) => Promise<{ branch?: string, goal?: string, roles?: Record<string,string> }>|{ branch?: string, goal?: string, roles?: Record<string,string> },
1255
+ * driftCheck?: (branch: string|null, base: string|null) => Promise<number|null>|number|null,
1256
+ * backlog?: { renderHtml: () => Promise<string>|string },
1257
+ * logger?: { log?: Function, error?: Function },
1258
+ * eventsIntervalMs?: number, // (apra-fleet-siqi.1.1) GET /events signal cadence; defaults to DEFAULT_EVENTS_INTERVAL_MS
1259
+ * beadsIdentity?: { get: () => object|null, getWarning?: () => string|null }, // beads-identity.mjs handle; drives the "Beads: ..." header line (or its warning form)
1260
+ * }} [deps]
1261
+ * @returns {{
1262
+ * name: string,
1263
+ * start(): Promise<void>,
1264
+ * stop(): Promise<void>,
1265
+ * buildSprintViews(): Promise<SprintView[]>,
1266
+ * renderIndexPage(): Promise<string>,
1267
+ * onChange(listener: () => void): () => void,
1268
+ * }}
1269
+ */
1270
+ export function createDashboard(deps = {}) {
1271
+ const ledger = deps.ledger;
1272
+ if (!ledger || typeof ledger.list !== 'function') {
1273
+ throw new TypeError('createDashboard requires a ledger with a list() method');
1274
+ }
1275
+ const watchdog = deps.watchdog;
1276
+ if (!watchdog || typeof watchdog.classifySprint !== 'function') {
1277
+ throw new TypeError('createDashboard requires a watchdog with classifySprint()');
1278
+ }
1279
+ const logger = deps.logger ?? console;
1280
+ const logError = (...a) => (logger.error ?? logger.log)?.(...a);
1281
+ // Optional beads-identity handle (beads-identity.mjs's
1282
+ // createBeadsIdentityState(); bin/serve.mjs wires the real one) -- read
1283
+ // on every renderIndexPage() for the header line. Absent -> no line.
1284
+ const beadsIdentity = deps.beadsIdentity && typeof deps.beadsIdentity.get === 'function' ? deps.beadsIdentity : null;
1285
+ // apra-fleet-c4s.1: `deps.expandScope`, when injected, is called verbatim
1286
+ // (the pre-existing test seam -- see the module doc comment above). When
1287
+ // absent (production default, bin/serve.mjs), buildSprintViews() below
1288
+ // expands EVERY sprint's scope in-memory off the single listAllBeads()
1289
+ // fetch it already makes for progress bars, via buildChildIndex() +
1290
+ // expandScopeInMemory() -- never a subprocess walker.
1291
+ const explicitExpand = deps.expandScope ?? null;
1292
+ // apra-fleet-x8r.2: one bulk `bd list --all --json` fetch per
1293
+ // renderIndexPage() call (reused across every sprint row below), not one
1294
+ // per row -- same "one query fewer" discipline bdListScoped('')
1295
+ // documents in runner.js. Reuses scope-overlap.mjs's already-tested
1296
+ // bdListAllBeadsWithClosed() (normalizeBead()-compatible raw rows, `--all`
1297
+ // included) rather than a second bulk-fetch implementation -- see the
1298
+ // apra-fleet-72o0 note on the import above for why this must NOT be
1299
+ // backlog.mjs's bdListAllBeads().
1300
+ const listAllBeads = deps.listAllBeads ?? bdListAllBeadsWithClosed;
1301
+ // apra-fleet-3i3.2: best-effort per-sprint metadata (branch/goal/member
1302
+ // roles). Defaults to reading branch/goal straight off the ledger entry
1303
+ // (which now persists them -- see ledger.mjs) when the caller injects
1304
+ // nothing; per-member roles still have no ledger-backed source, so this
1305
+ // default never populates `roles`, matching the pre-existing "no roles ->
1306
+ // every member's role renders null" fallback. `ledger.get` is OPTIONAL on
1307
+ // the injected ledger (some tests only implement list()) -- guarded so
1308
+ // this default is a safe no-op, not a throw, against those.
1309
+ const getSprintMeta = deps.getSprintMeta ?? ((sprintId) => {
1310
+ if (typeof ledger.get !== 'function') return {};
1311
+ const entry = ledger.get(sprintId);
1312
+ return entry ? { branch: entry.branch ?? null, goal: entry.goal ?? null } : {};
1313
+ });
1314
+ // (apra-fleet-p2to.3.1) Base-drift check, injectable so a test can drive a
1315
+ // deterministic commit count without a real git checkout. Defaults to
1316
+ // computeBaseDrift() above, which never throws (resolves to `null` on any
1317
+ // failure -- unresolvable ref, no local git repo, etc).
1318
+ const driftCheck = deps.driftCheck ?? computeBaseDrift;
1319
+ // Backlog-last tree (eft.6.2). Injected so the dashboard renders it as the
1320
+ // final page section without owning its full-tracker/claim computation. When
1321
+ // absent, renderIndexPageHtml() falls back to an explicit empty state.
1322
+ const backlog = deps.backlog ?? null;
1323
+ // Optional cached beads view (beads-view.mjs): only its snapshot() is read
1324
+ // here, for the "Beads as of" line / failure notice. Rows reach this seam
1325
+ // through the injected `listAllBeads` (the snapshot reader), never bd.
1326
+ const beadsView = deps.beadsView && typeof deps.beadsView.snapshot === 'function' ? deps.beadsView : null;
1327
+ function beadsFreshness() {
1328
+ if (!beadsView) return null;
1329
+ try {
1330
+ return toBeadsFreshness(beadsView.snapshot());
1331
+ } catch (err) {
1332
+ logError('[dashboard] beads view snapshot failed:', err);
1333
+ return null;
1334
+ }
1335
+ }
1336
+
1337
+ // Per-row progress comes from the child's own published summary (GET
1338
+ // /state?summary=1), pulled on every buildSprintViews(). resolvePort
1339
+ // defaults to the shared ledger+spawner resolver (child-port.mjs);
1340
+ // without a spawner it resolves nothing and every row reads as
1341
+ // unreachable/status unavailable rather than a supervisor recompute.
1342
+ const resolvePort = typeof deps.resolvePort === 'function'
1343
+ ? deps.resolvePort
1344
+ : createChildPortResolver({ ledger, spawner: deps.spawner ?? null });
1345
+ const summaryTimeoutMs = Number.isFinite(deps.summaryTimeoutMs) && deps.summaryTimeoutMs > 0
1346
+ ? deps.summaryTimeoutMs
1347
+ : DEFAULT_SUMMARY_TIMEOUT_MS;
1348
+ const fetchSummary = typeof deps.fetchSummary === 'function'
1349
+ ? deps.fetchSummary
1350
+ : (port) => fetchChildSummary(port, { timeoutMs: summaryTimeoutMs });
1351
+ // Last good (state 'ok') summary per sprintId -- in memory only; entries
1352
+ // for sprints no longer in the ledger list are evicted each build.
1353
+ const lastGoodSummary = new Map();
1354
+
1355
+ /**
1356
+ * Pull + classify one sprint's summary. Never throws.
1357
+ * @param {string} sprintId
1358
+ * @returns {Promise<SummaryView>}
1359
+ */
1360
+ async function pullSprintSummary(sprintId) {
1361
+ let port;
1362
+ try {
1363
+ port = resolvePort(sprintId);
1364
+ } catch (err) {
1365
+ logError(`[dashboard] resolvePort failed for sprint '${sprintId}':`, err);
1366
+ port = undefined;
1367
+ }
1368
+ const unreachable = (rejected) => {
1369
+ const last = lastGoodSummary.get(sprintId);
1370
+ if (!last) return { state: 'unavailable' };
1371
+ return { ...last, state: 'unreachable', ...(rejected ? { rejected: true } : {}) };
1372
+ };
1373
+ if (!Number.isInteger(port) || port <= 0) return unreachable(false);
1374
+ let response;
1375
+ try {
1376
+ response = await fetchSummary(port, { timeoutMs: summaryTimeoutMs, sprintId });
1377
+ } catch {
1378
+ return unreachable(false);
1379
+ }
1380
+ const verdict = classifyChildSummary(response, sprintId);
1381
+ switch (verdict.kind) {
1382
+ case 'ok':
1383
+ lastGoodSummary.set(sprintId, verdict.summary);
1384
+ return verdict.summary;
1385
+ case 'rejected':
1386
+ logError(`[dashboard] summary from port ${port} carries runId '${String(verdict.runId)}', not sprint '${sprintId}' -- port reused by another run; ignoring it`);
1387
+ return unreachable(true);
1388
+ case 'no-summary':
1389
+ return { state: 'no-summary' };
1390
+ default:
1391
+ return { state: 'unavailable' };
1392
+ }
1393
+ }
1394
+
1395
+ // (apra-fleet-siqi.1.1) GET /events plumbing -- see DEFAULT_EVENTS_INTERVAL_MS
1396
+ // above for why this is a periodic signal rather than a per-mutation push.
1397
+ // Lifecycle-owned by THIS seam's own start()/stop() (below), the same
1398
+ // pattern every other supervisor seam already follows (server.mjs calls
1399
+ // seam.start()/stop() for every entry in `seams`, dashboard included) --
1400
+ // registerDashboardRoutes() never touches the timer directly, only
1401
+ // subscribes/unsubscribes SSE clients via `onChange()`.
1402
+ const changeEmitter = new EventEmitter();
1403
+ // An SSE stream may stay open indefinitely (one per connected dashboard
1404
+ // tab); the default 10-listener cap is not a "too many listeners" leak
1405
+ // here, it's the expected steady state.
1406
+ changeEmitter.setMaxListeners(0);
1407
+ const eventsIntervalMs = Number.isInteger(deps.eventsIntervalMs) && deps.eventsIntervalMs > 0
1408
+ ? deps.eventsIntervalMs
1409
+ : DEFAULT_EVENTS_INTERVAL_MS;
1410
+ let eventsTimer = null;
1411
+
1412
+ /**
1413
+ * Builds every RUNNING sprint's view model. A sprint classified `finished`
1414
+ * by the watchdog is dropped entirely (acceptance criterion: finished
1415
+ * sprints must not appear in the live stack). Per-entry failures (a
1416
+ * transient `bd` error while expanding scope, a throwing getSprintMeta)
1417
+ * are isolated to that one entry -- rendered with graceful "unknown"
1418
+ * fallbacks -- rather than taking the whole page down.
1419
+ * @returns {Promise<SprintView[]>}
1420
+ */
1421
+ async function buildSprintViews() {
1422
+ const entries = ledger.list();
1423
+ // Last-good cache eviction: a sprint no longer in the ledger list
1424
+ // never comes back under the same id, so its cached summary is dead.
1425
+ const liveIds = new Set(entries.map((e) => e.sprintId));
1426
+ for (const id of lastGoodSummary.keys()) {
1427
+ if (!liveIds.has(id)) lastGoodSummary.delete(id);
1428
+ }
1429
+ // Every row's child summary is pulled CONCURRENTLY and started FIRST
1430
+ // (before the bulk beads fetch and any per-row await), so the page
1431
+ // waits at most one summary timeout, never a serial sum of them.
1432
+ // pullSprintSummary() never rejects.
1433
+ const summaryPulls = new Map(entries.map((e) => [e.sprintId, pullSprintSummary(e.sprintId)]));
1434
+ // apra-fleet-x8r.2: fetched ONCE for the whole page render (not once
1435
+ // per sprint row) -- feeds only the claimed-scope bead count now; a
1436
+ // failure here is isolated to "unknown" counts this round, never a
1437
+ // thrown page render.
1438
+ let allBeads = null;
1439
+ try {
1440
+ const rawBeads = await listAllBeads();
1441
+ // The default fetcher (bdListAllBeadsWithClosed) returns RAW,
1442
+ // unnormalized `bd list` rows -- normalizeBead() derives
1443
+ // `parentId` (buildChildIndex() below needs it). A test-injected
1444
+ // `deps.listAllBeads` may already return normalized rows;
1445
+ // normalizeBead() is idempotent on its own fields, so mapping
1446
+ // unconditionally is safe either way.
1447
+ allBeads = (Array.isArray(rawBeads) ? rawBeads : []).map(normalizeBead).filter((b) => b.id.length > 0);
1448
+ } catch (err) {
1449
+ logError('[dashboard] bulk beads fetch failed (claimed-scope counts will show unknown this round):', err);
1450
+ }
1451
+ // apra-fleet-c4s.1: built ONCE off the same bulk fetch above (not one
1452
+ // subprocess walk per sprint row) -- `null` when either a test injects
1453
+ // its own `explicitExpand` (childIndex would be unused) or the bulk
1454
+ // fetch itself failed this round (each row's own try/catch below then
1455
+ // falls back to an empty Map, i.e. "scope is just the roots
1456
+ // themselves" rather than a crash).
1457
+ const childIndex = (!explicitExpand && Array.isArray(allBeads)) ? buildChildIndex(allBeads) : null;
1458
+ const built = await Promise.all(entries.map(async (entry) => {
1459
+ const classification = await watchdog.classifySprint(entry);
1460
+
1461
+ let meta = {};
1462
+ try {
1463
+ meta = (await getSprintMeta(entry.sprintId)) || {};
1464
+ } catch (err) {
1465
+ logError(`[dashboard] getSprintMeta failed for sprint '${entry.sprintId}':`, err);
1466
+ }
1467
+ const roles = meta.roles && typeof meta.roles === 'object' ? meta.roles : {};
1468
+ const branch = meta.branch ?? null;
1469
+ // (apra-fleet-p2to.3.1) `base` lives directly on the ledger entry
1470
+ // (ledger.mjs's Reservation.base), the same axis as issueRoots/
1471
+ // members below -- unlike branch/goal, no getSprintMeta
1472
+ // indirection exists for it (nothing has ever needed to override
1473
+ // it independently of the ledger).
1474
+ const base = entry.base ?? null;
1475
+
1476
+ let baseDrift = null;
1477
+ try {
1478
+ baseDrift = (await driftCheck(branch, base)) ?? null;
1479
+ } catch (err) {
1480
+ logError(`[dashboard] base-drift check failed for sprint '${entry.sprintId}':`, err);
1481
+ }
1482
+
1483
+ let beadCount = null;
1484
+ try {
1485
+ const roots = entry.issueRoots ?? [];
1486
+ // apra-fleet-c4s.1: in-memory expansion off `childIndex`
1487
+ // (built once above) is the production path -- zero `bd`
1488
+ // subprocess spawns. `explicitExpand`, when a caller injects
1489
+ // one, is used verbatim instead (test seam).
1490
+ const scope = explicitExpand
1491
+ ? await explicitExpand(roots)
1492
+ : expandScopeInMemory(roots, childIndex ?? new Map());
1493
+ beadCount = scope.size;
1494
+ } catch (err) {
1495
+ logError(`[dashboard] scope expansion failed for sprint '${entry.sprintId}':`, err);
1496
+ }
1497
+
1498
+ const progress = await summaryPulls.get(entry.sprintId);
1499
+
1500
+ return {
1501
+ sprintId: entry.sprintId,
1502
+ branch,
1503
+ goal: meta.goal ?? null,
1504
+ status: classification.status,
1505
+ issueRoots: entry.issueRoots ?? [],
1506
+ beadCount,
1507
+ progress,
1508
+ members: (entry.members ?? []).map((name) => ({ name, role: roles[name] ?? null })),
1509
+ base,
1510
+ baseDrift,
1511
+ beadsPrefix: entry.beads && entry.beads.prefix ? entry.beads.prefix : null,
1512
+ };
1513
+ }));
1514
+ return built.filter((v) => v.status !== WATCHDOG_STATUS.FINISHED);
1515
+ }
1516
+
1517
+ return {
1518
+ name: 'dashboard',
1519
+ async start() {
1520
+ // Idempotent -- a second start() (e.g. a supervisor restart-in-
1521
+ // place test) must not leak a second interval.
1522
+ if (eventsTimer) return;
1523
+ eventsTimer = setInterval(() => changeEmitter.emit('change'), eventsIntervalMs);
1524
+ },
1525
+ async stop() {
1526
+ if (eventsTimer) {
1527
+ clearInterval(eventsTimer);
1528
+ eventsTimer = null;
1529
+ }
1530
+ },
1531
+ buildSprintViews,
1532
+ beadsFreshness,
1533
+ /**
1534
+ * (apra-fleet-siqi.1.1) Subscribe to the periodic "state may have
1535
+ * changed, go poll /state" signal GET /events (registerDashboardRoutes
1536
+ * below) relays to connected clients. Returns an unsubscribe function.
1537
+ * Exposed here (rather than reaching into this closure's private
1538
+ * `changeEmitter` from outside) so registerDashboardRoutes() only ever
1539
+ * talks to the dashboard seam's own public surface, the same
1540
+ * discipline `buildSprintViews`/`renderIndexPage` already follow.
1541
+ * @param {() => void} listener
1542
+ * @returns {() => void} unsubscribe
1543
+ */
1544
+ onChange(listener) {
1545
+ changeEmitter.on('change', listener);
1546
+ return () => changeEmitter.off('change', listener);
1547
+ },
1548
+ async renderIndexPage() {
1549
+ // Render the sprint stack and the Backlog tab content concurrently
1550
+ // with the page shell; a Backlog render failure is isolated so it
1551
+ // can never take the whole page down (renderIndexPageHtml falls
1552
+ // back to an explicit empty state when backlogHtml is undefined).
1553
+ //
1554
+ // Prefers buildBacklogTasks() (the flat, filterable, renderBeadsHtml-
1555
+ // shaped data createBacklog() now exposes -- see backlog.mjs) over
1556
+ // the older renderHtml() (the plain <ul>/<li> tree), so the real
1557
+ // supervisor renders the SAME beads-tree UI fleet-sprint's own
1558
+ // viewer uses. A caller injecting a minimal backlog stub that only
1559
+ // implements renderHtml() (as some tests still do) still works via
1560
+ // that fallback.
1561
+ let backlogHtml;
1562
+ if (backlog && typeof backlog.buildBacklogTasks === 'function') {
1563
+ try {
1564
+ const { tasks, filterOptions } = await backlog.buildBacklogTasks();
1565
+ backlogHtml = renderBacklogPanelHtml(tasks, filterOptions);
1566
+ } catch (err) {
1567
+ logError('[dashboard] backlog render failed:', err);
1568
+ }
1569
+ } else if (backlog && typeof backlog.renderHtml === 'function') {
1570
+ try {
1571
+ backlogHtml = await backlog.renderHtml();
1572
+ } catch (err) {
1573
+ logError('[dashboard] backlog render failed:', err);
1574
+ }
1575
+ }
1576
+ let beads = null;
1577
+ let beadsWarning = null;
1578
+ if (beadsIdentity) {
1579
+ try {
1580
+ beads = toBeadsSummary(beadsIdentity.get());
1581
+ if (!beads && typeof beadsIdentity.getWarning === 'function') beadsWarning = beadsIdentity.getWarning() || null;
1582
+ } catch (err) {
1583
+ logError('[dashboard] beads identity read failed:', err);
1584
+ }
1585
+ }
1586
+ return renderIndexPageHtml(await buildSprintViews(), backlogHtml, undefined, { beads, beadsWarning, beadsFreshness: beadsFreshness() });
1587
+ },
1588
+ };
1589
+ }
1590
+
1591
+ /**
1592
+ * Registers `GET /` against a supervisor (server.mjs), mirroring the
1593
+ * registration pattern of registerSprintRoutes()/registerReservationRoutes().
1594
+ * @param {{ route: (method: string, path: string, handler: Function) => void }} supervisor
1595
+ * @param {ReturnType<typeof createDashboard>} dashboard
1596
+ */
1597
+ export function registerDashboardRoutes(supervisor, dashboard) {
1598
+ supervisor.route('GET', '/', async (req, res) => {
1599
+ const html = await dashboard.renderIndexPage();
1600
+ const body = Buffer.from(html, 'utf-8');
1601
+ res.writeHead(200, {
1602
+ 'content-type': 'text/html; charset=utf-8',
1603
+ 'content-length': body.length,
1604
+ });
1605
+ res.end(body);
1606
+ });
1607
+
1608
+ // (apra-fleet-siqi.1.1) GET /state -- the lean JSON poll endpoint: the
1609
+ // SAME sprint-stack view model GET / renders into HTML (acceptance
1610
+ // criterion: ids, statuses, claimed-scope/progress counts), but as
1611
+ // application/json and WITHOUT the page shell -- never the GET / HTML.
1612
+ // Built via buildStatePayload() above off the SAME buildSprintViews()
1613
+ // GET / already calls: there is exactly one "how do I compute the
1614
+ // running sprint list" implementation; this route and GET / only format
1615
+ // it differently, mirroring apra-fleet-workflow's own GET /state
1616
+ // (src/viewer/index.mjs) being a lean transform of the same `state` its
1617
+ // GET / embeds into HTML_TEMPLATE.
1618
+ supervisor.route('GET', '/state', async (req, res) => {
1619
+ const views = await dashboard.buildSprintViews();
1620
+ const body = Buffer.from(JSON.stringify(buildStatePayload(views, { beadsFreshness: typeof dashboard.beadsFreshness === 'function' ? dashboard.beadsFreshness() : null })), 'utf-8');
1621
+ res.writeHead(200, {
1622
+ 'content-type': 'application/json; charset=utf-8',
1623
+ 'content-length': body.length,
1624
+ 'cache-control': 'no-store, no-cache, must-revalidate, proxy-revalidate',
1625
+ });
1626
+ res.end(body);
1627
+ });
1628
+
1629
+ // (apra-fleet-siqi.1.1) GET /events -- Server-Sent-Events change-signal
1630
+ // stream, the SAME shape as apra-fleet-workflow's own GET /events
1631
+ // (src/viewer/index.mjs): text/event-stream, one connection held open per
1632
+ // client, each message a bare `data: <json>\n\n` line. Unlike that
1633
+ // per-run viewer (which broadcasts on its own workflow.on(...) engine
1634
+ // events), the supervisor has no single internal event stream to relay,
1635
+ // so every message here is the SAME generic `{ type: 'update' }` signal
1636
+ // -- see DEFAULT_EVENTS_INTERVAL_MS above for why a periodic cadence
1637
+ // stands in for per-mutation push. Client (apra-fleet-siqi.1.2) reacts to
1638
+ // ANY message identically: schedule a poll('/state'). This handler never
1639
+ // calls res.end() itself -- the connection only ever closes via the
1640
+ // client disconnecting (req 'close', which unsubscribes from further
1641
+ // signals) or the supervisor process exiting.
1642
+ supervisor.route('GET', '/events', async (req, res) => {
1643
+ res.writeHead(200, {
1644
+ 'content-type': 'text/event-stream',
1645
+ 'connection': 'keep-alive',
1646
+ 'cache-control': 'no-cache',
1647
+ });
1648
+ const send = () => {
1649
+ res.write(`data: ${JSON.stringify({ type: 'update' })}\n\n`);
1650
+ };
1651
+ // Immediate signal on connect: a freshly-opened stream has no
1652
+ // guarantee any prior /state fetch is still current, so the client
1653
+ // should poll once right away rather than wait a full
1654
+ // eventsIntervalMs for the first periodic signal.
1655
+ send();
1656
+ const unsubscribe = dashboard.onChange(send);
1657
+ req.on('close', unsubscribe);
1658
+ });
1659
+ }