@apralabs/apra-fleet 0.4.4 → 0.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (268) hide show
  1. package/README.md +49 -4
  2. package/dist/agents/backlog-groomer.md +5 -0
  3. package/dist/agents/ci-watcher.md +5 -0
  4. package/dist/agents/deployer.md +20 -2
  5. package/dist/agents/doer.md +38 -2
  6. package/dist/agents/harvester.md +12 -9
  7. package/dist/agents/integ-test-runner.md +5 -0
  8. package/dist/agents/kb-reconciler.md +6 -0
  9. package/dist/agents/plan-reviewer.md +5 -0
  10. package/dist/agents/planner.md +5 -0
  11. package/dist/agents/regression-test-runner.md +5 -0
  12. package/dist/agents/reviewer.md +67 -15
  13. package/dist/agents/schemas/deployer-output.json +5 -0
  14. package/dist/agents/schemas/doer-output.json +78 -2
  15. package/dist/agents/schemas/reviewer-output.json +104 -2
  16. package/dist/cli/auth.js +5 -1
  17. package/dist/cli/beads-pin.js +6 -7
  18. package/dist/cli/claude-mod.d.ts +75 -0
  19. package/dist/cli/claude-mod.js +288 -0
  20. package/dist/cli/dolt-install.d.ts +1 -1
  21. package/dist/cli/dolt-install.js +5 -1
  22. package/dist/cli/fleet-se-guard.d.ts +8 -0
  23. package/dist/cli/fleet-se-guard.js +19 -3
  24. package/dist/cli/install-guard.d.ts +9 -0
  25. package/dist/cli/install-guard.js +24 -0
  26. package/dist/cli/install.d.ts +12 -0
  27. package/dist/cli/install.js +180 -20
  28. package/dist/cli/kb-profile.d.ts +16 -0
  29. package/dist/cli/kb-profile.js +81 -0
  30. package/dist/cli/start.js +3 -0
  31. package/dist/cli/uninstall.js +13 -3
  32. package/dist/cli/update.d.ts +4 -0
  33. package/dist/cli/update.js +19 -3
  34. package/dist/commands/kb-server.d.ts +10 -1
  35. package/dist/commands/kb-server.js +285 -11
  36. package/dist/index.js +22 -1
  37. package/dist/os/git-executable.d.ts +57 -0
  38. package/dist/os/git-executable.js +85 -0
  39. package/dist/os/go-concurrency.d.ts +44 -0
  40. package/dist/os/go-concurrency.js +53 -0
  41. package/dist/os/index.d.ts +1 -0
  42. package/dist/os/index.js +1 -0
  43. package/dist/os/linux.d.ts +2 -0
  44. package/dist/os/linux.js +10 -1
  45. package/dist/os/os-commands.d.ts +25 -0
  46. package/dist/os/os-commands.js +2 -0
  47. package/dist/os/windows-executable.d.ts +53 -0
  48. package/dist/os/windows-executable.js +185 -0
  49. package/dist/os/windows-gitbash.d.ts +23 -14
  50. package/dist/os/windows-gitbash.js +40 -16
  51. package/dist/os/windows.d.ts +2 -0
  52. package/dist/os/windows.js +37 -6
  53. package/dist/paths.d.ts +10 -1
  54. package/dist/paths.js +19 -2
  55. package/dist/services/agy-project.d.ts +7 -1
  56. package/dist/services/agy-project.js +7 -2
  57. package/dist/services/auth-socket.d.ts +18 -0
  58. package/dist/services/auth-socket.js +30 -4
  59. package/dist/services/credential-store.d.ts +33 -0
  60. package/dist/services/credential-store.js +79 -2
  61. package/dist/services/http-transport.d.ts +29 -0
  62. package/dist/services/http-transport.js +166 -37
  63. package/dist/services/kb-tool-profile.d.ts +36 -0
  64. package/dist/services/kb-tool-profile.js +88 -0
  65. package/dist/services/knowledge/bible-blob-id.js +10 -1
  66. package/dist/services/knowledge/bible-import.d.ts +108 -0
  67. package/dist/services/knowledge/bible-import.js +137 -4
  68. package/dist/services/knowledge/file-hash.js +6 -5
  69. package/dist/services/knowledge/http-provider.d.ts +303 -20
  70. package/dist/services/knowledge/http-provider.js +795 -125
  71. package/dist/services/knowledge/kb-config.d.ts +65 -1
  72. package/dist/services/knowledge/kb-config.js +143 -3
  73. package/dist/services/knowledge/kb-http-auth-state.d.ts +26 -0
  74. package/dist/services/knowledge/kb-http-auth-state.js +40 -0
  75. package/dist/services/knowledge/kb-providers.d.ts +9 -2
  76. package/dist/services/knowledge/kb-providers.js +67 -37
  77. package/dist/services/knowledge/kb-removed-scope-keys.js +1 -1
  78. package/dist/services/knowledge/kb-self.d.ts +122 -9
  79. package/dist/services/knowledge/kb-self.js +196 -36
  80. package/dist/services/knowledge/member-bible-view.js +16 -3
  81. package/dist/services/knowledge/path-validation.d.ts +7 -0
  82. package/dist/services/knowledge/path-validation.js +11 -0
  83. package/dist/services/knowledge/project-slug.js +3 -2
  84. package/dist/services/knowledge/repository-header.d.ts +77 -0
  85. package/dist/services/knowledge/repository-header.js +233 -0
  86. package/dist/services/knowledge/require-sqlite-project.d.ts +1 -1
  87. package/dist/services/knowledge/require-sqlite-project.js +1 -1
  88. package/dist/services/knowledge/sqlite-provider.d.ts +169 -0
  89. package/dist/services/knowledge/sqlite-provider.js +416 -4
  90. package/dist/services/knowledge/types.d.ts +15 -2
  91. package/dist/services/member-busy.d.ts +12 -0
  92. package/dist/services/member-busy.js +20 -0
  93. package/dist/services/member-config-io.d.ts +3 -2
  94. package/dist/services/member-config-io.js +7 -4
  95. package/dist/services/member-fleet-install.js +1 -0
  96. package/dist/services/member-tool-allowlist.d.ts +1 -1
  97. package/dist/services/member-tool-allowlist.js +8 -4
  98. package/dist/services/port-holder.js +2 -1
  99. package/dist/services/service-manager/types.d.ts +17 -1
  100. package/dist/services/service-manager/windows.d.ts +7 -2
  101. package/dist/services/service-manager/windows.js +28 -11
  102. package/dist/services/service-notice.d.ts +7 -0
  103. package/dist/services/service-notice.js +19 -0
  104. package/dist/services/session-registry.d.ts +13 -0
  105. package/dist/services/session-registry.js +13 -0
  106. package/dist/services/session-roots.d.ts +67 -0
  107. package/dist/services/session-roots.js +126 -0
  108. package/dist/services/statusline.d.ts +21 -0
  109. package/dist/services/statusline.js +97 -1
  110. package/dist/services/supervisor-service-cleanup.js +2 -1
  111. package/dist/services/tool-registry.js +108 -20
  112. package/dist/services/tool-scope.d.ts +34 -1
  113. package/dist/services/tool-scope.js +27 -2
  114. package/dist/services/vcs/azure-devops.js +10 -0
  115. package/dist/services/vcs/bitbucket.d.ts +22 -1
  116. package/dist/services/vcs/bitbucket.js +163 -17
  117. package/dist/services/vcs/types.d.ts +25 -2
  118. package/dist/services/watch/project-resolver.js +2 -1
  119. package/dist/skills/pm/cost.md +5 -1
  120. package/dist/skills/pm/index.md +9 -9
  121. package/dist/skills/pm/sprint.md +2 -1
  122. package/dist/tools/check-status.d.ts +51 -0
  123. package/dist/tools/check-status.js +124 -12
  124. package/dist/tools/code-intelligence-freshness.js +1 -1
  125. package/dist/tools/code-intelligence-gitnexus.d.ts +19 -0
  126. package/dist/tools/code-intelligence-gitnexus.js +166 -9
  127. package/dist/tools/code-intelligence-readiness.d.ts +58 -1
  128. package/dist/tools/code-intelligence-readiness.js +93 -8
  129. package/dist/tools/code-intelligence-reindex.d.ts +25 -1
  130. package/dist/tools/code-intelligence-reindex.js +76 -4
  131. package/dist/tools/code-intelligence.d.ts +1 -1
  132. package/dist/tools/code-intelligence.js +1 -1
  133. package/dist/tools/execute-command.js +14 -8
  134. package/dist/tools/execute-prompt.js +6 -2
  135. package/dist/tools/fleet-snapshot.d.ts +21 -0
  136. package/dist/tools/fleet-snapshot.js +78 -0
  137. package/dist/tools/kb-bible-commit.d.ts +25 -11
  138. package/dist/tools/kb-bible-commit.js +142 -33
  139. package/dist/tools/kb-capture.d.ts +2 -2
  140. package/dist/tools/kb-context.js +47 -27
  141. package/dist/tools/kb-demote.d.ts +27 -0
  142. package/dist/tools/kb-demote.js +37 -0
  143. package/dist/tools/kb-export.d.ts +35 -3
  144. package/dist/tools/kb-export.js +56 -13
  145. package/dist/tools/kb-feedback.d.ts +2 -0
  146. package/dist/tools/kb-feedback.js +17 -7
  147. package/dist/tools/kb-harvest.js +28 -9
  148. package/dist/tools/kb-import.d.ts +18 -2
  149. package/dist/tools/kb-import.js +24 -9
  150. package/dist/tools/kb-invalidate.d.ts +11 -3
  151. package/dist/tools/kb-invalidate.js +80 -7
  152. package/dist/tools/kb-list.js +38 -10
  153. package/dist/tools/kb-promote.js +6 -4
  154. package/dist/tools/kb-query.d.ts +3 -0
  155. package/dist/tools/kb-query.js +181 -37
  156. package/dist/tools/kb-session-prime.d.ts +4 -4
  157. package/dist/tools/kb-session-prime.js +89 -9
  158. package/dist/tools/kb-setup.d.ts +20 -0
  159. package/dist/tools/kb-setup.js +149 -11
  160. package/dist/tools/list-members.js +1 -1
  161. package/dist/tools/member-detail.js +7 -3
  162. package/dist/tools/provision-vcs-auth.d.ts +28 -3
  163. package/dist/tools/provision-vcs-auth.js +53 -7
  164. package/dist/tools/receive-files.js +7 -4
  165. package/dist/tools/send-files.js +5 -4
  166. package/dist/tools/send-message.d.ts +3 -0
  167. package/dist/tools/send-message.js +15 -2
  168. package/dist/tools/stop-prompt.js +3 -1
  169. package/dist/tools/vcs-credential-exec.d.ts +45 -3
  170. package/dist/tools/vcs-credential-exec.js +90 -11
  171. package/dist/utils/process-utils.js +5 -1
  172. package/dist/utils/redact-known-secrets.d.ts +17 -0
  173. package/dist/utils/redact-known-secrets.js +70 -0
  174. package/dist/utils/skill-matrix.js +1 -1
  175. package/dist/utils/vcs-provider-detect.js +2 -2
  176. package/dist/workflows/auto-sprint.js +245 -9
  177. package/package.json +10 -7
  178. package/packages/apra-fleet-client/package.json +1 -1
  179. package/packages/apra-fleet-client/src/client/api.mjs +172 -19
  180. package/packages/apra-fleet-client/src/client/reconnecting-transport.mjs +35 -2
  181. package/packages/apra-fleet-client/src/client/transport.mjs +6 -0
  182. package/packages/apra-fleet-se/apra-pm/agents/backlog-groomer.md +5 -0
  183. package/packages/apra-fleet-se/apra-pm/agents/ci-watcher.md +5 -0
  184. package/packages/apra-fleet-se/apra-pm/agents/deployer.md +20 -2
  185. package/packages/apra-fleet-se/apra-pm/agents/doer.md +38 -2
  186. package/packages/apra-fleet-se/apra-pm/agents/harvester.md +12 -9
  187. package/packages/apra-fleet-se/apra-pm/agents/integ-test-runner.md +5 -0
  188. package/packages/apra-fleet-se/apra-pm/agents/kb-reconciler.md +6 -0
  189. package/packages/apra-fleet-se/apra-pm/agents/plan-reviewer.md +5 -0
  190. package/packages/apra-fleet-se/apra-pm/agents/planner.md +5 -0
  191. package/packages/apra-fleet-se/apra-pm/agents/regression-test-runner.md +5 -0
  192. package/packages/apra-fleet-se/apra-pm/agents/reviewer.md +67 -15
  193. package/packages/apra-fleet-se/apra-pm/agents/schemas/deployer-output.json +5 -0
  194. package/packages/apra-fleet-se/apra-pm/agents/schemas/doer-output.json +78 -2
  195. package/packages/apra-fleet-se/apra-pm/agents/schemas/reviewer-output.json +104 -2
  196. package/packages/apra-fleet-se/apra-pm/skills/pm/cost.md +5 -1
  197. package/packages/apra-fleet-se/apra-pm/skills/pm/index.md +9 -9
  198. package/packages/apra-fleet-se/apra-pm/skills/pm/sprint.md +2 -1
  199. package/packages/apra-fleet-se/bin/cli.mjs +104 -31
  200. package/packages/apra-fleet-se/bin/serve.mjs +46 -8
  201. package/packages/apra-fleet-se/fleet-sprint/abort.mjs +184 -32
  202. package/packages/apra-fleet-se/fleet-sprint/bd-sync-command.mjs +69 -0
  203. package/packages/apra-fleet-se/fleet-sprint/beads-children.mjs +21 -0
  204. package/packages/apra-fleet-se/fleet-sprint/beads-lock-probe.mjs +176 -0
  205. package/packages/apra-fleet-se/fleet-sprint/beads-reachability.mjs +126 -0
  206. package/packages/apra-fleet-se/fleet-sprint/beads-scope.mjs +158 -1
  207. package/packages/apra-fleet-se/fleet-sprint/contracts.mjs +82 -2
  208. package/packages/apra-fleet-se/fleet-sprint/coordination.mjs +23 -6
  209. package/packages/apra-fleet-se/fleet-sprint/decision-notify.mjs +338 -0
  210. package/packages/apra-fleet-se/fleet-sprint/decision-wait.mjs +731 -0
  211. package/packages/apra-fleet-se/fleet-sprint/decisions.mjs +372 -0
  212. package/packages/apra-fleet-se/fleet-sprint/dispatch-role.mjs +44 -11
  213. package/packages/apra-fleet-se/fleet-sprint/docs/README.md +4 -1
  214. package/packages/apra-fleet-se/fleet-sprint/dolt-settle.mjs +9 -3
  215. package/packages/apra-fleet-se/fleet-sprint/dolt-sync.mjs +314 -19
  216. package/packages/apra-fleet-se/fleet-sprint/errors.mjs +72 -4
  217. package/packages/apra-fleet-se/fleet-sprint/git-sync.mjs +7 -1
  218. package/packages/apra-fleet-se/fleet-sprint/git-topology.mjs +112 -1
  219. package/packages/apra-fleet-se/fleet-sprint/guarded-modules.mjs +36 -2
  220. package/packages/apra-fleet-se/fleet-sprint/kb.mjs +736 -101
  221. package/packages/apra-fleet-se/fleet-sprint/member-init-probe.mjs +1 -1
  222. package/packages/apra-fleet-se/fleet-sprint/member-provisioning.mjs +7 -1
  223. package/packages/apra-fleet-se/fleet-sprint/phases/deploy.mjs +49 -2
  224. package/packages/apra-fleet-se/fleet-sprint/phases/develop.mjs +206 -3
  225. package/packages/apra-fleet-se/fleet-sprint/phases/final-review.mjs +61 -3
  226. package/packages/apra-fleet-se/fleet-sprint/phases/harvest.mjs +81 -31
  227. package/packages/apra-fleet-se/fleet-sprint/phases/plan.mjs +7 -3
  228. package/packages/apra-fleet-se/fleet-sprint/phases/publish-pr.mjs +39 -14
  229. package/packages/apra-fleet-se/fleet-sprint/phases/re-review.mjs +17 -1
  230. package/packages/apra-fleet-se/fleet-sprint/phases/review.mjs +18 -3
  231. package/packages/apra-fleet-se/fleet-sprint/pr-body.mjs +14 -1
  232. package/packages/apra-fleet-se/fleet-sprint/prompts.mjs +32 -5
  233. package/packages/apra-fleet-se/fleet-sprint/runner.js +824 -98
  234. package/packages/apra-fleet-se/fleet-sprint/se-os-commands.mjs +4 -2
  235. package/packages/apra-fleet-se/fleet-sprint/se-posix.mjs +54 -1
  236. package/packages/apra-fleet-se/fleet-sprint/se-windows.mjs +29 -2
  237. package/packages/apra-fleet-se/fleet-sprint/set-aside.mjs +288 -0
  238. package/packages/apra-fleet-se/fleet-sprint/skills/fleet-supervisor/SKILL.md +3 -2
  239. package/packages/apra-fleet-se/fleet-sprint/sprint-args.mjs +20 -0
  240. package/packages/apra-fleet-se/fleet-sprint/sprint-report.mjs +21 -0
  241. package/packages/apra-fleet-se/fleet-sprint/sprint-state.mjs +9 -0
  242. package/packages/apra-fleet-se/fleet-sprint/vcs-auth.mjs +605 -32
  243. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/bitbucket.mjs +811 -17
  244. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/index.mjs +89 -1
  245. package/packages/apra-fleet-se/fleet-sprint/viewer-extensions.mjs +225 -2
  246. package/packages/apra-fleet-se/fleet-sprint/worklists.mjs +59 -3
  247. package/packages/apra-fleet-se/src/supervisor/api.mjs +148 -8
  248. package/packages/apra-fleet-se/src/supervisor/dashboard.mjs +6 -3
  249. package/packages/apra-fleet-se/src/supervisor/dolt-mutex.mjs +30 -10
  250. package/packages/apra-fleet-se/src/supervisor/fleet-members.mjs +17 -4
  251. package/packages/apra-fleet-se/src/supervisor/history.mjs +8 -1
  252. package/packages/apra-fleet-se/src/supervisor/id-allocator.mjs +92 -2
  253. package/packages/apra-fleet-se/src/supervisor/proxy.mjs +26 -1
  254. package/packages/apra-fleet-se/src/supervisor/server.mjs +151 -8
  255. package/packages/apra-fleet-se/src/supervisor/spawner.mjs +11 -9
  256. package/packages/apra-fleet-se/src/supervisor/watchdog.mjs +7 -1
  257. package/packages/apra-fleet-workflow/package.json +2 -1
  258. package/packages/apra-fleet-workflow/src/viewer/index.mjs +86 -5
  259. package/packages/apra-fleet-workflow/src/viewer/request-guard.mjs +222 -0
  260. package/packages/apra-fleet-workflow/src/workflow/index.mjs +34 -2
  261. package/plugins/claude-code/fleet-status/.claude-plugin/plugin.json +7 -0
  262. package/plugins/claude-code/fleet-status/hooks/hooks.json +1 -0
  263. package/plugins/claude-code/fleet-status/hooks/register.tsx +906 -0
  264. package/plugins/claude-code/fleet-status/types/index.d.ts +88 -0
  265. package/skills/fleet/auth-bitbucket.md +47 -20
  266. package/skills/fleet/onboarding.md +1 -1
  267. package/skills/fleet/skill-matrix.md +3 -3
  268. package/version.json +1 -1
@@ -5,12 +5,12 @@ import {
5
5
  ROLES, planReviewerVerdict, doerReport, reviewerVerdict, streakAssignment,
6
6
  deployerReport, integReport, regressionReport, finalVerdict, harvesterReport, wrapUntrustedBlock,
7
7
  } from './contracts.mjs';
8
- import { SprintPlanRejectedError, StalledSprintError, ReviewerContractViolationError, DoltSyncError, PlanReviewDispatchFailedError, PreSprintValidationError, PRE_SPRINT_REFUSAL_REASONS, isNonRetryableDispatchError, isAuthDispatchError, isInfraDispatchFailure, isPostDispatchSyncFailure } from './errors.mjs';
8
+ import { SprintPlanRejectedError, StalledSprintError, ReviewerContractViolationError, DoltSyncError, GitSyncError,PlanReviewDispatchFailedError, PreSprintValidationError, PRE_SPRINT_REFUSAL_REASONS, isNonRetryableDispatchError, isAuthDispatchError, isInfraDispatchFailure, isPostDispatchSyncFailure } from './errors.mjs';
9
9
  // The ONLY dolt command surface in fleet-sprint (apra-fleet-417.2.1). Every
10
10
  // runner.js call site uses the purpose-based entry points on DoltSync
11
11
  // (apra-fleet-417.2.2); the named primitives are imported here only to be
12
12
  // re-exported below for the existing unit suites that drive them directly.
13
- import { DoltSync, doltPullBefore, doltPushAfter, preflightBeadsHealthGate } from './dolt-sync.mjs';
13
+ import { DoltSync, doltPullBefore, doltPushAfter, preflightBeadsHealthGate, setMemberTargetResolver } from './dolt-sync.mjs';
14
14
 
15
15
  import { parseUnmergedPaths } from './conflict-ladder.mjs';
16
16
  // The deterministic dolt conflict settlement callback (docs/dolt-sync-
@@ -52,6 +52,7 @@ import { buildCreatePrCommand, resolveProvider, parseProviderRepoRef, getVcsProv
52
52
  // brackets that were its only caller here.
53
53
  import {
54
54
  checkMemberTopology, classifyGitFailure, runGitStep, commandResultToSoftGit,
55
+ resolveReviewMergeBase,
55
56
  } from './git-topology.mjs';
56
57
  import { getSeCommands } from './se-os-commands.mjs';
57
58
  import { resultText, toolErrorText } from './mcp-result.mjs';
@@ -112,6 +113,7 @@ import {
112
113
  selectStreaks, groupStreaksFromLaneMetadata, SIZE_POINTS, MODEL_WEIGHT, DEFAULT_EFFORT_THRESHOLD,
113
114
  computeLaneEffort, streakRequiredTier, streakMinPriority, streakEffortPoints, beadBlocksDependencyIds,
114
115
  resolveWorklistTierPolicy, hasContextHeadroomForResume, assignDoerWorklists,
116
+ holdBackByLaneOrder,
115
117
  } from './worklists.mjs';
116
118
  import {
117
119
  isTypedAbortError, finalizeAbort, persistNewTaskBestEffort, validateNewTask,
@@ -138,6 +140,8 @@ import { policyFor, USAGE_LIMIT_BUDGET_DEFAULTS, agentTypeAppliesKbCaptures } fr
138
140
  // apra-fleet-hzeb.4.2: the usage-limit pause/resume/re-probe controller wired
139
141
  // into the dispatchRole engine as ctx.onUsageLimit below.
140
142
  import { createUsageLimitPauseController } from './usage-limit-controller.mjs';
143
+ import { createDecisionWait } from './decision-wait.mjs';
144
+ import { notifyDecision, prepareDecisionNotify } from './decision-notify.mjs';
141
145
  // apra-fleet-3swo.6.2: the first two of runSprintCycle's twelve phase()
142
146
  // boundaries, sliced into their own modules under ./phases/. Each takes ONE
143
147
  // explicit state argument instead of closing over runSprintCycle's locals; the
@@ -162,7 +166,8 @@ import { runDevelopPhase } from './phases/develop.mjs';
162
166
  // around Deploy, and the dashboard/still-open loop control after Review,
163
167
  // stayed here.
164
168
  import { runReviewPhase } from './phases/review.mjs';
165
- import { runDeployPhase, latestDeployFailure, formatDeployFailureReason, DEPLOY_RETRY_CYCLE_LIMIT } from './phases/deploy.mjs';
169
+ import { runDeployPhase, latestDeployFailure, formatDeployFailureReason, formatDeploySetAsideNotes, DEPLOY_RETRY_CYCLE_LIMIT } from './phases/deploy.mjs';
170
+ import { collectSetAsideEntries, evaluateSetAsideStall, formatSetAsideStallMessage, stuckBehindSetAside, collectWaitEntries } from './set-aside.mjs';
166
171
  // apra-fleet-3swo.6.8: the next two phase() boundaries -- the per-cycle Integ
167
172
  // Test and the Re-Review that Cycle Evaluation dispatches when the goal-
168
173
  // priority count already reads 0 but no review ran this cycle. Integ Test is
@@ -197,7 +202,7 @@ import { runRegressionTestPhase } from './phases/regression-test.mjs';
197
202
  // return value is its own contract, and group('Finalization')/endGroup() wrap
198
203
  // all four Finalization phases rather than either of these two). Their ORDER
199
204
  // is load-bearing: the harvester is a code-writing role whose
200
- // docs/sprint-analysis commits must be G-pushed by its own policy
205
+ // docs/README commits must be G-pushed by its own policy
201
206
  // bracket before Publish PR pushes the branch and raises the PR a human reads.
202
207
  // See each module's header for where its boundary is drawn.
203
208
  import { runHarvestPhase } from './phases/harvest.mjs';
@@ -228,7 +233,7 @@ import {
228
233
  // second one.
229
234
  import {
230
235
  createKbPrimingClient, KB_SELF_INJECTING_ROLES, kbQueryTerms,
231
- kbKnowledgeBlock, kbPromotionBlock,
236
+ kbKnowledgeBlock, kbPromotionBlock, kbDemotionBlock,
232
237
  } from './kb.mjs';
233
238
  import { createKbInjection } from './kb-injection.mjs';
234
239
  import { pathsFromText, isPriorityTierToken } from './kb-hints.mjs';
@@ -247,6 +252,8 @@ import {
247
252
  // Develop-dispatch goal filter: below-goal ready leaves are excluded
248
253
  // unless they block in-goal work or the sprint already worked on them.
249
254
  partitionReadyByGoal, formatBelowGoalExclusionLog,
255
+ // Set-aside v2: a waiting bead is held until its prerequisites close.
256
+ unmetPrerequisites,
250
257
  // apra-fleet-rp7a.1: the deferred split the Cycle Evaluation completion
251
258
  // math and phases/final-review.mjs's closing count BOTH apply, so the two
252
259
  // cannot drift apart. See its own doc comment for why 'deferred' -- and
@@ -314,6 +321,11 @@ import { DEFAULT_CONTEXT_CEILING, createRoundSessionRegistry } from './round-ses
314
321
  // dispatched on, so a claim a failed doer of this run left in_progress is
315
322
  // re-laned in the same sprint (see reclaimInRunOrphanedClaims below).
316
323
  import { createOrphanClaimTracker } from './orphan-reclaim.mjs';
324
+ // The pre-launch stale-claim rule, its fresh-read gate, and the downstream
325
+ // beads each reclaim unblocks (see reclaimStaleInProgress below).
326
+ import {
327
+ isPreLaunchReclaimCandidate, confirmPreLaunchCandidates, downstreamSuffix,
328
+ } from './beads-reachability.mjs';
317
329
  // GitHub #717: the verify-block deadlock diagnosis -- a bead blocked only by
318
330
  // verify-routed beads while the Integration Test phase cannot run.
319
331
  import {
@@ -407,12 +419,12 @@ export {
407
419
  KB_CAPTURE_TYPES, KB_MAX_PROMOTION_CANDIDATES, vetKbWork, createKbWorkClient,
408
420
  };
409
421
  // Re-exported so importers of the KB priming client and the prompt-
410
- // construction helpers (kbKnowledgeBlock, kbPromotionBlock, kbQueryTerms,
411
- // KB_SELF_INJECTING_ROLES) from runner.js keep working; kb.mjs is the
412
- // single source of truth for their implementation (apra-fleet-3swo.6.11).
422
+ // construction helpers (kbKnowledgeBlock, kbPromotionBlock, kbDemotionBlock,
423
+ // kbQueryTerms, KB_SELF_INJECTING_ROLES) from runner.js keep working; kb.mjs
424
+ // is the single source of truth for their implementation (apra-fleet-3swo.6.11).
413
425
  export {
414
426
  createKbPrimingClient, KB_SELF_INJECTING_ROLES, kbQueryTerms,
415
- kbKnowledgeBlock, kbPromotionBlock,
427
+ kbKnowledgeBlock, kbPromotionBlock, kbDemotionBlock,
416
428
  };
417
429
  // member-call.mjs is the single owner of memberCall/listTools (a MEMBER-scoped
418
430
  // tool call: local in-process session, or remote/relay via send_files +
@@ -552,6 +564,208 @@ function computeBranchEnsureMembers(getMembersForRole, kbMaintainers, backlogMem
552
564
  }
553
565
  export { computeBranchEnsureMembers };
554
566
 
567
+ // Factory for kbWork.demotionCandidates()'s
568
+ // roundChangedFiles callback -- THIS REVIEW ROUND's changed-file set,
569
+ // deliberately separate from kbInjection's diffFiles (the cumulative
570
+ // origin/base...branch diff computed for the reviewer/harvester hint
571
+ // context, left completely unchanged by this).
572
+ //
573
+ // Pulled out as its own factory, injected with `command` and `pullGitBefore`
574
+ // rather than written inline, so this can be unit-tested directly against
575
+ // fakes that discriminate the two defects a diff guard spawning git is prone
576
+ // to (a detection function welded to its own git spawn can only be
577
+ // exercised against the one diff a test can cheaply construct in-repo,
578
+ // which proves nothing). Here the two defects are: (1) computing the diff
579
+ // BEFORE the fetch/fast-forward-merge instead of after -- a stale read that
580
+ // can miss exactly the files this round touched -- and (2) collapsing to
581
+ // the cumulative sprint diff instead of the per-round one. A fake
582
+ // `pullGitBefore` and `command` can flip between a pre-merge and a
583
+ // post-merge tree deterministically, so a test can assert the returned set
584
+ // came from the POST-merge tree without needing a real git repository.
585
+ //
586
+ // One factory call carries ONE piece of state across its returned
587
+ // function's calls: the previous round's diffed-to commit sha (`lastSha`).
588
+ // The first call has no previous round, so it diffs from the sprint's base
589
+ // branch instead -- the only point "the previous round" can mean before any
590
+ // round has run.
591
+ //
592
+ // @param {{
593
+ // command: (cmd: string, opts: { member_name: string, silent?: boolean, failSoft?: boolean }) => Promise<{ ok: boolean, output?: string }>,
594
+ // pullGitBefore: (memberName: string) => Promise<any>,
595
+ // baseBranch: string,
596
+ // log?: Function,
597
+ // }} opts
598
+ // @returns {(memberName: string) => Promise<string[]>}
599
+ function createRoundChangedFiles({ command, pullGitBefore, baseBranch, log = () => {} }) {
600
+ let lastSha = null;
601
+ return async function roundChangedFiles(memberName) {
602
+ // AFTER the fetch and fast-forward merge, never before -- computing
603
+ // the diff first would read a snapshot that has not yet absorbed
604
+ // this round's commits (the superseded upstream attempt's defect).
605
+ try {
606
+ await pullGitBefore(memberName);
607
+ } catch (err) {
608
+ log(`[kb-work] could not fetch/fast-forward-merge '${memberName}' before computing this round's changed files (non-fatal): ${err && err.message ? err.message : String(err)}`);
609
+ return [];
610
+ }
611
+ const revParseCmd = 'git rev-parse HEAD';
612
+ const headRes = await command(revParseCmd, { member_name: memberName, silent: true, failSoft: true });
613
+ const head = (headRes && headRes.ok) ? String(headRes.output || '').trim() : '';
614
+ if (!head) {
615
+ log(`[kb-work] WARN: '${revParseCmd}' failed on '${memberName}' -- no changed files for this round's demotion candidates${failedCommandDetail(headRes)}`);
616
+ return [];
617
+ }
618
+ // THIS round's diff only: from the previous round's merged tip (or,
619
+ // on the first round, the sprint's base branch) to the new tip --
620
+ // never the cumulative origin/base...branch diff diffFiles computes.
621
+ const fromRef = lastSha || `origin/${baseBranch}`;
622
+ const diffCmd = `git diff --name-only ${fromRef}...${head}`;
623
+ const diffRes = await command(diffCmd, { member_name: memberName, silent: true, failSoft: true });
624
+ if (!diffRes || !diffRes.ok) {
625
+ // lastSha is NOT advanced: the next round diffs from the last tip
626
+ // whose diff succeeded, so this round's files are not lost.
627
+ log(`[kb-work] WARN: '${diffCmd}' failed on '${memberName}' -- no changed files for this round's demotion candidates; the next round diffs from ${fromRef} again${failedCommandDetail(diffRes)}`);
628
+ return [];
629
+ }
630
+ lastSha = head;
631
+ return String(diffRes.output || '').split('\n').map((l) => l.trim()).filter(Boolean);
632
+ };
633
+ }
634
+ export { createRoundChangedFiles };
635
+
636
+ // Factory for kbWork.demotionCandidates({ scope: 'sprint' })'s
637
+ // sprintChangedFiles callback -- the CUMULATIVE sprint changed-file set, which
638
+ // is the FINAL review's scope.
639
+ //
640
+ // WHY THIS EXISTS SEPARATELY FROM createRoundChangedFiles. Final review judges
641
+ // the WHOLE sprint diff in one pass, so "this round" is not a thing it has:
642
+ // there is no previous round's merged tip to diff from, and scoping its
643
+ // demotion candidates to the last round's diff would hide every entry the
644
+ // earlier rounds' files made worth re-checking. The two scopes are therefore
645
+ // two injected callbacks chosen by an explicit `scope` argument, not one
646
+ // callback that tries to work out which review is asking.
647
+ //
648
+ // WHY IT IS NOT kbInjection's `diffFiles` either. That one computes the same
649
+ // cumulative range but is wired for the reviewer/harvester KB-injection HINT
650
+ // context and is deliberately left untouched; it also does no fetch/merge
651
+ // first. This pulls before diffing for exactly the reason its round sibling
652
+ // does -- a pre-merge tree has not absorbed the sprint's latest commits -- and
653
+ // is STATELESS, unlike the round factory, because a cumulative range has
654
+ // nothing to carry between calls.
655
+ //
656
+ // @param {{
657
+ // command: (cmd: string, opts: { member_name: string, silent?: boolean, failSoft?: boolean }) => Promise<{ ok: boolean, output?: string }>,
658
+ // pullGitBefore: (memberName: string) => Promise<any>,
659
+ // baseBranch: string,
660
+ // branch: string,
661
+ // log?: Function,
662
+ // }} opts
663
+ // @returns {(memberName: string) => Promise<string[]>}
664
+ function createSprintChangedFiles({ command, pullGitBefore, baseBranch, branch, log = () => {} }) {
665
+ return async function sprintChangedFiles(memberName) {
666
+ try {
667
+ await pullGitBefore(memberName);
668
+ } catch (err) {
669
+ log(`[kb-work] could not fetch/fast-forward-merge '${memberName}' before computing the sprint's cumulative changed files (non-fatal): ${err && err.message ? err.message : String(err)}`);
670
+ return [];
671
+ }
672
+ const diffCmd = `git diff --name-only origin/${baseBranch}...${branch}`;
673
+ const diffRes = await command(diffCmd, { member_name: memberName, silent: true, failSoft: true });
674
+ if (!diffRes || !diffRes.ok) {
675
+ log(`[kb-work] WARN: '${diffCmd}' failed on '${memberName}' -- no changed files for the final review's demotion candidates${failedCommandDetail(diffRes)}`);
676
+ return [];
677
+ }
678
+ return String(diffRes.output || '').split('\n').map((l) => l.trim()).filter(Boolean);
679
+ };
680
+ }
681
+ export { createSprintChangedFiles };
682
+
683
+ // Factory for kbWork.promotionCandidates()'s D6 in-sprint ping-pong guard:
684
+ // the CURRENT sha256 of a bounded set of files, read on a member's own
685
+ // checkout. kb.mjs has no shell/fs access of its own (every kb_* call there
686
+ // goes through memberCall, never a shell) and this is the one disk fact no
687
+ // kb_* tool answers -- demoted_basis_hashes (surfaced on an INFERRED entry's
688
+ // kb_query row once it has ever been demoted) is a snapshot taken AT DEMOTE
689
+ // TIME, not a live one, so telling "basis unchanged" from "basis moved on"
690
+ // needs a fresh read of the SAME files right now.
691
+ //
692
+ // MUST hash the SAME way SqliteProvider's demoteBasisHashes does -- plain
693
+ // sha256 of the raw bytes, never `git hash-object` (which normalizes line
694
+ // endings and therefore would not reliably equal a plain sha256 of the same
695
+ // content) -- or the two sides of kb.mjs's comparison would silently never
696
+ // match. Run through a disposable `node -e` script rather than a shell
697
+ // pipeline. The file list is KB-supplied text, so it is NEVER interpolated
698
+ // into the command string: it travels as one base64 argv token (alphabet
699
+ // A-Za-z0-9+/=, inert in POSIX shells, PowerShell and cmd.exe) and the fixed
700
+ // script, which carries no `$`, backticks or double quotes, decodes it --
701
+ // the same recipe as stageCommandBodyMemberSide in member-provisioning.mjs.
702
+ // A JSON.stringify'd list inside a double-quoted shell string is NOT safe:
703
+ // POSIX shells still expand `$(...)` and backticks inside double quotes.
704
+ //
705
+ // A missing or unreadable file is simply absent from the result (never a
706
+ // fabricated hash); a failed command, or output that is not the JSON object
707
+ // this script prints, degrades to {} with a WARN naming the member -- the caller's "never falsely
708
+ // suppress" rule then leaves every candidate offered, exactly as it does for
709
+ // an unparseable demoted_basis_hashes snapshot.
710
+ //
711
+ // @param {{
712
+ // command: (cmd: string, opts: { member_name: string, silent?: boolean, failSoft?: boolean }) => Promise<{ ok: boolean, output?: string }>,
713
+ // log?: Function,
714
+ // }} opts
715
+ // @returns {(memberName: string, files: string[]) => Promise<Record<string, string>>}
716
+ const CURRENT_FILE_HASHES_SCRIPT =
717
+ "const fs=require('fs'),crypto=require('crypto');" +
718
+ "const files=JSON.parse(Buffer.from(process.argv[1],'base64').toString('utf8'));" +
719
+ "const out={};" +
720
+ "for (const f of files) { try { out[f]=crypto.createHash('sha256').update(fs.readFileSync(f)).digest('hex'); } catch (e) {} }" +
721
+ "process.stdout.write(JSON.stringify(out));";
722
+ // How a WARN line names the hashing command: the full string carries the whole
723
+ // script plus a base64 file list, which would bury the message.
724
+ const CURRENT_FILE_HASHES_LABEL = 'node -e <current-file-hashes script> <base64 file list>';
725
+ const FAILED_OUTPUT_MAX_CHARS = 300;
726
+
727
+ // ": <the command's output, capped at FAILED_OUTPUT_MAX_CHARS>", or "" when it
728
+ // printed nothing -- the reason a WARN line quotes for a failed member command.
729
+ function failedCommandDetail(res) {
730
+ const out = res && typeof res.output === 'string' ? res.output.trim() : '';
731
+ if (!out) return '';
732
+ return `: ${out.length > FAILED_OUTPUT_MAX_CHARS ? `${out.slice(0, FAILED_OUTPUT_MAX_CHARS)}...` : out}`;
733
+ }
734
+
735
+ function createCurrentFileHashes({ command, log = () => {} }) {
736
+ return async function currentFileHashes(memberName, files) {
737
+ const list = Array.isArray(files) ? files.filter((f) => typeof f === 'string' && f.length > 0) : [];
738
+ if (list.length === 0) return {};
739
+ const filesB64 = Buffer.from(JSON.stringify(list), 'utf-8').toString('base64');
740
+ let res;
741
+ try {
742
+ res = await command(`node -e "${CURRENT_FILE_HASHES_SCRIPT}" "${filesB64}"`, { member_name: memberName, silent: true, failSoft: true });
743
+ } catch (err) {
744
+ log(`[kb-work] could not re-hash ${list.length} file(s) on '${memberName}' for the in-sprint ping-pong guard (non-fatal): ${err && err.message ? err.message : String(err)}`);
745
+ return {};
746
+ }
747
+ // A member without a working `node` lands here on every call, which
748
+ // disables the guard -- so say so, every time.
749
+ if (!res || !res.ok) {
750
+ log(`[kb-work] WARN: '${CURRENT_FILE_HASHES_LABEL}' failed on '${memberName}' -- the in-sprint ping-pong guard has no current hashes for ${list.length} file(s) and suppresses nothing${failedCommandDetail(res)}`);
751
+ return {};
752
+ }
753
+ let parsed;
754
+ try {
755
+ parsed = JSON.parse(String(res.output || '{}'));
756
+ } catch (err) {
757
+ log(`[kb-work] WARN: '${CURRENT_FILE_HASHES_LABEL}' on '${memberName}' printed output that is not JSON (${err.message}) -- the in-sprint ping-pong guard has no current hashes for ${list.length} file(s) and suppresses nothing${failedCommandDetail(res)}`);
758
+ return {};
759
+ }
760
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
761
+ log(`[kb-work] WARN: '${CURRENT_FILE_HASHES_LABEL}' on '${memberName}' printed JSON that is not a file -> hash object -- the in-sprint ping-pong guard suppresses nothing${failedCommandDetail(res)}`);
762
+ return {};
763
+ }
764
+ return parsed;
765
+ };
766
+ }
767
+ export { createCurrentFileHashes };
768
+
555
769
  // ---------------------------------------------------------------------------
556
770
  // Canonical role-name constants for the Develop/Review loop
557
771
  // ---------------------------------------------------------------------------
@@ -666,7 +880,10 @@ export const meta = { name: 'fleet-sprint-runner' };
666
880
  // would pass them literally into argv. Double quotes are stripped as real
667
881
  // quoting by PowerShell and cmd.exe alike, and are a harmless no-op under POSIX
668
882
  // shells.
669
- const NOT_DONE_STATUSES = '"open,in_progress,blocked,deferred"';
883
+ const NOT_DONE_STATUS_LIST = ['open', 'in_progress', 'blocked', 'deferred'];
884
+ const NOT_DONE_STATUSES = `"${NOT_DONE_STATUS_LIST.join(',')}"`;
885
+ // The same statuses as a Set, for filtering already-fetched bead records.
886
+ const NOT_DONE_STATUS_SET = new Set(NOT_DONE_STATUS_LIST);
670
887
 
671
888
  // ---------------------------------------------------------------------------
672
889
  // Git sync brackets: G-pull / G-push -- MOVED to ./member-sync.mjs
@@ -878,6 +1095,10 @@ async function runSprintCycle(context) {
878
1095
  // controller is only wired when BOTH are present, so those callers keep the
879
1096
  // pre-feature behaviour (a usage-limit error falls through the retry ladder).
880
1097
  const { requestPause, requestResume } = context;
1098
+ // The engine's run stop signal (absent for direct/legacy callers): lets
1099
+ // the decision wait see an operator stop while it holds the run parked
1100
+ // with nothing dispatched.
1101
+ const stopSignal = typeof context.stopSignal === 'function' ? context.stopSignal : undefined;
881
1102
 
882
1103
  // Validate BEFORE any agent()/command() dispatch: a rejected/malformed arg
883
1104
  // must result in zero fleet dispatches. This must happen early so the
@@ -1133,6 +1354,14 @@ async function runSprintCycle(context) {
1133
1354
  log,
1134
1355
  });
1135
1356
 
1357
+ // Every `bd dolt pull`/`bd dolt push` DoltSync issues is built per member
1358
+ // OS/shell (a Windows member runs bd with a bounded GOMAXPROCS). Install
1359
+ // the sprint's cached member_detail-backed resolver once, here; with no
1360
+ // fleet client the resolver is cleared and members are treated as POSIX.
1361
+ setMemberTargetResolver(sprintState.fleetApi
1362
+ ? (member) => resolveMemberTarget({ fleetApi: sprintState.fleetApi, member, log })
1363
+ : null);
1364
+
1136
1365
  // Guards every resume re-dispatch below against spawning a second
1137
1366
  // concurrent session on top of a prior one that is presumed dead/timed out
1138
1367
  // but may still be alive (see createMemberSessionGuard's doc comment).
@@ -1330,6 +1559,15 @@ async function runSprintCycle(context) {
1330
1559
 
1331
1560
  let cycle = 1;
1332
1561
  const MAX_CYCLES = validated.maxCycles;
1562
+ // The cycle loop's ceiling. A decision answered at Cycle Evaluation of the
1563
+ // last allowed cycle (a "late" answer) raises it by one cycle -- when the
1564
+ // run's budget allows -- so the released bead is still dispatched; see
1565
+ // handleLateDecisionAnswers(). Starts at MAX_CYCLES.
1566
+ let effectiveMaxCycles = MAX_CYCLES;
1567
+ // Answers applied at the last cycle's evaluation, not yet resolved into an
1568
+ // extra cycle or a report; and the beads reported released too late.
1569
+ let lateDecisionAnswers = [];
1570
+ const lateUnworkedReports = [];
1333
1571
 
1334
1572
  // Per-(role, cycle) session registry: a role's session is resumed across
1335
1573
  // ROUNDS within one cycle via an explicit session id, but NEVER across
@@ -1513,10 +1751,41 @@ async function runSprintCycle(context) {
1513
1751
  // maintainer is mid-dispatch (dispatchStarted/dispatchEnded below).
1514
1752
  // gitSync is bound further down; the G-pull closure resolves it lazily,
1515
1753
  // and no KB write can be applied before the first dispatch completes.
1754
+ // THIS REVIEW ROUND's changed-file set for
1755
+ // kbWork.demotionCandidates(), deliberately separate from kbInjection's
1756
+ // diffFiles below (the cumulative origin/base...branch diff, left
1757
+ // unchanged for its existing reviewer/harvester hint-context callers).
1758
+ // gitSync.pullGitBefore is bound lazily here exactly like gPull/gPush
1759
+ // below -- gitSync is defined further down in this function, and
1760
+ // roundChangedFiles is not CALLED until long after that assignment runs.
1761
+ const roundChangedFiles = context.roundChangedFiles ?? createRoundChangedFiles({
1762
+ command,
1763
+ pullGitBefore: (memberName) => gitSync.pullGitBefore(memberName),
1764
+ baseBranch: validated.baseBranch,
1765
+ log,
1766
+ });
1767
+ // THE SPRINT's CUMULATIVE changed-file set, for the FINAL review's
1768
+ // demotion-candidate read -- final review has no round, so it scopes to
1769
+ // the whole baseBranch...branch diff. Same lazy gitSync binding as its
1770
+ // per-round sibling above.
1771
+ const sprintChangedFiles = context.sprintChangedFiles ?? createSprintChangedFiles({
1772
+ command,
1773
+ pullGitBefore: (memberName) => gitSync.pullGitBefore(memberName),
1774
+ baseBranch: validated.baseBranch,
1775
+ branch: validated.branch,
1776
+ log,
1777
+ });
1778
+ const currentFileHashes = context.currentFileHashes ?? createCurrentFileHashes({ command, log });
1516
1779
  const kbWork = context.kbWork ?? createKbWorkClient({
1517
1780
  memberCall: kbMemberCall,
1518
1781
  maintainers: () => context.kbMaintainers,
1519
1782
  gPull: (maintainerName, options) => gitSync.pullGitBefore(maintainerName, options),
1783
+ roundChangedFiles,
1784
+ sprintChangedFiles,
1785
+ // D6 in-sprint ping-pong guard (promotionCandidates): re-hash a
1786
+ // candidate's cited files on demand to tell "basis unchanged since
1787
+ // the demotion" from "basis moved on" -- see createCurrentFileHashes.
1788
+ currentFileHashes,
1520
1789
  // The review-round bible commit (kbWork.commitRound): G-push, the
1521
1790
  // retry's rebase --abort, and the base branch/commit recorded as the
1522
1791
  // bible's provenance -- all on the maintainer, all bracketed.
@@ -1536,6 +1805,8 @@ async function runSprintCycle(context) {
1536
1805
  // Promotion candidates are limited to entries created since the
1537
1806
  // sprint started -- the sprint state's one start stamp.
1538
1807
  sprintStartMs: () => sprintState.startedAtMs,
1808
+ // Reviewer demotion loop switch ('on' default, 'off'): sprint arg kb_demotion_loop.
1809
+ demotionLoop: validated.kbDemotionLoop,
1539
1810
  log,
1540
1811
  });
1541
1812
  // Stored on the sprint context (like kbMaintainers) so the terminal-abort
@@ -1835,6 +2106,50 @@ async function runSprintCycle(context) {
1835
2106
  })
1836
2107
  : undefined;
1837
2108
 
2109
+ // NEEDS-DECISION wait (./decision-wait.mjs): when the run would stall
2110
+ // with a decision still pending, it parks once through the same
2111
+ // cooperative pause instead of throwing StalledSprintError (members stay
2112
+ // reserved and idle) and resumes once an answer is available. Only wired with the engine's pause/resume
2113
+ // primitives (absent for direct/legacy runSprintCycle() callers, which
2114
+ // keep the stall). recordDecisionAnswer is exposed on sprintState for an
2115
+ // in-process answer route.
2116
+ const decisionWait = (typeof requestPause === 'function' && typeof requestResume === 'function')
2117
+ ? createDecisionWait({
2118
+ sprintState,
2119
+ requestPause,
2120
+ requestResume,
2121
+ command,
2122
+ member: backlogMember,
2123
+ pullBeads: (m) => gitSync.syncBeadsBefore(m),
2124
+ pushBeads: (m) => gitSync.syncBeadsAfter(m, { pushBeads: true }),
2125
+ publishState: typeof publishState === 'function' ? publishState : undefined,
2126
+ log,
2127
+ ...(stopSignal ? { stopSignal } : {}),
2128
+ })
2129
+ : null;
2130
+ if (decisionWait) sprintState.recordDecisionAnswer = decisionWait.recordDecisionAnswer;
2131
+ // Operator notification (message + email, once per decision, never fatal).
2132
+ // Targets are resolved ONCE here at launch (default message target: the
2133
+ // operator's orchestrating session); a channel with no target is logged
2134
+ // once now, not once per decision.
2135
+ // The message target is also checked once here (a read-only probe):
2136
+ // when no channel-capable session holds it, one launch line names the
2137
+ // remedy and later decisions log one short line each.
2138
+ const notifyFleetApi = (args && typeof args.callTool === 'function') ? sprintScopedFleetApi({ callTool: args.callTool, log }) : null;
2139
+ const notifyConfig = await prepareDecisionNotify({ config: validated.decisionNotify, fleetApi: notifyFleetApi, log });
2140
+ sprintState.notifyDecision = async (record) => {
2141
+ // Publish first (the banner shows the decision at once), notify, then
2142
+ // publish again so the per-channel outcome shows.
2143
+ if (decisionWait) decisionWait.publish();
2144
+ await notifyDecision({
2145
+ decision: record,
2146
+ config: notifyConfig,
2147
+ fleetApi: notifyFleetApi,
2148
+ log,
2149
+ });
2150
+ if (decisionWait) decisionWait.publish();
2151
+ };
2152
+
1838
2153
  // --- dispatchRole engine context (apra-fleet-3swo.5.3) -------------------
1839
2154
  // Every runner-side primitive fleet-sprint/dispatch-role.mjs needs to run
1840
2155
  // a role's ladder out of role-policies.mjs's data table. INJECTED, never
@@ -2012,12 +2327,17 @@ async function runSprintCycle(context) {
2012
2327
  return ready.filter((b) => !parentIds.has(b.id));
2013
2328
  }
2014
2329
 
2015
- // How many times a given bead has already been auto-reclaimed this sprint
2016
- // (see reclaimStaleInProgress below). Keyed by bead id, lives for the
2017
- // whole sprint process so the bounce cap accumulates across cycles, not
2018
- // just within one call.
2019
- const staleInProgressReclaimCounts = new Map();
2020
- const STALE_IN_PROGRESS_RECLAIM_LIMIT = 2;
2330
+ // Bead ids the PRE-LAUNCH rule (reclaimStaleInProgress below) must never
2331
+ // touch again this run: every id it has already reclaimed, and every id a
2332
+ // doer of this run was dispatched on (added after each Develop round).
2333
+ // From then on any claim of that bead is this run's own (or a later
2334
+ // actor's), and only the in-run tracker (reclaimInRunOrphanedClaims) may
2335
+ // re-lane it, under its own rules (claimed-elsewhere, completed work, its
2336
+ // re-dispatch cap). started_at cannot draw that line: bd keeps a bead's
2337
+ // FIRST claim stamp on every re-claim, so this run's own claim of a bead
2338
+ // that was stale at launch still reads as predating the launch. Also
2339
+ // bounds the pre-launch rule to one reclaim per bead per sprint.
2340
+ const preLaunchSettledIds = new Set();
2021
2341
  // Read once, on the FIRST call to reclaimStaleInProgress (the pre-sprint
2022
2342
  // one), from the sprint state's start stamp (createSprintState) -- the
2023
2343
  // same instant the KB promotion-candidate window starts at, so the sprint
@@ -2028,77 +2348,91 @@ async function runSprintCycle(context) {
2028
2348
 
2029
2349
  /**
2030
2350
  * Reclaims 'in_progress' beads that are safe to redispatch to 'open':
2031
- * no unmet `blocks` dependencies (nothing left to wait on) AND claimed
2032
- * BEFORE this sprint incarnation's own launch time -- so this very
2033
- * sprint's own in-flight work is never touched here (a claim a failed doer
2034
- * of THIS run left behind is reclaimed separately, by
2035
- * reclaimInRunOrphanedClaims). The pre-launch rule is NOT safe against
2036
- * concurrency on its own: a claim an EARLIER-launched sprint that is
2037
- * still running holds also predates this launch and would be reclaimed;
2038
- * only the supervisor's issue-scope overlap guard (which refuses to launch
2039
- * two sprints over overlapping scope) keeps such a claim out of this
2040
- * sprint's scope. A bead with no
2041
- * parseable `started_at` is treated as predating this sprint (`bd
2042
- * update --claim` always stamps `started_at`, so a bead claimed by
2043
- * THIS sprint always has one -- an unparseable/absent value can only
2044
- * mean orphaned state from something else).
2351
+ * no unmet `blocks` dependencies (nothing left to wait on), claimed
2352
+ * BEFORE this sprint incarnation's own launch time, and not in
2353
+ * preLaunchSettledIds (never reclaimed or dispatched by this run). So this
2354
+ * sprint's own work is never touched here -- a claim a failed doer of
2355
+ * THIS run left behind is reclaimed separately, by
2356
+ * reclaimInRunOrphanedClaims -- and each bead is reclaimed by this rule
2357
+ * at most once per sprint. A bead with no parseable `started_at` is
2358
+ * treated as predating this sprint (`bd update --claim` stamps
2359
+ * `started_at` on a first claim, so an absent value can only mean
2360
+ * orphaned state from something else, e.g. a bare `--status
2361
+ * in_progress`).
2362
+ *
2363
+ * THE WRITE. `bd update <id> --status open --assignee= --force
2364
+ * --if-status in_progress`, the same write reclaimInRunOrphanedClaims
2365
+ * uses: the stale assignee is cleared because a different actor's `bd
2366
+ * update --claim` refuses a bead another actor still holds (`--force` is
2367
+ * bd's documented override for that abandoned-claim case), and
2368
+ * `--if-status in_progress` makes bd refuse the write if the bead
2369
+ * changed since it was read (logged, left as is).
2370
+ *
2371
+ * `freshRead`: set when `notDoneBeads` came from the cached snapshot,
2372
+ * which can lag a cycle behind agent-made closes. The candidates are then
2373
+ * re-read with `bd show`, and only those a fresh read still shows
2374
+ * in_progress under the same assignee are written. Callers passing a
2375
+ * fresh `bd list` need no second read.
2045
2376
  *
2046
- * Bounded per bead via staleInProgressReclaimCounts: a bead that keeps
2047
- * landing back in 'in_progress' (a doer repeatedly failing on it
2048
- * specifically, not a one-off orphaned claim) stops being silently
2049
- * reclaimed after STALE_IN_PROGRESS_RECLAIM_LIMIT attempts and is
2050
- * surfaced as needing human investigation instead -- the same
2051
- * bounce-cap precedent already used for the verify-route gap counter
2052
- * (VERIFY_GAP_LIMIT) elsewhere in this file, applied to this failure
2053
- * mode.
2377
+ * Call sites: pre-sprint ONCE whether or not other work is ready (a stale
2378
+ * claim hides its whole `blocks` chain from `bd ready` even while
2379
+ * unrelated work is ready -- see the pre-sprint stale-claim check), and
2380
+ * per cycle only when the ready set is otherwise empty.
2054
2381
  *
2055
- * Originally this reclaim only ran ONCE, as a pre-sprint gate, and only
2056
- * when the pre-sprint ready set was empty -- a bead orphaned mid-sprint
2057
- * (a crashed doer, a killed dispatch, or -- as observed in practice --
2058
- * a prior aborted sprint incarnation whose claims were still in_progress
2059
- * on relaunch) was invisible to every later cycle, so the sprint just
2060
- * spun Plan-finds-nothing -> Deploy forever until the stall detector
2061
- * eventually gave up, burning cycles/cost for zero progress. This is
2062
- * now also called at the top of every cycle's readiness check (when the
2063
- * ready set is empty), so a PRE-LAUNCH orphaned claim self-heals on the
2064
- * very next cycle instead of silently persisting for the rest of the run.
2065
- * It never reclaims a claim made after the launch -- including one a
2066
- * crashed doer of THIS run left -- which is reclaimInRunOrphanedClaims'
2067
- * job.
2068
- * @param {{ notDoneBeads: object[], reasonTag: string }} opts
2069
- * @returns {Promise<{ reclaimedIds: string[], cappedIds: string[] }>}
2382
+ * KNOWN LIMIT -- this rule cannot tell an abandoned claim from a live one.
2383
+ * "Claimed before this launch" is all it knows. A bead's assignee is a bd
2384
+ * actor name, and the engine has no map from an actor to a live sprint
2385
+ * or a working human (member reservations are keyed by member, not by bd
2386
+ * actor), so no liveness gate is possible here. Specifically, it WILL
2387
+ * reopen and clear the assignee of: (a) a claim held by an
2388
+ * earlier-launched sprint that is still running, if that bead is inside
2389
+ * this sprint's scope -- only the supervisor's issue-scope overlap guard
2390
+ * prevents that, so two sprints launched directly from the CLI over
2391
+ * overlapping scope (bypassing the supervisor) can both work such a bead;
2392
+ * (b) a bead a human claimed before the launch and is still working.
2393
+ * Because the pre-sprint call is unconditional, this applies to every
2394
+ * launch, not only one with nothing ready. Each such bead is reclaimed at
2395
+ * most once per sprint (preLaunchSettledIds) and every reclaim is logged
2396
+ * with the bead id.
2397
+ *
2398
+ * Each reclaim log names the downstream beads (its `blocks` dependents)
2399
+ * the reclaim puts back on the path to ready.
2400
+ * @param {{ notDoneBeads: object[], reasonTag: string, freshRead?: boolean }} opts
2401
+ * @returns {Promise<{ reclaimedIds: string[] }>}
2070
2402
  */
2071
- async function reclaimStaleInProgress({ notDoneBeads, reasonTag }) {
2403
+ async function reclaimStaleInProgress({ notDoneBeads, reasonTag, freshRead = false }) {
2072
2404
  if (sprintLaunchTime === null) sprintLaunchTime = sprintState.startedAtMs;
2073
2405
  const notDoneIds = new Set(notDoneBeads.map((b) => b.id));
2074
- const unmetBlockers = (bead) => (bead.dependencies || [])
2075
- .filter((d) => d.type === 'blocks' && notDoneIds.has(d.depends_on_id))
2076
- .map((d) => d.depends_on_id);
2077
-
2078
- const candidates = notDoneBeads.filter((b) => {
2079
- if (b.status !== 'in_progress') return false;
2080
- if (unmetBlockers(b).length > 0) return false;
2081
- const startedAtMs = b.started_at ? Date.parse(b.started_at) : NaN;
2082
- return Number.isNaN(startedAtMs) || startedAtMs < sprintLaunchTime;
2083
- });
2406
+ let candidates = notDoneBeads.filter((b) => isPreLaunchReclaimCandidate(b, {
2407
+ notDoneIds, sprintLaunchTime, settledIds: preLaunchSettledIds,
2408
+ }));
2084
2409
 
2085
2410
  const reclaimedIds = [];
2086
- const cappedIds = [];
2411
+ if (candidates.length === 0) return { reclaimedIds };
2412
+
2413
+ if (freshRead) {
2414
+ const ids = candidates.map((b) => b.id);
2415
+ const showLabel = `bd show ${ids.join(' ')} --json`;
2416
+ const fresh = parseBdJson(await command(showLabel, { member_name: backlogMember, silent: true }), showLabel);
2417
+ const { confirmed, rejected } = confirmPreLaunchCandidates(candidates, fresh);
2418
+ for (const r of rejected) {
2419
+ log(`${reasonTag}: ${r.id} looked stuck 'in_progress' with a pre-launch claim in the cached snapshot, but ${r.reason} -- not reclaiming it.`);
2420
+ }
2421
+ candidates = confirmed;
2422
+ }
2423
+
2087
2424
  for (const bead of candidates) {
2088
- const priorAttempts = staleInProgressReclaimCounts.get(bead.id) ?? 0;
2089
- if (priorAttempts >= STALE_IN_PROGRESS_RECLAIM_LIMIT) {
2090
- cappedIds.push(bead.id);
2425
+ try {
2426
+ await command(`bd update ${bead.id} --status open --assignee= --force --if-status in_progress`, { member_name: backlogMember, silent: true });
2427
+ } catch (err) {
2428
+ log(`${reasonTag}: reclaiming ${bead.id} was refused (${err.message}) -- leaving it as it is.`);
2091
2429
  continue;
2092
2430
  }
2093
- staleInProgressReclaimCounts.set(bead.id, priorAttempts + 1);
2094
- log(`${reasonTag}: ${bead.id} is stuck 'in_progress' (started_at=${bead.started_at || 'n/a'}) with no unmet blockers and predates this sprint's launch -- reclaiming to 'open' so the sprint can dispatch it (attempt ${priorAttempts + 1}/${STALE_IN_PROGRESS_RECLAIM_LIMIT}).`);
2095
- await command(`bd update ${bead.id} --status open`, { member_name: backlogMember, silent: true });
2431
+ preLaunchSettledIds.add(bead.id);
2432
+ log(`${reasonTag}: ${bead.id} is stuck 'in_progress' (started_at=${bead.started_at || 'n/a'}, assignee=${bead.assignee || 'none'}) with no unmet blockers and predates this sprint's launch -- ${freshRead ? 'confirmed by a fresh read and ' : ''}reclaimed to 'open' with its assignee cleared so the sprint can dispatch it (once per sprint; any later claim of it is this run's own).${downstreamSuffix(notDoneBeads, bead.id)}`);
2096
2433
  reclaimedIds.push(bead.id);
2097
2434
  }
2098
- if (cappedIds.length > 0) {
2099
- log(`${reasonTag}: ${cappedIds.length} bead(s) hit the stale-in_progress reclaim bounce cap (limit ${STALE_IN_PROGRESS_RECLAIM_LIMIT}) and were left 'in_progress' rather than reclaimed again -- needs human investigation: ${cappedIds.join(', ')}.`);
2100
- }
2101
- return { reclaimedIds, cappedIds };
2435
+ return { reclaimedIds };
2102
2436
  }
2103
2437
 
2104
2438
  /**
@@ -2154,7 +2488,8 @@ async function runSprintCycle(context) {
2154
2488
  */
2155
2489
  async function reclaimInRunOrphanedClaims({ reasonTag }) {
2156
2490
  if (!orphanClaims.hasFailed()) return [];
2157
- const { candidates, newlyCappedIds } = orphanClaims.candidates(await fetchAllBeadsShared());
2491
+ const snapshotBeads = await fetchAllBeadsShared();
2492
+ const { candidates, newlyCappedIds } = orphanClaims.candidates(snapshotBeads);
2158
2493
  if (newlyCappedIds.length > 0) {
2159
2494
  log(`${reasonTag}: ${newlyCappedIds.length} bead(s) a failed doer of this run left 'in_progress' already hit the re-dispatch cap (limit ${orphanClaims.limit}) and are left as they are -- needs human investigation: ${newlyCappedIds.join(', ')}.`);
2160
2495
  }
@@ -2194,12 +2529,44 @@ async function runSprintCycle(context) {
2194
2529
  continue;
2195
2530
  }
2196
2531
  const attempt = orphanClaims.markReclaimed(c.id);
2197
- log(`${reasonTag}: ${c.id} was left 'in_progress' by a failed doer streak of this run (member '${c.doerMember || 'unknown'}') -- confirmed by a fresh read and reclaimed to 'open' so it is dispatched again this sprint (attempt ${attempt}/${orphanClaims.limit}).`);
2532
+ log(`${reasonTag}: ${c.id} was left 'in_progress' by a failed doer streak of this run (member '${c.doerMember || 'unknown'}') -- confirmed by a fresh read and reclaimed to 'open' so it is dispatched again this sprint (attempt ${attempt}/${orphanClaims.limit}).${downstreamSuffix(snapshotBeads, c.id)}`);
2198
2533
  reclaimedIds.push(c.id);
2199
2534
  }
2200
2535
  return reclaimedIds;
2201
2536
  }
2202
2537
 
2538
+ /**
2539
+ * The review diff base SHA for `member` (see resolveReviewMergeBase in
2540
+ * git-topology.mjs). Shared by the per-round reviewer and Final Review.
2541
+ * @param {string} member
2542
+ * @returns {Promise<string>}
2543
+ */
2544
+ function reviewMergeBaseFor(member) {
2545
+ return resolveReviewMergeBase({
2546
+ command, member, baseBranch: validated.baseBranch, branch: validated.branch,
2547
+ log, onAuthFailure, resolveMemberProvider: resolveMemberVcsProvider,
2548
+ });
2549
+ }
2550
+
2551
+ /**
2552
+ * The degraded verdict for a review round whose diff base could not be
2553
+ * computed: the reviewer policy's own synthesized-verdict degrade (same
2554
+ * shape, note template, dispatchFailed marker and clear-round-session
2555
+ * step), applied without dispatching the reviewer.
2556
+ * @param {Error} err
2557
+ */
2558
+ function degradedReviewForReviewBase(err) {
2559
+ const reviewerPolicy = policyFor('reviewer');
2560
+ const d = reviewerPolicy.degrade;
2561
+ roundSessions.clear(reviewerPolicy.ladder);
2562
+ log(
2563
+ `Reviewer: review diff base failed, degrading (${d.kind}) -- the reviewer was NOT dispatched this round ` +
2564
+ `and no fallback to the local '${validated.baseBranch}' branch was used: ${err.message}`
2565
+ );
2566
+ const note = d.noteTemplates.dispatch.replace(/\{(message|name)\}/g, (_, f) => (f === 'name' ? err.name : err.message));
2567
+ return { ...d.synthesized, [d.notesField]: note, ...(d.marker ? { [d.marker]: true } : {}) };
2568
+ }
2569
+
2203
2570
  /**
2204
2571
  * Dispatches one reviewer round and returns its schema-validated verdict.
2205
2572
  * Shared by the per-round Develop/Review dispatch and the Cycle Evaluation
@@ -2214,6 +2581,25 @@ async function runSprintCycle(context) {
2214
2581
  */
2215
2582
  async function dispatchReview({ beadIds, acceptanceCriteriaJson }) {
2216
2583
  const reviewerPool = getMembersForRole(ROLE_REVIEWER);
2584
+ // The diff range the reviewer is told to use: the fork point of the
2585
+ // sprint branch from a freshly fetched origin/<base>, computed on the
2586
+ // reviewer's own member. Throws (fails the review loudly) rather than
2587
+ // ever falling back to the member's possibly stale local base branch.
2588
+ //
2589
+ // A GitSyncError here (fetch/merge-base failed after runGitStep's own
2590
+ // retry and auth self-heal) degrades the ROUND exactly like the
2591
+ // reviewer ladder's own read-side sync failure does: the reviewer is
2592
+ // NOT dispatched (never with a wrong range), the round is recorded as a
2593
+ // synthesized CHANGES_NEEDED marked dispatchFailed (counts toward the
2594
+ // stall budget, not a contract violation), and its session is not
2595
+ // resumed by the next round. Anything else still propagates.
2596
+ let mergeBaseSha;
2597
+ try {
2598
+ mergeBaseSha = await reviewMergeBaseFor(reviewerPool[0]);
2599
+ } catch (err) {
2600
+ if (!(err instanceof GitSyncError)) throw err;
2601
+ return degradedReviewForReviewBase(err);
2602
+ }
2217
2603
  // apra-fleet-0ef: fetch the INFERRED entries this reviewer may promote
2218
2604
  // and hand them to it in the prompt. The reviewer has no MCP kb_* tools
2219
2605
  // of its own, so without this it can never name an entry id and
@@ -2226,6 +2612,16 @@ async function runSprintCycle(context) {
2226
2612
  if (kbCandidates.length > 0) {
2227
2613
  log(`[kb-work] offering ${kbCandidates.length} INFERRED entr(ies) to the reviewer for promotion.`);
2228
2614
  }
2615
+ // The CONFIRMED entries this reviewer may demote
2616
+ // back to INFERRED, scoped to the files THIS round's diff actually
2617
+ // touched (see createKbWorkClient's roundChangedFiles wiring above).
2618
+ // Best-effort exactly like promotionCandidates: a cold or unreachable
2619
+ // KB, or a round diff that could not be computed, must not fail the
2620
+ // review.
2621
+ const kbDemoteCandidates = await kbWork.demotionCandidates(reviewerPool[0], { scope: 'round' });
2622
+ if (kbDemoteCandidates.length > 0) {
2623
+ log(`[kb-work] offering ${kbDemoteCandidates.length} CONFIRMED entr(ies) to the reviewer for demotion.`);
2624
+ }
2229
2625
  // What the KB knows about the beads UNDER REVIEW, not just whatever the
2230
2626
  // sprint-start prime happened to surface. Falls back to the primed set
2231
2627
  // when the query returns nothing (a KB with no matching rows yet).
@@ -2270,8 +2666,10 @@ async function runSprintCycle(context) {
2270
2666
  acceptanceCriteriaJson,
2271
2667
  baseBranch: validated.baseBranch,
2272
2668
  branch: validated.branch,
2669
+ mergeBaseSha,
2273
2670
  goal: validated.goal,
2274
2671
  kbCandidates,
2672
+ kbDemoteCandidates,
2275
2673
  kbBlock: reviewerKbBlock,
2276
2674
  }),
2277
2675
  // Restate the review scope: a resumed dispatch replaces the
@@ -2285,7 +2683,7 @@ async function runSprintCycle(context) {
2285
2683
  + (Array.isArray(beadIds) && beadIds.length > 0
2286
2684
  ? `bead id(s) under review ${beadIds.join(', ')} `
2287
2685
  : `the entire sprint scope (no individual bead ids -- you are judging whether the sprint as a whole is complete) `)
2288
- + `on branch ${validated.branch} against base ${validated.baseBranch}. ` +
2686
+ + `on branch ${validated.branch}, diff range ${mergeBaseSha}..${validated.branch} (use exactly this range for git diff and git log). ` +
2289
2687
  'Finish evaluating the remaining acceptance criteria and return your final verdict now.',
2290
2688
  roleLabel: 'Reviewer',
2291
2689
  resumeLabel: `Review (resume, max_turns=${TURN_BASES.BASE_REVIEWER_MAX_TURNS * 2})`,
@@ -2298,8 +2696,10 @@ async function runSprintCycle(context) {
2298
2696
  // on the first round of any cycle (roundSessions never resumes
2299
2697
  // across cycles) and cleared on a failed round by the policy's
2300
2698
  // 'clear-round-session' degrade step. The max_turns-exhaustion
2301
- // resume overrides this to `resume: true`, which is an in-dispatch
2302
- // continuation, not a cross-round one.
2699
+ // resume overrides this with the exhausted dispatch's OWN session
2700
+ // id (`resume: "<sessionId>"`, never `resume: true`, which the
2701
+ // server resolves to the member's last session, whichever role ran
2702
+ // it) -- an in-dispatch continuation, not a cross-round one.
2303
2703
  resumeArg: roundSessions.resumeArgFor('reviewer', cycle),
2304
2704
  onSessionId: (id, meta) => roundSessions.record('reviewer', cycle, id, meta),
2305
2705
  onResultRejected: (reason) => new ReviewerContractViolationError(
@@ -2585,6 +2985,31 @@ async function runSprintCycle(context) {
2585
2985
  log(`Pre-sprint validation: no ready leaf beads, but ${preSprintVerifyIds.length} bead(s) are implementation-complete and routed to verify: ${preSprintVerifyIds.join(', ')}. Proceeding as a verify-only sprint.`);
2586
2986
  }
2587
2987
 
2988
+ // GitHub #715: pre-sprint stale-claim check, run ONCE whether or not other
2989
+ // work is ready. A bead left in_progress by an earlier run is invisible to
2990
+ // `bd ready`, and so is every bead blocked on it -- unrelated ready work
2991
+ // must not hide that whole chain for the entire sprint. The empty-ready
2992
+ // case runs the same reclaim inside the refusal block below (from a fresh
2993
+ // `bd list` it needs there anyway), so this covers every other case.
2994
+ // Pre-filters on the shared snapshot readyLeafBeads() just cached -- no
2995
+ // bd call at all unless a candidate exists -- then confirms each
2996
+ // candidate with a fresh `bd show` before writing (freshRead), because
2997
+ // the snapshot alone never authorizes a write. Same pre-launch rule and
2998
+ // concurrency caveat as reclaimStaleInProgress' doc comment.
2999
+ if (initialBeads.length > 0 || preSprintVerifyIds.length > 0) {
3000
+ const notDoneFromSnapshot = (await bdListScoped(''))
3001
+ .filter((b) => NOT_DONE_STATUS_SET.has(b.status))
3002
+ .filter((b) => !validated.assignee || b.assignee === validated.assignee);
3003
+ const { reclaimedIds: preSprintStaleReclaimedIds } = await reclaimStaleInProgress({
3004
+ notDoneBeads: notDoneFromSnapshot,
3005
+ reasonTag: 'Pre-sprint self-heal',
3006
+ freshRead: true,
3007
+ });
3008
+ if (preSprintStaleReclaimedIds.length > 0) {
3009
+ initialBeads = await readyLeafBeads();
3010
+ }
3011
+ }
3012
+
2588
3013
  if (initialBeads.length === 0 && preSprintVerifyIds.length === 0) {
2589
3014
  // An empty `--ready` set is not by itself "nothing left to do": real
2590
3015
  // unblocked work can be deadlocked on a bead stuck in a stale
@@ -2795,16 +3220,56 @@ async function runSprintCycle(context) {
2795
3220
  // above goal priority, so an excluded bead never holds the sprint open.
2796
3221
  // Pre-sprint validation keeps the unfiltered readyLeafBeads(): its
2797
3222
  // deadlock diagnosis is about the graph, not about goal membership.
3223
+ //
3224
+ // Set-aside v2 (all in-memory over the same scope read, no extra bd call):
3225
+ // - a bead that WAITS after a BLOCKED report (sprintState.waitingIds)
3226
+ // is held while any prerequisite of it is still open;
3227
+ // - lane order is a prerequisite: a laned bead whose lower-order
3228
+ // lane-mate is open and not itself dispatchable this round is held
3229
+ // (holdBackByLaneOrder). Set-aside and publish-blocked beads stay in
3230
+ // the returned list (phases/develop.mjs excludes them and the
3231
+ // start-of-round check reads them) but never count as "ahead" of a
3232
+ // lane-mate.
3233
+ // A hold line is logged whenever it changes.
2798
3234
  const loggedBelowGoalExclusions = new Set();
3235
+ let lastDispatchHoldLog = '';
2799
3236
  async function dispatchableReadyLeafBeads() {
2800
3237
  const [ready, scopeAll] = await Promise.all([readyLeafBeads(), bdListScoped('')]);
3238
+ const setAsideMap = sprintState.doctorBlockedIds instanceof Map ? sprintState.doctorBlockedIds : new Map();
3239
+ const waitingMap = sprintState.waitingIds instanceof Map ? sprintState.waitingIds : new Map();
3240
+ const permissionBlocked = sprintState.permissionScopeBlockedBeads instanceof Map ? sprintState.permissionScopeBlockedBeads : new Map();
3241
+ const holdLines = [];
2801
3242
  const { dispatchable, excluded } = partitionReadyByGoal(ready, scopeAll, validated.goal, { workedOnIds: workedOnBeadIds });
2802
3243
  const fresh = excluded.filter((e) => !loggedBelowGoalExclusions.has(e.id));
2803
3244
  if (fresh.length > 0) {
2804
3245
  for (const e of fresh) loggedBelowGoalExclusions.add(e.id);
2805
3246
  log(formatBelowGoalExclusionLog(fresh, validated.goal));
2806
3247
  }
2807
- return dispatchable;
3248
+ let candidates = dispatchable;
3249
+ if (waitingMap.size > 0) {
3250
+ const stillWaiting = [];
3251
+ candidates = dispatchable.filter((b) => {
3252
+ if (!waitingMap.has(b.id)) return true;
3253
+ const on = unmetPrerequisites(b, { scopeBeads: scopeAll }).inScope;
3254
+ if (on.length === 0) return true;
3255
+ stillWaiting.push(`${b.id} waiting on ${on.join(', ')}`);
3256
+ return false;
3257
+ });
3258
+ if (stillWaiting.length > 0) holdLines.push(`WAITING ${stillWaiting.join('; ')} (reported BLOCKED while a prerequisite was open)`);
3259
+ }
3260
+ const isAside = (b) => setAsideMap.has(b.id) || permissionBlocked.has(b.id);
3261
+ const { dispatchable: laneOk, held } = holdBackByLaneOrder(candidates.filter((b) => !isAside(b)), scopeAll);
3262
+ if (held.length > 0) {
3263
+ holdLines.push(`HELD by lane order ${held.map((h) => `${h.id} (after ${h.on.join(', ')})`).join('; ')} -- ` +
3264
+ 'a lower-order lane-mate is still open and not dispatchable this round');
3265
+ }
3266
+ if (holdLines.length > 0) {
3267
+ const line = `Develop dispatch: ${holdLines.join('. ')}.`;
3268
+ if (line !== lastDispatchHoldLog) { lastDispatchHoldLog = line; log(line); }
3269
+ }
3270
+ if (held.length === 0) return candidates;
3271
+ const keep = new Set([...laneOk, ...candidates.filter(isAside)].map((b) => b.id));
3272
+ return candidates.filter((b) => keep.has(b.id));
2808
3273
  }
2809
3274
 
2810
3275
  // Stall detection: abort with a typed StalledSprintError after two
@@ -2846,6 +3311,171 @@ async function runSprintCycle(context) {
2846
3311
  // oscillating in and out of eligibility.
2847
3312
  const verifyEverIds = new Set();
2848
3313
 
3314
+ // Applies the decision answers recorded while the run was running
3315
+ // (decision-wait.mjs recordDecisionAnswer only queues them). The bd writes
3316
+ // and the beads push happen INSIDE one sync bracket, after its pull, under
3317
+ // the same dolt mutex as every other phase's pull/push -- never as a
3318
+ // free-standing push. No bracket and no command when nothing is queued.
3319
+ async function applyRecordedDecisionAnswers() {
3320
+ if (!decisionWait || !decisionWait.hasQueuedAnswers()) return [];
3321
+ const settleShell = await resolveSettleShell({ args, member: backlogMember, log, sprintState });
3322
+ return gitSync.withOpenSyncBracket(async () => {
3323
+ await gitSync.syncBeadsBefore(backlogMember, { fatal: true, settle: buildSettleCallback(backlogMember, { command, log, shell: settleShell }) });
3324
+ return decisionWait.applyRecordedAnswers();
3325
+ });
3326
+ }
3327
+
3328
+ // Whether the run's cost budget leaves room to dispatch more work.
3329
+ function budgetAllowsMoreWork() {
3330
+ try {
3331
+ return !(budget && typeof budget.remaining === 'function' && budget.remaining() <= 0);
3332
+ } catch { return true; }
3333
+ }
3334
+
3335
+ // Called at the end of a cycle. A decision answered at the evaluation of the
3336
+ // last allowed cycle grants exactly ONE extra cycle (per late answer batch)
3337
+ // when the budget allows, so the released bead is dispatched; otherwise the
3338
+ // unworked released bead and its decision are named in the log and in the
3339
+ // final verdict notes.
3340
+ function handleLateDecisionAnswers() {
3341
+ if (lateDecisionAnswers.length === 0) return;
3342
+ const batch = lateDecisionAnswers;
3343
+ lateDecisionAnswers = [];
3344
+ const named = batch.map((a) => `${(a.released && a.released.length ? a.released : [a.beadId]).join(', ')} (decision ${a.decisionId})`).join('; ');
3345
+ if (cycle >= effectiveMaxCycles && budgetAllowsMoreWork()) {
3346
+ effectiveMaxCycles = cycle + 1;
3347
+ log(`Cycle ${cycle}: decision answered at the last allowed cycle (maxCycles ${MAX_CYCLES}); granting one extra cycle (${cycle + 1}) so the released bead(s) are dispatched: ${named}.`);
3348
+ return;
3349
+ }
3350
+ const why = budgetAllowsMoreWork() ? `maxCycles ${MAX_CYCLES} reached` : 'the budget is exhausted';
3351
+ const line = `Decision answered too late to be worked: released bead(s) ${named} were not dispatched in this run (${why}). Re-run the sprint to work them.`;
3352
+ lateUnworkedReports.push(line);
3353
+ log(line);
3354
+ }
3355
+
3356
+ // Immediate set-aside stall (see ./set-aside.mjs). When nothing is ready
3357
+ // and every open in-scope bead at goal priority is set aside for this run
3358
+ // -- doer-BLOCKED (sprintState.doctorBlockedIds) or, while the deploy is
3359
+ // set aside (sprintState.deploySetAside), bound to Integration Test -- no
3360
+ // further round or cycle can make progress, so throw StalledSprintError
3361
+ // now instead of after STALL_CYCLE_LIMIT empty cycles. A no-op (no bd
3362
+ // call at all) unless something was set aside this run. `openAtGoal` and
3363
+ // `closedIds` may be passed in when the caller already read them (Cycle
3364
+ // Evaluation); otherwise they are read fresh here. `runbooks`
3365
+ // ({ hasDeploy, hasPlaybook }) may likewise be passed in; otherwise the
3366
+ // two runbooks are probed here when the deploy is not set aside.
3367
+ //
3368
+ // An open verify-routed parent (every child closed, the parent itself
3369
+ // waiting on Integration Test) is neither set aside nor waiting on a
3370
+ // set-aside deploy while Integration Test can still run (deploy.md and
3371
+ // integ-test-playbook.md present, deploy not set aside): Deploy and
3372
+ // Integration Test later in this cycle can still close it, so it counts
3373
+ // as open work that keeps the run going. Without the runbooks it cannot
3374
+ // be verified at all; the existing "cannot verify" exit owns that case.
3375
+ //
3376
+ // A pending operator decision turns the stall into a resumable pause
3377
+ // (./decision-wait.mjs): when the stall would be thrown and any decision
3378
+ // is still pending -- even if other set-aside reasons are mixed in, since
3379
+ // the answer may unblock work -- the run waits in state
3380
+ // 'paused-awaiting-decision' until at least one decision is answered,
3381
+ // releases the answered bead(s), resets the no-progress counter (an answer
3382
+ // is progress), and returns true so the caller re-reads the ready set.
3383
+ // Returns false when there is no stall; throws StalledSprintError when
3384
+ // there is one and no decision is pending. A decision whose decision bead
3385
+ // could not be filed does not count as pending here (nothing can answer
3386
+ // it in-run); the stall error names it with its full question.
3387
+ async function throwIfSetAsideStall({ where, cycle, openAtGoal = null, closedIds = null, runbooks = null, queueLateAnswers = false }) {
3388
+ const doctorBlockedIds = sprintState.doctorBlockedIds instanceof Map ? sprintState.doctorBlockedIds : new Map();
3389
+ const deploySetAside = sprintState.deploySetAside || null;
3390
+ if (doctorBlockedIds.size === 0 && !deploySetAside) return false;
3391
+ let open = openAtGoal;
3392
+ if (!open) {
3393
+ const [raw, parentIds] = await Promise.all([
3394
+ bdListScoped(`--status=${NOT_DONE_STATUSES} --priority-max=${goalMax} --json`),
3395
+ decomposedParentIds(),
3396
+ ]);
3397
+ open = partitionDeferredBeads(raw.filter((b) => !parentIds.has(b.id))).active;
3398
+ }
3399
+ let integBoundIds = [];
3400
+ let verifyBlockedIds = [];
3401
+ if (deploySetAside) {
3402
+ // Beads that can only close through Integration Test: verify-routed
3403
+ // parents (classified fresh -- a parent whose last child closed this
3404
+ // cycle is not in verifyEverIds yet) plus beads blocked only by them.
3405
+ invalidateAllBeadsCache();
3406
+ const allBeads = await fetchAllBeadsShared();
3407
+ const closed = closedIds || new Set(allBeads.filter((b) => b.status === 'closed').map((b) => b.id));
3408
+ const fresh = classifyVerifySet(allBeads, targetIssues).verifyIds;
3409
+ integBoundIds = [...new Set([...fresh, ...[...verifyEverIds].filter((id) => !closed.has(id))])];
3410
+ const knownClosed = [...closed].map((id) => ({ id, status: 'closed' }));
3411
+ verifyBlockedIds = findVerifyBlockedBeads(open, knownClosed, integBoundIds).map((b) => b.id);
3412
+ } else {
3413
+ const { hasDeploy, hasPlaybook } = runbooks || await (async () => {
3414
+ const deployMd = await probeFileExists('deploy.md', getMemberForRole('deployer'));
3415
+ const playbook = deployMd && await probeFileExists('integ-test-playbook.md', getMemberForRole('integ-test-runner'));
3416
+ return { hasDeploy: deployMd, hasPlaybook: playbook };
3417
+ })();
3418
+ if (hasDeploy && hasPlaybook) {
3419
+ // Open verify-routed parents become uncovered candidates:
3420
+ // with the deploy not set aside, evaluateSetAsideStall never
3421
+ // treats an integ-bound id as covered.
3422
+ invalidateAllBeadsCache();
3423
+ const allBeads = await fetchAllBeadsShared();
3424
+ const closed = closedIds || new Set(allBeads.filter((b) => b.status === 'closed').map((b) => b.id));
3425
+ integBoundIds = classifyVerifySet(allBeads, targetIssues).verifyIds.filter((id) => !closed.has(id));
3426
+ }
3427
+ }
3428
+ // Set-aside v2: an open bead that is not set aside but can only run
3429
+ // after a prerequisite that cannot close in this run (set aside,
3430
+ // itself stuck, or -- for a bead waiting after a BLOCKED report --
3431
+ // outside the scope) is stuck too. Computed only when some open bead
3432
+ // is otherwise uncovered, from the same in-memory scope read.
3433
+ let stuckIds = new Map();
3434
+ if (doctorBlockedIds.size > 0 && open.some((b) => !doctorBlockedIds.has(b.id))) {
3435
+ const scopeAll = await bdListScoped('');
3436
+ const allBeads = await fetchAllBeadsShared();
3437
+ stuckIds = stuckBehindSetAside({
3438
+ scopeBeads: scopeAll, allBeads, doctorBlockedIds,
3439
+ waitingIds: sprintState.waitingIds instanceof Map ? sprintState.waitingIds : new Map(),
3440
+ });
3441
+ }
3442
+ const stall = evaluateSetAsideStall({
3443
+ openIds: open.map((b) => b.id), integBoundIds, verifyBlockedIds, doctorBlockedIds, deploySetAside, stuckIds,
3444
+ });
3445
+ if (!stall) return false;
3446
+ if (decisionWait && decisionWait.hasPending()) {
3447
+ const answers = await decisionWait.awaitAnswer({ where, cycle });
3448
+ staleCycles = 0;
3449
+ // Answered at the end of the last allowed cycle: the loop would
3450
+ // end before the released bead is dispatched.
3451
+ // Only a wait at Cycle Evaluation is late: a wait at the start of a
3452
+ // Develop round dispatches the released bead in the same cycle.
3453
+ if (queueLateAnswers && cycle >= effectiveMaxCycles && Array.isArray(answers)) lateDecisionAnswers.push(...answers);
3454
+ return true;
3455
+ }
3456
+ const unfiledDecisions = decisionWait ? decisionWait.unfiled() : [];
3457
+ if (unfiledDecisions.length > 0) {
3458
+ // A pending decision whose decision bead could not be filed has
3459
+ // no answer path in this run, so it cannot hold a pause open.
3460
+ log(
3461
+ `Not pausing for ${unfiledDecisions.length} pending decision(s) whose decision bead could NOT be filed ` +
3462
+ `(no bd human respond path): ${unfiledDecisions.map((d) => `${d.beadId} -- ${d.question}`).join('; ')}`,
3463
+ );
3464
+ }
3465
+ const message = formatSetAsideStallMessage(stall, { where, scope: sprintFilter });
3466
+ log(message);
3467
+ throw new StalledSprintError(message, {
3468
+ staleCycles, closedCountHistory, highWaterClosedCount,
3469
+ thrashIds: thrashingBeadIds(),
3470
+ blockerIds: stall.blockerIds,
3471
+ blockerReasons: stall.blockerReasons,
3472
+ setAside: stall.entries,
3473
+ waited: collectWaitEntries(sprintState),
3474
+ cycle,
3475
+ details: { setAsideStall: true, where },
3476
+ });
3477
+ }
3478
+
2849
3479
  // apra-fleet-rp7a.1: every bead id ever seen DEFERRED at/above goal
2850
3480
  // priority during Cycle Evaluation, monotone for the same reason
2851
3481
  // verifyEverIds is. These beads are excluded from the completion/stall
@@ -2935,9 +3565,13 @@ async function runSprintCycle(context) {
2935
3565
  let lastReviewVerdict = null;
2936
3566
  let reviewedThisCycle = false;
2937
3567
 
2938
- while (cycle <= MAX_CYCLES) {
3568
+ while (cycle <= effectiveMaxCycles) {
2939
3569
  group(`Sprint Cycle ${cycle}`);
2940
3570
 
3571
+ // Answers recorded since the last bracket are applied (and pushed) now,
3572
+ // inside a sync bracket, before this cycle reads the ready set.
3573
+ await applyRecordedDecisionAnswers();
3574
+
2941
3575
  // Reset per-cycle review state -- a verdict is only ever trustworthy
2942
3576
  // for the cycle that actually produced it.
2943
3577
  lastReviewVerdict = null;
@@ -3133,6 +3767,25 @@ async function runSprintCycle(context) {
3133
3767
 
3134
3768
  if (currentReadyAll.length === 0) break;
3135
3769
 
3770
+ // Start-of-round set-aside check: when every still-ready bead is set
3771
+ // aside for this run (doer-BLOCKED or a dependent of one), stall now
3772
+ // if nothing else open can progress; otherwise skip the remaining
3773
+ // rounds (nothing here is dispatchable) and go on to Cycle
3774
+ // Evaluation. Mixed rounds are passed through unchanged --
3775
+ // ./phases/develop.mjs excludes the set-aside beads itself.
3776
+ const roundSetAside = sprintState.doctorBlockedIds instanceof Map ? sprintState.doctorBlockedIds : null;
3777
+ if (roundSetAside && currentReadyAll.every((b) => roundSetAside.has(b.id))) {
3778
+ // true: an operator answered a pending decision while the run
3779
+ // was paused -- re-read the ready set (the released bead is
3780
+ // in it again) and dispatch this round.
3781
+ if (await throwIfSetAsideStall({ where: `start of Develop C${cycle} R${devRounds + 1}`, cycle })) continue;
3782
+ log(
3783
+ `Develop C${cycle} R${devRounds + 1}: every still-ready bead is set aside for this run ` +
3784
+ `(${currentReadyAll.map((b) => b.id).join(', ')}) -- skipping the remaining develop/review rounds this cycle.`
3785
+ );
3786
+ break;
3787
+ }
3788
+
3136
3789
  // In-cycle SCOPED replan, taken on a bead's FIRST replan flag: when
3137
3790
  // a reviewer flags a still-ready bead via `replanIds` -- its
3138
3791
  // acceptance criteria are defective and cannot be satisfied by
@@ -3218,6 +3871,8 @@ async function runSprintCycle(context) {
3218
3871
  sprintState, gitSync, updateDashboard,
3219
3872
  kbPriming, kbWork, kbInjection, kbSprintContext,
3220
3873
  devRounds, currentReady, doerPool, perBeadFeedback,
3874
+ bdListScoped,
3875
+ fetchAllBeadsShared,
3221
3876
  claimBeadsBatched,
3222
3877
  verifyDoerStreakClosed,
3223
3878
  normalizeTierToken,
@@ -3227,6 +3882,11 @@ async function runSprintCycle(context) {
3227
3882
  for (const id of (o.beadIds || [])) workedOnBeadIds.add(id);
3228
3883
  }
3229
3884
  orphanClaims.recordOutcomes(streakOutcomes);
3885
+ // Dispatched by this run: the pre-launch rule never touches these
3886
+ // again (see preLaunchSettledIds).
3887
+ for (const o of streakOutcomes) {
3888
+ for (const id of (o.beadIds || [])) preLaunchSettledIds.add(id);
3889
+ }
3230
3890
 
3231
3891
  // --- Review: self-contained, schema-validated, orchestrator-applied ---
3232
3892
  // The phase body lives in ./phases/review.mjs
@@ -3243,7 +3903,7 @@ async function runSprintCycle(context) {
3243
3903
  ({ lastReviewVerdict, reviewedThisCycle, pendingRejectedNewTasks } = await runReviewPhase({
3244
3904
  phase, log, command,
3245
3905
  cycle, validated, targetIssues, backlogMember,
3246
- gitSync,
3906
+ gitSync, sprintState,
3247
3907
  replanIds, replannedThisCycle, perBeadFeedback, rejectedNewTasks,
3248
3908
  devRounds, streakOutcomes, readyTitleById,
3249
3909
  lastReviewVerdict, reviewedThisCycle, pendingRejectedNewTasks,
@@ -3294,7 +3954,13 @@ async function runSprintCycle(context) {
3294
3954
 
3295
3955
  let deployedThisCycle = false;
3296
3956
 
3297
- if (hasDeploy) {
3957
+ // Deploy set aside for the run (a Permissions pre-step failure in an
3958
+ // earlier cycle -- see DEPLOY SET-ASIDE in ./phases/deploy.mjs): never
3959
+ // dispatch the deployer again; this cycle's deploy counts as failed.
3960
+ const deploySetAside = sprintState.deploySetAside || null;
3961
+ if (hasDeploy && deploySetAside) {
3962
+ log(`Skipping Deploy Phase C${cycle}: ${formatDeploySetAsideNotes(deploySetAside)}. Skipping Integration Test phase.`);
3963
+ } else if (hasDeploy) {
3298
3964
  // The phase body lives in ./phases/deploy.mjs
3299
3965
  // (apra-fleet-3swo.6.5), which receives its state explicitly
3300
3966
  // instead of closing over runSprintCycle's locals. The
@@ -3308,12 +3974,13 @@ async function runSprintCycle(context) {
3308
3974
  phase, log, dispatchCtx,
3309
3975
  cycle, sprintSelfIdLine,
3310
3976
  getMemberForRole, ensureUnattendedAuto, ensureDeployPermissions,
3977
+ sprintState,
3311
3978
  deployFailures, deployedThisCycle,
3312
3979
  }));
3313
3980
  } else {
3314
3981
  log('Skipping Deploy Phase (no deploy.md found, or the probe itself failed -- see prior log line)');
3315
3982
  }
3316
- lastDeployFailure = latestDeployFailure({ hasDeploy, deployedThisCycle, cycle, deployFailures });
3983
+ lastDeployFailure = latestDeployFailure({ hasDeploy, deployedThisCycle, cycle, deployFailures, deploySetAside });
3317
3984
  if (!lastDeployFailure) deployBlockedCycles = 0;
3318
3985
 
3319
3986
  // apra-fleet-66u.2: declared here, OUTSIDE the `if (hasPlaybook &&
@@ -3463,6 +4130,14 @@ async function runSprintCycle(context) {
3463
4130
  staleCycles++;
3464
4131
  }
3465
4132
 
4133
+ // Immediate set-aside stall, checked BEFORE the STALL_CYCLE_LIMIT
4134
+ // stall and the deploy-blocked retry exit below, so neither can delay
4135
+ // it: everything left is set aside, so no later cycle can progress.
4136
+ await throwIfSetAsideStall({
4137
+ where: `Cycle ${cycle} evaluation`, cycle, openAtGoal, closedIds: closedIdsNow,
4138
+ runbooks: { hasDeploy, hasPlaybook }, queueLateAnswers: true,
4139
+ });
4140
+
3466
4141
  // apra-fleet-b4g.102.1: a cycle spent re-attempting a failed deploy
3467
4142
  // after the work itself was already satisfied is not a stall -- it is
3468
4143
  // bounded separately (DEPLOY_RETRY_CYCLE_LIMIT and maxCycles) by the
@@ -3479,10 +4154,18 @@ async function runSprintCycle(context) {
3479
4154
  // a "blocker" told an operator to go unblock something the
3480
4155
  // dispatcher was never going to offer in the first place. They are
3481
4156
  // reported separately, as skipped scope, by deferredStallSuffix.
3482
- const blockerIds = openAtGoal.map((b) => b.id);
3483
- const blockerSuffix = blockerIds.length > 0
3484
- ? ` Still open at/above goal priority ${goalMax}: [${blockerIds.join(', ')}].`
3485
- : ' No beads remain open at/above goal priority -- the stall is in closing out the sprint, not in the work itself.';
4157
+ // Beads set aside for this run (doer-BLOCKED and their dependents)
4158
+ // are named too, even below goal priority, unless already closed.
4159
+ const setAsideOpenIds = sprintState.doctorBlockedIds instanceof Map
4160
+ ? [...sprintState.doctorBlockedIds.keys()].filter((id) => !closedIdsNow.has(id))
4161
+ : [];
4162
+ const openAtGoalIds = openAtGoal.map((b) => b.id);
4163
+ const blockerIds = [...new Set([...openAtGoalIds, ...setAsideOpenIds])];
4164
+ const setAsideOnlyIds = setAsideOpenIds.filter((id) => !openAtGoalIds.includes(id));
4165
+ const blockerSuffix = (openAtGoalIds.length > 0
4166
+ ? ` Still open at/above goal priority ${goalMax}: [${openAtGoalIds.join(', ')}].`
4167
+ : ' No beads remain open at/above goal priority -- the stall is in closing out the sprint, not in the work itself.') +
4168
+ (setAsideOnlyIds.length > 0 ? ` Also set aside for this run (doer-BLOCKED or a dependent of one): [${setAsideOnlyIds.join(', ')}].` : '');
3486
4169
  const deferredStallIds = [...deferredEverIds];
3487
4170
  const deferredStallSuffix = deferredStallIds.length > 0
3488
4171
  ? ` Not counted as blockers (deferred, therefore never dispatchable): [${deferredStallIds.join(', ')}].`
@@ -3518,7 +4201,7 @@ async function runSprintCycle(context) {
3518
4201
  `[${closedCountHistory.join(', ')}] (high-water mark on progress score: ${highWaterClosedCount}).` +
3519
4202
  blockerSuffix + deferredStallSuffix + thrashSuffix + verifySuffix +
3520
4203
  ` Aborting rather than burning the remaining cycles.`,
3521
- { staleCycles, closedCountHistory, highWaterClosedCount, blockerIds, deferredIds: deferredStallIds, thrashIds, reopenCounts: Object.fromEntries(reopenCounts), verifyEverIds: [...verifyEverIds], cycle }
4204
+ { staleCycles, closedCountHistory, highWaterClosedCount, blockerIds, deferredIds: deferredStallIds, thrashIds, reopenCounts: Object.fromEntries(reopenCounts), verifyEverIds: [...verifyEverIds], cycle, setAside: collectSetAsideEntries(sprintState), waited: collectWaitEntries(sprintState) }
3522
4205
  );
3523
4206
  }
3524
4207
 
@@ -3581,7 +4264,7 @@ async function runSprintCycle(context) {
3581
4264
  ({ lastReviewVerdict, reviewedThisCycle, pendingRejectedNewTasks } = await runReReviewPhase({
3582
4265
  phase, log, command,
3583
4266
  cycle, validated, targetIssues, backlogMember,
3584
- gitSync,
4267
+ gitSync, sprintState,
3585
4268
  rejectedNewTasks,
3586
4269
  lastReviewVerdict, reviewedThisCycle, pendingRejectedNewTasks,
3587
4270
  dispatchReview, bdListScoped, goalMax, recordReopen,
@@ -3650,8 +4333,19 @@ async function runSprintCycle(context) {
3650
4333
  const rootsAllClosed = targetIssues.length > 0 && targetIssues.every((id) => closedIdsNow.has(id));
3651
4334
  const goalSatisfied = openAtGoal.length === 0 && lastReviewVerdict === 'APPROVED' && stillOpenVerifyIds.length === 0;
3652
4335
  if ((rootsAllClosed || goalSatisfied) && lastDeployFailure) {
3653
- deployBlockedCycles++;
3654
4336
  const which = rootsAllClosed ? 'every configured sprint root/target bead is closed' : `goal priority ${validated.goal} (<=${goalMax}) is otherwise satisfied`;
4337
+ // A deploy set aside for the run is never re-dispatched, so a
4338
+ // retry cycle could only spin (Plan, Re-Review) waiting on a
4339
+ // deploy that will not run: exit to the finish phases now. The
4340
+ // set-aside deploy is reported in the result and its "Set aside
4341
+ // this run" section, and the deploy-failure verdict gate forces
4342
+ // FAIL.
4343
+ if (sprintState.deploySetAside) {
4344
+ log(`Cycle ${cycle}: ${which}, but NOT exiting as satisfied -- ${formatDeploySetAsideNotes(sprintState.deploySetAside)}. No deploy retry is possible this run; exiting cycle loop, the sprint verdict will be FAIL.`);
4345
+ endGroup();
4346
+ break;
4347
+ }
4348
+ deployBlockedCycles++;
3655
4349
  if (cycle < MAX_CYCLES && deployBlockedCycles < DEPLOY_RETRY_CYCLE_LIMIT) {
3656
4350
  log(`Cycle ${cycle}: ${which}, but NOT exiting as satisfied -- ${formatDeployFailureReason(lastDeployFailure)}. Re-attempting deploy next cycle (deploy-blocked cycle ${deployBlockedCycles} of at most ${DEPLOY_RETRY_CYCLE_LIMIT}).`);
3657
4351
  cycle++;
@@ -3701,14 +4395,22 @@ async function runSprintCycle(context) {
3701
4395
  `. Continuing.`
3702
4396
  );
3703
4397
 
4398
+ handleLateDecisionAnswers();
3704
4399
  cycle++;
3705
4400
  endGroup();
3706
4401
  }
3707
4402
 
4403
+ // An answer recorded after the last cycle's bracket never reached a cycle.
4404
+ if (decisionWait && decisionWait.hasQueuedAnswers()) {
4405
+ const line = 'Decision answer(s) recorded too late to be applied in this run (the cycle loop had ended); the decision(s) stay pending. Re-run the sprint to work the released bead(s).';
4406
+ lateUnworkedReports.push(line);
4407
+ log(line);
4408
+ }
4409
+
3708
4410
  // When the loop exits because `cycle` exceeded MAX_CYCLES (rather than via
3709
4411
  // an early `break`), `cycle` is MAX_CYCLES + 1 at this point; the labels
3710
4412
  // below must report the last cycle actually run.
3711
- const finalCycleLabel = Math.min(cycle, MAX_CYCLES);
4413
+ const finalCycleLabel = Math.min(cycle, effectiveMaxCycles);
3712
4414
 
3713
4415
  // =======================
3714
4416
  // 6. Finalization: the evidence-based final verdict drives the return value
@@ -3742,6 +4444,7 @@ async function runSprintCycle(context) {
3742
4444
  kbPriming, kbWork, kbInjection, kbSprintContext, getMemberForRole,
3743
4445
  childIdAllocator, sprintMutexId, resolveSettleShell,
3744
4446
  computeChildFloor, createChildBeadWithAllocatedId, sanitizePrText,
4447
+ reviewMergeBaseFor,
3745
4448
  });
3746
4449
 
3747
4450
  // =======================
@@ -3804,9 +4507,10 @@ async function runSprintCycle(context) {
3804
4507
  }
3805
4508
 
3806
4509
  // The phase body lives in ./phases/harvest.mjs (apra-fleet-3swo.6.9). The
3807
- // sprint-analysis document, the docs commits and the issue deferrals are
3808
- // all written by the DISPATCHED harvester in its own repo, and the
3809
- // 'harvester' policy row's pushCode/pushBeads bracket publishes them. The
4510
+ // sprint-analysis document (written locally, never committed), the docs
4511
+ // commits and the issue deferrals are all made by the DISPATCHED harvester
4512
+ // in its own repo, and the 'harvester' policy row's pushCode/pushBeads
4513
+ // bracket publishes the commits and deferrals. The
3810
4514
  // only value it returns is the cost block Publish PR renders. It must
3811
4515
  // nonetheless run HERE, after Regression Test (whose summary it folds into
3812
4516
  // the analysis document) and before Publish PR (which pushes the branch the
@@ -3819,7 +4523,10 @@ async function runSprintCycle(context) {
3819
4523
  integTestRunnerSpend, integTestRunnerDispatchCount,
3820
4524
  finalVerdictResult, finalClosedCount, finalOpenAtGoalCount, finalDeferredAtGoalIds, regressionResult, regressionSkippedBy,
3821
4525
  dispatchToolCalls: sprintState.dispatchToolCalls,
4526
+ setAside: collectSetAsideEntries(sprintState),
4527
+ waited: collectWaitEntries(sprintState),
3822
4528
  kbWork,
4529
+ command, memberSeCommands,
3823
4530
  computeBranchSlug, buildAnalysisText, buildCostAnalysis,
3824
4531
  });
3825
4532
 
@@ -3840,14 +4547,21 @@ async function runSprintCycle(context) {
3840
4547
  // phase, before the endGroup() below, exactly as the inline version did.
3841
4548
  // Sprint-summary WARN: repeat the lower-quality banner once at the end.
3842
4549
  const lowerQualityBanner = logLowerQualityWarn(log, MEMBER_INIT_LOG_PREFIX, sprintState.memberInit, 'summary');
3843
- const { pushed } = await runPublishPrPhase({
4550
+ const { pushed, prSkipped } = await runPublishPrPhase({
3844
4551
  lowerQualityBanner,
3845
4552
  phase, log, command,
3846
4553
  args, validated, targetIssues, backlogMember, finalCycleLabel,
3847
4554
  gitSync, getMemberForRole,
3848
4555
  finalVerdictResult, costAnalysis,
4556
+ setAside: collectSetAsideEntries(sprintState),
4557
+ waited: collectWaitEntries(sprintState),
3849
4558
  });
3850
4559
 
4560
+ // Final summary line: a skipped PR must not read as a clean success.
4561
+ if (prSkipped) {
4562
+ log(`[Sprint Summary] ${finalVerdictResult.verdict}, ${prSkipped.message} (reason: ${prSkipped.reason}); branch '${validated.branch}' is pushed.`);
4563
+ }
4564
+
3851
4565
  endGroup();
3852
4566
 
3853
4567
  // The final verdict -- not a blanket, unconditional 'success' -- drives the
@@ -3860,12 +4574,24 @@ async function runSprintCycle(context) {
3860
4574
  return {
3861
4575
  status: finalVerdictResult.verdict === 'PASS' ? 'success' : 'failed',
3862
4576
  verdict: finalVerdictResult.verdict,
3863
- notes: finalVerdictResult.notes,
4577
+ notes: lateUnworkedReports.length > 0 && typeof finalVerdictResult.notes === 'string'
4578
+ ? `${finalVerdictResult.notes}\n${lateUnworkedReports.join('\n')}`
4579
+ : finalVerdictResult.notes,
3864
4580
  branch: validated.branch,
3865
4581
  baseBranch: validated.baseBranch,
3866
4582
  goal: validated.goal,
3867
4583
  maxCycles: validated.maxCycles,
3868
4584
  pushed,
4585
+ // Present only when the branch was pushed but no PR was opened
4586
+ // ({ reason, message }); surfaces in the supervisor's persisted
4587
+ // terminal state as state.result.prSkipped. Never changes the verdict.
4588
+ // A PASS whose PR was skipped (push ok, PR not opened) ends as
4589
+ // 'success-with-warnings' so it never reads as a plain success.
4590
+ ...(prSkipped ? {
4591
+ ...(finalVerdictResult.verdict === 'PASS' ? { status: 'success-with-warnings' } : {}),
4592
+ prSkipped,
4593
+ warnings: [`${prSkipped.message} (reason: ${prSkipped.reason})`],
4594
+ } : {}),
3869
4595
  };
3870
4596
  }
3871
4597