@apralabs/apra-fleet 0.4.2 → 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (370) hide show
  1. package/README.md +38 -5
  2. package/dist/agents/backlog-groomer.md +25 -0
  3. package/dist/agents/ci-watcher.md +11 -0
  4. package/dist/agents/deployer.md +37 -2
  5. package/dist/agents/doer.md +36 -12
  6. package/dist/agents/harvester.md +11 -0
  7. package/dist/agents/integ-test-runner.md +11 -0
  8. package/dist/agents/kb-reconciler.md +9 -0
  9. package/dist/agents/plan-reviewer.md +110 -22
  10. package/dist/agents/planner.md +125 -37
  11. package/dist/agents/regression-test-runner.md +11 -0
  12. package/dist/agents/reviewer.md +13 -2
  13. package/dist/agents/schemas/plan-reviewer-output.json +37 -0
  14. package/dist/cli/agent-transform.d.ts +83 -2
  15. package/dist/cli/agent-transform.d.ts.map +1 -1
  16. package/dist/cli/agent-transform.js +266 -21
  17. package/dist/cli/agent-transform.js.map +1 -1
  18. package/dist/cli/auth.d.ts.map +1 -1
  19. package/dist/cli/auth.js +28 -9
  20. package/dist/cli/auth.js.map +1 -1
  21. package/dist/cli/config.d.ts +7 -5
  22. package/dist/cli/config.d.ts.map +1 -1
  23. package/dist/cli/config.js +44 -34
  24. package/dist/cli/config.js.map +1 -1
  25. package/dist/cli/install.d.ts +33 -0
  26. package/dist/cli/install.d.ts.map +1 -1
  27. package/dist/cli/install.js +290 -23
  28. package/dist/cli/install.js.map +1 -1
  29. package/dist/cli/kb-directives.d.ts.map +1 -1
  30. package/dist/cli/kb-directives.js +2 -1
  31. package/dist/cli/kb-directives.js.map +1 -1
  32. package/dist/cli/register-member.d.ts.map +1 -1
  33. package/dist/cli/register-member.js +6 -2
  34. package/dist/cli/register-member.js.map +1 -1
  35. package/dist/commands/kb-server.d.ts +3 -0
  36. package/dist/commands/kb-server.d.ts.map +1 -1
  37. package/dist/commands/kb-server.js +43 -3
  38. package/dist/commands/kb-server.js.map +1 -1
  39. package/dist/index.js +3 -3
  40. package/dist/os/linux.d.ts +6 -0
  41. package/dist/os/linux.d.ts.map +1 -1
  42. package/dist/os/linux.js +35 -2
  43. package/dist/os/linux.js.map +1 -1
  44. package/dist/os/os-commands.d.ts +61 -2
  45. package/dist/os/os-commands.d.ts.map +1 -1
  46. package/dist/os/windows-gitbash.d.ts +5 -0
  47. package/dist/os/windows-gitbash.d.ts.map +1 -1
  48. package/dist/os/windows-gitbash.js +15 -0
  49. package/dist/os/windows-gitbash.js.map +1 -1
  50. package/dist/os/windows.d.ts +6 -0
  51. package/dist/os/windows.d.ts.map +1 -1
  52. package/dist/os/windows.js +46 -3
  53. package/dist/os/windows.js.map +1 -1
  54. package/dist/providers/agy.d.ts +115 -6
  55. package/dist/providers/agy.d.ts.map +1 -1
  56. package/dist/providers/agy.js +569 -53
  57. package/dist/providers/agy.js.map +1 -1
  58. package/dist/providers/claude.d.ts +81 -3
  59. package/dist/providers/claude.d.ts.map +1 -1
  60. package/dist/providers/claude.js +344 -10
  61. package/dist/providers/claude.js.map +1 -1
  62. package/dist/providers/codex.d.ts +4 -2
  63. package/dist/providers/codex.d.ts.map +1 -1
  64. package/dist/providers/codex.js +19 -2
  65. package/dist/providers/codex.js.map +1 -1
  66. package/dist/providers/copilot.d.ts +4 -2
  67. package/dist/providers/copilot.d.ts.map +1 -1
  68. package/dist/providers/copilot.js +20 -2
  69. package/dist/providers/copilot.js.map +1 -1
  70. package/dist/providers/none.d.ts +4 -2
  71. package/dist/providers/none.d.ts.map +1 -1
  72. package/dist/providers/none.js +17 -2
  73. package/dist/providers/none.js.map +1 -1
  74. package/dist/providers/opencode.d.ts +3 -1
  75. package/dist/providers/opencode.d.ts.map +1 -1
  76. package/dist/providers/opencode.js +22 -2
  77. package/dist/providers/opencode.js.map +1 -1
  78. package/dist/providers/provider.d.ts +201 -6
  79. package/dist/providers/provider.d.ts.map +1 -1
  80. package/dist/providers/provider.js +56 -0
  81. package/dist/providers/provider.js.map +1 -1
  82. package/dist/services/agy-project.d.ts +102 -0
  83. package/dist/services/agy-project.d.ts.map +1 -0
  84. package/dist/services/agy-project.js +356 -0
  85. package/dist/services/agy-project.js.map +1 -0
  86. package/dist/services/auth-socket.js +4 -4
  87. package/dist/services/auth-web.js +1 -1
  88. package/dist/services/cloud/lifecycle.d.ts.map +1 -1
  89. package/dist/services/cloud/lifecycle.js +33 -4
  90. package/dist/services/cloud/lifecycle.js.map +1 -1
  91. package/dist/services/credential-cleanup.d.ts.map +1 -1
  92. package/dist/services/credential-cleanup.js +35 -17
  93. package/dist/services/credential-cleanup.js.map +1 -1
  94. package/dist/services/exit-drain.d.ts +44 -0
  95. package/dist/services/exit-drain.d.ts.map +1 -0
  96. package/dist/services/exit-drain.js +52 -0
  97. package/dist/services/exit-drain.js.map +1 -0
  98. package/dist/services/github-app.d.ts.map +1 -1
  99. package/dist/services/github-app.js +32 -4
  100. package/dist/services/github-app.js.map +1 -1
  101. package/dist/services/http-transport.d.ts +1 -0
  102. package/dist/services/http-transport.d.ts.map +1 -1
  103. package/dist/services/http-transport.js +48 -1
  104. package/dist/services/http-transport.js.map +1 -1
  105. package/dist/services/knowledge/kb-config.d.ts +42 -0
  106. package/dist/services/knowledge/kb-config.d.ts.map +1 -0
  107. package/dist/services/knowledge/kb-config.js +54 -0
  108. package/dist/services/knowledge/kb-config.js.map +1 -0
  109. package/dist/services/knowledge/kb-providers.d.ts +7 -1
  110. package/dist/services/knowledge/kb-providers.d.ts.map +1 -1
  111. package/dist/services/knowledge/kb-providers.js +191 -17
  112. package/dist/services/knowledge/kb-providers.js.map +1 -1
  113. package/dist/services/knowledge/require-sqlite-project.d.ts +32 -0
  114. package/dist/services/knowledge/require-sqlite-project.d.ts.map +1 -0
  115. package/dist/services/knowledge/require-sqlite-project.js +38 -0
  116. package/dist/services/knowledge/require-sqlite-project.js.map +1 -0
  117. package/dist/services/model-pricing.d.ts.map +1 -1
  118. package/dist/services/model-pricing.js +7 -3
  119. package/dist/services/model-pricing.js.map +1 -1
  120. package/dist/services/secret-token.d.ts +38 -0
  121. package/dist/services/secret-token.d.ts.map +1 -0
  122. package/dist/services/secret-token.js +51 -0
  123. package/dist/services/secret-token.js.map +1 -0
  124. package/dist/services/service-manager/types.d.ts +3 -1
  125. package/dist/services/service-manager/types.d.ts.map +1 -1
  126. package/dist/services/service-manager/windows.d.ts +14 -2
  127. package/dist/services/service-manager/windows.d.ts.map +1 -1
  128. package/dist/services/service-manager/windows.js +65 -7
  129. package/dist/services/service-manager/windows.js.map +1 -1
  130. package/dist/services/ssh.d.ts.map +1 -1
  131. package/dist/services/ssh.js +58 -2
  132. package/dist/services/ssh.js.map +1 -1
  133. package/dist/services/stall/read-log-tail.d.ts.map +1 -1
  134. package/dist/services/stall/read-log-tail.js +20 -10
  135. package/dist/services/stall/read-log-tail.js.map +1 -1
  136. package/dist/services/stall/stall-detector.d.ts +53 -4
  137. package/dist/services/stall/stall-detector.d.ts.map +1 -1
  138. package/dist/services/stall/stall-detector.js +212 -34
  139. package/dist/services/stall/stall-detector.js.map +1 -1
  140. package/dist/services/strategy.d.ts.map +1 -1
  141. package/dist/services/strategy.js +79 -2
  142. package/dist/services/strategy.js.map +1 -1
  143. package/dist/services/substitution-engine.js +2 -2
  144. package/dist/services/substitution-engine.js.map +1 -1
  145. package/dist/services/tool-registry.d.ts.map +1 -1
  146. package/dist/services/tool-registry.js +5 -3
  147. package/dist/services/tool-registry.js.map +1 -1
  148. package/dist/services/vcs/azure-devops.d.ts +66 -1
  149. package/dist/services/vcs/azure-devops.d.ts.map +1 -1
  150. package/dist/services/vcs/azure-devops.js +192 -21
  151. package/dist/services/vcs/azure-devops.js.map +1 -1
  152. package/dist/services/vcs/types.d.ts +1 -1
  153. package/dist/skills/fleet-sprint-cli/SKILL.md +18 -0
  154. package/dist/skills/pm/SKILL.md +1 -1
  155. package/dist/skills/pm/cost.md +0 -3
  156. package/dist/skills/pm/fleet-addendum.md +2 -2
  157. package/dist/tools/check-status.d.ts +7 -4
  158. package/dist/tools/check-status.d.ts.map +1 -1
  159. package/dist/tools/check-status.js +2 -0
  160. package/dist/tools/check-status.js.map +1 -1
  161. package/dist/tools/compose-permissions.d.ts +6 -0
  162. package/dist/tools/compose-permissions.d.ts.map +1 -1
  163. package/dist/tools/compose-permissions.js +182 -34
  164. package/dist/tools/compose-permissions.js.map +1 -1
  165. package/dist/tools/credential-store-set.js +1 -1
  166. package/dist/tools/execute-command.d.ts.map +1 -1
  167. package/dist/tools/execute-command.js +31 -20
  168. package/dist/tools/execute-command.js.map +1 -1
  169. package/dist/tools/execute-prompt.d.ts +15 -2
  170. package/dist/tools/execute-prompt.d.ts.map +1 -1
  171. package/dist/tools/execute-prompt.js +1196 -892
  172. package/dist/tools/execute-prompt.js.map +1 -1
  173. package/dist/tools/kb-capture.d.ts +2 -2
  174. package/dist/tools/kb-capture.d.ts.map +1 -1
  175. package/dist/tools/kb-capture.js +29 -5
  176. package/dist/tools/kb-capture.js.map +1 -1
  177. package/dist/tools/kb-export.d.ts +2 -2
  178. package/dist/tools/kb-export.d.ts.map +1 -1
  179. package/dist/tools/kb-export.js +3 -28
  180. package/dist/tools/kb-export.js.map +1 -1
  181. package/dist/tools/kb-feedback.d.ts.map +1 -1
  182. package/dist/tools/kb-feedback.js +3 -1
  183. package/dist/tools/kb-feedback.js.map +1 -1
  184. package/dist/tools/kb-freshness-sweep.d.ts.map +1 -1
  185. package/dist/tools/kb-freshness-sweep.js +3 -1
  186. package/dist/tools/kb-freshness-sweep.js.map +1 -1
  187. package/dist/tools/kb-import.d.ts.map +1 -1
  188. package/dist/tools/kb-import.js +2 -1
  189. package/dist/tools/kb-import.js.map +1 -1
  190. package/dist/tools/kb-list.d.ts.map +1 -1
  191. package/dist/tools/kb-list.js +3 -1
  192. package/dist/tools/kb-list.js.map +1 -1
  193. package/dist/tools/kb-query.d.ts +2 -2
  194. package/dist/tools/kb-reconcile-prefilter.d.ts.map +1 -1
  195. package/dist/tools/kb-reconcile-prefilter.js +3 -1
  196. package/dist/tools/kb-reconcile-prefilter.js.map +1 -1
  197. package/dist/tools/kb-resolve-contradiction.d.ts.map +1 -1
  198. package/dist/tools/kb-resolve-contradiction.js +3 -1
  199. package/dist/tools/kb-resolve-contradiction.js.map +1 -1
  200. package/dist/tools/kb-setup.d.ts.map +1 -1
  201. package/dist/tools/kb-setup.js +125 -20
  202. package/dist/tools/kb-setup.js.map +1 -1
  203. package/dist/tools/kb-stats.d.ts.map +1 -1
  204. package/dist/tools/kb-stats.js +64 -43
  205. package/dist/tools/kb-stats.js.map +1 -1
  206. package/dist/tools/list-members.d.ts +2 -2
  207. package/dist/tools/list-members.d.ts.map +1 -1
  208. package/dist/tools/list-members.js +1 -0
  209. package/dist/tools/list-members.js.map +1 -1
  210. package/dist/tools/member-detail.d.ts +2 -2
  211. package/dist/tools/member-detail.d.ts.map +1 -1
  212. package/dist/tools/member-detail.js +17 -0
  213. package/dist/tools/member-detail.js.map +1 -1
  214. package/dist/tools/member-reservation.d.ts +58 -1
  215. package/dist/tools/member-reservation.d.ts.map +1 -1
  216. package/dist/tools/member-reservation.js +61 -20
  217. package/dist/tools/member-reservation.js.map +1 -1
  218. package/dist/tools/provision-auth.d.ts +80 -1
  219. package/dist/tools/provision-auth.d.ts.map +1 -1
  220. package/dist/tools/provision-auth.js +142 -54
  221. package/dist/tools/provision-auth.js.map +1 -1
  222. package/dist/tools/provision-vcs-auth.d.ts +91 -1
  223. package/dist/tools/provision-vcs-auth.d.ts.map +1 -1
  224. package/dist/tools/provision-vcs-auth.js +209 -49
  225. package/dist/tools/provision-vcs-auth.js.map +1 -1
  226. package/dist/tools/register-member.d.ts +12 -9
  227. package/dist/tools/register-member.d.ts.map +1 -1
  228. package/dist/tools/register-member.js +99 -12
  229. package/dist/tools/register-member.js.map +1 -1
  230. package/dist/tools/remove-member.d.ts.map +1 -1
  231. package/dist/tools/remove-member.js +27 -2
  232. package/dist/tools/remove-member.js.map +1 -1
  233. package/dist/tools/send-email.d.ts +2 -2
  234. package/dist/tools/setup-git-app.d.ts.map +1 -1
  235. package/dist/tools/setup-git-app.js +11 -7
  236. package/dist/tools/setup-git-app.js.map +1 -1
  237. package/dist/tools/shutdown-server.d.ts +2 -0
  238. package/dist/tools/shutdown-server.d.ts.map +1 -1
  239. package/dist/tools/shutdown-server.js +23 -1
  240. package/dist/tools/shutdown-server.js.map +1 -1
  241. package/dist/tools/update-member.d.ts +12 -9
  242. package/dist/tools/update-member.d.ts.map +1 -1
  243. package/dist/tools/update-member.js +43 -11
  244. package/dist/tools/update-member.js.map +1 -1
  245. package/dist/tools/vcs-credential-exec.d.ts +127 -0
  246. package/dist/tools/vcs-credential-exec.d.ts.map +1 -0
  247. package/dist/tools/vcs-credential-exec.js +197 -0
  248. package/dist/tools/vcs-credential-exec.js.map +1 -0
  249. package/dist/types.d.ts +13 -0
  250. package/dist/types.d.ts.map +1 -1
  251. package/dist/utils/log-helpers.d.ts.map +1 -1
  252. package/dist/utils/log-helpers.js +2 -2
  253. package/dist/utils/log-helpers.js.map +1 -1
  254. package/dist/utils/prompt-errors.d.ts.map +1 -1
  255. package/dist/utils/prompt-errors.js +7 -1
  256. package/dist/utils/prompt-errors.js.map +1 -1
  257. package/dist/utils/shell-escape.d.ts +16 -0
  258. package/dist/utils/shell-escape.d.ts.map +1 -1
  259. package/dist/utils/shell-escape.js +22 -2
  260. package/dist/utils/shell-escape.js.map +1 -1
  261. package/dist/utils/vcs-provider-detect.d.ts +65 -0
  262. package/dist/utils/vcs-provider-detect.d.ts.map +1 -0
  263. package/dist/utils/vcs-provider-detect.js +109 -0
  264. package/dist/utils/vcs-provider-detect.js.map +1 -0
  265. package/dist/utils/workspace-trust.d.ts +20 -17
  266. package/dist/utils/workspace-trust.d.ts.map +1 -1
  267. package/dist/utils/workspace-trust.js +87 -1
  268. package/dist/utils/workspace-trust.js.map +1 -1
  269. package/dist/workflows/auto-sprint.js +176 -15
  270. package/package.json +6 -4
  271. package/packages/apra-fleet-client/src/client/api.mjs +319 -17
  272. package/packages/apra-fleet-client/src/client/errors.mjs +6 -2
  273. package/packages/apra-fleet-se/apra-pm/agents/_shared/GRAPH-SEMANTICS.md +10 -2
  274. package/packages/apra-fleet-se/apra-pm/agents/backlog-groomer.md +25 -0
  275. package/packages/apra-fleet-se/apra-pm/agents/ci-watcher.md +11 -0
  276. package/packages/apra-fleet-se/apra-pm/agents/deployer.md +37 -2
  277. package/packages/apra-fleet-se/apra-pm/agents/doer.md +36 -12
  278. package/packages/apra-fleet-se/apra-pm/agents/harvester.md +11 -0
  279. package/packages/apra-fleet-se/apra-pm/agents/integ-test-runner.md +11 -0
  280. package/packages/apra-fleet-se/apra-pm/agents/kb-reconciler.md +9 -0
  281. package/packages/apra-fleet-se/apra-pm/agents/plan-reviewer.md +110 -22
  282. package/packages/apra-fleet-se/apra-pm/agents/planner.md +125 -37
  283. package/packages/apra-fleet-se/apra-pm/agents/regression-test-runner.md +11 -0
  284. package/packages/apra-fleet-se/apra-pm/agents/reviewer.md +13 -2
  285. package/packages/apra-fleet-se/apra-pm/agents/schemas/plan-reviewer-output.json +37 -0
  286. package/packages/apra-fleet-se/apra-pm/skills/pm/SKILL.md +1 -1
  287. package/packages/apra-fleet-se/apra-pm/skills/pm/cost.md +0 -3
  288. package/packages/apra-fleet-se/apra-pm/skills/pm/fleet-addendum.md +2 -2
  289. package/packages/apra-fleet-se/bin/cli.mjs +149 -1
  290. package/packages/apra-fleet-se/bin/serve.mjs +78 -4
  291. package/packages/apra-fleet-se/fleet-sprint/abort.mjs +481 -0
  292. package/packages/apra-fleet-se/fleet-sprint/beads-children.mjs +491 -0
  293. package/packages/apra-fleet-se/fleet-sprint/beads-identity-check.mjs +282 -0
  294. package/packages/apra-fleet-se/fleet-sprint/beads-identity.mjs +208 -0
  295. package/packages/apra-fleet-se/fleet-sprint/beads-scope.mjs +638 -0
  296. package/packages/apra-fleet-se/fleet-sprint/beads-transitions.mjs +301 -0
  297. package/packages/apra-fleet-se/fleet-sprint/branch-ensure.mjs +96 -0
  298. package/packages/apra-fleet-se/fleet-sprint/conflict-ladder.mjs +8 -0
  299. package/packages/apra-fleet-se/fleet-sprint/contracts.mjs +61 -14
  300. package/packages/apra-fleet-se/fleet-sprint/coordination.mjs +516 -0
  301. package/packages/apra-fleet-se/fleet-sprint/dispatch-failure.mjs +184 -0
  302. package/packages/apra-fleet-se/fleet-sprint/dispatch-role.mjs +1121 -0
  303. package/packages/apra-fleet-se/fleet-sprint/dispatch-safety-guard.mjs +216 -4
  304. package/packages/apra-fleet-se/fleet-sprint/docs/README.md +1 -1
  305. package/packages/apra-fleet-se/fleet-sprint/docs/dolt-sync-redesign.md +276 -0
  306. package/packages/apra-fleet-se/fleet-sprint/docs/escalate-to-llm-design.md +1 -1
  307. package/packages/apra-fleet-se/fleet-sprint/docs/run-sprint-cycle-prelude-decision.md +215 -0
  308. package/packages/apra-fleet-se/fleet-sprint/dolt-literal-guard.mjs +56 -1
  309. package/packages/apra-fleet-se/fleet-sprint/dolt-sync.mjs +996 -32
  310. package/packages/apra-fleet-se/fleet-sprint/errors.mjs +267 -0
  311. package/packages/apra-fleet-se/fleet-sprint/explicit-id-create-guard.mjs +501 -0
  312. package/packages/apra-fleet-se/fleet-sprint/fatal-diagnostics.mjs +134 -0
  313. package/packages/apra-fleet-se/fleet-sprint/full-db-fetch-guard.mjs +102 -0
  314. package/packages/apra-fleet-se/fleet-sprint/git-sync.mjs +556 -0
  315. package/packages/apra-fleet-se/fleet-sprint/git-topology.mjs +495 -0
  316. package/packages/apra-fleet-se/fleet-sprint/guarded-modules.mjs +564 -0
  317. package/packages/apra-fleet-se/fleet-sprint/inline-ladder-guard.mjs +216 -0
  318. package/packages/apra-fleet-se/fleet-sprint/kb.mjs +728 -0
  319. package/packages/apra-fleet-se/fleet-sprint/mcp-result.mjs +75 -0
  320. package/packages/apra-fleet-se/fleet-sprint/member-provisioning.mjs +252 -0
  321. package/packages/apra-fleet-se/fleet-sprint/member-sync.mjs +581 -0
  322. package/packages/apra-fleet-se/fleet-sprint/member-target.mjs +93 -0
  323. package/packages/apra-fleet-se/fleet-sprint/newtask-text.mjs +266 -0
  324. package/packages/apra-fleet-se/fleet-sprint/parent-notes-staleness.mjs +201 -0
  325. package/packages/apra-fleet-se/fleet-sprint/phases/deploy.mjs +136 -0
  326. package/packages/apra-fleet-se/fleet-sprint/phases/develop.mjs +822 -0
  327. package/packages/apra-fleet-se/fleet-sprint/phases/ensure-sprint-branch.mjs +294 -0
  328. package/packages/apra-fleet-se/fleet-sprint/phases/final-review.mjs +403 -0
  329. package/packages/apra-fleet-se/fleet-sprint/phases/harvest.mjs +180 -0
  330. package/packages/apra-fleet-se/fleet-sprint/phases/integ-test.mjs +358 -0
  331. package/packages/apra-fleet-se/fleet-sprint/phases/plan.mjs +390 -0
  332. package/packages/apra-fleet-se/fleet-sprint/phases/publish-pr.mjs +323 -0
  333. package/packages/apra-fleet-se/fleet-sprint/phases/re-review.mjs +232 -0
  334. package/packages/apra-fleet-se/fleet-sprint/phases/regression-test.mjs +174 -0
  335. package/packages/apra-fleet-se/fleet-sprint/phases/replan.mjs +197 -0
  336. package/packages/apra-fleet-se/fleet-sprint/phases/review.mjs +305 -0
  337. package/packages/apra-fleet-se/fleet-sprint/prompts.mjs +559 -0
  338. package/packages/apra-fleet-se/fleet-sprint/role-policies.mjs +1416 -0
  339. package/packages/apra-fleet-se/fleet-sprint/round-session.mjs +100 -0
  340. package/packages/apra-fleet-se/fleet-sprint/runner.js +1467 -9798
  341. package/packages/apra-fleet-se/fleet-sprint/se-posix.mjs +17 -12
  342. package/packages/apra-fleet-se/fleet-sprint/shell-command-guard.mjs +304 -0
  343. package/packages/apra-fleet-se/fleet-sprint/skills/fleet-sprint-cli/SKILL.md +18 -0
  344. package/packages/apra-fleet-se/fleet-sprint/skills/fleet-supervisor/SKILL.md +21 -2
  345. package/packages/apra-fleet-se/fleet-sprint/sprint-args.mjs +454 -0
  346. package/packages/apra-fleet-se/fleet-sprint/sprint-report.mjs +239 -0
  347. package/packages/apra-fleet-se/fleet-sprint/sprint-state.mjs +163 -0
  348. package/packages/apra-fleet-se/fleet-sprint/unbracketed-push-guard.mjs +234 -0
  349. package/packages/apra-fleet-se/fleet-sprint/usage-limit-controller.mjs +211 -0
  350. package/packages/apra-fleet-se/fleet-sprint/vcs-auth.mjs +1279 -0
  351. package/packages/apra-fleet-se/fleet-sprint/vcs-module.mjs +153 -19
  352. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/azure-devops.mjs +71 -21
  353. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/bitbucket.mjs +28 -0
  354. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/github.mjs +131 -0
  355. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/index.mjs +140 -16
  356. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/shell-helpers.mjs +1 -0
  357. package/packages/apra-fleet-se/fleet-sprint/viewer-extensions.mjs +77 -2
  358. package/packages/apra-fleet-se/fleet-sprint/worklists.mjs +559 -0
  359. package/packages/apra-fleet-se/package.json +1 -1
  360. package/packages/apra-fleet-workflow/src/viewer/index.mjs +17 -6
  361. package/packages/apra-fleet-workflow/src/workflow/index.mjs +49 -7
  362. package/skills/fleet/SKILL.md +8 -8
  363. package/skills/fleet/auth-azdevops.md +14 -3
  364. package/skills/fleet/auth-bitbucket.md +2 -2
  365. package/skills/fleet/auth-github.md +5 -4
  366. package/skills/fleet/onboarding.md +3 -3
  367. package/skills/fleet/permissions.md +5 -1
  368. package/skills/fleet/profiles/node.json +1 -1
  369. package/skills/fleet/troubleshooting.md +3 -3
  370. package/version.json +1 -1
@@ -0,0 +1,638 @@
1
+ // Beads scope discovery + the shared full-DB snapshot for fleet-sprint
2
+ // (apra-fleet-3swo.4.6). Extracted out of runner.js; runner.js re-exports
3
+ // every symbol it previously exported from this region, so existing importers
4
+ // of fleet-sprint/runner.js resolve unchanged.
5
+ //
6
+ // This module owns TWO things that used to be spread across runner.js:
7
+ //
8
+ // 1. ONE BFS scope-discovery implementation (discoverScope below). Before
9
+ // the extraction there were two byte-independent copies of the same
10
+ // rule -- one inside bdListScoped()'s closure and one inside
11
+ // classifyVerifySet() -- kept apart only because classifyVerifySet had
12
+ // to stay pure and testable while bdListScoped lived inside
13
+ // runSprintCycle()'s closure. discoverScope() is pure, so both callers
14
+ // now share it and the two copies cannot drift apart again.
15
+ //
16
+ // 2. The shared full-DB beads snapshot (createBeadsScope below): the single
17
+ // `bd list --all --limit 0 --json` fetch per phase, its in-flight
18
+ // coalescing, and -- critically -- the choke points that invalidate it.
19
+ //
20
+ // -----------------------------------------------------------------------------
21
+ // SNAPSHOT INVALIDATION CONTRACT (this is what the code ACTUALLY does; earlier
22
+ // planning text claiming the snapshot "is only invalidated at planner
23
+ // boundaries" was wrong)
24
+ // -----------------------------------------------------------------------------
25
+ //
26
+ // The snapshot lives AT MOST ONE PHASE. It is dropped on ALL of:
27
+ //
28
+ // (a) EVERY phase boundary. wrapPhase() invalidates unconditionally on every
29
+ // phase() call, so a new step can never inherit the previous step's
30
+ // view. This is the dominant invalidation in practice -- a snapshot
31
+ // almost never survives more than one phase step.
32
+ // (b) EVERY beads-mutating command issued through the wrapCommand() wrapper.
33
+ // `bd list|show|ready|config` are known reads (BD_READ_ONLY_RE) and keep
34
+ // the snapshot; update/create/close/note/dep/dolt-pull and ANY
35
+ // unrecognized `bd` subcommand are conservatively treated as mutations
36
+ // and drop it. The failure mode is a redundant full fetch, never
37
+ // silently stale data. Non-`bd` commands (git, node probes) never touch
38
+ // beads state.
39
+ // (c) EVERY planner dispatch that returns successfully -- runner.js calls
40
+ // invalidateAllBeadsCache() explicitly right after dispatchPlanner() in
41
+ // both the main Planning Loop and the in-cycle scoped replan. The
42
+ // planner mutates beads on ITS OWN clone via its own `bd create` tool
43
+ // calls, never through this wrapper, so (b) cannot see it; and
44
+ // Execution Prep runs later in the SAME "Plan C{cycle} R{round}" phase
45
+ // (no intervening phase() call), so (a) cannot see it either. Without
46
+ // (c) the planner's freshly created tasks are invisible to the very next
47
+ // Execution Prep step, whose parent-feature filter then finds nothing
48
+ // ready and silently skips Develop for the whole cycle. Deliberately
49
+ // scoped to the PLANNER only: an unconditional per-dispatch
50
+ // invalidation was tried and reverted, because it defeats the
51
+ // "one full-DB fetch per phase" cost control that
52
+ // full-db-fetch-tripwire.test.mjs pins, for every other role
53
+ // (doer/reviewer/deployer/...) that has no same-phase reader depending
54
+ // on its bead mutations.
55
+ //
56
+ // WHAT THE CONTRACT DOES *NOT* COVER, and the deliberate bypass sites that
57
+ // exist because of it: a bead mutation performed INSIDE an agent() dispatch
58
+ // (a doer's or the integ runner's own `bd close`) never passes through
59
+ // wrapCommand(), so (b) cannot see it. In a topology with no dolt sync remote
60
+ // nothing else forces a refresh either (doltPullBefore/After are benign
61
+ // no-ops there), so the snapshot can be stale by a full cycle. Three read
62
+ // sites in runner.js therefore deliberately BYPASS the snapshot by calling
63
+ // bdListScoped() with a non-empty filter -- which always issues a real,
64
+ // freshly-scoped `bd list` command (see bdListScoped below) -- instead of
65
+ // reading fetchAllBeadsShared():
66
+ //
67
+ // 1. the per-cycle stall-detection closed-list read (`closedBeadsNow`, the
68
+ // `--status=closed --json` read feeding closedCountHistory),
69
+ // 2. the per-cycle verify-set exit check (`closedIdsForExitCheck`), which
70
+ // runs after the Re-Review block may have pushed further mutations this
71
+ // cycle, and
72
+ // 3. Final Review's `finalClosedBeads` read, which backs both
73
+ // finalClosedCount and finalUnclosedVerifyIds.
74
+ //
75
+ // All three are counting/gating reads whose whole job is to observe closures
76
+ // an agent made; serving them from the snapshot would let a sprint exit (or
77
+ // declare a stall) on a stale count. Do not "optimize" them onto
78
+ // fetchAllBeadsShared().
79
+ // =============================================================================
80
+
81
+ /**
82
+ * `bd` subcommands that can never change beads state, so they must not drop a
83
+ * cached full-DB snapshot. Anything else starting with `bd` is conservatively
84
+ * treated as a mutation. Mirrored (deliberately, as an independent copy) by
85
+ * full-db-fetch-guard.mjs, which judges the same rule from a command log.
86
+ */
87
+ export const BD_READ_ONLY_RE = /^bd\s+(list|show|ready|config)\b/i;
88
+
89
+ /**
90
+ * True iff `cmdStr` is a `bd` command that must invalidate the shared full-DB
91
+ * snapshot -- see clause (b) of the invalidation contract above.
92
+ *
93
+ * @param {string} cmdStr - a command string, already trimmed or not
94
+ * @returns {boolean}
95
+ */
96
+ export function isBeadsMutatingCommand(cmdStr) {
97
+ if (typeof cmdStr !== 'string') return false;
98
+ const trimmed = cmdStr.trim();
99
+ return /^bd\b/i.test(trimmed) && !BD_READ_ONLY_RE.test(trimmed);
100
+ }
101
+
102
+ // ---------------------------------------------------------------------------
103
+ // bd JSON-parse helper
104
+ // ---------------------------------------------------------------------------
105
+ //
106
+ // All `bd ... --json` output must be parsed through this rather than a bare
107
+ // JSON.parse: non-JSON noise on stdout (a warning or deprecation line) would
108
+ // otherwise raise an anonymous SyntaxError deep inside a multi-cycle run. This
109
+ // names the offending command and includes a snippet of the raw output.
110
+ //
111
+ // apra-fleet-3swo.6.13: moved verbatim out of runner.js -- it belongs with
112
+ // this module's other bd-output consumers (buildBeadGraph, discoverScope,
113
+ // classifyVerifySet, createBeadsScope's bdListScoped/fetchAllBeadsShared).
114
+ // runner.js re-exports it unchanged so no importer is edited by the move.
115
+ /**
116
+ * @param {string} raw - the raw text returned by `command()`
117
+ * @param {string} commandLabel - the `bd` command that produced `raw`, for diagnostics
118
+ * @returns {any}
119
+ */
120
+ export function parseBdJson(raw, commandLabel) {
121
+ const text = raw === undefined || raw === null || raw === '' ? '[]' : raw;
122
+ try {
123
+ return JSON.parse(text);
124
+ } catch (err) {
125
+ const snippet = text.length > 500 ? `${text.slice(0, 500)}... (truncated, ${text.length} chars total)` : text;
126
+ throw new Error(
127
+ `[bd JSON Parse Error] Failed to parse JSON output from '${commandLabel}': ${err.message}. ` +
128
+ `Raw output snippet: ${JSON.stringify(snippet)}`
129
+ );
130
+ }
131
+ }
132
+
133
+ // ---------------------------------------------------------------------------
134
+ // Goal-priority helpers
135
+ // ---------------------------------------------------------------------------
136
+ //
137
+ // `validated.goal` is a slash-separated priority list (e.g. 'P1', 'P1/P2'),
138
+ // already validated against GOAL_PATTERN above. The sprint's exit condition
139
+ // (distinct from "is there work dispatchable right now", which `--ready`
140
+ // answers) is: are there any NOT-YET-CLOSED beads in scope at or above
141
+ // (numerically <=) the worst priority named in the goal? `bd list
142
+ // --priority-max=Pn` is inclusive of Pn, so the worst (highest numeric)
143
+ // priority in the goal is exactly the right `--priority-max` value.
144
+ //
145
+ // apra-fleet-3swo.6.13: moved verbatim out of runner.js, together with
146
+ // partitionByGoalMembership below, which calls it. runner.js re-exports both
147
+ // unchanged so no importer is edited by the move.
148
+ /**
149
+ * @param {string} goal - e.g. 'P1', 'P1/P2', 'P1/P2/P3'
150
+ * @returns {string} the lowest-priority (highest 'Pn' number) tier named in `goal`, e.g. 'P2'
151
+ */
152
+ export function goalPriorityMax(goal) {
153
+ const tiers = goal.split('/').map((p) => Number(p.slice(1)));
154
+ const worst = Math.max(...tiers);
155
+ return `P${worst}`;
156
+ }
157
+
158
+ // ---------------------------------------------------------------------------
159
+ // Deferred beads are DISPATCH-INELIGIBLE, so they are not "open work"
160
+ // (apra-fleet-rp7a.1)
161
+ // ---------------------------------------------------------------------------
162
+ //
163
+ // 'deferred' is a member of runner.js's NOT_DONE_STATUSES because it is
164
+ // genuinely not CLOSED -- but the Develop loop dispatches from `bd --ready`,
165
+ // which never offers a deferred bead, so nothing in a sprint can ever move one
166
+ // forward. Counting it as still-open at goal priority therefore makes the
167
+ // completion check unsatisfiable AND pins the closed-bead high-water mark,
168
+ // which is how a sprint whose real scope was finished still aborted as
169
+ // SPRINT_STALLED after STALL_CYCLE_LIMIT cycles.
170
+ //
171
+ // This is the ONE status whose meaning changes. 'blocked' and 'in_progress'
172
+ // deliberately KEEP counting as open (they are exactly the states `bd --ready`
173
+ // hides but a human still owes work on -- see NOT_DONE_STATUSES's own comment
174
+ // on why an empty `--ready` list must never be read as "the sprint is done").
175
+ //
176
+ // The deferred ids are RETURNED, not merely dropped, because a bead silently
177
+ // vanishing from the completion math is precisely the failure mode this
178
+ // function exists to fix: every caller is expected to name them in whatever
179
+ // text it emits, so a human can see what was skipped and why the sprint was
180
+ // allowed to finish.
181
+ //
182
+ // Lives here rather than in runner.js so the per-cycle Cycle Evaluation count
183
+ // and the Final Review's closing count cannot drift apart -- two consumers,
184
+ // one rule.
185
+ export const DEFERRED_BEAD_STATUS = 'deferred';
186
+
187
+ /**
188
+ * Split a not-done bead list into the beads that still count as open work and
189
+ * the ids of the deferred ones (dispatch-ineligible, treated as out of scope).
190
+ *
191
+ * Tolerant of a missing/odd `status` on purpose: an entry whose status cannot
192
+ * be read as 'deferred' stays in `active`. Under-matching here leaves today's
193
+ * behavior (the bead keeps counting as open); over-matching would let real
194
+ * work disappear from the completion check.
195
+ *
196
+ * @param {Array<{id?: (string|number), status?: string}>} beads
197
+ * @returns {{ active: object[], deferredIds: string[] }}
198
+ */
199
+ export function partitionDeferredBeads(beads) {
200
+ const list = Array.isArray(beads) ? beads : [];
201
+ const active = [];
202
+ const deferredIds = [];
203
+ for (const bead of list) {
204
+ const status = bead && typeof bead.status === 'string' ? bead.status.trim().toLowerCase() : '';
205
+ if (status === DEFERRED_BEAD_STATUS) deferredIds.push(String(bead.id));
206
+ else active.push(bead);
207
+ }
208
+ return { active, deferredIds };
209
+ }
210
+
211
+ // apra-fleet-eft.52.1.3: server-side goal-membership placement for the
212
+ // fleet-sprint dashboard's Sprint vs Backlog split. The viewer must NOT
213
+ // decide this itself (no CSS display:none hiding in the browser, no
214
+ // priority-only guess): goal membership is graph knowledge -- it needs the
215
+ // full dependency edge set to honor the blocks-edge exception below -- so it
216
+ // is computed here, in the state payload, and every task is returned tagged
217
+ // with a `placement` field ('sprint' | 'backlog') the viewer consumes
218
+ // verbatim.
219
+ //
220
+ // Rules, applied to TOP-LEVEL items only (an item whose `parent` points at no
221
+ // other item in the dataset -- same "only an in-dataset parent nests" rule
222
+ // the viewer's containment tree uses; descendants inherit their root's
223
+ // placement):
224
+ //
225
+ // - A top-level item is a SPRINT item unless it is DEFINITIVELY below the
226
+ // sprint's goal band -- i.e. it has a finite numeric priority strictly
227
+ // greater (numerically) than goalPriorityMax(goal). An item with no /
228
+ // non-numeric priority is NOT demoted (it is in-scope sprint work of
229
+ // unknown rank, not deliberately-deferred backlog).
230
+ // - EXCEPTION (visual continuity): a below-goal top-level item connected to
231
+ // an in-goal top-level item by a 'blocks'-type dependency edge (in either
232
+ // direction) stays a SPRINT item, so it renders alongside the sprint
233
+ // subtree it blocks / is blocked by rather than being split off into the
234
+ // Backlog section.
235
+ //
236
+ // Descendants of a top-level item always inherit that item's placement, so a
237
+ // whole subtree lands in one section.
238
+ /**
239
+ * @param {Array<{id: (string|number), parent?: (string|number), priority?: number, dependencies?: Array<{depends_on_id: (string|number), type: string}>}>} tasks - scoped bead objects
240
+ * @param {string} goal - sprint goal band, e.g. 'P1/P2'
241
+ * @returns {{ sprintTasks: object[], backlogTasks: object[] }} the same tasks, each tagged with a `placement` field, partitioned by section
242
+ */
243
+ export function partitionByGoalMembership(tasks, goal) {
244
+ const list = Array.isArray(tasks) ? tasks : [];
245
+ const byId = new Map();
246
+ list.forEach((t) => {
247
+ if (t && t.id !== undefined && t.id !== null) byId.set(String(t.id), t);
248
+ });
249
+
250
+ const hasInDatasetParent = (t) => {
251
+ const p = t && t.parent;
252
+ return p !== undefined && p !== null && byId.has(String(p));
253
+ };
254
+
255
+ // Walk `parent` up to the top-level in-dataset ancestor (cycle-guarded).
256
+ const rootOf = (t) => {
257
+ let cur = t;
258
+ const seen = new Set();
259
+ while (hasInDatasetParent(cur) && !seen.has(String(cur.id))) {
260
+ seen.add(String(cur.id));
261
+ cur = byId.get(String(cur.parent));
262
+ }
263
+ return cur;
264
+ };
265
+
266
+ const goalMaxNum = Number(goalPriorityMax(goal).slice(1));
267
+ const isBelowGoal = (t) =>
268
+ typeof t.priority === 'number' && Number.isFinite(t.priority) && t.priority > goalMaxNum;
269
+
270
+ const topLevel = list.filter((t) => t && !hasInDatasetParent(t));
271
+ // In-goal top-level items: everything not definitively below the goal band.
272
+ const inGoalTopIds = new Set(
273
+ topLevel.filter((t) => !isBelowGoal(t)).map((t) => String(t.id))
274
+ );
275
+
276
+ // Sprint set starts as the in-goal top-levels, then absorbs below-goal
277
+ // top-levels connected to an in-goal top-level by a 'blocks' edge, in
278
+ // either direction.
279
+ const sprintTopIds = new Set(inGoalTopIds);
280
+ topLevel.forEach((t) => {
281
+ const id = String(t.id);
282
+ if (sprintTopIds.has(id)) return;
283
+ // Outgoing: this below-goal top-level depends_on (is blocked by) an
284
+ // in-goal top-level -> keep it in Sprint.
285
+ const deps = Array.isArray(t.dependencies) ? t.dependencies : [];
286
+ if (deps.some((d) => d && d.type === 'blocks' && inGoalTopIds.has(String(d.depends_on_id)))) {
287
+ sprintTopIds.add(id);
288
+ }
289
+ });
290
+ // Incoming: an in-goal top-level depends_on (is blocked by) a below-goal
291
+ // top-level -> keep that below-goal item in Sprint too.
292
+ topLevel.forEach((t) => {
293
+ if (!inGoalTopIds.has(String(t.id))) return;
294
+ const deps = Array.isArray(t.dependencies) ? t.dependencies : [];
295
+ deps.forEach((d) => {
296
+ if (!d || d.type !== 'blocks') return;
297
+ const other = byId.get(String(d.depends_on_id));
298
+ if (other && !hasInDatasetParent(other)) sprintTopIds.add(String(other.id));
299
+ });
300
+ });
301
+
302
+ const sprintTasks = [];
303
+ const backlogTasks = [];
304
+ list.forEach((t) => {
305
+ if (!t) return;
306
+ const root = rootOf(t);
307
+ const placement = sprintTopIds.has(String(root.id)) ? 'sprint' : 'backlog';
308
+ const tagged = { ...t, placement };
309
+ if (placement === 'backlog') backlogTasks.push(tagged);
310
+ else sprintTasks.push(tagged);
311
+ });
312
+ return { sprintTasks, backlogTasks };
313
+ }
314
+
315
+ /**
316
+ * Build the id->bead and parent->children indexes every scope walk needs.
317
+ *
318
+ * A bead is a child iff its `parent` field is a non-empty id: `undefined`,
319
+ * `null` and `''` all mean "no parent" and must never create a `Map` entry
320
+ * keyed on an empty string (which would then look like a real parent id to
321
+ * the BFS).
322
+ *
323
+ * @param {Array<object>} allBeads - the FULL, unfiltered project bead list
324
+ * @returns {{ byId: Map<string, object>, childrenOf: Map<string, object[]> }}
325
+ */
326
+ export function buildBeadGraph(allBeads) {
327
+ const beads = allBeads || [];
328
+ const byId = new Map();
329
+ const childrenOf = new Map();
330
+ for (const b of beads) {
331
+ if (!b) continue;
332
+ if (b.id !== undefined && b.id !== null) byId.set(b.id, b);
333
+ if (b.parent !== undefined && b.parent !== null && b.parent !== '') {
334
+ if (!childrenOf.has(b.parent)) childrenOf.set(b.parent, []);
335
+ childrenOf.get(b.parent).push(b);
336
+ }
337
+ }
338
+ return { byId, childrenOf };
339
+ }
340
+
341
+ /**
342
+ * THE scope-discovery rule -- the single implementation both former call
343
+ * sites (bdListScoped and classifyVerifySet) now share.
344
+ *
345
+ * Scope cannot be built on `bd list --parent`: that flag accepts exactly one
346
+ * id per invocation (a comma-joined list is treated as one nonexistent id and
347
+ * returns `[]`) and is single-level only -- direct children, never
348
+ * grandchildren -- so a level-3+ descendant would be invisible to the
349
+ * dispatch scope, not just the dashboard tree. Instead this is an IN-MEMORY
350
+ * BFS over the full project bead list: build a parent->children map, then
351
+ * walk outward from every target issue to find every descendant at any depth,
352
+ * regardless of status. That subsumes the multi-target union case without a
353
+ * separate code path.
354
+ *
355
+ * Every target issue's OWN id is seeded into the result UNCONDITIONALLY. The
356
+ * BFS only ever adds descendants, so without the seed a childless leaf
357
+ * target's scope would be empty and every query would short-circuit to `[]`.
358
+ * The seed used to be conditional on the target having no children, on the
359
+ * theory that a target WITH children is a pure grouping node whose own status
360
+ * never matters -- that is false: a target with pre-existing children (a
361
+ * verify-routed parent) can itself transition open->closed, and
362
+ * status-counting queries need to see that transition. Excluding it silently
363
+ * dropped such a parent's own closure from the stall-detection progress
364
+ * score.
365
+ *
366
+ * A childful target is STILL excluded from dispatch (readyLeafBeads()) and
367
+ * from the exit-gate open-at-goal counts, via a separate structural
368
+ * "is this someone's .parent" check that is independent of scope membership
369
+ * -- so seeding here does not let a still-open childful target masquerade as
370
+ * done, nor block dispatch as if it were a leaf.
371
+ *
372
+ * @param {Array<object>} allBeads - the FULL, unfiltered project bead list
373
+ * @param {string[]} targetIssues - the sprint's target issue root id(s)
374
+ * @returns {{ byId: Map<string, object>, childrenOf: Map<string, object[]>, scopeIds: Set<string> }}
375
+ */
376
+ export function discoverScope(allBeads, targetIssues) {
377
+ const { byId, childrenOf } = buildBeadGraph(allBeads);
378
+ const targets = targetIssues || [];
379
+
380
+ const scopeIds = new Set();
381
+ const frontier = [...targets];
382
+ while (frontier.length > 0) {
383
+ const id = frontier.shift();
384
+ for (const child of (childrenOf.get(id) || [])) {
385
+ if (!scopeIds.has(child.id)) {
386
+ scopeIds.add(child.id);
387
+ frontier.push(child.id);
388
+ }
389
+ }
390
+ }
391
+ for (const id of targets) scopeIds.add(id);
392
+
393
+ return { byId, childrenOf, scopeIds };
394
+ }
395
+
396
+ /**
397
+ * Classify beads whose every child is closed as ready for the `verify` route:
398
+ * implementation-complete parents that must be excluded from
399
+ * Plan/Develop/Review and verified against the live deployed product, never
400
+ * administratively closed on child-closure alone -- see
401
+ * docs/fleet-sprint-phase-routing-design.md for the design.
402
+ *
403
+ * Pure: derives the verify set fresh from `allBeads` on every call. There is
404
+ * no persisted list -- callers re-invoke this at each classification point
405
+ * (pre-sprint validation, cycle top, IntegTest dispatch) rather than caching,
406
+ * so a crash-restart re-derives it for free and nothing can drift out of sync
407
+ * with the beads DB.
408
+ *
409
+ * Eligibility (a bead qualifies iff ALL of):
410
+ * 1. in scope: is itself one of `targetIssues`, or is a BFS descendant of
411
+ * one -- via discoverScope() above, the same rule bdListScoped uses.
412
+ * 2. status is 'open' or 'in_progress' (not already closed/deferred).
413
+ * 3. has at least one child. Childless beads are leaves -- they route
414
+ * through the normal Plan/Develop pipeline, never verify. A parent with
415
+ * NO children is never eligible, regardless of anything else.
416
+ * 4. EVERY child (any issue_type) has status 'closed', checked against the
417
+ * FULL unfiltered `allBeads` list, not a scope-filtered subset -- an
418
+ * out-of-scope open child must still block eligibility. Partial closure
419
+ * never qualifies.
420
+ * 5. no unmet 'blocks' dependency: a parent whose blocker is still being
421
+ * implemented in this same run must not be verified against today's
422
+ * incomplete state.
423
+ *
424
+ * @param {Array<object>} allBeads - the FULL, unfiltered project bead list.
425
+ * @param {string[]} targetIssues - the sprint's target issue root id(s).
426
+ * @returns {{ verifyIds: string[], ineligible: Array<{id: string, reason: string}> }}
427
+ */
428
+ export function classifyVerifySet(allBeads, targetIssues) {
429
+ const { byId, childrenOf, scopeIds } = discoverScope(allBeads, targetIssues);
430
+
431
+ const verifyIds = [];
432
+ const ineligible = [];
433
+ for (const id of scopeIds) {
434
+ const bead = byId.get(id);
435
+ if (!bead) continue;
436
+ if (bead.status !== 'open' && bead.status !== 'in_progress') continue;
437
+
438
+ const kids = childrenOf.get(id) || [];
439
+ if (kids.length === 0) continue; // leaf -- normal pipeline, not eligible
440
+
441
+ if (!kids.every((k) => k.status === 'closed')) continue; // partial closure never qualifies
442
+
443
+ const unmetBlockerIds = (bead.dependencies || [])
444
+ .filter((d) => d.type === 'blocks')
445
+ .map((d) => d.depends_on_id)
446
+ .filter((depId) => {
447
+ const dep = byId.get(depId);
448
+ return dep && dep.status !== 'closed';
449
+ });
450
+ if (unmetBlockerIds.length > 0) {
451
+ ineligible.push({ id, reason: `unmet blocker(s): ${unmetBlockerIds.join(', ')}` });
452
+ continue;
453
+ }
454
+
455
+ verifyIds.push(id);
456
+ }
457
+
458
+ return { verifyIds, ineligible };
459
+ }
460
+
461
+ /**
462
+ * The per-sprint beads scope client: the shared full-DB snapshot, the two
463
+ * invalidation choke points that keep it correct (wrapCommand/wrapPhase), and
464
+ * the scoped query helper every caller reads beads through.
465
+ *
466
+ * The wrappers are returned rather than applied by the caller so the
467
+ * invalidation contract documented at the top of this file is implemented
468
+ * HERE, in one place, instead of being re-derived at each call site. runner.js
469
+ * installs both before any other statement in runSprintCycle() uses `command`
470
+ * or `phase`, so every direct call -- and every helper that receives
471
+ * `command` via an options object -- transparently goes through them.
472
+ *
473
+ * `getOrchestratorMember` is a getter, not a value, because the orchestrator
474
+ * member is resolved from the role->member mapping well after this client is
475
+ * constructed (the snapshot must exist before the `command` wrapper does,
476
+ * and the wrapper must exist before anything can resolve members). No fetch
477
+ * can happen before that point, so the getter is always called on a resolved
478
+ * value.
479
+ *
480
+ * @param {object} opts
481
+ * @param {string[]} opts.targetIssues - the sprint's target issue root id(s)
482
+ * @param {string|null} [opts.assignee] - `--assignee` narrowing for filtered queries
483
+ * @param {(raw: string, label: string) => any} opts.parseBdJson - bd JSON parser (injected to avoid an import cycle back into runner.js)
484
+ * @param {() => string} opts.getOrchestratorMember - resolves the member every read is dispatched to
485
+ */
486
+ export function createBeadsScope(opts = {}) {
487
+ const targetIssues = opts.targetIssues || [];
488
+ const assignee = opts.assignee || null;
489
+ const parseBdJson = opts.parseBdJson;
490
+ const getOrchestratorMember = opts.getOrchestratorMember;
491
+ if (typeof parseBdJson !== 'function') {
492
+ throw new TypeError('createBeadsScope({ parseBdJson }): parseBdJson must be a function');
493
+ }
494
+ if (typeof getOrchestratorMember !== 'function') {
495
+ throw new TypeError('createBeadsScope({ getOrchestratorMember }): getOrchestratorMember must be a function');
496
+ }
497
+
498
+ let allBeadsSnapshot = null; // { beads } -- cleared by invalidateAllBeadsCache()
499
+ let allBeadsInFlight = null;
500
+ let command = null; // installed by wrapCommand(); see fetchAllBeadsShared
501
+
502
+ /** Drop the shared snapshot. Cheap and idempotent. */
503
+ function invalidateAllBeadsCache() { allBeadsSnapshot = null; }
504
+
505
+ /** Whether a snapshot is currently cached -- diagnostics/tests only. */
506
+ function hasCachedSnapshot() { return allBeadsSnapshot !== null; }
507
+
508
+ /**
509
+ * Wrap the raw `command()` seam so clause (b) of the invalidation
510
+ * contract holds for every orchestrator-side command, and remember the
511
+ * wrapped function as the one this module issues its own reads through
512
+ * (so a scope read can never sneak past its own invalidation seam).
513
+ *
514
+ * `onCommand(trimmedCmd, opts)` is an optional post-command hook for
515
+ * concerns that are NOT beads-snapshot related but need the same single
516
+ * choke point (runner.js uses it for DoltSync's per-member sync.remote
517
+ * memo invalidation). It runs after the invalidation decision, matching
518
+ * the pre-extraction ordering.
519
+ */
520
+ function wrapCommand(rawCommand, wrapOpts = {}) {
521
+ if (typeof rawCommand !== 'function') {
522
+ throw new TypeError('beadsScope.wrapCommand(rawCommand): rawCommand must be a function');
523
+ }
524
+ const onCommand = typeof wrapOpts.onCommand === 'function' ? wrapOpts.onCommand : null;
525
+ const wrapped = async (cmdStr, cmdOpts) => {
526
+ const result = await rawCommand(cmdStr, cmdOpts);
527
+ if (typeof cmdStr === 'string') {
528
+ const trimmed = cmdStr.trim();
529
+ if (isBeadsMutatingCommand(trimmed)) {
530
+ invalidateAllBeadsCache();
531
+ }
532
+ if (onCommand) onCommand(trimmed, cmdOpts);
533
+ }
534
+ return result;
535
+ };
536
+ command = wrapped;
537
+ return wrapped;
538
+ }
539
+
540
+ /**
541
+ * Wrap the raw `phase()` seam so clause (a) of the invalidation contract
542
+ * holds: a new step never inherits the previous step's snapshot.
543
+ */
544
+ function wrapPhase(rawPhase) {
545
+ if (typeof rawPhase !== 'function') {
546
+ throw new TypeError('beadsScope.wrapPhase(rawPhase): rawPhase must be a function');
547
+ }
548
+ return (title) => {
549
+ invalidateAllBeadsCache();
550
+ return rawPhase(title);
551
+ };
552
+ }
553
+
554
+ /**
555
+ * The one full-DB fetch. Serves from the snapshot whenever one is still
556
+ * valid -- the snapshot survives across separate, non-overlapping calls
557
+ * (see the invalidation contract at the top of this file for what drops
558
+ * it) -- and otherwise coalesces concurrent callers onto a single
559
+ * in-flight request.
560
+ *
561
+ * Coalescing matters beyond saving a round trip: the command text is
562
+ * identical for every caller, and the bd-replay test shim matches
563
+ * recorded responses FIFO per exact command string, so N indistinguishable
564
+ * concurrent commands have no reliable replay order.
565
+ *
566
+ * `--all` because `bd list` excludes closed issues by default, which would
567
+ * drop a closed node's parent link and orphan its whole subtree from
568
+ * discovery; `--limit 0` because the default row cap could silently
569
+ * truncate a larger scope.
570
+ */
571
+ async function fetchAllBeadsShared() {
572
+ if (allBeadsSnapshot) return allBeadsSnapshot.beads;
573
+ if (!command) {
574
+ throw new Error('beadsScope.fetchAllBeadsShared(): wrapCommand() must be installed before any beads read');
575
+ }
576
+ if (!allBeadsInFlight) {
577
+ const allLabel = 'bd list --all --limit 0 --json';
578
+ allBeadsInFlight = command(allLabel, { member_name: getOrchestratorMember(), silent: true })
579
+ .then((raw) => parseBdJson(raw, allLabel))
580
+ .then((beads) => {
581
+ allBeadsSnapshot = { beads };
582
+ return beads;
583
+ })
584
+ .finally(() => { allBeadsInFlight = null; });
585
+ }
586
+ return allBeadsInFlight;
587
+ }
588
+
589
+ /**
590
+ * Scope-filtered `bd list`. With no extra args this is the pure in-memory
591
+ * path (the already-fetched project-wide any-status dump filtered to
592
+ * scope, no new command issued).
593
+ *
594
+ * With extra args it ALWAYS issues a real, fresh `bd list` -- the caller's
595
+ * filter flags (--ready/--status/--type/--priority-max/etc) express
596
+ * bd-side computed properties, readiness in particular, that a plain
597
+ * in-memory filter over the snapshot cannot reliably replicate. That
598
+ * freshness is also exactly why the three deliberate cache-bypass sites
599
+ * documented at the top of this file call this with a filter instead of
600
+ * reading fetchAllBeadsShared(). When an assignee is configured,
601
+ * `--assignee` narrows that query to this sprint's claimed beads so two
602
+ * sprints never select the same one.
603
+ *
604
+ * Note the asymmetry, which is deliberate: the SCOPE always comes from
605
+ * the (possibly cached) snapshot, while the FILTER result is always
606
+ * fresh. Scope membership is structural and changes only when beads are
607
+ * created/reparented; status is what moves under the sprint's feet.
608
+ */
609
+ async function bdListScoped(restArgs) {
610
+ const rest = restArgs ? restArgs.trim() : '';
611
+
612
+ const allBeads = await fetchAllBeadsShared();
613
+ const { scopeIds } = discoverScope(allBeads, targetIssues);
614
+
615
+ if (scopeIds.size === 0) return [];
616
+
617
+ if (!rest) {
618
+ return allBeads.filter((b) => b && scopeIds.has(b.id));
619
+ }
620
+
621
+ let filterArgs = rest;
622
+ if (assignee) {
623
+ filterArgs = `${rest} --assignee ${assignee}`;
624
+ }
625
+ const filterLabel = `bd list ${filterArgs} --limit 0`;
626
+ const filterRaw = await command(filterLabel, { member_name: getOrchestratorMember(), silent: true });
627
+ return parseBdJson(filterRaw, filterLabel).filter((b) => b && scopeIds.has(b.id));
628
+ }
629
+
630
+ return {
631
+ invalidateAllBeadsCache,
632
+ hasCachedSnapshot,
633
+ wrapCommand,
634
+ wrapPhase,
635
+ fetchAllBeadsShared,
636
+ bdListScoped,
637
+ };
638
+ }