@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
@@ -116,7 +116,7 @@ export const MEMBER_INIT_FIXES = Object.freeze({
116
116
  'code-index-timeout': 'the first code-index tick did not arrive within the bound; check code_status on the member (the index keeps building)',
117
117
  'code-intel-npx-missing': "npx or node is not on the apra-fleet service PATH, so code intelligence is unavailable: reinstall the service so it records node/npx (re-run the fleet installer on the host), or add node and npx to the service PATH and restart the server, then rerun code_reindex",
118
118
  'code-index-failed': 'code_reindex failed on the member: read its analyze log (code_status logPath) and rerun code_reindex',
119
- 'code-index-gitnexus-too-old': "the member's gitnexus is too old to support --index-only: upgrade gitnexus (npx -y gitnexus@latest analyze --index-only) or clear the npx cache (npm cache clean --force) on the member, then rerun code_reindex",
119
+ 'code-index-gitnexus-too-old': "the member's gitnexus is too old to support --index-only: upgrade gitnexus (npx -y gitnexus@latest analyze --index-only --force) or clear the npx cache (npm cache clean --force) on the member, then rerun code_reindex",
120
120
  'code-index-unrecognized': 'code_reindex returned an unrecognized answer: run update_member with fleet_install "auto" for the member so its fleet install is current',
121
121
  });
122
122
 
@@ -211,8 +211,14 @@ export function createDeployPermissionsProvisioner(opts = {}) {
211
211
  grant: prefixes,
212
212
  grant_reason: "deploy.md's declared Permissions section, auto-provisioned before dispatch",
213
213
  });
214
+ const failure = composeFailureText(result);
215
+ if (failure) {
216
+ // Refusal (e.g. NEVER_AUTO_GRANT): not ensured, not cached, so a later call retries.
217
+ log(`[deploy-permissions] compose_permissions refused deploy.md permissions on '${member}' (continuing -- the deployer's own Step 0a check remains the backstop): ${failure}`);
218
+ return;
219
+ }
214
220
  provisioned.add(member);
215
- log(`[deploy-permissions] ensured deploy.md's required permissions on '${member}': ${result}`);
221
+ log(`[deploy-permissions] ensured deploy.md's required permissions on '${member}': ${resultText(result)}`);
216
222
  } catch (err) {
217
223
  log(`[deploy-permissions] could not auto-provision deploy.md permissions on '${member}' (continuing -- the deployer's own Step 0a check remains the backstop): ${err.message}`);
218
224
  }
@@ -83,10 +83,43 @@ export const DEPLOY_RETRY_CYCLE_LIMIT = 3;
83
83
  * deploy.md exists and this cycle's deploy failed; null when it succeeded or
84
84
  * no deploy was attempted (no deploy.md).
85
85
  */
86
- export function latestDeployFailure({ hasDeploy, deployedThisCycle, cycle, deployFailures }) {
86
+ export function latestDeployFailure({ hasDeploy, deployedThisCycle, cycle, deployFailures, deploySetAside = null }) {
87
87
  if (!hasDeploy || deployedThisCycle) return null;
88
88
  const rec = [...deployFailures].reverse().find((f) => f && f.cycle === cycle);
89
- return { cycle, notes: rec && rec.notes != null ? String(rec.notes) : '(deployer returned no notes)' };
89
+ if (rec) return { cycle, notes: rec.notes != null ? String(rec.notes) : '(deployer returned no notes)' };
90
+ // No deployer ran this cycle because deploy is set aside for the run (see
91
+ // DEPLOY SET-ASIDE below): the failure is still the set-aside one.
92
+ if (deploySetAside) return { cycle, notes: formatDeploySetAsideNotes(deploySetAside) };
93
+ return { cycle, notes: '(deployer returned no notes)' };
94
+ }
95
+
96
+ // =============================================================================
97
+ // DEPLOY SET-ASIDE.
98
+ //
99
+ // A deploy that fails at the deploy.md Permissions check (deployer Step 0a: no
100
+ // deploy command ran) fails identically every cycle until an operator grants
101
+ // the missing permission, so re-dispatching the deployer only burns a turn.
102
+ // The deployer marks that stop with the structured `failedStep: 'permissions'`
103
+ // field (never inferred from its notes); runDeployPhase then records
104
+ // `sprintState.deploySetAside` = { reason, notes, cycle } (cycle = first seen)
105
+ // and the cycle loop does not dispatch the deployer again this run. The
106
+ // failure itself still goes onto deployFailures, so the verdict gate above
107
+ // keeps working; later cycles report it through latestDeployFailure's
108
+ // `deploySetAside` fallback. Any other failure (field absent, or a deploy
109
+ // command ran) keeps the normal per-cycle retry.
110
+ // =============================================================================
111
+
112
+ /** The structured deployer failedStep value that sets deploy aside for the run. */
113
+ export const DEPLOY_PERMISSIONS_FAILED_STEP = 'permissions';
114
+
115
+ /**
116
+ * Notes for a cycle whose deploy was not dispatched because it is set aside.
117
+ *
118
+ * @param {{ reason: string, cycle: number }} setAside
119
+ * @returns {string}
120
+ */
121
+ export function formatDeploySetAsideNotes(setAside) {
122
+ return `deploy not dispatched -- set aside for this run since C${setAside.cycle}: ${setAside.reason}`;
90
123
  }
91
124
 
92
125
  /**
@@ -146,6 +179,9 @@ export async function runDeployPhase({
146
179
  getMemberForRole,
147
180
  ensureUnattendedAuto,
148
181
  ensureDeployPermissions,
182
+ // Per-sprint state; `deploySetAside` is recorded on it (see DEPLOY
183
+ // SET-ASIDE above).
184
+ sprintState,
149
185
  // Mutated in place; reassigned and returned, respectively (see header).
150
186
  deployFailures,
151
187
  deployedThisCycle,
@@ -212,6 +248,17 @@ export async function runDeployPhase({
212
248
  if (!deployedThisCycle) {
213
249
  deployFailures.push({ cycle, notes: deployResult.notes });
214
250
  log(`Deploy FAILED this cycle (C${cycle}): ${deployResult.notes}. Skipping Integration Test phase.`);
251
+ if (deployResult.failedStep === DEPLOY_PERMISSIONS_FAILED_STEP && sprintState && !sprintState.deploySetAside) {
252
+ sprintState.deploySetAside = {
253
+ reason: 'deployer stopped at the deploy.md Permissions check before running any deploy command',
254
+ notes: deployResult.notes,
255
+ cycle,
256
+ };
257
+ log(
258
+ `Deploy SET ASIDE for the rest of this run (first seen C${cycle}): ${sprintState.deploySetAside.reason}. ` +
259
+ 'Not dispatching the deployer again this run -- grant the missing permission(s) and re-trigger the sprint.'
260
+ );
261
+ }
215
262
  }
216
263
 
217
264
  return { deployedThisCycle };
@@ -48,7 +48,8 @@
48
48
  //
49
49
  // GUARD COVERAGE: registered as 'phases/develop.mjs' in ../guarded-modules.mjs.
50
50
  // It carries NO command() call site of its own -- every bd read/write it needs
51
- // goes through an injected runner helper or a gitSync bracket -- plus the two
51
+ // goes through an injected runner helper or a gitSync bracket (the
52
+ // NEEDS-DECISION writes run in ../decisions.mjs, inside one) -- plus the two
52
53
  // dispatchRole call sites for the streak-assignment and doer ladders.
53
54
  // =============================================================================
54
55
 
@@ -65,6 +66,9 @@ import { isPostDispatchSyncFailure } from '../errors.mjs';
65
66
  import { isPermissionScopePostDispatchSyncFailure } from '../dispatch-failure.mjs';
66
67
  import { policyFor } from '../role-policies.mjs';
67
68
  import { CLAIMED_ELSEWHERE_REASON } from '../orphan-reclaim.mjs';
69
+ import { openBlocksDependents } from '../beads-scope.mjs';
70
+ import { classifyBlockedReport } from '../set-aside.mjs';
71
+ import { NEEDS_DECISION, validateDecisionRequest, recordPendingDecision } from '../decisions.mjs';
68
72
 
69
73
  /**
70
74
  * Runs ONE Develop round: streak grouping, per-doer worklist packing, and the
@@ -109,6 +113,13 @@ export async function runDevelopPhase({
109
113
  doerPool,
110
114
  perBeadFeedback,
111
115
  // Injected runner helpers -- see the header for why these are not imports.
116
+ // `bdListScoped` is read only to find the open in-scope dependents of a
117
+ // doer-BLOCKED bead (see doctorBlockedIds below).
118
+ bdListScoped,
119
+ // Read only on the doer-BLOCKED path, right after bdListScoped(''), so it
120
+ // is served from the same snapshot: the status of a prerequisite that
121
+ // lies outside the sprint scope.
122
+ fetchAllBeadsShared,
112
123
  claimBeadsBatched,
113
124
  verifyDoerStreakClosed,
114
125
  normalizeTierToken,
@@ -146,11 +157,195 @@ export async function runDevelopPhase({
146
157
  );
147
158
  currentReady = currentReady.filter((b) => !permissionScopeBlockedBeads.has(b.id));
148
159
  }
160
+
161
+ // --- Doer-BLOCKED set-aside carry-over ---
162
+ // A bead a doer reported BLOCKED (see recordDoerBlocked below), plus every
163
+ // open in-scope bead depending on it over 'blocks' edges, is set aside for
164
+ // the rest of the RUN: re-dispatching it would only hit the same block, and
165
+ // its dependents cannot start until it closes. Same lazily-attached,
166
+ // sprint-lifetime Map pattern as permissionScopeBlockedBeads above, so the
167
+ // exclusion holds across rounds AND cycles. Each entry is
168
+ // { kind: 'blocked'|'dependent', blockedBy, reason, cycle, round } --
169
+ // `blockedBy` is the bead the doer reported (itself, for kind 'blocked'),
170
+ // and cycle/round record when the bead was first set aside. Lane-mates of
171
+ // the blocked bead are NOT set aside: lower-order ones return to the next
172
+ // round's pool; higher-order ones stay open but are held back by lane
173
+ // order (the runner's holdBackByLaneOrder), and count as stuck for the
174
+ // immediate-stall check.
175
+ sprintState.doctorBlockedIds = sprintState.doctorBlockedIds || new Map();
176
+ const doctorBlockedIds = sprintState.doctorBlockedIds;
177
+ // Beads a doer reported BLOCKED while they still had an open prerequisite
178
+ // in this sprint: they WAIT (id -> { on, cycle, round }) instead of being
179
+ // set aside, and doctorBlockedIds keeps genuine blockers only. The runner's
180
+ // ready set (dispatchableReadyLeafBeads) holds a waiting bead back until
181
+ // its prerequisites close; the entry is kept for the "Waited this run"
182
+ // report line and to bound the retry (a second BLOCKED sets it aside).
183
+ sprintState.waitingIds = sprintState.waitingIds || new Map();
184
+ const waitingIds = sprintState.waitingIds;
185
+ const setAsideReady = currentReady.filter((b) => doctorBlockedIds.has(b.id));
186
+ if (setAsideReady.length > 0) {
187
+ log(
188
+ `Develop C${cycle} R${devRounds}: excluding ${setAsideReady.length} bead(s) set aside after a doer BLOCKED report ` +
189
+ `(${setAsideReady.map((b) => `${b.id}: ${doctorBlockedIds.get(b.id).reason}`).join('; ')}) from this round's streak ` +
190
+ 'assignment -- not re-dispatching them this run.'
191
+ );
192
+ currentReady = currentReady.filter((b) => !doctorBlockedIds.has(b.id));
193
+ }
149
194
  if (currentReady.length === 0) {
150
- log(`Develop C${cycle} R${devRounds}: every still-ready bead this round is publish-blocked -- skipping streak assignment and dispatch entirely.`);
195
+ log(setAsideReady.length > 0
196
+ ? `Develop C${cycle} R${devRounds}: every still-ready bead this round is set aside (doer-BLOCKED or publish-blocked) -- skipping streak assignment and dispatch entirely.`
197
+ : `Develop C${cycle} R${devRounds}: every still-ready bead this round is publish-blocked -- skipping streak assignment and dispatch entirely.`);
151
198
  return { streakOutcomes: [], readyTitleById: new Map() };
152
199
  }
153
200
 
201
+ // Records the bead(s) a doer reported BLOCKED, and their open in-scope
202
+ // 'blocks' dependents, on doctorBlockedIds. WHICH open beads are blocked is
203
+ // read off the report's structured `blockedIds` field, never its notes:
204
+ // the reported ids that the engine's own read-back still shows open. An
205
+ // explicit empty `blockedIds` means the doer left nothing open BECAUSE of
206
+ // the block, so nothing is set aside. With the field omitted, the only
207
+ // unambiguous case is a single-bead dispatch whose one bead is still open:
208
+ // that bead is the blocked one. In any larger dispatch an open bead the
209
+ // doer did not name may simply not have been reached (for example after
210
+ // the doer closed an earlier bead as blocked and stopped), so a bead the
211
+ // doer never named is never set aside: nothing is set aside and the
212
+ // existing left-open retry applies.
213
+ const recordDoerBlocked = async ({ report, unclosedIds, streakIds, doerMember }) => {
214
+ const hasField = Array.isArray(report.blockedIds);
215
+ const reported = hasField ? report.blockedIds.map(String) : [];
216
+ let blockedIds;
217
+ if (hasField && reported.length === 0) {
218
+ log(
219
+ `Doer streak [${streakIds.join(', ')}] reported BLOCKED with an empty blockedIds -- no bead was left open ` +
220
+ 'because of the block, so nothing is set aside; the open beads stay eligible for the next round.'
221
+ );
222
+ return;
223
+ } else if (reported.length > 0) {
224
+ blockedIds = reported.filter((id) => unclosedIds.includes(id));
225
+ const ignored = reported.filter((id) => !unclosedIds.includes(id));
226
+ if (ignored.length > 0) {
227
+ log(`Doer streak [${streakIds.join(', ')}] reported blockedIds not open in this streak (ignored): ${ignored.join(', ')}.`);
228
+ }
229
+ } else if (streakIds.length === 1 && unclosedIds.length === 1) {
230
+ blockedIds = [...unclosedIds];
231
+ } else {
232
+ log(
233
+ `Doer streak [${streakIds.join(', ')}] reported BLOCKED with ${unclosedIds.length} bead(s) still open ` +
234
+ 'and no blockedIds naming which -- cannot tell blocked from not reached, so nothing is set aside; ' +
235
+ 'the open beads stay eligible for the next round.'
236
+ );
237
+ return;
238
+ }
239
+ if (blockedIds.length === 0) return;
240
+ const where = { cycle, round: devRounds };
241
+ // The doer's own notes are carried verbatim (whitespace-collapsed,
242
+ // never shortened) so the stall report says what to fix; they are
243
+ // reported, never parsed. They used to be capped at 300 characters,
244
+ // which cut an operator-facing request to a few words in the stall
245
+ // abort text.
246
+ const doerNotes = typeof report.notes === 'string' ? report.notes.replace(/\s+/g, ' ').trim() : '';
247
+ const doerReason = `doer on member '${doerMember}' reported BLOCKED on streak [${streakIds.join(', ')}]` +
248
+ (doerNotes ? `: ${doerNotes}` : '');
249
+
250
+ // Wait vs set-aside, decided mechanically from the bead graph (never
251
+ // from the notes): a reported bead that still has an open
252
+ // prerequisite in this sprint -- an open 'blocks' dependency or an
253
+ // open lower-order lane-mate -- WAITS (sprintState.waitingIds) instead
254
+ // of being set aside; it is not dispatched again until those close. A
255
+ // bead with no open prerequisite, or one that already waited once, or
256
+ // one whose open prerequisite lies outside the sprint scope (it cannot
257
+ // close in this run), is set aside as before. The streak's own beads
258
+ // are read from the verified unclosedIds (fresh) rather than the
259
+ // possibly older snapshot.
260
+ let scopeBeads = [];
261
+ let allBeads = [];
262
+ if (typeof bdListScoped === 'function') {
263
+ const closedNow = new Set(streakIds.filter((id) => !unclosedIds.includes(id)));
264
+ scopeBeads = (await bdListScoped('')).map((b) => (b && closedNow.has(b.id) ? { ...b, status: 'closed' } : b));
265
+ if (typeof fetchAllBeadsShared === 'function') allBeads = await fetchAllBeadsShared();
266
+ }
267
+ const decision = classifyBlockedReport({
268
+ blockedIds, scopeBeads, allBeads, doctorBlockedIds, waitingIds,
269
+ });
270
+ const fresh = [];
271
+ const waitedNow = [];
272
+ for (const w of decision.wait) {
273
+ waitingIds.set(w.id, { on: [...w.on], ...where });
274
+ waitedNow.push(w.id);
275
+ }
276
+ for (const s of decision.setAside) {
277
+ doctorBlockedIds.set(s.id, {
278
+ kind: 'blocked', blockedBy: s.id,
279
+ reason: s.suffix ? `${doerReason}${s.suffix}` : doerReason,
280
+ ...where,
281
+ });
282
+ fresh.push(s.id);
283
+ }
284
+ for (const id of waitedNow) {
285
+ log(
286
+ `Doer BLOCKED wait C${cycle} R${devRounds}: bead '${id}' waiting on ${waitingIds.get(id).on.join(', ')} ` +
287
+ '(open prerequisite(s) in this sprint) -- not set aside; it is not dispatched again until they close.'
288
+ );
289
+ }
290
+ if (fresh.length === 0) return;
291
+ let dependents = new Map();
292
+ if (typeof bdListScoped === 'function') {
293
+ dependents = openBlocksDependents(fresh, scopeBeads);
294
+ }
295
+ const freshDependents = [];
296
+ for (const [id, root] of dependents) {
297
+ if (doctorBlockedIds.has(id)) continue;
298
+ doctorBlockedIds.set(id, {
299
+ kind: 'dependent', blockedBy: root,
300
+ reason: `depends (via blocks edges) on doer-BLOCKED bead '${root}'`,
301
+ ...where,
302
+ });
303
+ freshDependents.push(id);
304
+ }
305
+ log(
306
+ `Doer BLOCKED set-aside C${cycle} R${devRounds}: setting aside for the rest of this run bead(s) ` +
307
+ `[${fresh.join(', ')}] reported BLOCKED and their open dependent(s) [${freshDependents.join(', ')}]; ` +
308
+ `other open bead(s) of streak [${streakIds.join(', ')}] return to the ready pool. Entries: ` +
309
+ JSON.stringify(Object.fromEntries([...fresh, ...freshDependents].map((id) => [id, doctorBlockedIds.get(id)])))
310
+ );
311
+ };
312
+
313
+ // Records a doer NEEDS-DECISION report (../decisions.mjs): the named
314
+ // bead -- which must still be open in this streak -- gets a decision bead
315
+ // labelled for a human, an appended note with the full request, an entry
316
+ // on sprintState.pendingDecisions, and is set aside (kind
317
+ // 'needs-decision') with its open blocks-edge dependents, so it is never
318
+ // re-dispatched in this run while the decision is pending. Other open
319
+ // beads of the streak are not set aside: lower-order lane-mates return
320
+ // to the pool and higher-order ones are held by lane order. Returns true
321
+ // when the bead was set aside.
322
+ const recordDoerNeedsDecision = async ({ report, unclosedIds, streakIds, doerMember }) => {
323
+ const checked = validateDecisionRequest(report.decision);
324
+ if (!checked.ok) {
325
+ log(`Doer streak [${streakIds.join(', ')}] reported NEEDS-DECISION with an unusable decision (${checked.reason}) -- nothing is set aside; the open beads stay eligible for the next round.`);
326
+ return false;
327
+ }
328
+ const decision = checked.decision;
329
+ if (!unclosedIds.includes(decision.beadId)) {
330
+ log(`Doer streak [${streakIds.join(', ')}] reported NEEDS-DECISION on '${decision.beadId}', which is not open in this streak -- nothing is set aside.`);
331
+ return false;
332
+ }
333
+ let scopeBeads = [];
334
+ if (typeof bdListScoped === 'function') {
335
+ const closedNow = new Set(streakIds.filter((id) => !unclosedIds.includes(id)));
336
+ scopeBeads = (await bdListScoped('')).map((b) => (b && closedNow.has(b.id) ? { ...b, status: 'closed' } : b));
337
+ }
338
+ await gitSync.withOpenSyncBracket(() => recordPendingDecision({
339
+ sprintState, decision,
340
+ raisedBy: `doer on member '${doerMember}'`,
341
+ cycle, round: devRounds, command, member: backlogMember, scopeBeads, log,
342
+ }));
343
+ // The engine just mutated beads (decision bead, note) in its own
344
+ // clone: D-push so the operator and every member see them.
345
+ await gitSync.syncBeadsAfter(backlogMember, { pushBeads: true });
346
+ return true;
347
+ };
348
+
154
349
  // --- Streak grouping ------------------------------------------
155
350
  // PREFER deterministic grouping straight from the planner's lane
156
351
  // metadata (`streak`/`streakOrder`, emitted per planner.md through
@@ -771,10 +966,18 @@ export async function runDevelopPhase({
771
966
 
772
967
  // The doer RETURNED (its session ended) but left bead(s) open: a
773
968
  // BLOCKED report, or a success-looking report the bd read disproves.
774
- const leftOpenReason = report && report.status === 'BLOCKED' ? 'blocked' : 'left-open';
969
+ const leftOpenReason = report && report.status === 'BLOCKED'
970
+ ? 'blocked'
971
+ : (report && report.status === NEEDS_DECISION ? 'needs-decision' : 'left-open');
775
972
  if (unclosedIds.length > 0) {
776
973
  log(`Doer streak [${actualBeadIds.join(', ')}] reported status '${report ? report.status : 'unknown'}' but bead(s) still open: ${unclosedIds.join(', ')} -- treating streak as FAILED.`);
777
974
  }
975
+ if (leftOpenReason === 'blocked' && unclosedIds.length > 0) {
976
+ await recordDoerBlocked({ report, unclosedIds, streakIds: actualBeadIds, doerMember });
977
+ }
978
+ if (leftOpenReason === 'needs-decision' && unclosedIds.length > 0) {
979
+ await recordDoerNeedsDecision({ report, unclosedIds, streakIds: actualBeadIds, doerMember });
980
+ }
778
981
 
779
982
  if (batchStreaks) {
780
983
  // Mode (i): PER-STREAK outcome attribution for the batch
@@ -78,9 +78,10 @@
78
78
 
79
79
  import { dispatchRole, TURN_BASES } from '../dispatch-role.mjs';
80
80
  import { buildFinalVerdictPrompt } from '../prompts.mjs';
81
+ import { resolveFinalReviewMergeBase } from '../git-topology.mjs';
81
82
  import { applyGuardedReopens, parseIdWithReasonEntry } from '../beads-transitions.mjs';
82
83
  import {
83
- validateNewTask, appendRejectedFindingToParentNotes, persistNewTaskBestEffort,
84
+ validateNewTask, buildFallbackNewTask, appendRejectedFindingToParentNotes, persistNewTaskBestEffort,
84
85
  } from '../abort.mjs';
85
86
  import { buildSettleCallback } from '../dolt-settle.mjs';
86
87
  // apra-fleet-rp7a.1: the SAME deferred split Cycle Evaluation applies. Shared
@@ -163,6 +164,10 @@ export async function runFinalReviewPhase({
163
164
  computeChildFloor,
164
165
  createChildBeadWithAllocatedId,
165
166
  sanitizePrText,
167
+ // (member) => Promise<sha>: the review diff base (merge-base of a freshly
168
+ // fetched origin/<base> and the branch) on that member. Injected so this
169
+ // phase issues no fleet command of its own; it throws on failure.
170
+ reviewMergeBaseFor,
166
171
  }) {
167
172
  phase(`Final Review C${finalCycleLabel}`);
168
173
 
@@ -224,6 +229,28 @@ export async function runFinalReviewPhase({
224
229
  if (finalKbCandidates.length > 0) {
225
230
  log(`[kb-work] offering ${finalKbCandidates.length} INFERRED entr(ies) to the final reviewer for promotion.`);
226
231
  }
232
+ // The CONFIRMED entries the final reviewer may demote back to INFERRED.
233
+ // buildFinalVerdictPrompt has always accepted and rendered kbDemoteCandidates,
234
+ // but nothing ever passed it here, so that block was dead on this path and
235
+ // the final reviewer -- the one review that reads the WHOLE diff -- could
236
+ // never demote, exactly as it could never promote before promotion
237
+ // candidates were added above.
238
+ //
239
+ // SCOPE IS 'sprint', PASSED EXPLICITLY. Final review judges the entire
240
+ // sprint diff and has no round, so its changed-file scope is the
241
+ // cumulative baseBranch...branch diff. demotionCandidates never infers
242
+ // this from who called it -- see its doc comment.
243
+ //
244
+ // Fetched ONCE, BEFORE the dispatch, for the same reason the promotion
245
+ // candidates above are: the retry and resume paths then reuse the
246
+ // identical block rather than re-reading a KB this review's own
247
+ // demotions may already have changed. Best-effort like every other KB
248
+ // read: a cold or unreachable KB, or a diff that could not be computed,
249
+ // degrades to [] and must never fail the final review.
250
+ const finalKbDemoteCandidates = await kbWork.demotionCandidates(getMemberForRole('reviewer'), { scope: 'sprint' });
251
+ if (finalKbDemoteCandidates.length > 0) {
252
+ log(`[kb-work] offering ${finalKbDemoteCandidates.length} CONFIRMED entr(ies) to the final reviewer for demotion.`);
253
+ }
227
254
  // apra-fleet-3swo.5.7: the final-review ladder -- its dispatch, its
228
255
  // read-side git-sync bracket, its max_turns-exhaustion resume at doubled
229
256
  // turns, its retry-once wrapper, its auth self-heal and its FAIL degrade --
@@ -246,11 +273,23 @@ export async function runFinalReviewPhase({
246
273
  // dispatching the reviewer persona over the whole sprint -- so its policy
247
274
  // routes to getMemberForRole('reviewer'), unlike the per-round reviewer
248
275
  // which takes the pool head.
276
+ // The diff range the final reviewer must use, computed on its own member.
277
+ // A failure throws and fails Final Review loudly: never a fallback to the
278
+ // member's (possibly stale) local base branch.
279
+ if (typeof reviewMergeBaseFor !== 'function') {
280
+ throw new Error('runFinalReviewPhase requires reviewMergeBaseFor (the review diff base resolver).');
281
+ }
282
+ // Retried once; a second failure ends the run loudly with a relaunch hint
283
+ // (the sprint's work is already on the remote branch).
284
+ const finalMergeBaseSha = await resolveFinalReviewMergeBase(reviewMergeBaseFor, {
285
+ member: getMemberForRole('reviewer'), branch: validated.branch, baseBranch: validated.baseBranch, log,
286
+ });
249
287
  const finalReviewOutcome = await dispatchRole(dispatchCtx, 'final-review', {
250
288
  prompt: buildFinalVerdictPrompt({
251
289
  targetIssues,
252
290
  branch: validated.branch,
253
291
  baseBranch: validated.baseBranch,
292
+ mergeBaseSha: finalMergeBaseSha,
254
293
  goal: validated.goal,
255
294
  cyclesRun: finalCycleLabel,
256
295
  closedCount: finalClosedCount,
@@ -261,6 +300,7 @@ export async function runFinalReviewPhase({
261
300
  unclosedVerifyIds: finalUnclosedVerifyIds,
262
301
  deferredAtGoalIds: finalDeferredAtGoalIds,
263
302
  kbCandidates: finalKbCandidates,
303
+ kbDemoteCandidates: finalKbDemoteCandidates,
264
304
  kbKnowledge: kbInjection ? undefined : kbPriming.knowledgeOf(getMemberForRole('reviewer')),
265
305
  kbBlock: kbInjection
266
306
  ? await kbInjection.blockFor({
@@ -271,7 +311,9 @@ export async function runFinalReviewPhase({
271
311
  })
272
312
  : undefined,
273
313
  }),
274
- resumePrompt: 'Continue your final review exactly where you left off in this same session -- do not restart or re-read the diff from scratch. Weigh the remaining evidence and return your final PASS/FAIL verdict now (with newTasks findings if FAIL).',
314
+ resumePrompt: 'Continue your final review exactly where you left off in this same session -- do not restart or re-read the diff from scratch. ' +
315
+ `The diff range is ${finalMergeBaseSha}..${validated.branch} (use exactly this range for git diff and git log). ` +
316
+ 'Weigh the remaining evidence and return your final PASS/FAIL verdict now (with newTasks findings if FAIL).',
275
317
  roleLabel: 'Final Review',
276
318
  label: 'Final Review',
277
319
  resumeLabel: `Final Review (resume, max_turns=${TURN_BASES.FINAL_REVIEW_MAX_TURNS * 2})`,
@@ -347,7 +389,23 @@ export async function runFinalReviewPhase({
347
389
  const createdIds = [];
348
390
  let createdCountUnknownId = 0;
349
391
  for (const newTask of finalNewTasks) {
350
- const validation = validateNewTask(newTask);
392
+ let validation = validateNewTask(newTask);
393
+ if (!validation.ok) {
394
+ // Final Review findings are the handoff to the next sprint's
395
+ // planner and there is no later review round to resubmit
396
+ // them, so a finding whose only problem is a title the
397
+ // sanitiser could not rescue is still filed as a bead: under
398
+ // a catch-all-stripped fallback title, with the ORIGINAL
399
+ // title preserved (ASCII-escaped) in the description, which
400
+ // still travels via --body-file. Priority/description
401
+ // failures are not rescued and fall through to the rejection
402
+ // path below.
403
+ const fallback = buildFallbackNewTask(newTask);
404
+ if (fallback) {
405
+ log(`Final Review newTasks: title failed the allowlist (${validation.reason}); filing under fallback title ${JSON.stringify(fallback.title)} with the original title escaped into the description.`);
406
+ validation = fallback;
407
+ }
408
+ }
351
409
  if (!validation.ok) {
352
410
  log(`Final Review newTasks: REJECTED (not sent to bd create) -- ${validation.reason}`);
353
411
  rejectedNewTasks.push({ cycle: finalCycleLabel, reason: validation.reason, raw: newTask });
@@ -19,7 +19,7 @@
19
19
  // summary is folded into docs/sprint-analysis-<slug>.md through
20
20
  // buildAnalysisText() -- harvesting first would publish an analysis document
21
21
  // with a hole where the regression section belongs. BEFORE Publish PR, because
22
- // the harvester is a code-writing role: the docs/sprint-analysis
22
+ // the harvester is a code-writing role: the docs/README
23
23
  // commits it makes must be pushed before Publish PR pushes the branch and
24
24
  // raises the PR a human will read. That ordering is structural here, not a
25
25
  // comment: ./publish-pr.mjs's call site sits below this one in runner.js and
@@ -47,8 +47,8 @@
47
47
  // modules and are imported directly.
48
48
  //
49
49
  // THE COST BLOCK IS ENGINE-RENDERED, NOT HARVESTER-WRITTEN. It is NOT part of
50
- // analysisText (the harvester commits that text to the product branch, and
51
- // spend data does not belong there); it is returned for ./publish-pr.mjs to
50
+ // analysisText (the harvester writes that text into the target repo's
51
+ // working tree, and spend data does not belong there); it is returned for ./publish-pr.mjs to
52
52
  // render in the PR body. The harvester no
53
53
  // longer writes a CHANGELOG entry: a shared, prepend-only file conflicted on
54
54
  // every concurrent sprint PR merge.
@@ -58,13 +58,23 @@
58
58
  // docs commits are made by the DISPATCHED harvester inside its own
59
59
  // repo, and its pushes are the policy row's bracket -- but it took ONE
60
60
  // dispatchRole() site (the harvester ladder), which is exactly what
61
- // dispatch-safety-guard and the phase 3 dispatch census read. Both baselines
62
- // are pinned rather than assumed.
61
+ // dispatch-safety-guard and the phase 3 dispatch census read. It has since
62
+ // gained exactly ONE member_name-bearing command() site of its own: the
63
+ // pre-dispatch git exclude of the uncommitted analysis document on the
64
+ // harvester's member. Both baselines are pinned rather than assumed.
63
65
  // =============================================================================
64
66
 
65
67
  import { dispatchRole, TURN_BASES } from '../dispatch-role.mjs';
66
68
  import { buildHarvesterPrompt } from '../prompts.mjs';
67
69
 
70
+ /**
71
+ * The local git-exclude pattern covering every analysisArtifactFile this
72
+ * phase derives (docs/sprint-analysis-<slug>.md). The document is written to
73
+ * the harvester's working tree but never committed; listing this pattern in
74
+ * that clone's own exclude file keeps it out of status, stashes and commits.
75
+ */
76
+ export const SPRINT_ANALYSIS_EXCLUDE_PATTERN = 'docs/sprint-analysis-*.md';
77
+
68
78
  /**
69
79
  * Runs the Harvest phase: assemble the sprint-analysis inputs, dispatch the
70
80
  * harvester ladder, and log what it reported.
@@ -104,8 +114,17 @@ export async function runHarvestPhase({
104
114
  regressionSkippedBy = null,
105
115
  // Sprint state's per-dispatch kb_* and code_* call records (dispatch-accounting.mjs).
106
116
  dispatchToolCalls = null,
117
+ // The run's set-aside records (../set-aside.mjs collectSetAsideEntries).
118
+ setAside = [],
119
+ // The run's wait records (../set-aside.mjs collectWaitEntries).
120
+ waited = [],
107
121
  // The KB work client: the harvest round's bible commit runs through it.
108
122
  kbWork = null,
123
+ // Member-bound command runner and the per-member OS/shell command builder
124
+ // (getSeCommands over resolveMemberTarget), for the pre-dispatch git
125
+ // exclude of the analysis document.
126
+ command,
127
+ memberSeCommands,
109
128
  // Defined BY runner.js; injected to avoid a circular import (see header).
110
129
  computeBranchSlug,
111
130
  buildAnalysisText,
@@ -141,6 +160,8 @@ export async function runHarvestPhase({
141
160
  regressionResult,
142
161
  regressionSkippedBy,
143
162
  dispatchToolCalls,
163
+ setAside,
164
+ waited,
144
165
  // Confirmations the final review round's bible commit could not
145
166
  // publish -- persisted here so the warning outlives the live log.
146
167
  kbBibleUnpublished: kbWork && typeof kbWork.unpublishedBible === 'function' ? kbWork.unpublishedBible() : null,
@@ -149,7 +170,7 @@ export async function runHarvestPhase({
149
170
  spend: integTestRunnerSpend,
150
171
  dispatchCount: integTestRunnerDispatchCount,
151
172
  });
152
- // The harvester commits analysisText to the product branch, so it carries
173
+ // The harvester writes analysisText into the target repo's tree, so it carries
153
174
  // the sprint report ONLY: spend data stays out of the repository. The cost
154
175
  // block is returned below for Publish PR, which renders it in the PR body.
155
176
  const analysisText = reportText;
@@ -169,33 +190,62 @@ export async function runHarvestPhase({
169
190
  // labels, and what the caller does with the report.
170
191
  //
171
192
  // The harvester is a code-writing role (pushCode: true) alongside the doer
172
- // -- G-pull before, G-push after so the docs/sprint-analysis
173
- // commits it makes are published before anything downstream (Publish PR,
174
- // below) reads the branch. It ALSO mutates beads (issue-defer of
175
- // low-priority items), so it D-pushes those mutations alongside its git
176
- // push. Both flags live in the policy row now.
177
- const harvestOutcome = await dispatchRole(dispatchCtx, 'harvester', {
178
- prompt: harvesterPrompt,
179
- resumePrompt: 'Continue your harvest exactly where you left off in this same session -- do not redo docs sections already written. Finish the remaining updates, commit them, and return your final report now.',
180
- roleLabel: 'Harvester',
181
- resumeLabel: `Harvest (resume, max_turns=${TURN_BASES.HARVESTER_MAX_TURNS * 2})`,
182
- });
183
- const harvesterResult = harvestOutcome.value;
184
- // No duplicate log() dump -- see dispatchReview() for why. The file
185
- // path itself IS worth a line: it is the durable, committed record of
186
- // the Final Review verdict (and everything else in analysisText) --
187
- // unlike the verdict object, it survives after this process exits.
193
+ // -- G-pull before, G-push after so the docs/README commits it makes are
194
+ // published before anything downstream (Publish PR, below) reads the
195
+ // branch. It ALSO mutates beads (issue-defer of low-priority items), so it
196
+ // D-pushes those mutations alongside its git push. Both flags live in the
197
+ // policy row now.
188
198
  //
189
- // A degraded harvest proceeds WITHOUT a validated report (the sprint
190
- // verdict is already decided by this point), so everything below is
191
- // gated on actually having one. The report's kb_captures were applied by
192
- // the policy's 'kb-apply' postResult step, which only runs on success.
193
- if (!harvestOutcome.ok) {
194
- log(`Harvester: proceeding without a validated harvester report: ${harvestOutcome.error?.message ?? 'no report'}`);
195
- } else if (harvesterResult.status !== 'OK') {
196
- log(`Harvester reported FAILED: ${harvesterResult.notes}`);
199
+ // The analysis document is written to the harvester's working tree but
200
+ // NEVER committed. Before the dispatch, the engine lists its pattern in
201
+ // that clone's local git exclude file (never committed, idempotent, built
202
+ // for the member's OS/shell), so the untracked file is never reported
203
+ // dirty, never auto-stashed by a later sprint's branch ensure, and never
204
+ // swept into a commit by `git add -A`/`git add docs/`. It runs BEFORE the
205
+ // dispatch because the harvester's own docs/ commit happens inside it. If
206
+ // it fails, the harvester is NOT dispatched (its docs/ commit could sweep
207
+ // the file in) and that is logged loudly; the sprint's verdict is already
208
+ // decided, so Publish PR still runs, exactly as for a degraded harvest.
209
+ const harvesterMember = dispatchCtx.getMemberForRole('harvester');
210
+ const memberCommands = await memberSeCommands(harvesterMember);
211
+ const excludeResult = await command(memberCommands.ensureGitExcluded(SPRINT_ANALYSIS_EXCLUDE_PATTERN), {
212
+ member_name: harvesterMember,
213
+ silent: true,
214
+ failSoft: true,
215
+ label: `Exclude ${SPRINT_ANALYSIS_EXCLUDE_PATTERN} from git on member '${harvesterMember}'`,
216
+ });
217
+ if (!excludeResult || !excludeResult.ok) {
218
+ log(
219
+ `ERROR Harvester: NOT dispatched -- could not add '${SPRINT_ANALYSIS_EXCLUDE_PATTERN}' to the local git ` +
220
+ `exclude file on member '${harvesterMember}' (${(excludeResult && excludeResult.error) || 'unknown error'}). ` +
221
+ 'Without it the harvester\'s docs/ commit could sweep the uncommitted sprint analysis into the branch. ' +
222
+ 'No sprint analysis, docs or README harvest was produced for this sprint.'
223
+ );
197
224
  } else {
198
- log(`Harvester: wrote sprint analysis (including the Final Review verdict) to ${analysisArtifactFile}.`);
225
+ const harvestOutcome = await dispatchRole(dispatchCtx, 'harvester', {
226
+ prompt: harvesterPrompt,
227
+ resumePrompt: 'Continue your harvest exactly where you left off in this same session -- do not redo docs sections already written. Finish the remaining updates, commit them, and return your final report now.',
228
+ roleLabel: 'Harvester',
229
+ resumeLabel: `Harvest (resume, max_turns=${TURN_BASES.HARVESTER_MAX_TURNS * 2})`,
230
+ });
231
+ const harvesterResult = harvestOutcome.value;
232
+ // No duplicate log() dump -- see dispatchReview() for why. The file
233
+ // path itself IS worth a line: it is the local record of the Final
234
+ // Review verdict (and everything else in analysisText) on the
235
+ // harvester's member -- unlike the verdict object, it survives after
236
+ // this process exits. It is deliberately not committed.
237
+ //
238
+ // A degraded harvest proceeds WITHOUT a validated report (the sprint
239
+ // verdict is already decided by this point), so everything below is
240
+ // gated on actually having one. The report's kb_captures were applied by
241
+ // the policy's 'kb-apply' postResult step, which only runs on success.
242
+ if (!harvestOutcome.ok) {
243
+ log(`Harvester: proceeding without a validated harvester report: ${harvestOutcome.error?.message ?? 'no report'}`);
244
+ } else if (harvesterResult.status !== 'OK') {
245
+ log(`Harvester reported FAILED: ${harvesterResult.notes}`);
246
+ } else {
247
+ log(`Harvester: wrote sprint analysis (including the Final Review verdict) locally to ${analysisArtifactFile} on member '${harvesterMember}' (not committed; git-excluded).`);
248
+ }
199
249
  }
200
250
 
201
251
  // The harvest round's bible commit: confirmations still pending (a