@staix/agent-hub 0.52.0 → 0.54.0

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 (196) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +4 -3
  3. package/docs/addons/open-code-review.md +3 -6
  4. package/docs/agent-notes/README.md +1 -1
  5. package/docs/agent-notes/adapters.md +5 -4
  6. package/docs/agent-notes/budget.md +2 -2
  7. package/docs/agent-notes/bus.md +1 -0
  8. package/docs/agent-notes/daemon.md +6 -5
  9. package/docs/agent-notes/models.md +1 -1
  10. package/docs/agent-notes/tasks.md +3 -3
  11. package/docs/agent-notes/tests.md +4 -4
  12. package/docs/contracts/companion-cli-v2.json +90 -0
  13. package/docs/contracts/companion-cli-v3.json +348 -0
  14. package/docs/design/adapters.md +1 -1
  15. package/docs/design/agent-hub-architecture.md +8 -5
  16. package/docs/design/bus.md +1 -1
  17. package/docs/design/cli-output-inventory.md +4 -2
  18. package/docs/design/execution-reference.md +1 -1
  19. package/docs/design/guidance-experiments.md +1 -0
  20. package/docs/design/guidance-probes.md +1 -0
  21. package/docs/design/model-routes.md +20 -5
  22. package/docs/design/roadmap.md +6 -4
  23. package/docs/design/task-board.md +21 -2
  24. package/docs/dogfood.md +13 -6
  25. package/docs/events.md +1 -1
  26. package/docs/memory.md +2 -2
  27. package/docs/operations.md +158 -50
  28. package/docs/quickstart.md +14 -2
  29. package/docs/security.md +17 -9
  30. package/docs/specs/2026-09-19-agent-hub-design.md +5 -3
  31. package/docs/specs/2026-09-19-multi-project-design.md +1 -1
  32. package/docs/specs/2026-09-20-upgrade-recovery-design.md +24 -0
  33. package/docs/specs/2026-12-04-arev-adoption-design.md +84 -0
  34. package/docs/specs/mcp-endpoint.md +15 -4
  35. package/docs/specs/relay-contract.md +38 -0
  36. package/docs/verification/2026-12-04-host-shared-receipts.md +43 -0
  37. package/docs/verification/2026-12-05-0.53.0.md +101 -0
  38. package/docs/verification/2026-12-05-agy-1.5.24.md +55 -0
  39. package/docs/verification/2026-12-05-claude-implementer-2.1.337.md +43 -0
  40. package/docs/verification/2026-12-06-0.54.0.md +76 -0
  41. package/docs/verification/2026-12-06-codex-0174-reviewer-isolation.md +43 -0
  42. package/docs/verification/2026-12-06-codex-0174-reviewer-tool-call.md +34 -0
  43. package/docs/verification/2026-12-06-compat-codex-capabilities-0.174.0.md +25 -0
  44. package/docs/verification/2026-12-06-compat-pi-1.8.0.md +23 -0
  45. package/docs/verified.json +38 -29
  46. package/package.json +9 -3
  47. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  48. package/plugins/agent-hub/.mcp.json +1 -1
  49. package/plugins/agent-hub/compat.json +9 -5
  50. package/plugins/agent-hub/kimi-hook.js +892 -874
  51. package/plugins/agent-hub/relay-launcher.js +24 -0
  52. package/plugins/agent-hub/server.js +27271 -25146
  53. package/src/adapters/acp-session-model.ts +1 -1
  54. package/src/adapters/acp.ts +5 -4
  55. package/src/adapters/agy/definition.ts +1 -1
  56. package/src/adapters/agy/hooks.ts +1 -1
  57. package/src/adapters/channel-peer.ts +3 -1
  58. package/src/adapters/claude-channel-evidence.ts +26 -1
  59. package/src/adapters/claude-channel.ts +27 -30
  60. package/src/adapters/claude-connection-policy.ts +62 -0
  61. package/src/adapters/claude-relay.ts +255 -0
  62. package/src/adapters/codex-review-isolation.ts +1 -2
  63. package/src/adapters/compat.ts +28 -18
  64. package/src/adapters/definitions/native-cli-preview-pi.ts +2 -1
  65. package/src/adapters/definitions/native-config-defaults.ts +1 -1
  66. package/src/adapters/definitions/native-context.ts +1 -2
  67. package/src/adapters/definitions/native-factories.ts +4 -1
  68. package/src/adapters/definitions/native-quota.ts +1 -1
  69. package/src/adapters/definitions/native-recovery.ts +3 -1
  70. package/src/adapters/external-modules.ts +2 -2
  71. package/src/adapters/kimi-review.ts +1 -1
  72. package/src/adapters/kimi-tui-facts.ts +1 -1
  73. package/src/adapters/local-worker.ts +3 -3
  74. package/src/adapters/native-capabilities.ts +1 -1
  75. package/src/adapters/pi.ts +26 -7
  76. package/src/adapters/registry-types.ts +2 -0
  77. package/src/adapters/relay-launcher.ts +27 -0
  78. package/src/adapters/reviewer-mcp.ts +1 -1
  79. package/src/cli/agents.ts +20 -8
  80. package/src/cli/agy-mcp.ts +1 -1
  81. package/src/cli/claude-profile-hook.ts +1 -1
  82. package/src/cli/command-table.ts +1 -0
  83. package/src/cli/commands/agents.ts +18 -1
  84. package/src/cli/commands/doctor.ts +18 -4
  85. package/src/cli/commands/launch-line.ts +32 -0
  86. package/src/cli/commands/status.ts +14 -3
  87. package/src/cli/help.ts +7 -4
  88. package/src/cli/identity.ts +1 -1
  89. package/src/cli/init-roles.ts +1 -1
  90. package/src/cli/init-settings.ts +1 -1
  91. package/src/cli/launch-line-plan.ts +82 -0
  92. package/src/cli/launch-line-project.ts +13 -0
  93. package/src/cli/main.ts +10 -9
  94. package/src/cli/pi-steps-warning.ts +14 -0
  95. package/src/cli/recovery-package.ts +60 -6
  96. package/src/cli/reset.ts +1 -1
  97. package/src/cli/shell-quote.ts +1 -3
  98. package/src/cli/upgrade-interactive.ts +7 -2
  99. package/src/cli/upgrade-keep-plan.ts +47 -0
  100. package/src/cli/upgrade-restore-state.ts +1 -1
  101. package/src/cli/upgrade-runtime.ts +119 -18
  102. package/src/cli/upgrade.ts +17 -2
  103. package/src/hub/accounts.ts +8 -4
  104. package/src/hub/action-class.ts +1 -3
  105. package/src/hub/adec-triage.ts +105 -0
  106. package/src/hub/autonomy.ts +1 -1
  107. package/src/hub/board.ts +3 -27
  108. package/src/hub/bus.ts +39 -6
  109. package/src/hub/capabilities.ts +1 -1
  110. package/src/hub/channel-project-base.ts +46 -0
  111. package/src/hub/channel-project.ts +21 -46
  112. package/src/hub/config-apply.ts +1 -1
  113. package/src/hub/config-edit.ts +1 -1
  114. package/src/hub/config-tier.ts +1 -1
  115. package/src/hub/config.ts +2 -2
  116. package/src/hub/confirmation-matrix.ts +1 -1
  117. package/src/hub/control/board-messages.ts +415 -0
  118. package/src/hub/control/dashboard-messages.ts +221 -0
  119. package/src/hub/control/delivery-messages.ts +356 -0
  120. package/src/hub/control/dispatch.ts +114 -0
  121. package/src/hub/control/hub-tool-helpers.ts +243 -0
  122. package/src/hub/control/hub-tools.ts +147 -0
  123. package/src/hub/control/native-messages.ts +665 -0
  124. package/src/hub/control/operations-messages.ts +269 -0
  125. package/src/hub/control/peer-messages.ts +126 -0
  126. package/src/hub/control/recovery-messages.ts +391 -0
  127. package/src/hub/control/recovery-operation.ts +480 -0
  128. package/src/hub/control/scope.ts +460 -0
  129. package/src/hub/control/sdlc-messages.ts +373 -0
  130. package/src/hub/control/task-ops-more.ts +245 -0
  131. package/src/hub/control/task-ops.ts +553 -0
  132. package/src/hub/control/ui-actions.ts +241 -0
  133. package/src/hub/control-write-trace.ts +1 -4
  134. package/src/hub/daemon.ts +485 -4324
  135. package/src/hub/delivery-hints.ts +2 -0
  136. package/src/hub/delivery-journal.ts +17 -6
  137. package/src/hub/events.ts +2 -1
  138. package/src/hub/execution-reference.ts +1 -1
  139. package/src/hub/host.ts +41 -9
  140. package/src/hub/hub-tools.ts +3 -4
  141. package/src/hub/invocations.ts +1 -1
  142. package/src/hub/lifecycle.ts +4 -3
  143. package/src/hub/mcp-endpoint-serve.ts +4 -3
  144. package/src/hub/mcp-endpoint.ts +15 -6
  145. package/src/hub/memory-profile-check.ts +1 -1
  146. package/src/hub/no-writes.ts +1 -1
  147. package/src/hub/peers.ts +2 -0
  148. package/src/hub/pi-exit-policy.ts +27 -0
  149. package/src/hub/progress.ts +1 -1
  150. package/src/hub/project-runtime-state.ts +17 -4
  151. package/src/hub/project-runtime.ts +3 -1
  152. package/src/hub/protocol-window.ts +1 -1
  153. package/src/hub/recovery-continuity.ts +3 -3
  154. package/src/hub/recovery-kept-roster.ts +50 -0
  155. package/src/hub/review-anchor.ts +13 -181
  156. package/src/hub/review-brief.ts +78 -28
  157. package/src/hub/review-findings.ts +15 -193
  158. package/src/hub/review-ledger.ts +162 -0
  159. package/src/hub/review-material.ts +3 -3
  160. package/src/hub/reviewer-pool.ts +4 -2
  161. package/src/hub/roadmap-issue-states.ts +65 -14
  162. package/src/hub/roadmap-sync.ts +39 -14
  163. package/src/hub/routing.ts +9 -0
  164. package/src/hub/runtime-capture-prune.ts +8 -2
  165. package/src/hub/runtime-package-assets.ts +3 -0
  166. package/src/hub/sdlc-release-policy.ts +1 -2
  167. package/src/hub/settings.ts +1 -1
  168. package/src/hub/spec-ack-tool.ts +4 -0
  169. package/src/hub/spec-report-history.ts +36 -0
  170. package/src/hub/specs.ts +1 -4
  171. package/src/hub/supervision.ts +33 -6
  172. package/src/hub/tasks-audit.ts +390 -0
  173. package/src/hub/tasks-backlog.ts +522 -0
  174. package/src/hub/tasks-handoff.ts +208 -0
  175. package/src/hub/tasks-release.ts +257 -0
  176. package/src/hub/tasks-roadmap.ts +17 -3
  177. package/src/hub/tasks-specs.ts +672 -0
  178. package/src/hub/tasks-types.ts +334 -0
  179. package/src/hub/tasks.ts +286 -1961
  180. package/src/hub/upgrade-session-contract.ts +11 -0
  181. package/src/local/probe-sandbox.ts +1 -2
  182. package/src/local/probe-workspace.ts +1 -1
  183. package/src/models/route/config.ts +4 -4
  184. package/src/models/route/decision.ts +18 -10
  185. package/src/models/route/observation-signals.ts +1 -2
  186. package/src/models/route/runtime.ts +8 -5
  187. package/src/npm-artifact.ts +76 -0
  188. package/src/omniroute/client.ts +6 -0
  189. package/src/pi/extension.ts +5 -2
  190. package/src/pi/install.ts +77 -0
  191. package/src/pi/pin.ts +49 -0
  192. package/src/primitives.ts +14 -0
  193. package/src/version.ts +2 -0
  194. package/templates/adec/README.md +10 -6
  195. package/templates/config.json +1 -1
  196. package/templates/specs.block.md +1 -0
@@ -0,0 +1,522 @@
1
+ // #1830 S4e-2: backlog planning, pulls and notices. Tasks supplies the board write operations.
2
+ import { planningPatch, type PlanningFields } from "./planning.ts";
3
+ import { taskCanPlan, taskHasStarted, isClosedTaskState, type Board, type Task } from "./board.ts";
4
+ import { HUB, newEnvelope, sanitize, USER, type PeerId } from "./envelope.ts";
5
+ import { assign, isRemotePeerId, peerEntry, type Assignment } from "./routing.ts";
6
+ import { realPath } from "./project.ts";
7
+ import { PreEffectToolRefusal } from "./tool-refusal.ts";
8
+ import { definitionOf as builtinDefinitionOf } from "../adapters/registry.ts";
9
+ import { plannerGrooming, plannedStartPending } from "./task-sweep.ts";
10
+ import { planningIssueReceipt, readPlanIssueMetadata, sdlcConfig, type PlanIssueMetadata, sdlcGh } from "./sdlc.ts";
11
+ import type { Tasks } from "./tasks.ts";
12
+ import type { TasksDeps } from "./tasks-types.ts";
13
+
14
+ /** #758: the planner "board changed" notice. Its body starts with this, so an unsettled copy is found (and replaced) by the prefix. */
15
+ const GROOM_NOTICE_PREFIX = "The board changed";
16
+ /** #758: a board change that needs no plan review is recorded at most once per planner in this window. */
17
+ export const GROOM_FYI_WINDOW_MS = 10 * 60_000;
18
+
19
+ interface BacklogHost {
20
+ assignOwner: Tasks["assignOwner"];
21
+ backfillIssueLinks: Tasks["backfillIssueLinks"];
22
+ readonly excluded: Tasks["excluded"];
23
+ explicitQueueAssignment: Tasks["explicitQueueAssignment"];
24
+ fillPick: Tasks["fillPick"];
25
+ fillSlot: Tasks["fillSlot"];
26
+ hasPersonReservation: Tasks["hasPersonReservation"];
27
+ health: Tasks["health"];
28
+ readonly isPii: Tasks["isPii"];
29
+ ownedReadyDependents: Tasks["ownedReadyDependents"];
30
+ ownedReadyNow: Tasks["ownedReadyNow"];
31
+ ownerRefusals: Tasks["ownerRefusals"];
32
+ planIssueIdentity: Tasks["planIssueIdentity"];
33
+ plannerAssignment: Tasks["plannerAssignment"];
34
+ plannerBinding: Tasks["plannerBinding"];
35
+ plannerPullRecord: Tasks["plannerPullRecord"];
36
+ plannerRefusal: Tasks["plannerRefusal"];
37
+ planningAuthority: Tasks["planningAuthority"];
38
+ planningRecorded: Tasks["planningRecorded"];
39
+ prerequisiteOf: Tasks["prerequisiteOf"];
40
+ readonly publicMetadataText: Tasks["publicMetadataText"];
41
+ readonly publicTitle: Tasks["publicTitle"];
42
+ publicView: Tasks["publicView"];
43
+ queueAutoPulls: Tasks["queueAutoPulls"];
44
+ releaseNotice: Tasks["releaseNotice"];
45
+ requestCheck: Tasks["requestCheck"];
46
+ requireCapabilities: Tasks["requireCapabilities"];
47
+ stalled: Tasks["stalled"];
48
+ states: Tasks["states"];
49
+ studyDispatchCheck: Tasks["studyDispatchCheck"];
50
+ taskPlanner: Tasks["taskPlanner"];
51
+ topReservedReady: Tasks["topReservedReady"];
52
+ readonly waitsFor: Tasks["waitsFor"];
53
+ wip: Tasks["wip"];
54
+ wipLimit: Tasks["wipLimit"];
55
+ withholds: Tasks["withholds"];
56
+ saveBacklogPlan: Board["plan"];
57
+ savePlannedPull: Board["pullPlanned"];
58
+ }
59
+
60
+ export class BacklogDomain {
61
+ constructor(private readonly d: TasksDeps, private readonly host: BacklogHost) {}
62
+
63
+ readonly incomingBacklog = new Set<number>();
64
+
65
+ private readonly plannerBacklog = new Map<PeerId, Set<number>>();
66
+
67
+ readonly plannerBlockedQueue = new Map<PeerId, string>();
68
+
69
+ readonly knownPlanners = new Set<PeerId>();
70
+
71
+ /**
72
+ * #758: what the planner board-changed notice has read of the board. `revision` is the board status revision last scanned, `lengths` each task's
73
+ * history length at that scan (so only entries added since are read), `pending` what each planner has not yet been told (`review`: a planning
74
+ * revision or dependency change of a card it plans; `other`: a state move, review or assignment) and `sent` when it was last told.
75
+ * ponytail: a scan lists the whole board once per status revision (at most one per flush); the upgrade is an indexed history read.
76
+ */
77
+ private readonly groomScan = { revision: -1, lengths: new Map<number, number>(), deps: new Map<number, string>(), pending: new Map<PeerId, { review: boolean; other: boolean }>(), sent: new Map<PeerId, { fyiAt: number }>() };
78
+
79
+ readonly autoPullAttached = new Set<PeerId>();
80
+
81
+ autoPullForAttachment(peer: PeerId): void {
82
+ if (this.autoPullAttached.has(peer) || this.d.autoPull?.() !== true) return;
83
+ this.autoPullAttached.add(peer);
84
+ // #1626 B: a ready unowned task also starts a pull, so a reservation is not needed.
85
+ if (this.host.topReservedReady(peer, undefined, true) || this.host.fillPick(peer)) this.host.queueAutoPulls(new Set([peer]), "peer available");
86
+ }
87
+
88
+ /** Write-driven wake-ups (#785): one unsettled ids-only task notice per planner, never a polling pull. */
89
+ writePlannerNotices(task: Task, before: ReadonlyMap<PeerId, number>, approved = false): void {
90
+ this.host.releaseNotice(`task #${task.id}: could not notify planner about ready work`, () => {
91
+ const now = this.d.now?.() ?? Date.now();
92
+ const changes = new Map<PeerId, { capacity: Set<PeerId>; ready: Set<number>; owned: Set<number> }>();
93
+ const add = (planner: PeerId, peer?: PeerId, id?: number, owned?: number) => {
94
+ if (!this.d.bus.isRostered(planner)) return;
95
+ const change = changes.get(planner) ?? { capacity: new Set<PeerId>(), ready: new Set<number>(), owned: new Set<number>() };
96
+ if (peer) change.capacity.add(peer);
97
+ if (id !== undefined) change.ready.add(id);
98
+ if (owned !== undefined) change.owned.add(owned);
99
+ changes.set(planner, change);
100
+ };
101
+ const released = new Set<PeerId>();
102
+ const readied = new Set<PeerId>();
103
+ for (const [peer, used] of before) if (this.host.wip(peer) < used) { released.add(peer); for (const planner of this.host.taskPlanner(task)) add(planner, peer); }
104
+ if (approved) for (const card of this.d.board.list("backlog")) {
105
+ if (card.deps?.includes(task.id) && !this.host.waitsFor(card).length && !plannedStartPending(card, now)) {
106
+ for (const planner of this.host.taskPlanner(card)) add(planner, undefined, card.id);
107
+ if (card.reserved) readied.add(card.reserved);
108
+ }
109
+ }
110
+ // #1801: a dependent that already has an owner is ready too; the planner sees it beside the reserved ready ones.
111
+ if (approved) for (const card of this.host.ownedReadyDependents(task)) for (const planner of this.host.taskPlanner(card)) add(planner, undefined, undefined, card.id);
112
+ for (const [planner, change] of changes) this.host.releaseNotice(`could not notify planner ${planner} about ready work`, () => {
113
+ const pending = this.d.bus.pendingEnvelopes(planner).filter(env => env.from === HUB && env.kind === "task" && env.body.startsWith("Planner work ready:"));
114
+ // The bus retains these hub-written lines across restart; an in-memory cache would lose unsettled events.
115
+ for (const env of pending) for (const line of env.body.split("\n")) {
116
+ const capacity = /^capacity_released: (\S+) WIP \d+; reserved ready (?:#\d+|none)$/.exec(line);
117
+ if (capacity) change.capacity.add(capacity[1]!);
118
+ const ready = /^backlog_ready: #(\d+)$/.exec(line);
119
+ if (ready && Number.isSafeInteger(Number(ready[1]))) change.ready.add(Number(ready[1]));
120
+ const owned = /^owned_ready: #(\d+) \(\S+\)$/.exec(line);
121
+ if (owned && Number.isSafeInteger(Number(owned[1]))) change.owned.add(Number(owned[1]));
122
+ }
123
+ const lines: string[] = [];
124
+ for (const peer of change.capacity) {
125
+ const top = this.host.topReservedReady(peer, planner);
126
+ lines.push(`capacity_released: ${peer} WIP ${this.host.wip(peer)}; reserved ready ${top ? `#${top.id}` : "none"}`);
127
+ }
128
+ for (const id of change.ready) {
129
+ const card = this.d.board.get(id);
130
+ if (card?.state === "backlog" && this.host.taskPlanner(card).includes(planner) && !this.host.waitsFor(card).length && !plannedStartPending(card, now)) lines.push(`backlog_ready: #${id}`);
131
+ else change.ready.delete(id);
132
+ }
133
+ for (const id of change.owned) {
134
+ const card = this.d.board.get(id);
135
+ if (card?.owner && this.host.ownedReadyNow(card) && this.host.taskPlanner(card).includes(planner)) lines.push(`owned_ready: #${id} (${card.owner})`);
136
+ else change.owned.delete(id);
137
+ }
138
+ for (const env of pending) this.d.bus.withdraw(env.id);
139
+ const env = newEnvelope(HUB, sanitize(`Planner work ready:\n${lines.join("\n")}\nRead the current board before planning or pulling work.`), { to: [planner], kind: "task" });
140
+ if (!this.d.bus.publish(env).includes(planner)) throw new Error("the notice was not queued");
141
+ });
142
+ // Only this write's own release or newly ready dependency, never a merged earlier notice.
143
+ if (this.d.autoPull?.() === true) this.host.queueAutoPulls(released);
144
+ if (this.d.autoPull?.() === true) this.host.queueAutoPulls(new Set([...readied].filter(peer => !released.has(peer))), "backlog ready");
145
+ });
146
+ }
147
+
148
+ /** Whether the hub may still start work on its own: the setting is on, and no recovery, shutdown or storage hold is active. Read at entry and again right before the assignment write. */
149
+ autoPullAdmitted(): boolean {
150
+ return this.d.autoPull?.() === true && !this.d.sweepHeld?.() && !this.d.bus.isRecoveryHeld && !this.d.bus.storageError;
151
+ }
152
+
153
+ async autoPull(peer: PeerId, cause: string): Promise<void> {
154
+ if (!this.autoPullAdmitted()) return;
155
+ const card = this.host.topReservedReady(peer, undefined, true);
156
+ if (!card) { await this.host.fillSlot(peer, cause); return; }
157
+ // The planner of record is the card's own: its bound planner, else the first current holder, and it must be rostered. A private card never gets here (topReservedReady skips it).
158
+ const planner = this.host.taskPlanner(card)[0];
159
+ if (!planner || !this.d.bus.isRostered(planner)) return;
160
+ const reason = `auto_pull: ${cause} for ${peer}; hub acted for planner ${planner}`;
161
+ try {
162
+ await this.pullPlanned(HUB, { id: card.id, revision: card.planningRevision ?? 0, reason }, { onBehalfOf: planner, guard: () => {
163
+ if (!this.autoPullAdmitted()) throw new PreEffectToolRefusal("auto pull is no longer admitted: tasks.auto_pull was turned off or a recovery, shutdown or storage hold began");
164
+ const current = this.d.board.get(card.id);
165
+ if (current && plannedStartPending(current, this.d.now?.() ?? Date.now())) throw new PreEffectToolRefusal("auto pull is waiting for the planned start");
166
+ } });
167
+ } catch (e) {
168
+ // A guard refusal is the setting or a hold doing its job, not a failure to report.
169
+ const current = this.d.board.get(card.id);
170
+ if (!this.autoPullAdmitted() || current && plannedStartPending(current, this.d.now?.() ?? Date.now())) return;
171
+ this.host.releaseNotice(`task ${this.host.publicTitle(card)}: auto_pull for ${peer} refused: ${e instanceof Error ? e.message : String(e)}`);
172
+ }
173
+ }
174
+
175
+ /** Keep routing refusals even when other peers also have known WIP or delivery pressure. */
176
+ private pullRefusal(task: Task, assignment: Assignment): string {
177
+ const known = this.host.plannerRefusal(task);
178
+ const routing = this.host.ownerRefusals(assignment);
179
+ return routing ? `${known}; ${routing}` : known;
180
+ }
181
+
182
+ async pullPlanned(by: PeerId, input: { id: number; revision: number; reason: string }, opts: { onBehalfOf?: PeerId; guard?: () => void } = {}): Promise<Task> {
183
+ // #455: one authority check, made before the screen and again after it (a person may move the planner meanwhile).
184
+ // #785 P1c: `by` is the actor the history records; the hub's opt-in auto pull names the planner it acts for, and that planner's authority is what is checked.
185
+ if (opts.onBehalfOf !== undefined && by !== HUB) throw new PreEffectToolRefusal("only the hub pulls on a planner's behalf");
186
+ const planner = opts.onBehalfOf ?? by;
187
+ let queueAssignment: { current: () => void } | undefined;
188
+ // `opts.guard` (the auto pull's own admission, #785 P1c) throws a PreEffectToolRefusal once the pull is no longer wanted; it runs wherever authority is rechecked, so it
189
+ // also runs after the awaited PII screen and right before the assignment write, where a setting turned off or a recovery that began meanwhile must still stop it.
190
+ const instructionCheck = this.host.requestCheck(by);
191
+ const authorized = () => { instructionCheck(); this.host.planningAuthority(planner); opts.guard?.(); queueAssignment?.current(); };
192
+ authorized();
193
+ if (!Number.isSafeInteger(input.id) || input.id <= 0 || !Number.isSafeInteger(input.revision) || input.revision < 0 || typeof input.reason !== "string" || !input.reason.trim() || input.reason.length > 1000) throw new PreEffectToolRefusal("planner pull needs an id, revision and bounded reason");
194
+ queueAssignment = by !== HUB && opts.onBehalfOf === undefined && this.d.board.get(input.id)?.reserved
195
+ ? this.host.explicitQueueAssignment(by, "owner", true) : undefined;
196
+ queueAssignment?.current();
197
+ const validate = () => {
198
+ const task = this.d.board.get(input.id);
199
+ if (task?.draft) throw new PreEffectToolRefusal(`task #${task.id} is an intake draft; the person approves it first`);
200
+ if (!task || (task.planningRevision ?? 0) !== input.revision || task.state !== "backlog" || task.owner || !taskCanPlan(task) || task.pinned) throw new PreEffectToolRefusal("planner pull changed, pinned or already started");
201
+ // #1176: the one gate every agent pull passes (a planner's hub_backlog_pull and the opt-in auto pull alike): a person-run leg is never pulled into an agent's To Do.
202
+ if (task.needsPerson) throw new PreEffectToolRefusal(`task #${task.id} is a person-run leg: it waits on the person (live receipts, their accounts or approvals), so no agent is offered it; the person runs it or clears the mark with ahub backlog plan`);
203
+ this.host.planningAuthority(planner, task);
204
+ const release = task.release == null ? undefined : this.d.board.release(task.release);
205
+ if (task.release != null && (!release || ["frozen", "shipped", "dropped"].includes(release.state))) throw new PreEffectToolRefusal("planner pull requires unfrozen release scope");
206
+ // refusal:by-design world-action: the dependency needs its own approval before this pull can proceed
207
+ if (this.host.waitsFor(task).length) throw new PreEffectToolRefusal("planner pull waits for dependency approval");
208
+ const priority = task.priority ?? (task.signals.includes("urgent") ? 0 : 2);
209
+ if (priority === 0) {
210
+ const goals = this.d.board.list().filter(goal => !isClosedTaskState(goal.state) && (goal.priority ?? (goal.signals.includes("urgent") ? 0 : 2)) === 0 && goal.rank != null && goal.history.some(entry => entry.by === USER && entry.planning?.fields.includes("rank")));
211
+ const effectiveOrder = (candidate: Task) => goals.filter(goal => goal.id === candidate.id || this.host.prerequisiteOf(goal, candidate.id)).map(goal => ({ rank: goal.rank!, id: goal.id })).sort((a,b) => a.rank-b.rank || a.id-b.id)[0];
212
+ const order = effectiveOrder(task) ?? { rank: task.rank ?? Number.MAX_SAFE_INTEGER, id: task.id };
213
+ if (this.d.board.list("backlog").some(other => {
214
+ if (other.id === task.id || this.host.prerequisiteOf(other, task.id) || (other.priority ?? (other.signals.includes("urgent") ? 0 : 2)) !== 0) return false;
215
+ const competing = effectiveOrder(other);
216
+ return !!competing && (competing.rank < order.rank || competing.rank === order.rank && competing.id < order.id);
217
+ })) throw new PreEffectToolRefusal("a person's P0 backlog order is retained");
218
+ }
219
+ if (task.reserved && this.host.excluded(task).includes(task.reserved)) throw new PreEffectToolRefusal(this.host.plannerRefusal(task));
220
+ const assignment = this.host.plannerAssignment(task, !!task.reserved, this.d.routing(), queueAssignment ? "owner" : undefined);
221
+ if (!assignment.owner) {
222
+ // #1430: an unreserved card names what routing refused instead of dropping it, and every pull refusal names the route out.
223
+ const personReserved = this.host.hasPersonReservation(task);
224
+ const nextStep = personReserved ? "ask the person to change the reservation" : "reserve a peer with hub_backlog_plan fields.reserved, then pull again";
225
+ const refusal = task.reserved
226
+ ? `reserved peer ${task.reserved} cannot take the planner pull: ${assignment.refusals?.find(row => row.role === "owner" && row.peer === task.reserved)?.reason ?? "not eligible"}; ${this.host.plannerRefusal(task)}`
227
+ : this.pullRefusal(task, assignment);
228
+ throw new PreEffectToolRefusal(`${personReserved ? "a person's reservation is retained; " : ""}${refusal}; ${nextStep}`);
229
+ }
230
+ this.host.studyDispatchCheck(task, assignment.owner);
231
+ return { task, owner: assignment.owner, assignment };
232
+ };
233
+ const initial = validate(), withheld = await this.host.withholds("note", input.reason, initial.task);
234
+ authorized();
235
+ const current = validate();
236
+ if (current.task.reserved) {
237
+ return this.host.assignOwner(current.task, by, { candidates: [current.owner], namedOwner: current.owner, planner: true, refuseNamed: "pre", ...(queueAssignment ? { queueOverride: "owner" as const, current: queueAssignment.current } : {}),
238
+ plannerPull: { revision: input.revision, note: input.reason.trim(), withheld, guard: () => {
239
+ authorized();
240
+ const checked = validate();
241
+ // refusal:by-design operator-knowledge: reread the task to identify the current owner and revision before retrying
242
+ if (checked.task.history.length !== current.task.history.length || checked.owner !== current.owner) throw new PreEffectToolRefusal("planner pull changed during admission");
243
+ } } });
244
+ }
245
+ opts.guard?.();
246
+ this.host.studyDispatchCheck(current.task, current.owner);
247
+ const pulled = this.host.savePlannedPull(current.task.id, by, current.owner, input.revision, input.reason.trim(), withheld, this.host.plannerBinding(current.task, current.assignment, true));
248
+ this.host.planningRecorded({ by, task: pulled.id, fields: ["pull", "reserved"], revision: pulled.planningRevision! });
249
+ return pulled;
250
+ }
251
+
252
+ backlogList(by: PeerId): Record<string, unknown>[] {
253
+ this.host.planningAuthority(by);
254
+ return this.d.board.list("backlog").sort((a, b) => (a.rank ?? Number.MAX_SAFE_INTEGER) - (b.rank ?? Number.MAX_SAFE_INTEGER) || a.id - b.id).map(task => this.host.publicView(task));
255
+ }
256
+
257
+ addPlannerBacklog(peer: PeerId, ids: readonly number[]): void {
258
+ if (!this.d.roles?.[peer]?.includes("planner")) return;
259
+ const pending = this.plannerBacklog.get(peer) ?? new Set<number>();
260
+ for (const id of ids) {
261
+ const task = this.d.board.get(id);
262
+ if (task?.state === "backlog" && !task.draft && this.host.taskPlanner(task).includes(peer)) pending.add(id);
263
+ }
264
+ if (pending.size) this.plannerBacklog.set(peer, pending);
265
+ }
266
+
267
+ /**
268
+ * The planner "board changed" notice (#758). Read only what was added to a card's history since the last scan, and tell each attached planner of
269
+ * what it did not write itself and plans (`taskPlanner`, the #525-2 scoping): a planning revision or dependency change (in or outside a
270
+ * `planning` entry) or the creation of a card is a task notice, replacing a copy that
271
+ * is still unsettled so the planner meets the latest revision once; a state move, review or assignment is recorded at `fyi` weight (no turn),
272
+ * at most once per planner per ten minutes. The hub's own bookkeeping entries tell nobody. A planner with no earlier notice gets one task notice
273
+ * (a restart, or the first one after it was attached), as before.
274
+ */
275
+ private groomNotices(configured: readonly PeerId[], planners: readonly PeerId[]): void {
276
+ const scan = this.groomScan, revision = this.d.board.statusRevision(), first = scan.revision < 0;
277
+ if (scan.revision !== revision) {
278
+ for (const task of this.d.board.list()) {
279
+ const seen = scan.lengths.get(task.id), depsKey = JSON.stringify(task.deps ?? []), depsBefore = scan.deps.get(task.id);
280
+ scan.lengths.set(task.id, task.history.length); scan.deps.set(task.id, depsKey);
281
+ if (first || seen === task.history.length && depsBefore === depsKey) continue;
282
+ const holders = this.host.taskPlanner(task);
283
+ const tell = (author: string, review: boolean) => {
284
+ for (const holder of configured) { // every configured planner, so a change made while one was offline is not lost
285
+ if (holder === author || !holders.includes(holder)) continue;
286
+ const pending = scan.pending.get(holder) ?? { review: false, other: false };
287
+ if (review) pending.review = true; else pending.other = true;
288
+ scan.pending.set(holder, pending);
289
+ }
290
+ };
291
+ // A card's creation (a propose, with or without `after`, a split child, a generated card) is new work to consolidate, so it needs a plan review.
292
+ if (seen === undefined) tell(task.history[0]?.by ?? HUB, true);
293
+ for (const entry of seen === undefined ? task.history.slice(1) : task.history.slice(seen)) {
294
+ if (entry.by === HUB && entry.planning === undefined) continue; // the hub's own bookkeeping (lifecycle links, sweeps, holds) is not a board change to tell anyone about
295
+ tell(entry.by, entry.planning !== undefined);
296
+ }
297
+ // Dependencies changed outside a `planning` entry (a propose with `after`, a split, any other write): the same as a planning change.
298
+ // Its author is the last entry's only when this scan saw a new entry; a write with no entry has no known author, so no planner is skipped.
299
+ if (depsBefore !== undefined && depsBefore !== depsKey) tell(seen !== undefined && seen < task.history.length ? task.history.at(-1)!.by : "", true);
300
+ }
301
+ scan.revision = revision;
302
+ }
303
+ const now = this.d.now?.() ?? Date.now();
304
+ const configuredFyiMin = this.d.groomFyiWindowMin?.();
305
+ const fyiWindowMs = configuredFyiMin === undefined ? GROOM_FYI_WINDOW_MS : configuredFyiMin * 60_000;
306
+ for (const peer of planners) {
307
+ const told = scan.sent.get(peer), pending = scan.pending.get(peer);
308
+ const review = told === undefined || pending?.review === true;
309
+ if (!review && !pending?.other) continue;
310
+ if (!review && now - told!.fyiAt < fyiWindowMs) { scan.pending.delete(peer); continue; }
311
+ this.host.releaseNotice(`could not notify planner ${peer} about grooming`, () => {
312
+ if (review) this.sendGroomNotice(peer, revision);
313
+ else this.d.bus.publish(newEnvelope(HUB, `${GROOM_NOTICE_PREFIX} (revision ${revision}): state moves, reviews or assignments only. No plan review is needed.`, { to: [peer], kind: "task", priority: "fyi" }));
314
+ scan.pending.delete(peer);
315
+ scan.sent.set(peer, { fyiAt: review ? told?.fyiAt ?? 0 : now });
316
+ });
317
+ }
318
+ }
319
+
320
+ /** The task-weight notice: an unsettled earlier copy for this planner is withdrawn and replaced, never a second one queued. */
321
+ private sendGroomNotice(peer: PeerId, revision: number): void {
322
+ const body = `${GROOM_NOTICE_PREFIX} (revision ${revision}). Before offering or accepting build work, read hub_planner_groom, consolidate dependencies and priorities, and record hub_plan_review against the current planning revision.`;
323
+ for (const old of this.d.bus.pendingEnvelopes(peer)) if (old.from === HUB && old.kind === "task" && old.body.startsWith(GROOM_NOTICE_PREFIX)) this.d.bus.withdraw(old.id);
324
+ const recipients = this.d.bus.publish(newEnvelope(HUB, body, { to: [peer], kind: "task" }));
325
+ if (!recipients.includes(peer)) throw new Error("the notice was not queued");
326
+ }
327
+
328
+ /** One bounded ids-only batch per attached planner; failed or evicted copies stay pending. */
329
+ flushPlannerNotices(): number {
330
+ const configured = Object.entries(this.d.roles ?? {}).filter(([peer, roles]) => !isRemotePeerId(peer) && roles.includes("planner")).map(([peer]) => peer);
331
+ for (const peer of this.knownPlanners) if (!configured.includes(peer)) {
332
+ this.knownPlanners.delete(peer); this.plannerBacklog.delete(peer); this.plannerBlockedQueue.delete(peer);
333
+ this.groomScan.pending.delete(peer); this.groomScan.sent.delete(peer);
334
+ }
335
+ for (const peer of configured) if (!this.knownPlanners.has(peer)) {
336
+ this.knownPlanners.add(peer);
337
+ const retained = this.d.bus.queuedBacklogIds(peer);
338
+ this.addPlannerBacklog(peer, this.d.board.list("backlog").filter(task => !retained.has(task.id)).map(task => task.id));
339
+ }
340
+ const planners = configured.filter(peer => this.d.bus.isRostered(peer) && this.d.bus.peers.has(peer) && this.d.bus.stateOf(peer) !== "offline");
341
+ if (!planners.length) return 0;
342
+ if ((this.d.sdlc?.config().mode ?? "off") !== "off") this.groomNotices(configured, planners);
343
+ for (const id of this.incomingBacklog) if (this.d.board.get(id)?.state !== "backlog") this.incomingBacklog.delete(id);
344
+ const incoming = [...this.incomingBacklog].sort((a, b) => a - b).slice(0, 64);
345
+ if (incoming.length) {
346
+ for (const peer of configured) {
347
+ const queued = this.d.bus.queuedBacklogIds(peer);
348
+ this.addPlannerBacklog(peer, incoming.filter(id => !queued.has(id)));
349
+ }
350
+ }
351
+ for (const id of incoming) this.incomingBacklog.delete(id);
352
+ const notified = new Set<number>();
353
+ for (const peer of planners) {
354
+ const pending = this.plannerBacklog.get(peer);
355
+ if (!pending) continue;
356
+ for (const id of pending) {
357
+ const task = this.d.board.get(id);
358
+ if (task?.state !== "backlog") pending.delete(id);
359
+ else if (!this.host.taskPlanner(task).includes(peer)) {
360
+ pending.delete(id);
361
+ for (const recipient of this.host.taskPlanner(task)) this.addPlannerBacklog(recipient, [id]);
362
+ }
363
+ }
364
+ const blockedQueue = this.plannerBlockedQueue.get(peer);
365
+ if (blockedQueue !== undefined && blockedQueue === JSON.stringify(this.d.bus.queueIds(peer))) continue;
366
+ this.plannerBlockedQueue.delete(peer);
367
+ const ids = [...pending].sort((a, b) => a - b).slice(0, 64);
368
+ if (!ids.length) continue;
369
+ // Remove before publish: an immediate overflow callback may put this recipient's ids back.
370
+ for (const id of ids) pending.delete(id);
371
+ try {
372
+ const queued = this.d.bus.publish(newEnvelope(HUB, `Backlog items ${ids.map(id => `#${id}`).join(", ")}. Read hub_backlog_list and plan the next work with a reason for each change.`, { to: [peer], kind: "task", refs: { backlog: ids } }));
373
+ if (!queued.includes(peer)) this.addPlannerBacklog(peer, ids);
374
+ for (const id of ids) notified.add(id);
375
+ } catch (error) { this.addPlannerBacklog(peer, ids); throw error; }
376
+ }
377
+ return notified.size;
378
+ }
379
+
380
+ async planBacklog(by: PeerId, input: { id: number; revision: number; fields?: unknown; reason: string }): Promise<Task> {
381
+ const instructionCheck = this.host.requestCheck(by);
382
+ this.host.planningAuthority(by);
383
+ if (!Number.isSafeInteger(input.id) || input.id <= 0 || !Number.isSafeInteger(input.revision) || input.revision < 0) throw new PreEffectToolRefusal("invalid planning identity or revision");
384
+ if (typeof input.reason !== "string" || !input.reason.trim() || input.reason.length > 1000) throw new PreEffectToolRefusal("planning needs a bounded reason");
385
+ let patch: PlanningFields;
386
+ try { patch = planningPatch(input.fields); } catch (error) { throw new PreEffectToolRefusal((error as Error).message); }
387
+ const validate = () => {
388
+ const task = this.d.board.get(input.id);
389
+ // refusal:by-design operator-knowledge: reread the task to select its current planning revision
390
+ if (!task || (task.planningRevision ?? 0) !== input.revision) throw new PreEffectToolRefusal("planning revision changed");
391
+ this.host.planningAuthority(by, task);
392
+ if (patch.sdlc !== undefined) {
393
+ if (task.state !== "backlog" || task.owner || taskHasStarted(task)) throw new PreEffectToolRefusal("issue identity changes require unstarted backlog work");
394
+ if (by !== USER && this.host.isPii(task)) throw new PreEffectToolRefusal("private issue identity changes require the person");
395
+ if (!this.host.isPii(task) && !this.host.publicMetadataText(JSON.stringify(patch.sdlc))) throw new PreEffectToolRefusal("planning identity metadata is private or sensitive");
396
+ }
397
+ // refusal:by-design human-authority: a closed task is final and further work needs a separate task
398
+ if (isClosedTaskState(task.state)) throw new PreEffectToolRefusal("closed work is final");
399
+ // #1176: marking a card an agent already owns (an offer in its queue, or work it accepted) would leave the agent on it: the offer is not withdrawn by a mark. Refused, with the way out named.
400
+ if (patch.needsPerson === true && !task.needsPerson && (task.owner || !["backlog", "proposed"].includes(task.state))) throw new PreEffectToolRefusal(`task #${task.id} is already ${task.owner ? `${task.state} with ${task.owner}` : task.state}: take it off the agent first (its owner declines the offer, or ahub task cancel ${task.id} --reason <text>), then mark it person-run`);
401
+ if (by !== USER && (task.state !== "backlog" || !taskCanPlan(task) || task.pinned || Object.hasOwn(patch, "pinned"))) throw new PreEffectToolRefusal("planner changes only unpinned backlog work");
402
+ // #1176: whether a leg is the person's to run is the person's call, set or cleared: an agent that could clear the mark would put the card back in front of an agent.
403
+ if (by !== USER && (Object.hasOwn(patch, "needsPerson") || task.needsPerson)) throw new PreEffectToolRefusal("a person-run card is the person's to mark and plan: ask the person (ahub backlog plan <id> <revision> '{\"needsPerson\":true|false}' <reason>)");
404
+ if (by !== USER && patch.rank !== undefined && task.history.some(entry => entry.by === USER && entry.planning?.fields.includes("rank"))) throw new PreEffectToolRefusal("a person's backlog order is retained");
405
+ if (by !== USER && Object.hasOwn(patch, "reserved") && this.host.hasPersonReservation(task)) throw new PreEffectToolRefusal("a person's reservation is retained");
406
+ if (Object.hasOwn(patch, "deps") || Object.hasOwn(patch, "reserved")) {
407
+ const returnedUntouched = task.state === "backlog" && !task.owner && taskHasStarted(task) && taskCanPlan(task);
408
+ if (!returnedUntouched) {
409
+ if (task.state !== "backlog" || taskHasStarted(task) || task.owner) throw new PreEffectToolRefusal("dependency and reservation changes require unstarted backlog work");
410
+ }
411
+ const definitionOf = this.d.adapterCatalog?.definitionOf ?? builtinDefinitionOf;
412
+ if (patch.reserved && !definitionOf(patch.reserved, this.d.instances?.()) && !this.d.bus.knownPeers().includes(patch.reserved) && !this.d.routing().classes[task.class]?.peers.includes(patch.reserved)) throw new PreEffectToolRefusal("reserved owner is not a supported or configured peer");
413
+ if (patch.reserved && !this.d.bus.isRostered(patch.reserved)) throw new PreEffectToolRefusal("reserved owner is off roster");
414
+ // #531 D3: a reservation for a peer routing leaves out for good could never be honoured. Say so, and who can lift it.
415
+ if (patch.reserved && this.host.excluded(task).includes(patch.reserved)) throw new PreEffectToolRefusal(`${patch.reserved} is excluded from this task (it declined it or was escalated away from it for good); a reservation for it can never be honoured. Only a person's ahub task assign lifts the exclusion`);
416
+ if (patch.reserved) this.host.requireCapabilities(task, patch.reserved);
417
+ const rows = new Map(this.d.board.list().map(row => [row.id, row]));
418
+ const pending = [...(patch.deps ?? task.deps ?? [])], seen = new Set<number>();
419
+ while (pending.length) {
420
+ const id = pending.pop()!;
421
+ if (id === task.id) throw new PreEffectToolRefusal("planning dependencies would form a cycle");
422
+ if (seen.has(id)) continue;
423
+ seen.add(id);
424
+ const dependency = rows.get(id);
425
+ if (!dependency) throw new PreEffectToolRefusal(`no dependency task #${id}`);
426
+ pending.push(...(dependency.deps ?? []));
427
+ }
428
+ }
429
+ const target = patch.release === undefined ? task.release : patch.release;
430
+ if (target != null && !this.d.board.release(target)) throw new PreEffectToolRefusal("no such release");
431
+ for (const id of new Set([task.release, target])) {
432
+ if (id == null) continue;
433
+ const release = this.d.board.release(id)!;
434
+ if (Object.hasOwn(patch, "release")) this.host.planningAuthority(by, release);
435
+ if (["shipped", "dropped"].includes(release.state)) throw new PreEffectToolRefusal("settled release scope is final");
436
+ if (by !== USER && release.state === "frozen") throw new PreEffectToolRefusal("frozen release changes require a person");
437
+ }
438
+ return task;
439
+ };
440
+ const task = validate(), withheld = await this.host.withholds("note", input.reason, task);
441
+ instructionCheck();
442
+ this.host.planningAuthority(by); // #455: or moved the planner
443
+ const latest = validate(); // a person may have changed planning or frozen a release while the screen ran
444
+ let receipt: Task["sdlc"];
445
+ try { receipt = patch.sdlc === undefined ? undefined : planningIssueReceipt(patch.sdlc, latest.sdlc, this.d.sdlc?.config() ?? sdlcConfig(undefined)); }
446
+ catch (error) { throw new PreEffectToolRefusal((error as Error).message); }
447
+ const updated = this.host.saveBacklogPlan(task.id, by, patch, input.revision, input.reason.trim(), withheld, receipt);
448
+ this.host.planningRecorded({ by, task: task.id, fields: Object.keys(patch), revision: updated.planningRevision! });
449
+ if (updated.state === "backlog" && updated.reserved && ["reserved", "pinned", "deps", "plannedStart", "release", "needsPerson"].some(key => Object.hasOwn(patch, key)) && this.d.autoPull?.() === true)
450
+ this.host.queueAutoPulls(new Set([updated.reserved]), "backlog planned");
451
+ return updated; // persistence/readback failures must never claim no effect
452
+ }
453
+
454
+ async groomingDigest(by: PeerId): Promise<Record<string, unknown>> {
455
+ this.host.planningAuthority(by);
456
+ this.host.backfillIssueLinks(by); // #723: first, bounded, before the slow reads
457
+ const included = (task: Task) => !isClosedTaskState(task.state) || task.state === "cancelled" && task.history.some(entry => !!entry.supersededBy);
458
+ const snapshot = this.d.board.list().filter(included), issues = new Map<string, PlanIssueMetadata>(), attempted = new Set<string>();
459
+ const deadline = performance.now() + 4_000;
460
+ let reads = 0, incomplete = false;
461
+ // ponytail: at most eight metadata reads within four seconds; add paginated revision-bound readback for larger boards.
462
+ for (const listed of snapshot) {
463
+ this.host.planningAuthority(by);
464
+ const task = this.d.board.get(listed.id);
465
+ if (!task || this.host.isPii(task) || isClosedTaskState(task.state)) continue;
466
+ let source: { repo: string; issue: number } | undefined;
467
+ try { source = this.host.planIssueIdentity(task); } catch { continue; }
468
+ if (!source) continue;
469
+ const key = `${source.repo.toLowerCase()}#${source.issue}`;
470
+ if (attempted.has(key)) continue;
471
+ attempted.add(key);
472
+ if (reads >= 8 || performance.now() >= deadline) { incomplete = true; break; }
473
+ reads++;
474
+ const run = this.d.sdlc?.gh ?? sdlcGh;
475
+ const issue = await readPlanIssueMetadata(source.repo, source.issue, (args, timeout, cwd, cap) => run(args, Math.max(1, Math.min(timeout ?? 10_000, deadline - performance.now())), cwd, cap));
476
+ if (issue) issues.set(key, issue);
477
+ }
478
+ this.host.planningAuthority(by);
479
+ const all = this.d.board.list(), current = all.filter(included), visible = current.filter(task => !this.host.isPii(task));
480
+ // Include only bounded public dependency context, so approved intermediate phases do not disappear from reachability.
481
+ const indexed = new Map(all.map(task => [task.id, task])), dependencies = new Map<number, readonly number[]>();
482
+ const pending = visible.slice(0, 500).map(task => task.id).reverse(), visited = new Set<number>();
483
+ while (pending.length && visited.size < 500) {
484
+ const id = pending.pop()!; if (visited.has(id)) continue; visited.add(id);
485
+ const task = indexed.get(id); if (!task || this.host.isPii(task)) continue;
486
+ dependencies.set(id, task.deps ?? []); pending.push(...task.deps ?? []);
487
+ }
488
+ const dependencyTruncated = pending.some(id => !visited.has(id));
489
+ const peers = [...new Set([...Object.keys(this.host.states()), ...current.flatMap(task => task.owner ? [task.owner] : [])])];
490
+ const reviewedIssues = new Map(visible.flatMap(task => task.sdlc?.planReview?.issue ? [[task.id, task.sdlc.planReview.issue] as const] : []));
491
+ const acceptedIssues = new Map(visible.flatMap(task => task.sdlc?.acceptance ? [[task.id, task.sdlc.acceptance] as const] : []));
492
+ const currentNoWrites = new Set(this.host.stalled().filter(stall => stall.cause.kind === "no-writes").map(stall => stall.task));
493
+ const blockers: { task: number; code: string }[] = this.d.board.stalls().filter(stall => stall.cause.kind !== "no-writes" || currentNoWrites.has(stall.task)).map(stall => ({ task: stall.task, code: stall.cause.code }));
494
+ const health = this.host.health(), states = this.host.states(), routing = this.d.routing(), hostBlocks = this.d.plannerBlocks?.() ?? {};
495
+ for (const task of visible.filter(task => !isClosedTaskState(task.state)).slice(0, 500)) {
496
+ const owner = task.owner ?? task.reserved;
497
+ if (owner) for (const code of peerEntry(hostBlocks, owner) ?? []) blockers.push({ task: task.id, code });
498
+ const result = assign(task.state === "backlog" ? { ...task, state: "proposed" } : task, states, routing, { ...health, waitsFor: this.host.waitsFor(task), ...(owner ? { candidates: [owner], namedOwner: owner } : {}) });
499
+ if (!result.owner) for (const refusal of result.refusals ?? []) if (refusal.role === "owner") blockers.push({ task: task.id, code: refusal.code === "instance" || refusal.code === "family" ? "policy" : refusal.code });
500
+ if (this.host.waitsFor(task).length) blockers.push({ task: task.id, code: "dependency" });
501
+ }
502
+ const digest = plannerGrooming(visible, { dependencies, dependencyTruncated, repository: this.d.repository ?? `path:${realPath(this.d.cwd)}`, now: this.d.now?.() ?? Date.now(),
503
+ limits: Object.fromEntries(peers.map(peer => [peer, this.host.wipLimit(peer)])), wip: Object.fromEntries(peers.map(peer => [peer, this.host.wip(peer)])),
504
+ states, issues, reviewedIssues, acceptedIssues, blockers });
505
+ return { ...digest, truncated: digest.truncated || incomplete, ...(current.some(task => this.host.isPii(task)) ? { privateTasks: "withheld" } : {}) };
506
+ }
507
+
508
+ /**
509
+ * What counts toward `owner`'s WIP, split for a refusal and for #1080: `offered` is work handed to the owner that it has not accepted
510
+ * (state proposed), `reserved` is ownerless planner-pulled work held for it, and `accepted` is everything the owner is actually carrying
511
+ * (in progress, changes requested, in review).
512
+ */
513
+ wipSplit(owner: PeerId, except: number): { accepted: Task[]; offered: Task[]; reserved: Task[] } {
514
+ const open = this.d.board.list().filter(other => other.id !== except && !["backlog", "approved", "cancelled"].includes(other.state)
515
+ && (other.owner === owner || !other.owner && other.reserved === owner && this.host.plannerPullRecord(other)?.pull));
516
+ return {
517
+ accepted: open.filter(other => other.owner === owner && other.state !== "proposed"),
518
+ offered: open.filter(other => other.owner === owner && other.state === "proposed"),
519
+ reserved: open.filter(other => !other.owner),
520
+ };
521
+ }
522
+ }