@staix/agent-hub 0.44.0 → 0.46.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 (168) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/README.md +12 -11
  3. package/docs/adding-an-ai-tool.md +1 -0
  4. package/docs/agent-notes/adapters.md +35 -6
  5. package/docs/agent-notes/budget.md +2 -1
  6. package/docs/agent-notes/daemon.md +5 -1
  7. package/docs/agent-notes/local-worker.md +1 -1
  8. package/docs/agent-notes/security-review.md +3 -2
  9. package/docs/agent-notes/tasks.md +6 -2
  10. package/docs/agent-notes/tests.md +4 -3
  11. package/docs/design/adapters.md +20 -2
  12. package/docs/design/agent-hub-architecture.md +12 -0
  13. package/docs/design/agent-hub.md +1 -1
  14. package/docs/design/cli-output.md +2 -0
  15. package/docs/design/roadmap.md +158 -4
  16. package/docs/design/supervision.md +21 -1
  17. package/docs/design/task-board.md +32 -4
  18. package/docs/dogfood.md +28 -4
  19. package/docs/events.md +7 -3
  20. package/docs/influences.md +7 -0
  21. package/docs/memory.md +4 -4
  22. package/docs/operations.md +151 -36
  23. package/docs/quickstart.md +16 -4
  24. package/docs/research.md +16 -0
  25. package/docs/roadmap.json +4 -0
  26. package/docs/roadmap.md +9 -0
  27. package/docs/sdlc.md +15 -3
  28. package/docs/security.md +9 -7
  29. package/docs/smoke.md +1 -1
  30. package/docs/verification/2026-11-05-hardcoded-values-classification-rules.md +28 -0
  31. package/docs/verification/2026-11-19-claude-implementer-2.1.328.md +49 -0
  32. package/docs/verification/2026-11-20-claude-implementer-2.1.329.md +49 -0
  33. package/docs/verification/2026-11-20-sdlc-metrics-diagnosis.md +7 -0
  34. package/docs/verification/2026-11-21-0.45.0.md +69 -0
  35. package/docs/verification/2026-11-22-agy-1.5.14.md +27 -0
  36. package/docs/verification/2026-11-22-claude-instruction-hook.md +35 -0
  37. package/docs/verification/2026-11-22-codex-0171-reviewer-isolation.md +47 -0
  38. package/docs/verification/2026-11-22-instructed-ipc.md +9 -0
  39. package/docs/verification/2026-11-22-jcode-1.0.3.md +71 -0
  40. package/docs/verification/2026-11-22-jcode-separate-home.md +14 -0
  41. package/docs/verification/2026-11-22-qwen-0283-acp.md +28 -0
  42. package/docs/verification/2026-11-22-qwen-0283-dual-output.md +33 -0
  43. package/docs/verification/2026-11-22-roadmap-r5-view-receipt.md +63 -0
  44. package/docs/verification/2026-11-23-0.46.0.md +44 -0
  45. package/docs/verification/assets/1483-r5-detail-1440-light.png +0 -0
  46. package/docs/verification/assets/1483-r5-detail-390-light.png +0 -0
  47. package/docs/verification/assets/1483-r5-view-1440-dark.png +0 -0
  48. package/docs/verification/assets/1483-r5-view-1440-light.png +0 -0
  49. package/docs/verification/assets/1483-r5-view-390-dark.png +0 -0
  50. package/docs/verification/assets/1483-r5-view-390-light.png +0 -0
  51. package/docs/verification/assets/1483-r5-view-820-dark.png +0 -0
  52. package/docs/verification/assets/1483-r5-view-820-light.png +0 -0
  53. package/docs/verified.json +33 -27
  54. package/package.json +3 -2
  55. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  56. package/plugins/agent-hub/kimi-hook.js +4743 -4048
  57. package/plugins/agent-hub/kimi-review-policy-worker.js +5 -5
  58. package/plugins/agent-hub/server.js +1641 -1265
  59. package/plugins/agent-hub/skills/ahub/SKILL.md +17 -0
  60. package/plugins/agent-hub/skills/ahub-manage/SKILL.md +37 -0
  61. package/plugins/agent-hub/skills/ahub-status/SKILL.md +14 -0
  62. package/plugins/agent-hub/skills/ahub-use/SKILL.md +12 -0
  63. package/scripts/check-docs.mjs +9 -1
  64. package/src/adapters/acp.ts +11 -1
  65. package/src/adapters/claude-channel.ts +2 -1
  66. package/src/adapters/compat.ts +15 -14
  67. package/src/adapters/definitions/builtin-metadata.ts +2 -2
  68. package/src/adapters/definitions/native-cli-claude-setup.ts +9 -1
  69. package/src/adapters/definitions/native-cli-doctor.ts +8 -5
  70. package/src/adapters/definitions/native-cli-jcode-home-init.ts +158 -0
  71. package/src/adapters/definitions/native-cli-jcode-home.ts +72 -0
  72. package/src/adapters/definitions/native-cli-jcode-mcp.ts +20 -0
  73. package/src/adapters/definitions/native-cli-skills.ts +29 -0
  74. package/src/adapters/definitions/native-context.ts +10 -0
  75. package/src/adapters/jcode.ts +10 -0
  76. package/src/adapters/local-worker.ts +3 -2
  77. package/src/adapters/pi.ts +15 -4
  78. package/src/cli/claude-profile-hook.ts +40 -3
  79. package/src/cli/console-state.ts +58 -27
  80. package/src/cli/console-usage.ts +5 -3
  81. package/src/cli/console.ts +35 -4
  82. package/src/cli/help.ts +17 -10
  83. package/src/cli/identity.ts +4 -2
  84. package/src/cli/instruction-hook.ts +28 -0
  85. package/src/cli/jcode-mcp.ts +2 -1
  86. package/src/cli/main.js +8 -0
  87. package/src/cli/main.ts +149 -23
  88. package/src/cli/output-standard.ts +3 -55
  89. package/src/cli/output.ts +8 -2
  90. package/src/cli/recovery-package.ts +62 -13
  91. package/src/cli/roadmap-write.ts +59 -0
  92. package/src/cli/roadmap.ts +115 -4
  93. package/src/cli/sdlc-output.ts +4 -0
  94. package/src/cli/setup-homes.ts +1 -0
  95. package/src/cli/setup.ts +1 -1
  96. package/src/cli/skills-install.ts +463 -0
  97. package/src/cli/task-output.ts +1 -1
  98. package/src/cli/upgrade-presentation-flags.ts +1 -1
  99. package/src/cli/upgrade-runtime.ts +10 -6
  100. package/src/hub/agent-mem-range.ts +43 -0
  101. package/src/hub/board.ts +144 -5
  102. package/src/hub/budget-projection.ts +99 -0
  103. package/src/hub/check-runner.ts +25 -1
  104. package/src/hub/claude-launch-proof.ts +5 -1
  105. package/src/hub/conductor.ts +8 -3
  106. package/src/hub/config-apply.ts +6 -3
  107. package/src/hub/config-tier.ts +1 -1
  108. package/src/hub/config-trust.ts +1 -1
  109. package/src/hub/context-window.ts +1 -1
  110. package/src/hub/control-client.ts +9 -2
  111. package/src/hub/cost-governance.ts +11 -7
  112. package/src/hub/daemon.ts +707 -53
  113. package/src/hub/dogfood-read.ts +4 -2
  114. package/src/hub/edit-guard.ts +100 -0
  115. package/src/hub/events.ts +80 -9
  116. package/src/hub/execution-budget.ts +29 -8
  117. package/src/hub/facts.ts +57 -4
  118. package/src/hub/hub-tools.ts +3 -1
  119. package/src/hub/inference.ts +1 -1
  120. package/src/hub/instances.ts +10 -1
  121. package/src/hub/instructed-exact.ts +95 -0
  122. package/src/hub/instructed-intent.ts +64 -0
  123. package/src/hub/instructed-ipc.ts +33 -0
  124. package/src/hub/instructed-runtime.ts +19 -0
  125. package/src/hub/instruction-receipt.ts +218 -0
  126. package/src/hub/lifecycle.ts +6 -1
  127. package/src/hub/log-rotation.ts +130 -0
  128. package/src/hub/manager.ts +46 -3
  129. package/src/hub/memory-profile.ts +137 -21
  130. package/src/hub/no-writes.ts +1 -0
  131. package/src/hub/operational-authority.ts +3 -2
  132. package/src/hub/operational-settings.ts +2 -2
  133. package/src/hub/recovery-store.ts +49 -21
  134. package/src/hub/registry.ts +1 -1
  135. package/src/hub/research-experiments.ts +132 -0
  136. package/src/hub/research-quality.ts +8 -2
  137. package/src/hub/research-record.ts +35 -0
  138. package/src/hub/research.ts +128 -28
  139. package/src/hub/roadmap-check.ts +65 -0
  140. package/src/hub/roadmap-decompose.ts +139 -0
  141. package/src/hub/roadmap-export.ts +27 -0
  142. package/src/hub/roadmap-sync.ts +97 -0
  143. package/src/hub/roadmap.ts +59 -1
  144. package/src/hub/routing.ts +18 -1
  145. package/src/hub/runtime-capture-prune.ts +2 -1
  146. package/src/hub/sdlc-branch-ci.ts +128 -0
  147. package/src/hub/sdlc-merge.ts +6 -3
  148. package/src/hub/sdlc-metrics.ts +19 -5
  149. package/src/hub/sdlc.ts +73 -5
  150. package/src/hub/settings.ts +3 -1
  151. package/src/hub/snapshots.ts +13 -1
  152. package/src/hub/startup-event-seeds.ts +21 -15
  153. package/src/hub/startup-timing.ts +3 -1
  154. package/src/hub/supervision-proposals.ts +10 -2
  155. package/src/hub/supervision-rules.ts +26 -3
  156. package/src/hub/supervision.ts +7 -0
  157. package/src/hub/task-pr.ts +47 -0
  158. package/src/hub/task-worktree.ts +18 -11
  159. package/src/hub/tasks.ts +694 -44
  160. package/src/hub/ui.ts +6 -2
  161. package/src/hub/usage-rollup.ts +77 -22
  162. package/src/local/tools.ts +13 -1
  163. package/src/memory/client.ts +3 -2
  164. package/src/pi/extension.ts +15 -3
  165. package/src/pi/tool-receipts.ts +26 -0
  166. package/src/ui/index.html +342 -8
  167. package/src/ui/plugin.ts +6 -2
  168. package/src/ui/roadmap-model.ts +70 -0
package/src/hub/tasks.ts CHANGED
@@ -1,8 +1,15 @@
1
1
  import { requireConductor } from "./conductor.ts";
2
- import { parseMilestoneInput, parseMilestonePatch, milestoneId, milestoneRevision, milestoneLinkRef, githubRepo, MILESTONE_STATES, type Milestone, type MilestoneLinkKind, type MilestonePatch, type MilestoneState, type MilestoneSuggestion, type SuggestionItemKind } from "./roadmap.ts";
2
+ import { instructedExecution, instructedHistory } from "./instructed-exact.ts";
3
+ import { managedTaskPullRequest } from "./task-pr.ts";
4
+ import { parseMilestoneInput, parseMilestonePatch, milestoneId, milestoneRevision, milestoneLinkRef, githubRepo, MILESTONE_STATES, type Milestone, type MilestoneLinkKind, type MilestonePatch, type MilestoneState, type MilestoneSuggestion, type SuggestionItemKind, type DecomposePart, type DecomposeIntake, type MilestoneDecomposition, type DecompositionAccept } from "./roadmap.ts";
3
5
  import { milestoneViews, type MilestoneView, type RoadmapSnapshot } from "./roadmap-view.ts";
6
+ import { readMirrorSnapshot, planRoadmapMirror, recoverMirrorBinding } from "./roadmap-sync.ts";
7
+ import { roadmapExport } from "./roadmap-export.ts";
8
+ import { checkRoadmap, type DriftMilestone, type RoadmapDrift } from "./roadmap-check.ts";
9
+ import type { RoadmapConfig } from "./roadmap.ts";
4
10
  import { computeUnplaced, withTree, type ReadyToClose, type TreeRollup, type UnplacedResult } from "./roadmap-unplaced.ts";
5
11
  import { buildTriagePrompt, parseTriage, TRIAGE_BATCH, type TriageItem } from "./roadmap-triage.ts";
12
+ import { buildDecomposePrompt, parseDecomposition, planPartPublish, DECOMPOSE_ITEMS, DECOMPOSE_PATHS, type DecomposeItem, type PublishDraft, type PublishPlanPart } from "./roadmap-decompose.ts";
6
13
  import { pathCandidates } from "@staix/agent-mem";
7
14
  import { renderGuidanceVariantV1 } from "./guidance-variants.ts";
8
15
  import { GuidanceProbeFixtureHost, type GuidanceProbeStore } from "./guidance-probe-store.ts";
@@ -76,7 +83,7 @@ import { NoWriteTurns } from "./no-writes.ts";
76
83
  import { readGitHubImport, readGitHubIssuePages, readGitHubMilestonePages, type GitHubSource, type GitHubImportSelection } from "./github-import.ts";
77
84
  import { BACKLOG_SPLIT_SCREEN_TIMEOUT_MS, actualTaskDates, planningPatch, type PlanningFields, type Release, type ReleaseState } from "./planning.ts";
78
85
  import { readMergeQueue, type DeliveryTask, type MergeQueue } from "./sdlc-queue.ts";
79
- import { MERGE_READBACK_DEADLINE_MS, adoptMergeGates, guardedMerge, mergeModeFor, mergeView, readAdoptMergeEvidence, requiredChecksFor, type MergeView } from "./sdlc-merge.ts";
86
+ import { INLINE_MERGE_READBACK_DEADLINE_MS, MERGE_READBACK_DEADLINE_MS, adoptMergeGates, guardedMerge, mergeModeFor, mergeView, readAdoptMergeEvidence, requiredChecksFor, type MergeView } from "./sdlc-merge.ts";
80
87
  import { mirrorVerdict as mirrorToGitHub, type MirrorVerdict } from "./sdlc-mirror.ts";
81
88
  import { CODE_SCOPE_LINE, evidenceOnlyNotice, type ReviewScope } from "./review-scope.ts";
82
89
  import { DEFAULT_MAX_NITS, parseReviewFindings, findingsForHead, findingHead as resolveFindingHead, findingTally, findingFollowUps, positionalFindingId, type ReviewFinding, type ReviewFindingSet } from "./review-findings.ts";
@@ -107,15 +114,15 @@ import { isAbsolute, relative, resolve } from "node:path";
107
114
  import type { Briefs, NativeItem } from "../memory/brief.ts";
108
115
  import type { MemoryClient } from "../memory/client.ts";
109
116
  import { candidateTargetRevision, type CandidateInput, type CandidateStore, extractNodes, looksSecret, PROMOTED_KINDS, taskKey, type GoalView, type Kind, type MemoryStore, type NoteInput, type Scope, type Tier } from "@staix/agent-mem";
110
- import { HOST_SPEC_ACCEPTANCE_CARRY, HOST_MERGE_ADOPTION, parseClaimVerdict, taskClaimIdentity, CLASSES, OUTCOMES_KEPT_MS, ALL_PLAN_KEYS, TASK_MOVE_REASONS, taskCanPlan, taskHasWorkEvidence, taskHasStarted, planningUndoEntry, isClosedTaskState, type TaskStall, type HistoryEntry, type ReviewerHistory, type Board, type Task, type TaskClass, type TaskMoveReason, type TaskPlan, type TaskRefs, type SpecAcceptanceCandidate, type SpecAcceptanceCommit, type PlannerBinding, type SpecAck, type SpecTaskReport } from "./board.ts";
117
+ import { HOST_SPEC_ACCEPTANCE_CARRY, HOST_MERGE_ADOPTION, HOST_ROADMAP_DRAFT, parseClaimVerdict, taskClaimIdentity, CLASSES, OUTCOMES_KEPT_MS, ALL_PLAN_KEYS, TASK_MOVE_REASONS, taskCanPlan, taskHasWorkEvidence, taskHasStarted, planningUndoEntry, isClosedTaskState, type TaskStall, type HistoryEntry, type ReviewerHistory, type Board, type Task, type TaskClass, type TaskMoveReason, type TaskPlan, type TaskRefs, type SpecAcceptanceCandidate, type SpecAcceptanceCommit, type PlannerBinding, type SpecAck, type SpecTaskReport } from "./board.ts";
111
118
  import type { Bus } from "./bus.ts";
112
119
  import { HUB, newEnvelope, NOTE_KINDS, noteLine, sanitize, USER, type Envelope, type PeerId, type PeerState } from "./envelope.ts";
113
120
  import type { PiiVerdict, ScreenItem, ScreenRecord } from "./inference.ts";
114
- import { assign, isRemotePeerId, detectSignals, peerEntry, predictSplit, relayCandidates, writesRepository, ownerRoleOfClass, type Assignment, type InstanceRoutingOptions, type PeerCapabilities, type Routing, type SplitObservation, type SplitPrediction } from "./routing.ts";
121
+ import { assign, expandClassPeers, isRemotePeerId, detectSignals, peerEntry, predictSplit, relayCandidates, writesRepository, ownerRoleOfClass, type Assignment, type InstanceRoutingOptions, type PeerCapabilities, type Routing, type SplitObservation, type SplitPrediction } from "./routing.ts";
115
122
  import { ExecutionBudget, type ExecutionBudgetConfig, type ExecutionBudgetDecision, type ExecutionBudgetStatus, type ExecutionUnit } from "./execution-budget.ts";
116
123
  import { Cohorts, MAX_REQUESTS, type Cohort, type Completion } from "./cohorts.ts";
117
124
  import { realPath } from "./project.ts";
118
- import { TaskRepositories } from "./task-repository.ts";
125
+ import { TaskRepositories, githubOriginRepository } from "./task-repository.ts";
119
126
  import { mainCheckoutWarning } from "./main-checkout.ts";
120
127
  import { PreEffectToolRefusal } from "./tool-refusal.ts";
121
128
  import type { TaskWorktreePort } from "./task-worktree.ts";
@@ -232,11 +239,14 @@ export interface TasksDeps {
232
239
  /** Explicit, read-only inspection remains available when task notices are disabled. */
233
240
  specsRead?: (action: "check" | "covers", paths: readonly string[]) => SpecsCheckReport | SpecsCoverReport;
234
241
  /** R3 (#1481): spec ids with their status, for the unplaced list. Absent or throwing is "unavailable", never "no specs". */
235
- specsList?: () => { specs: { id: string; title: string; status: string | null }[]; errors: number; truncated: boolean };
242
+ specsList?: () => { specs: { id: string; title: string; status: string | null; type?: string; paths?: string[] }[]; errors: number; truncated: boolean };
236
243
  /** R3 (#1481): the model for triage. Absent, off or failing is no suggestion; it carries no authority and links nothing. */
237
244
  roadmapModel?: (system: string, user: string, allowed: () => boolean) => Promise<string | undefined>;
238
245
  /** R3 (#1481): host-only `gh` runner for the roadmap's read-only issue and milestone reads (tests); production uses `sdlc.gh`. */
239
246
  roadmapGh?: SdlcGh;
247
+ /** Host-only origin proof for tests; production reads the project-local Git origin. */
248
+ roadmapOrigin?: () => string | undefined;
249
+ roadmapConfig?: () => RoadmapConfig;
240
250
  /** Host-verified existing symbols at this task's admitted completion head; never plan guesses. */
241
251
  memorySymbolNodes?: (task: Task) => MemorySymbolNodes | undefined;
242
252
  /** Host-only release report selector; derives its answer from committed policy and the in-memory authorization ledger. */
@@ -568,7 +578,9 @@ export interface ExperimentView { attempts: ExperimentAttemptView[]; counts: { a
568
578
  interface ExperimentContext { task: Task; campaign: ResearchCampaignRecord; private: boolean; key: string; fence: ExperimentWriteFence }
569
579
  interface CompletionRefresh { revision: number; commit: string; state: "in_review" | "approved" }
570
580
  interface RefileHeadGuard { recorded?: string }
571
- interface IdentityLink { repo: string; pr: number; basis: { commit?: string; branch?: string } }
581
+ interface IdentityLink { repo: string; pr: number; basis: { commit?: string; branch?: string }; managedRevision?: number }
582
+ const MANAGED_HANDOFF = Symbol("managed worktree handoff");
583
+ type ManagedHandoffRefs = TaskRefs & { [MANAGED_HANDOFF]?: { task: number; owner: PeerId; revision: number; commit: string; branch: string; repo?: string; pr?: number } };
572
584
 
573
585
  /** What one live check of a task's files says as a whole (#317): `unchanged` only when EVERY file measured unchanged. A change outranks a missing file, which outranks one the hub could not read. */
574
586
  export type DeliverableResult = "changed" | "missing" | "unknown" | "unchanged";
@@ -843,6 +855,10 @@ export class Tasks {
843
855
  private readonly planReviewRequests = new Map<number, string>();
844
856
  private readonly repositories: TaskRepositories;
845
857
  private readonly incomingBacklog = new Set<number>();
858
+ /** One accept attempt per (answer, part), so two concurrent accepts of one part make one draft (#1480 R2 part 2). */
859
+ private readonly decompositionAccepts = new Map<string, Promise<unknown>>();
860
+ /** One apply per milestone while it creates issues, so a retried call cannot POST every planned issue twice (#1480 R2 part 3). */
861
+ private readonly roadmapPublishes = new Set<number>();
846
862
  private readonly plannerBacklog = new Map<PeerId, Set<number>>();
847
863
  private readonly plannerBlockedQueue = new Map<PeerId, string>();
848
864
  private readonly knownPlanners = new Set<PeerId>();
@@ -898,7 +914,9 @@ export class Tasks {
898
914
  if (d.bus.stateOf(peer) === "idle") this.autoPullForAttachment(peer);
899
915
  };
900
916
  d.bus.tap((e) => {
901
- if (e.t === "state" && e.state === "offline") this.autoPullAttached.delete(e.peer);
917
+ if (e.t === "state" && e.state === "offline") { this.autoPullAttached.delete(e.peer); this.capacityBackoff.delete(e.peer); }
918
+ // #1626 A2: the back-off ends at the peer's next idle state, and that idle is a trigger to offer it work (B).
919
+ if (e.t === "state" && e.state === "idle" && this.capacityBackoff.delete(e.peer) && this.d.autoPull?.() === true && (this.topReservedReady(e.peer, undefined, true) || this.fillPick(e.peer))) this.queueAutoPulls(new Set([e.peer]), "idle after a capacity decline");
902
920
  if (e.t === "state" && e.state === "idle" && !this.autoPullAttached.has(e.peer) && this.d.autoPull?.() === true) {
903
921
  this.autoPullForAttachment(e.peer);
904
922
  }
@@ -922,7 +940,8 @@ export class Tasks {
922
940
  private autoPullForAttachment(peer: PeerId): void {
923
941
  if (this.autoPullAttached.has(peer) || this.d.autoPull?.() !== true) return;
924
942
  this.autoPullAttached.add(peer);
925
- if (this.topReservedReady(peer, undefined, true)) this.queueAutoPulls(new Set([peer]), "peer available");
943
+ // #1626 B: a ready unowned task also starts a pull, so a reservation is not needed.
944
+ if (this.topReservedReady(peer, undefined, true) || this.fillPick(peer)) this.queueAutoPulls(new Set([peer]), "peer available");
926
945
  }
927
946
 
928
947
  isPii = (task: Pick<Task, "signals">) => task.signals.includes("pii_path") || (task.signals.includes("pii") && this.d.routing().constraints.pii === "local_only");
@@ -1169,10 +1188,10 @@ export class Tasks {
1169
1188
  else this.d.bus.publish(newEnvelope(HUB, body, { to: [peer], kind: "task", refs: { task: String(task.id), taskRecipient } }));
1170
1189
  }
1171
1190
 
1172
- configureExecutionBudget = (config: ExecutionBudgetConfig): ExecutionBudgetStatus | undefined => {
1191
+ configureExecutionBudget = (config: ExecutionBudgetConfig, meta: { reason?: string; by?: string } = {}): ExecutionBudgetStatus | undefined => {
1173
1192
  if (!this.d.executionBudget) return undefined;
1174
1193
  if (config.kind === "task" && (!config.taskId || !this.d.board.get(config.taskId))) throw new Error(`task #${config.taskId ?? "?"} does not exist`);
1175
- return this.d.executionBudget.configure(config);
1194
+ return this.d.executionBudget.configure(config, meta);
1176
1195
  };
1177
1196
  disableExecutionBudget = (id: string): boolean => this.d.executionBudget?.disable(id) ?? false;
1178
1197
  executionBudgetStatus = (id?: string): ExecutionBudgetStatus | ExecutionBudgetStatus[] | undefined => this.d.executionBudget?.status(id);
@@ -1424,6 +1443,7 @@ export class Tasks {
1424
1443
  const screenHistoryText = (text: string, field: string, withheld = false): string => !withheld && this.nameable(text) ? text : `[history ${field} withheld: ${this.whyWithheld(text)}; ahub task show ${task.id}]`;
1425
1444
  const publicHistory = (fullHistory ? history : history.slice(-5)).map(h => ({
1426
1445
  at: h.at, by: h.by, event: h.event,
1446
+ ...(h.instructed && h.instructedPeer && h.instructionReceipt ? { instructed: true, instructedPeer: h.instructedPeer, instructionReceipt: h.instructionReceipt } : {}),
1427
1447
  ...(h.note === undefined ? {} : { note: screenHistoryText(h.note, "note", h.withheld) }),
1428
1448
  ...(h.reviewFindings ? { reviewFindings: !h.withheld && this.findingTextAllowed(task, h.reviewFindings.items) ? h.reviewFindings
1429
1449
  : { ...(h.reviewFindings.head ? { head: h.reviewFindings.head } : {}), tally: findingTally(h.reviewFindings.items), withheld: true } } : {}),
@@ -2617,6 +2637,11 @@ export class Tasks {
2617
2637
  const now = this.studyTime(), deadline = Date.parse(original.contract.stopPolicy.deadline);
2618
2638
  if (deadline <= now || deadline - now > 90 * 86_400_000) throw new PreEffectToolRefusal("study deadline must be in the next ninety days at approval");
2619
2639
  priv ||= latest.private || current.private;
2640
+ const instruction = instructedExecution.getStore();
2641
+ if (instruction?.active) {
2642
+ instruction.current();
2643
+ if (priv || prepared.some(unit => unit.create?.signals?.some(signal => signal === "pii" || signal === "pii_path"))) throw new PreEffectToolRefusal("an instructed study approval cannot create private work; run it in a terminal");
2644
+ }
2620
2645
  if (priv && [...current.adopted.values(), ...current.reused.values()].some(task => !this.isPii(task)))
2621
2646
  throw new PreEffectToolRefusal("a private study cannot retain a public task without changing its authority");
2622
2647
  for (const unit of prepared) if (unit.create) {
@@ -2628,6 +2653,7 @@ export class Tasks {
2628
2653
  const mode = this.d.coordination?.();
2629
2654
  let result: ReturnType<Board["activateCampaign"]>;
2630
2655
  requestCheck();
2656
+ instruction?.beginStudy?.(); // The synchronous board transaction now owns the screened binding.
2631
2657
  try { result = this.d.board.activateCampaign(id, revision, this.d.project, by, now, prepared, current.parent.history.length, priv, { eligibleOwners: this.studyEligibleOwners(original.contract) }); }
2632
2658
  catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "study approval was not saved"); }
2633
2659
  for (const child of result.children) {
@@ -3157,7 +3183,7 @@ export class Tasks {
3157
3183
  private async autoPull(peer: PeerId, cause: string): Promise<void> {
3158
3184
  if (!this.autoPullAdmitted()) return;
3159
3185
  const card = this.topReservedReady(peer, undefined, true);
3160
- if (!card) return;
3186
+ if (!card) { await this.fillSlot(peer, cause); return; }
3161
3187
  // 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).
3162
3188
  const planner = this.taskPlanner(card)[0];
3163
3189
  if (!planner || !this.d.bus.isRostered(planner)) return;
@@ -3176,6 +3202,47 @@ export class Tasks {
3176
3202
  }
3177
3203
  }
3178
3204
 
3205
+ /** The first ready unowned task `peer` could be offered now, or undefined. Read-only. */
3206
+ private fillPick(peer: PeerId): Task | undefined {
3207
+ if (!this.autoPullAdmitted() || this.capacityBackoff.has(peer)) return undefined;
3208
+ const now = this.d.now?.() ?? Date.now();
3209
+ let routing: Routing;
3210
+ try { routing = this.d.routing(); } catch { return undefined; }
3211
+ return this.d.board.list("proposed").filter(task => this.fillEligible(task, peer, routing, now)).sort(this.readyOrder)[0];
3212
+ }
3213
+ private fillEligible(task: Task, peer: PeerId, routing: Routing, now: number, mine = false): boolean {
3214
+ if (task.state !== "proposed" || task.owner || (!mine && (this.offered.has(task.id) || this.readyInFlight.has(task.id))) || (task.reserved && task.reserved !== peer)) return false;
3215
+ if (task.pinned || task.draft || task.needsPerson || this.isPii(task) || this.personUnassigned(task) || plannedStartPending(task, now) || this.waitsFor(task).length) return false;
3216
+ if (task.release != null && !["planning", "active"].includes(this.d.board.release(task.release)?.state ?? "")) return false;
3217
+ if (this.excluded(task).includes(peer)) return false;
3218
+ // `candidates: [peer]` replaces the class's peer list inside assign(), so the class list is checked here: a freed slot never takes a class routing keeps the peer out of. A class with no entry offers nothing.
3219
+ const weights = this.weights(task.class, task);
3220
+ if (!expandClassPeers(routing.classes[task.class]?.peers ?? [], this.states(), weights).includes(peer)) return false;
3221
+ return assign(task, this.states(), routing, { candidates: [peer], exclude: this.excluded(task), excludeOwners: this.hubOfferFull(task), waitsFor: this.waitsFor(task), ...weights }).owner === peer;
3222
+ }
3223
+ /**
3224
+ * #1626 B: no reserved card was ready for `peer`, so offer it the first ready, unowned `proposed` task it is an eligible owner for, in the board's ready order, one per trigger.
3225
+ * Runs on the serialized auto-pull chain through `assignOwner` as the hub with `peer` the only candidate, so every routing gate still runs. A task another offer path holds is skipped.
3226
+ */
3227
+ private async fillSlot(peer: PeerId, cause: string): Promise<void> {
3228
+ const pick = this.fillPick(peer);
3229
+ if (!pick) return;
3230
+ // The check and the slot are one synchronous step, as in offerReady: a second offer must see this one as taking the slot.
3231
+ this.offered.add(pick.id); this.readyInFlight.set(pick.id, peer);
3232
+ try {
3233
+ const fresh = this.d.board.get(pick.id);
3234
+ if (!fresh || !this.autoPullAdmitted() || !this.fillEligible(fresh, peer, this.d.routing(), this.d.now?.() ?? Date.now(), true)) return;
3235
+ const ready = fresh.history.at(-1)?.event === "ready" ? fresh : this.d.board.update(fresh.id, HUB, "ready", {}, `auto_pull: ${cause} for ${peer}`);
3236
+ await this.assignOwner(ready, HUB, { candidates: [peer], current: () => { if (!this.autoPullAdmitted()) throw new PreEffectToolRefusal("auto pull is no longer admitted"); } });
3237
+ } catch (e) {
3238
+ if (e instanceof PreEffectToolRefusal || e instanceof AssignmentUndeliveredError || !this.autoPullAdmitted()) return;
3239
+ this.releaseNotice(`task ${this.publicTitle(pick)}: auto_pull for ${peer} could not offer it: ${e instanceof Error ? e.message : String(e)}`);
3240
+ } finally {
3241
+ this.readyInFlight.delete(pick.id);
3242
+ if (!this.d.board.get(pick.id)?.owner) this.offered.delete(pick.id);
3243
+ }
3244
+ }
3245
+
3179
3246
  /** #784 AC3: the read-only breakdown of `wip` for status, the console and the dashboard: one grouped query for every peer. Admission still reads `wip()`. */
3180
3247
  wipBreakdown(peers: readonly PeerId[]): Record<string, { wip: number; active: number; reviewWait: number; reserved: number; wipLimit: number }> {
3181
3248
  const grouped = this.d.board.plannerWipBreakdown();
@@ -3189,6 +3256,21 @@ export class Tasks {
3189
3256
  while (pending.length) { const id = pending.pop()!; if (id === prerequisite) return true; if (seen.has(id)) continue; seen.add(id); pending.push(...(this.d.board.get(id)?.deps ?? [])); }
3190
3257
  return false;
3191
3258
  }
3259
+ /**
3260
+ * Peers that capacity-declined and have not reported idle since (#1626 A2). A TUI or headless agent works one task per turn, so it declines an offer far below its WIP cap while mid-turn.
3261
+ * ponytail: kept in memory, not derived from history. A restart reattaches every peer idle, which is exactly when the back-off ends, so nothing is lost; deriving it from history would need an idle marker the board does not record.
3262
+ */
3263
+ private readonly capacityBackoff = new Set<PeerId>();
3264
+ /** #1626 A: peers a hub-initiated offer skips: at the WIP cap (counting offers not yet accepted and in flight, as `reservedHold` does), a held queue, or backing off after a capacity decline. */
3265
+ private hubOfferFull(task: Task): PeerId[] {
3266
+ const full = new Set(this.plannerFull(task));
3267
+ for (const peer of Object.keys(this.states())) {
3268
+ if (this.capacityBackoff.has(peer)) { full.add(peer); continue; }
3269
+ const flying = [...this.readyInFlight].filter(([id, p]) => p === peer && id !== task.id && !this.d.board.get(id)?.owner).length;
3270
+ if (this.wip(peer, task.id) + (this.pendingClaims.get(peer) ?? 0) + flying >= this.wipLimit(peer)) full.add(peer);
3271
+ }
3272
+ return [...full];
3273
+ }
3192
3274
  private plannerFull(task: Task): PeerId[] {
3193
3275
  return Object.keys(this.states()).filter(peer => { const queue = this.d.bus.queueSummary(peer); return this.wip(peer, task.id) >= this.wipLimit(peer) || !!queue.heldBy || queue.needsReview > 0; });
3194
3276
  }
@@ -3242,7 +3324,8 @@ export class Tasks {
3242
3324
  let queueAssignment: { current: () => void } | undefined;
3243
3325
  // `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
3244
3326
  // 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.
3245
- const authorized = () => { this.planningAuthority(planner); opts.guard?.(); queueAssignment?.current(); };
3327
+ const instructionCheck = this.requestCheck(by);
3328
+ const authorized = () => { instructionCheck(); this.planningAuthority(planner); opts.guard?.(); queueAssignment?.current(); };
3246
3329
  authorized();
3247
3330
  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");
3248
3331
  queueAssignment = by !== HUB && opts.onBehalfOf === undefined && this.d.board.get(input.id)?.reserved
@@ -3528,7 +3611,9 @@ export class Tasks {
3528
3611
  this.roadmapWriteAuthority(by); this.roadmapStateAuthority(by, state);
3529
3612
  this.roadmapParsed(() => parseMilestonePatch({ state }));
3530
3613
  const row = this.roadmapCurrent(id, state);
3531
- if (row.state !== state) this.d.board.updateMilestone(id, { state }, row.revision, { by, at: this.d.now?.() ?? Date.now(), event: "state", fields: ["state"] });
3614
+ // #1622 family 4: an instructed person verdict records the same three provenance keys task history does, for done and dropped only.
3615
+ const instruction = by === USER && (state === "done" || state === "dropped") ? instructedHistory(by) : {};
3616
+ if (row.state !== state) this.d.board.updateMilestone(id, { state }, row.revision, { by, at: this.d.now?.() ?? Date.now(), event: "state", fields: ["state"], ...instruction });
3532
3617
  return this.roadmapResult(by, id);
3533
3618
  }
3534
3619
 
@@ -3556,6 +3641,227 @@ export class Tasks {
3556
3641
  return row;
3557
3642
  }
3558
3643
 
3644
+ /** Host-sampled GitHub authority is never supplied by a tool argument. */
3645
+ private roadmapRepository(): string {
3646
+ const repo = this.roadmapParsed(() => githubRepo(this.d.repository));
3647
+ let origin: string | undefined;
3648
+ try { origin = this.d.roadmapOrigin ? this.d.roadmapOrigin() : githubOriginRepository(this.d.cwd); } catch { /* unknown is not a trusted origin */ }
3649
+ if (!origin || origin.toLowerCase() !== repo) throw new PreEffectToolRefusal("roadmap GitHub origin is unavailable or does not match this project; inspect the local origin before retrying");
3650
+ return repo;
3651
+ }
3652
+ private roadmapApplyAuthority(by: PeerId): void {
3653
+ this.roadmapReadAuthority(by);
3654
+ if (this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) throw new PreEffectToolRefusal("roadmap writes are held; retry after recovery");
3655
+ if (by !== USER && (!(this.d.roadmapConfig?.().github_write === "conductor") || !this.configuredManualConductor(by) || !this.d.bus.isRostered(by)))
3656
+ throw new PreEffectToolRefusal("GitHub roadmap writes require the person or the configured conductor with roadmap.github_write enabled");
3657
+ }
3658
+
3659
+ /** Render only screened views. Issue writes require an exact preview and fresh authority. */
3660
+ async roadmapExport(by: PeerId, input: { issue?: number; apply?: boolean; confirm?: string } = {}): Promise<{ json: string; markdown: string; fingerprint: string; call?: string[]; applied: boolean }> {
3661
+ const check = this.requestCheck(by, () => this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError ? "roadmap is held by recovery or storage" : undefined);
3662
+ check(); this.roadmapReadAuthority(by);
3663
+ if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some(key => !["issue", "apply", "confirm"].includes(key)) || input.apply !== undefined && typeof input.apply !== "boolean" || input.confirm !== undefined && (typeof input.confirm !== "string" || !/^[a-f0-9]{64}$/.test(input.confirm))) throw new PreEffectToolRefusal("invalid roadmap export options; preview before applying");
3664
+ if (input.issue !== undefined) this.roadmapParsed(() => milestoneId(input.issue));
3665
+ if (input.apply && input.issue === undefined) throw new PreEffectToolRefusal("roadmap export --apply needs an issue; preview with --issue first");
3666
+ if (input.apply) this.roadmapApplyAuthority(by);
3667
+ const rendered = roadmapExport(this.milestoneList(by));
3668
+ const repo = input.issue === undefined ? undefined : this.roadmapRepository();
3669
+ const call = repo === undefined ? undefined : ["api", `repos/${repo}/issues/${input.issue}`, "--hostname", "github.com", "--method", "PATCH", "-f", `body=${rendered.markdown}`];
3670
+ const fingerprint = createHash("sha256").update(JSON.stringify({ repo: repo ?? null, issue: input.issue ?? null, markdown: rendered.markdown })).digest("hex");
3671
+ if (!input.apply) return { ...rendered, fingerprint, ...(call ? { call } : {}), applied: false };
3672
+ if (input.confirm !== fingerprint) throw new PreEffectToolRefusal(`roadmap export preview changed; run ahub roadmap export --issue ${input.issue} and retry with --confirm ${fingerprint}`);
3673
+ check(); this.roadmapApplyAuthority(by); if (this.roadmapRepository() !== repo) throw new PreEffectToolRefusal("roadmap GitHub origin changed; preview again");
3674
+ let result: Awaited<ReturnType<SdlcGh>>;
3675
+ try { result = await this.roadmapGh()(call!, 10_000, undefined, 64 * 1024); }
3676
+ catch { throw new Error("roadmap issue update outcome is unknown; inspect the issue before retrying"); }
3677
+ if (result.code !== 0) throw new Error("roadmap issue update was not confirmed; inspect the issue before retrying");
3678
+ try { check(); this.roadmapApplyAuthority(by); if (this.roadmapRepository() !== repo || roadmapExport(this.milestoneList(by)).markdown !== rendered.markdown) throw new Error("changed"); }
3679
+ catch { throw new Error("roadmap or authority changed after issue update; inspect the issue and preview again"); }
3680
+ return { ...rendered, fingerprint, call, applied: true };
3681
+ }
3682
+
3683
+ /** Build drift only from the same screened views and host-owned evidence as roadmap reads. */
3684
+ async roadmapCheck(by: PeerId, include?: (finding: RoadmapDrift) => boolean): Promise<ReturnType<typeof checkRoadmap>> {
3685
+ const check = this.requestCheck(by); check(); this.roadmapReadAuthority(by);
3686
+ const views = this.milestoneList(by), config = this.d.roadmapConfig?.() ?? { github_mirror: false, github_write: "off" as const }, privacy = JSON.stringify([this.d.routing(), this.d.piiPaths, this.d.deny]);
3687
+ const snapshot = (rows: typeof views) => JSON.stringify([rows, rows.flatMap(view => view.tasks.map(member => this.d.board.get(member.id)))]);
3688
+ const evidence = snapshot(views);
3689
+ const current = () => { check(); this.roadmapReadAuthority(by); if (snapshot(this.milestoneList(by)) !== evidence || JSON.stringify(this.d.roadmapConfig?.() ?? { github_mirror: false, github_write: "off" }) !== JSON.stringify(config) || JSON.stringify([this.d.routing(), this.d.piiPaths, this.d.deny]) !== privacy) throw new PreEffectToolRefusal("roadmap or privacy policy changed while checking; retry ahub roadmap check"); };
3690
+ const rendered = roadmapExport(views), exportStates: (boolean | undefined)[] = [];
3691
+ for (const [path, expected] of [["docs/roadmap.json", rendered.json], ["docs/roadmap.md", rendered.markdown]] as const) {
3692
+ try {
3693
+ const file = await readGuardedDeliverable(path, { cwd: this.d.cwd, deny: this.d.deny ?? [], private: name => matchesPolicy(this.d.cwd, name, this.d.piiPaths ?? [], true) });
3694
+ current(); exportStates.push(Buffer.from(file.data).toString("utf8") === expected);
3695
+ } catch (error) { if (error instanceof PreEffectToolRefusal) throw error; exportStates.push(error instanceof DeliverableRefusal && error.message.includes("does not exist") ? false : undefined); }
3696
+ }
3697
+ const exportMatches = exportStates.includes(false) ? false : exportStates.every(value => value === true) ? true : undefined;
3698
+ current();
3699
+ const refs = new Set<string>();
3700
+ for (const view of views) {
3701
+ for (const issue of view.issues) refs.add(issue.ref);
3702
+ for (const member of view.tasks) {
3703
+ const task = this.d.board.get(member.id); if (!task) continue;
3704
+ try { const source = this.planIssueIdentity(task); if (source && this.publicMetadataText(source.repo)) refs.add(`${source.repo.toLowerCase()}#${source.issue}`); } catch { /* ambiguous identity is unknown */ }
3705
+ }
3706
+ }
3707
+ const issueStates = new Map<string, "open" | "closed">(), issueDeadline = performance.now() + 20_000;
3708
+ for (const ref of [...refs].sort().slice(0, 100)) {
3709
+ const match = /^([^#]+)#([1-9][0-9]*)$/.exec(ref); if (!match || issueDeadline <= performance.now()) break;
3710
+ const value = await readPlanIssueMetadata(match[1]!, Number(match[2]), async (args, timeout, cwd, cap) => {
3711
+ current(); const remaining = issueDeadline - performance.now();
3712
+ return remaining > 0 ? this.roadmapGh()([...args.slice(0, 2), "--hostname", "github.com", ...args.slice(2)], Math.min(timeout ?? remaining, remaining), cwd, cap) : { code: 1, stdout: "" };
3713
+ });
3714
+ current(); if (value) issueStates.set(ref, value.state === "CLOSED" ? "closed" : "open");
3715
+ }
3716
+ let mirror: Awaited<ReturnType<typeof readMirrorSnapshot>> | undefined, repo: string | undefined;
3717
+ if (config.github_mirror) {
3718
+ try { repo = this.roadmapRepository(); mirror = await readMirrorSnapshot(repo, this.roadmapGh()); }
3719
+ catch { /* partial or unavailable evidence stays unknown */ }
3720
+ current();
3721
+ }
3722
+ const milestones: DriftMilestone[] = views.map(view => {
3723
+ const tasks = view.tasks.map(member => {
3724
+ const task = this.d.board.get(member.id)!;
3725
+ let issue: string | null | undefined;
3726
+ try { const source = this.planIssueIdentity(task); issue = source ? `${source.repo.toLowerCase()}#${source.issue}` : null; } catch { issue = undefined; }
3727
+ const issueState: "open" | "closed" | "unknown" = issue ? issueStates.get(issue) ?? "unknown" : "unknown";
3728
+ const merge = task.sdlc?.merge?.state === "merged" ? task.sdlc.merge : task.sdlc?.mergeReadback;
3729
+ const mergedAt = merge?.state === "merged" ? merge.cost?.mergedAt ?? undefined : task.sdlc?.pr && task.state === "approved" ? undefined : null;
3730
+ const report = merge?.state === "merged" ? this.currentSpecReport(task) : undefined;
3731
+ const unchangedSpecs = mergedAt === null ? [] : report?.complete && report.errors === 0 && !report.truncated && report.head === merge?.head ? report.unchanged.map(row => row.id) : undefined;
3732
+ return { id: task.id, state: task.state, issue, issueState, feature: /^feat(?:\([^)]*\))?:/i.test(task.title), specIssue: !!task.sdlc?.issue, mergedAt, unchangedSpecs };
3733
+ });
3734
+ const children = view.children.map(id => views.find(row => row.id === id));
3735
+ const open = view.tasks.some(row => !["approved", "cancelled"].includes(row.state)) || view.issues.some(row => issueStates.get(row.ref) === "open") || view.releases.some(row => !["shipped", "dropped", "unknown"].includes(row.state)) || children.some(row => row && !["done", "dropped"].includes(row.state));
3736
+ const uncertain = !!view.withheld || view.issues.some(row => !issueStates.has(row.ref)) || view.releases.some(row => row.state === "unknown") || children.some(row => !row);
3737
+ const merged = view.tasks.some(row => { const task = this.d.board.get(row.id); return task?.sdlc?.merge?.state === "merged" || task?.sdlc?.mergeReadback?.state === "merged"; });
3738
+ let mirrorDiff: boolean | undefined;
3739
+ if (mirror && repo && !view.withheld && view.title !== "[withheld]") {
3740
+ try {
3741
+ const marker = `<!-- ahub-roadmap:${this.d.project}:${view.id} -->`, bound = this.d.board.mirrorMilestone(repo, view.id);
3742
+ const recovered = bound === undefined ? recoverMirrorBinding(marker, view.title, mirror.milestones) : undefined;
3743
+ if (recovered?.kind === "ambiguous" || recovered?.titleConflicts.length) mirrorDiff = true;
3744
+ else {
3745
+ const number = bound ?? (recovered?.kind === "bind" ? recovered.number : undefined), remote = number === undefined ? null : mirror.milestones.find(row => row.number === number);
3746
+ if (number === undefined || remote) mirrorDiff = bound === undefined || planRoadmapMirror(repo, { title: view.title, state: view.state === "done" || view.state === "dropped" ? "closed" : "open", marker, issues: view.issues.filter(row => row.ref.startsWith(`${repo}#`)).map(row => Number(row.ref.slice(repo!.length + 1))) }, remote ?? null, mirror.issues).calls.length > 0;
3747
+ }
3748
+ } catch { /* unknown mirror evidence */ }
3749
+ }
3750
+ return { id: view.id, state: view.state, tasks, openItems: open ? true : uncertain ? undefined : false, mergedCode: merged ? true : tasks.some(row => row.mergedAt === undefined) ? undefined : false, specs: view.specs, mirrorDiff };
3751
+ });
3752
+ current(); return checkRoadmap({ milestones, now: this.d.now?.() ?? Date.now(), closeLagMs: 24 * 60 * 60_000, mirrorEnabled: config.github_mirror, exportMatches }, include);
3753
+ }
3754
+
3755
+ /** Serialize at the host caller. Persist only admitted ids-only notices, so unavailable feeds can retry. */
3756
+ async roadmapNotify(taskIds: readonly number[], send: (task: number, milestone: number | null, rule: number, marker: string) => boolean): Promise<number> {
3757
+ if (!taskIds.length) return 0;
3758
+ const views = this.milestoneList(HUB);
3759
+ if (!views.some(view => view.tasks.some(task => taskIds.includes(task.id)))) return 0;
3760
+ const select = (finding: RoadmapDrift) => {
3761
+ const referenced = finding.items.filter(item => /^task:[1-9][0-9]*$/.test(item)).map(item => Number(item.slice(5)));
3762
+ const eligible = views.filter(view => finding.milestone === null || view.id === finding.milestone).flatMap(view => view.tasks.map(task => task.id));
3763
+ const marker = createHash("sha256").update(JSON.stringify([finding.rule, finding.milestone, finding.items, finding.cause])).digest("hex");
3764
+ return !this.d.board.hasRoadmapNotice(marker) && taskIds.some(id => eligible.includes(id) && (!referenced.length || referenced.includes(id)));
3765
+ };
3766
+ const checked = await this.roadmapCheck(HUB, select);
3767
+ let sent = 0;
3768
+ for (const finding of checked.findings) {
3769
+ const referenced = finding.items.filter(item => /^task:[1-9][0-9]*$/.test(item)).map(item => Number(item.slice(5)));
3770
+ const eligible = views.filter(view => finding.milestone === null || view.id === finding.milestone).flatMap(view => view.tasks.map(task => task.id));
3771
+ const task = taskIds.find(id => eligible.includes(id) && (!referenced.length || referenced.includes(id)));
3772
+ if (task === undefined) continue;
3773
+ const marker = createHash("sha256").update(JSON.stringify([finding.rule, finding.milestone, finding.items, finding.cause])).digest("hex");
3774
+ if (this.d.board.hasRoadmapNotice(marker)) continue;
3775
+ const latest = this.d.board.get(task);
3776
+ if (!latest || this.isPii(latest) || !this.milestoneList(HUB).some(view => (finding.milestone === null || view.id === finding.milestone) && view.tasks.some(row => row.id === task))) continue;
3777
+ if (send(task, finding.milestone, finding.rule, marker) && this.d.board.recordRoadmapNotice(marker)) sent++;
3778
+ }
3779
+ return sent;
3780
+ }
3781
+
3782
+ /** Preview every fixed GitHub call from a complete inventory; confirmation binds both calls and local bindings. */
3783
+ async roadmapSync(by: PeerId, input: { apply?: boolean; confirm?: string } = {}): Promise<{ repo: string; calls: string[][]; bindings: { milestone: number; number: number }[]; fingerprint: string; applied: boolean }> {
3784
+ this.roadmapReadAuthority(by);
3785
+ if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some(key => key !== "apply" && key !== "confirm") || typeof input.apply !== "undefined" && typeof input.apply !== "boolean" || input.confirm !== undefined && (typeof input.confirm !== "string" || !/^[a-f0-9]{64}$/.test(input.confirm))) throw new PreEffectToolRefusal("invalid roadmap sync options; preview before applying");
3786
+ if (input.apply) this.roadmapApplyAuthority(by);
3787
+ const config = this.d.roadmapConfig?.() ?? { github_mirror: false, github_write: "off" as const };
3788
+ if (!config.github_mirror) throw new PreEffectToolRefusal("roadmap GitHub mirror is off; enable roadmap.github_mirror in trusted configuration before syncing");
3789
+ const repo = this.roadmapRepository(), views = this.milestoneList(by);
3790
+ if (views.length > 100) throw new PreEffectToolRefusal("roadmap mirror exceeds 100 milestones; narrow the roadmap before syncing");
3791
+ const deadline = performance.now() + 50_000;
3792
+ const stamp = () => createHash("sha256").update(JSON.stringify([this.d.board.milestones(), this.d.board.milestoneLinks(), this.d.board.list(), views.map(view => [view.id, this.d.board.mirrorMilestone(repo, view.id)]), this.d.roadmapConfig?.(), this.d.routing(), this.d.piiPaths, this.d.deny])).digest("hex");
3793
+ let before = stamp(); const check = this.requestCheck(by, () => this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError ? "roadmap is held by recovery or storage" : undefined);
3794
+ const current = () => { check(); this.roadmapReadAuthority(by); if (input.apply) this.roadmapApplyAuthority(by); if (this.roadmapRepository() !== repo || stamp() !== before) throw new PreEffectToolRefusal("roadmap, origin or authority changed; preview sync again"); };
3795
+ const run = this.roadmapGh();
3796
+ const snapshot = await readMirrorSnapshot(repo, async (...args) => { current(); const result = await run(...args); current(); return result; });
3797
+ current();
3798
+ const bindings: { milestone: number; number: number }[] = [], calls: string[][] = [], createIds: (number | undefined)[] = [], issueOwners = new Set<number>();
3799
+ for (const view of views) for (const issue of view.issues) if (issue.ref.startsWith(`${repo}#`)) {
3800
+ const id = milestoneId(Number(issue.ref.slice(repo.length + 1)));
3801
+ if (issueOwners.has(id)) throw new PreEffectToolRefusal("an issue is linked to multiple roadmap milestones; settle its placement before syncing");
3802
+ issueOwners.add(id);
3803
+ }
3804
+ for (const view of views) {
3805
+ if (view.withheld || view.title === "[withheld]" || view.outcome === "[withheld]") throw new PreEffectToolRefusal("roadmap mirror contains withheld membership or metadata; inspect privacy before syncing");
3806
+ const marker = `<!-- ahub-roadmap:${this.d.project}:${view.id} -->`, bound = this.d.board.mirrorMilestone(repo, view.id);
3807
+ const matching = bound === undefined ? recoverMirrorBinding(marker, view.title, snapshot.milestones) : undefined;
3808
+ if (matching?.kind === "ambiguous" || matching?.titleConflicts.length) throw new PreEffectToolRefusal("roadmap GitHub milestone identity is ambiguous; inspect matching milestones before syncing");
3809
+ const remoteId = bound ?? (matching?.kind === "bind" ? matching.number : undefined);
3810
+ if (bound === undefined && remoteId !== undefined) bindings.push({ milestone: view.id, number: remoteId });
3811
+ const remote = remoteId === undefined ? null : snapshot.milestones.find(row => row.number === remoteId);
3812
+ if (remoteId !== undefined && !remote) throw new PreEffectToolRefusal("recorded GitHub milestone is missing from the complete inventory; inspect the binding");
3813
+ const issues = view.issues.filter(row => row.ref.startsWith(`${repo}#`)).map(row => Number(row.ref.slice(repo.length + 1)));
3814
+ const planned = planRoadmapMirror(repo, { title: view.title, state: view.state === "done" || view.state === "dropped" ? "closed" : "open", issues, marker }, remote ?? null, snapshot.issues);
3815
+ for (const call of planned.calls) {
3816
+ const detached = /^repos\/[^/]+\/[^/]+\/issues\/([1-9][0-9]*)$/.exec(call[1] ?? "");
3817
+ if (detached && call.includes("milestone=null") && issueOwners.has(Number(detached[1]))) continue;
3818
+ calls.push(call); createIds.push(remoteId === undefined ? view.id : undefined);
3819
+ if (calls.length > 200) throw new PreEffectToolRefusal("roadmap mirror exceeds 200 writes; narrow the roadmap before syncing");
3820
+ }
3821
+ }
3822
+ const hiddenIssues = new Set<number>();
3823
+ for (const task of this.d.board.list()) if (this.isPii(task) || task.signals.includes("pii") || task.signals.includes("pii_path")) {
3824
+ try { const issue = this.planIssueIdentity(task); if (issue?.repo.toLowerCase() === repo) hiddenIssues.add(issue.issue); }
3825
+ catch { throw new PreEffectToolRefusal("private issue placement is unknown; inspect privacy before syncing"); }
3826
+ }
3827
+ if (calls.some(call => { const match = /^repos\/[^/]+\/[^/]+\/issues\/([1-9][0-9]*)$/.exec(call[1] ?? ""); return !!match && hiddenIssues.has(Number(match[1])); })) throw new PreEffectToolRefusal("roadmap mirror would change private issue membership; inspect privacy before syncing");
3828
+ const fingerprint = createHash("sha256").update(JSON.stringify({ repo, bindings, calls })).digest("hex");
3829
+ if (!input.apply) return { repo, calls, bindings, fingerprint, applied: false };
3830
+ if (input.confirm !== fingerprint) throw new PreEffectToolRefusal(`roadmap sync preview changed; run ahub roadmap sync and retry with --confirm ${fingerprint}`);
3831
+ let effects = false;
3832
+ const effectCurrent = () => { try { current(); } catch (error) { if (effects) throw new Error("roadmap sync authority changed after effects; inspect the mirror and preview again before retrying"); throw error; } };
3833
+ effectCurrent();
3834
+ for (const binding of bindings) {
3835
+ effectCurrent();
3836
+ try { this.d.board.bindMirrorMilestone(repo, binding.milestone, binding.number); effects = true; before = stamp(); }
3837
+ catch (error) { if (effects) throw new Error("roadmap binding changed after effects; inspect the mirror and preview again"); throw error; }
3838
+ }
3839
+ for (let index = 0; index < calls.length; index++) {
3840
+ effectCurrent();
3841
+ let result: Awaited<ReturnType<SdlcGh>>;
3842
+ const remaining = deadline - performance.now();
3843
+ if (remaining <= 0) { if (effects) throw new Error("roadmap sync reached its deadline after effects; inspect the mirror and preview again"); throw new PreEffectToolRefusal("roadmap sync deadline expired before writes; preview again"); }
3844
+ effects = true;
3845
+ try { result = await run(calls[index]!, Math.min(10_000, remaining), undefined, 64 * 1024); }
3846
+ catch { throw new Error("roadmap GitHub write outcome is unknown; inspect the mirror and preview again before retrying"); }
3847
+ if (result.code !== 0 || Buffer.byteLength(result.stdout) > 64 * 1024) throw new Error("roadmap GitHub write was not confirmed; inspect the mirror and preview again before retrying");
3848
+ const local = createIds[index];
3849
+ if (local !== undefined) {
3850
+ let number: number;
3851
+ try {
3852
+ const created = JSON.parse(result.stdout) as Record<string, unknown>, call = calls[index]!;
3853
+ number = milestoneId(created.number);
3854
+ if (created.title !== call.find(value => value.startsWith("title="))?.slice(6) || created.description !== call.find(value => value.startsWith("description="))?.slice(12) || created.state !== call.find(value => value.startsWith("state="))?.slice(6) || typeof created.html_url !== "string" || created.html_url.toLowerCase() !== `https://github.com/${repo}/milestone/${number}`) throw new Error("mismatch");
3855
+ } catch { throw new Error("roadmap milestone creation was not confirmed; preview again to recover its marker"); }
3856
+ effectCurrent();
3857
+ try { this.d.board.bindMirrorMilestone(repo, local, number); before = stamp(); }
3858
+ catch { throw new Error("roadmap milestone was created but its binding is uncertain; preview again to recover its marker"); }
3859
+ }
3860
+ effectCurrent();
3861
+ }
3862
+ return { repo, calls, bindings, fingerprint, applied: true };
3863
+ }
3864
+
3559
3865
  // ---- R3 (#1481): bottom-up placement. Reads are the roadmap read authority; every write below is the R1 writer, never a new one. ----
3560
3866
 
3561
3867
  /** The one repository the roadmap reads from GitHub: the caller's choice, else the project's. Never derived from model text. */
@@ -3635,6 +3941,222 @@ export class Tasks {
3635
3941
  return done(saved, parsed.dropped + parsed.suggestions.length - saved.length, null);
3636
3942
  }
3637
3943
 
3944
+ /**
3945
+ * R2 (#1480) part 1: ask the hub's model how one milestone decomposes. The model sees only the milestone's public text, the
3946
+ * specs it links and the issues it links; each part must cite an id it was shown, and the answer is saved as a hub-attributed
3947
+ * model answer. Nothing is intaken, linked, published or accepted here.
3948
+ */
3949
+ async roadmapDecompose(by: PeerId, rawId: unknown, run?: SdlcGh): Promise<{ milestone: number; parts: DecomposePart[]; dropped: number; saved: MilestoneDecomposition | null; unavailable: string | null }> {
3950
+ const current = this.roadmapWriteAuthority(by);
3951
+ const id = this.roadmapParsed(() => milestoneId(rawId)), view = this.milestoneShow(by, id);
3952
+ current();
3953
+ if (view.title === "[withheld]" || view.outcome === "[withheld]") throw new PreEffectToolRefusal("milestone text is not cleared for public planning; remove private content before ahub roadmap decompose");
3954
+ const done = (parts: DecomposePart[], dropped: number, saved: MilestoneDecomposition | null, unavailable: string | null) => ({ milestone: id, parts, dropped, saved, unavailable });
3955
+ const publicText = (value: string): boolean => { try { return this.publicMetadataText(value); } catch { return false; } };
3956
+ let rows: { id: string; title: string; status: string | null; type?: string; paths?: string[] }[] | undefined;
3957
+ try { const list = this.d.specsList?.(); if (list && !list.truncated && list.errors === 0) rows = list.specs; } catch { rows = undefined; }
3958
+ const linked = new Set(view.specs.map(row => row.id));
3959
+ // Every field that enters the prompt passes the same public screen R3's unplaced list uses; a spec that fails it is not
3960
+ // offered at all, exactly as an unplaced spec is dropped from triage.
3961
+ const summaries = (rows ?? []).filter(row => linked.has(row.id)
3962
+ && [row.id, row.title, ...(row.type ? [row.type] : []), ...(row.status ? [row.status] : []), ...(row.paths ?? []).slice(0, DECOMPOSE_PATHS)].every(publicText));
3963
+ // The milestone's own context is the goal and architecture specs it links; when it links only other types, those are its context.
3964
+ const top = summaries.filter(row => row.type === "goal" || row.type === "architecture");
3965
+ const specs: DecomposeItem[] = (top.length ? top : summaries).map(row => ({ ref: row.id, label: `spec ${row.id}`,
3966
+ text: `${row.title} (${row.type || "spec"}${row.status ? `, ${row.status}` : ""})${row.paths?.length ? ` covers: ${row.paths.slice(0, DECOMPOSE_PATHS).join(", ")}` : ""}` }));
3967
+ // Titles for linked issues come from the same bounded page read R3 uses. A ref outside that repository, an unreadable
3968
+ // page, or a title the public screen refuses still offers its id with no text, so a part can cite it; the milestone's own
3969
+ // links are the only source of refs.
3970
+ const refs = view.issues.map(row => row.ref), first = refs.length ? /^([^#]+)#[1-9][0-9]*$/.exec(refs[0]!)![1]! : undefined;
3971
+ const titles = new Map<string, string>();
3972
+ if (first !== undefined) {
3973
+ try { const page = await readGitHubIssuePages({ repo: first }, this.roadmapGh(run)); current(); for (const row of page.rows) if (publicText(row.title)) titles.set(`${page.repo}#${row.number}`, row.title); }
3974
+ catch { /* unavailable titles are not an empty list: the ref is still offered */ }
3975
+ }
3976
+ const issues: DecomposeItem[] = refs.map(ref => ({ ref, label: `issue ${ref}`, text: titles.get(ref) ?? "" }));
3977
+ if (!specs.length && !issues.length) return done([], 0, null, "the milestone links no spec or issue to decompose from");
3978
+ if (!this.d.roadmapModel) return done([], 0, null, "no hub model is configured for roadmap decompose");
3979
+ const prompt = buildDecomposePrompt({ milestone: { id, title: view.title, outcome: view.outcome }, specs: specs.slice(0, DECOMPOSE_ITEMS), issues: issues.slice(0, DECOMPOSE_ITEMS) });
3980
+ const answer = await this.d.roadmapModel(prompt.system, prompt.user, () => { try { current(); return true; } catch { return false; } });
3981
+ current();
3982
+ if (!answer) return done([], 0, null, "the hub model gave no answer; retry ahub roadmap decompose later");
3983
+ const parsed = parseDecomposition(answer, prompt), kept: DecomposePart[] = [];
3984
+ for (const part of parsed.parts) {
3985
+ // Re-screen at the write, exactly as triage does: what is stored is public planning text only.
3986
+ const text = [part.title, part.detail, ...part.cites].join("\n");
3987
+ if (!this.publicMetadataText(text)) continue;
3988
+ if (this.screenOn() && (await this.screenCall(text)).label !== "clear") continue;
3989
+ current(); kept.push(part);
3990
+ }
3991
+ const dropped = parsed.dropped + parsed.parts.length - kept.length;
3992
+ if (!kept.length) return done([], dropped, null, null);
3993
+ const saved = this.d.board.addDecomposition({ milestone: id, parts: kept }, HUB, this.d.now?.() ?? Date.now());
3994
+ return done(kept, dropped, saved, null);
3995
+ }
3996
+
3997
+ /**
3998
+ * R2 (#1480) part 2: accept one proposed part as a held intake draft. The draft is the existing intake hold (`draft` and
3999
+ * `backlog`): nothing offers, pulls or routes it until the person approves it with `ahub intake approve`, and this path grants
4000
+ * no new release authority. It carries the milestone link and the part's `spec`/`task` kind, each part is accepted on its own,
4001
+ * and a second accept of the same part returns the draft the first one made. The reply is a public view, so a private draft
4002
+ * reads `[withheld]` and no notice repeats the part's words. One accept per part runs at a time: a concurrent caller waits for
4003
+ * the attempt in flight and then reads the accept row, so two accepts of one part cannot make two drafts.
4004
+ */
4005
+ async roadmapDecomposePart(by: PeerId, rawId: unknown, rawPart: unknown): Promise<{ milestone: number; part: number; intake: DecomposeIntake; task: Record<string, unknown>; created: boolean }> {
4006
+ const current = this.roadmapWriteAuthority(by);
4007
+ const id = this.roadmapParsed(() => milestoneId(rawId)), part = this.roadmapParsed(() => milestoneId(rawPart));
4008
+ const view = this.milestoneShow(by, id);
4009
+ current();
4010
+ if (view.title === "[withheld]" || view.outcome === "[withheld]") throw new PreEffectToolRefusal("milestone text is not cleared for public planning; remove private content before accepting a part");
4011
+ const pending = this.d.board.pendingDecomposition(id);
4012
+ if (!pending) throw new PreEffectToolRefusal(`milestone ${id} has no pending decomposition; run ahub roadmap decompose ${id} first`);
4013
+ if (part > pending.parts.length) throw new PreEffectToolRefusal(`milestone ${id} holds ${pending.parts.length} proposed part${pending.parts.length === 1 ? "" : "s"}; run ahub roadmap decompose ${id} to read them again`);
4014
+ const chosen = pending.parts[part - 1]!;
4015
+ // A retry reads the draft the first accept made, and records the link again if an interrupted tail lost it.
4016
+ const earlier = this.roadmapAcceptedPart(by, id, pending.id, part);
4017
+ if (earlier) return earlier;
4018
+ const taskClass = CLASSES.includes(chosen.class as TaskClass) ? chosen.class as TaskClass : undefined;
4019
+ if (!taskClass) throw new PreEffectToolRefusal(`part ${part} names no hub task class; run ahub roadmap decompose ${id} to replace the answer`);
4020
+ // A milestone settled while its answer was pending refuses here, before any write. The same check runs again where the link
4021
+ // is written, and there it is best-effort: the draft is durable by then.
4022
+ this.roadmapCurrent(id);
4023
+ current();
4024
+ // One accept per part: a concurrent caller of the same part waits for the attempt in flight and then reads the accept row.
4025
+ const key = `${pending.id}:${part}`, running = this.decompositionAccepts.get(key);
4026
+ if (running) {
4027
+ await running.catch(() => undefined);
4028
+ const after = this.roadmapAcceptedPart(by, id, pending.id, part);
4029
+ if (after) return after;
4030
+ if (this.d.board.pendingDecomposition(id)?.id !== pending.id) throw new PreEffectToolRefusal(`milestone ${id} has a newer decomposition answer; run ahub roadmap decompose ${id} to read it again`);
4031
+ }
4032
+ const attempt = this.acceptDecompositionPartOnce(by, id, part, pending, chosen, taskClass);
4033
+ this.decompositionAccepts.set(key, attempt);
4034
+ try { return await attempt; } finally { if (this.decompositionAccepts.get(key) === attempt) this.decompositionAccepts.delete(key); }
4035
+ }
4036
+
4037
+ /** The accept row's own draft, while that task exists: the retry's answer, with the milestone link recorded again. */
4038
+ private roadmapAcceptedPart(by: PeerId, id: number, decomposition: number, part: number): { milestone: number; part: number; intake: DecomposeIntake; task: Record<string, unknown>; created: boolean } | undefined {
4039
+ const accepted = this.d.board.decompositionAccept(decomposition, part), earlier = accepted ? this.d.board.get(accepted.task) : undefined;
4040
+ if (!accepted || !earlier) return undefined;
4041
+ // Idempotent, so a missing link heals here; a milestone settled since refuses that as a notice, never as the caller's refusal.
4042
+ this.releaseNotice(`task #${earlier.id}: milestone ${id} part ${part} accepted without its milestone link`, () => {
4043
+ const milestone = this.roadmapCurrent(id);
4044
+ this.d.board.linkMilestone(id, "task", String(earlier.id), by, milestone.revision, this.d.now?.() ?? Date.now());
4045
+ });
4046
+ return { milestone: id, part, intake: accepted.intake, task: this.publicView(earlier), created: false };
4047
+ }
4048
+
4049
+ /** One accept attempt: the durable draft, then a tail that records the hold and never refuses the caller. */
4050
+ private async acceptDecompositionPartOnce(by: PeerId, id: number, part: number, pending: MilestoneDecomposition, chosen: DecomposePart, taskClass: TaskClass): Promise<{ milestone: number; part: number; intake: DecomposeIntake; task: Record<string, unknown>; created: boolean }> {
4051
+ const draft = await this.propose(by, { [HOST_ROADMAP_DRAFT]: true, title: chosen.title, detail: this.decompositionDraftDetail(chosen, id, part, pending.parts.length), class: taskClass, backlog: true, draft: true });
4052
+ // The task and its hold are saved, so nothing below may fail the caller: a planner is not told about a held draft, and the
4053
+ // accept row, the milestone link and the notice are best-effort in that order.
4054
+ this.incomingBacklog.delete(draft.id);
4055
+ this.releaseNotice(`task #${draft.id}: milestone ${id} part ${part} accepted without its accept record`, () => {
4056
+ this.d.board.acceptDecompositionPart({ decomposition: pending.id, milestone: id, part, task: draft.id, intake: chosen.intake }, by, this.d.now?.() ?? Date.now());
4057
+ });
4058
+ this.releaseNotice(`task #${draft.id}: milestone ${id} part ${part} accepted without its milestone link`, () => {
4059
+ const milestone = this.roadmapCurrent(id);
4060
+ this.d.board.linkMilestone(id, "task", String(draft.id), by, milestone.revision, this.d.now?.() ?? Date.now());
4061
+ });
4062
+ this.releaseNotice(`task #${draft.id}: milestone ${id} part ${part} accepted as a held intake draft`);
4063
+ return { milestone: id, part, intake: chosen.intake, task: this.publicView(this.d.board.get(draft.id) ?? draft), created: true };
4064
+ }
4065
+
4066
+ /** The held draft's detail: the part's own words, then the one line a person reads before releasing it. */
4067
+ private decompositionDraftDetail(part: DecomposePart, milestone: number, index: number, total: number): string {
4068
+ const kind = part.intake === "spec" ? "needs its own spec issue before implementation" : "a mechanical chore that goes straight to a task";
4069
+ return [part.detail, `Milestone ${milestone} part ${index} of ${total}: ${kind}. Cites: ${part.cites.join(", ")}.`, `Held until released: ahub intake approve`].join("\n\n");
4070
+ }
4071
+
4072
+ /**
4073
+ * R2 (#1480) part 3: publish the milestone's held drafts to GitHub. `--publish` plans one issue per held `spec` part from a
4074
+ * complete reading of the holds and writes nothing; apply creates each issue through one gh call and links it to the
4075
+ * milestone: R1's own `issue` link, and the R4 membership field the create carries when the mirror has a binding, so this
4076
+ * path adds no second link. A `task` part is its own held draft, a released draft is no longer the hold's work, a private part
4077
+ * is only counted, and a refused or unconfirmed call leaves the draft held and names the failure.
4078
+ */
4079
+ async roadmapDecomposePublish(by: PeerId, rawId: unknown, input: { apply?: boolean; confirm?: string } = {}): Promise<{
4080
+ milestone: number; repo: string; githubMilestone: number | null; parts: PublishPlanPart[]; calls: string[][];
4081
+ skippedPrivate: number; skippedUnknown: number; fingerprint: string; applied: boolean; created: { part: number; task: number; issue: number }[];
4082
+ }> {
4083
+ const current = this.roadmapWriteAuthority(by);
4084
+ if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some(key => key !== "apply" && key !== "confirm")
4085
+ || input.apply !== undefined && typeof input.apply !== "boolean"
4086
+ || input.confirm !== undefined && (typeof input.confirm !== "string" || !/^[a-f0-9]{64}$/.test(input.confirm)))
4087
+ throw new PreEffectToolRefusal("invalid roadmap publish options; preview with ahub roadmap decompose <id> --publish before applying");
4088
+ if (input.apply && input.confirm === undefined) throw new PreEffectToolRefusal("roadmap decompose --apply needs its preview fingerprint; preview with ahub roadmap decompose <id> --publish first");
4089
+ if (input.apply) this.roadmapApplyAuthority(by);
4090
+ const id = this.roadmapParsed(() => milestoneId(rawId)), view = this.milestoneShow(by, id);
4091
+ if (view.title === "[withheld]" || view.outcome === "[withheld]") throw new PreEffectToolRefusal("milestone text is not cleared for public planning; remove private content before publishing a part");
4092
+ // A milestone settled while its drafts are held refuses here, before any read of GitHub or any write.
4093
+ this.roadmapCurrent(id);
4094
+ current();
4095
+ const repo = this.roadmapRepository(), config = this.d.roadmapConfig?.() ?? { github_mirror: false, github_write: "off" as const };
4096
+ // The GitHub milestone comes from the mirror binding, never from an argument; with the mirror off nothing is attached.
4097
+ const githubMilestone = config.github_mirror ? this.d.board.mirrorMilestone(repo, id) ?? null : null;
4098
+ const drafts: PublishDraft[] = [], held = new Map<number, DecompositionAccept>();
4099
+ let skippedPrivate = 0, skippedUnknown = 0;
4100
+ for (const accept of this.d.board.decompositionAcceptsFor(id)) {
4101
+ const task = this.d.board.get(accept.task);
4102
+ if (!task) continue;
4103
+ const part = this.d.board.decomposition(accept.decomposition)?.parts[accept.part - 1];
4104
+ // Without the answer a part's own words are gone; the draft stays held and the preview says to propose the parts again.
4105
+ const text = part ? [part.title, part.detail, ...part.cites].join("\n") : "";
4106
+ let privatePart = true;
4107
+ try { privatePart = this.isPii(task) || !part || !this.publicMetadataText(text); } catch { privatePart = true; }
4108
+ if (part && !privatePart && this.screenOn()) { const label = (await this.screenCall(text)).label; current(); privatePart = label !== "clear"; }
4109
+ if (!part) { skippedUnknown++; continue; }
4110
+ if (privatePart) { skippedPrivate++; continue; }
4111
+ held.set(task.id, accept);
4112
+ drafts.push({ part: accept.part, task: task.id, intake: accept.intake, title: part.title, detail: part.detail, cites: part.cites,
4113
+ published: this.d.board.decompositionPublish(accept.decomposition, accept.part) ?? null,
4114
+ hold: task.draft === true && task.state === "backlog" ? "held" : "released" });
4115
+ }
4116
+ const planned = planPartPublish({ project: this.d.project, repo, milestone: id, githubMilestone, parts: drafts });
4117
+ const fingerprint = createHash("sha256").update(JSON.stringify({ repo, milestone: id, githubMilestone, calls: planned.calls })).digest("hex");
4118
+ const reply = { milestone: id, repo, githubMilestone, ...planned, skippedPrivate, skippedUnknown, fingerprint, applied: false as boolean, created: [] as { part: number; task: number; issue: number }[] };
4119
+ if (!input.apply) return reply;
4120
+ if (input.confirm !== fingerprint) throw new PreEffectToolRefusal(`roadmap publish preview changed; run ahub roadmap decompose ${id} --publish and retry with --confirm ${fingerprint}`);
4121
+ current(); this.roadmapApplyAuthority(by); if (this.roadmapRepository() !== repo) throw new PreEffectToolRefusal("roadmap GitHub origin changed; preview the publish again");
4122
+ // A retried call whose first attempt is still creating must not POST every planned issue again: `INSERT OR IGNORE` would keep
4123
+ // the first publish row and GitHub would keep both issues. One apply per milestone, refused with the next step it can take.
4124
+ if (this.roadmapPublishes.has(id))
4125
+ throw new PreEffectToolRefusal(`a publish for milestone ${id} is already running; wait for it to finish and run ahub roadmap decompose ${id} --publish again`);
4126
+ this.roadmapPublishes.add(id);
4127
+ try {
4128
+ const creating = planned.parts.filter(row => row.action === "create"), created = reply.created;
4129
+ for (const [index, call] of planned.calls.entries()) {
4130
+ const row = creating[index]!, accept = held.get(row.task)!;
4131
+ // A part an earlier attempt already recorded has its issue: never POST it a second time.
4132
+ if (this.d.board.decompositionPublish(accept.decomposition, row.part) !== undefined) continue;
4133
+ const refused = `roadmap publish was refused for milestone ${id} part ${row.part}; the draft stays held and no issue was linked. Inspect ${repo} before retrying`;
4134
+ let result: Awaited<ReturnType<SdlcGh>>;
4135
+ try { result = await this.roadmapGh()(call, 10_000, undefined, 64 * 1024); }
4136
+ catch { throw new Error(`roadmap publish was not confirmed for milestone ${id} part ${row.part}; the draft stays held and no issue was linked. Inspect ${repo} before retrying`); }
4137
+ if (result.code !== 0 || Buffer.byteLength(result.stdout) > 64 * 1024) throw new Error(refused);
4138
+ let issue: number;
4139
+ try {
4140
+ const made = JSON.parse(result.stdout) as Record<string, unknown>;
4141
+ issue = milestoneId(made.number);
4142
+ if (made.title !== call.find(value => value.startsWith("title="))?.slice(6)
4143
+ || typeof made.html_url !== "string" || made.html_url.toLowerCase() !== `https://github.com/${repo}/issues/${issue}`) throw new Error("mismatch");
4144
+ } catch { throw new Error(`roadmap publish created an issue for milestone ${id} part ${row.part} but its answer was not confirmed; inspect ${repo} before retrying`); }
4145
+ // The issue exists, so nothing below may refuse the caller: the publish record and the milestone link are best effort.
4146
+ this.releaseNotice(`milestone ${id} part ${row.part}: issue ${repo}#${issue} created without its publish record`, () => {
4147
+ this.d.board.recordDecompositionPublish({ decomposition: accept.decomposition, milestone: id, part: row.part, issue }, by, this.d.now?.() ?? Date.now());
4148
+ });
4149
+ this.releaseNotice(`milestone ${id} part ${row.part}: issue ${repo}#${issue} created without its milestone link`, () => {
4150
+ const milestone = this.roadmapCurrent(id);
4151
+ this.d.board.linkMilestone(id, "issue", `${repo}#${issue}`, by, milestone.revision, this.d.now?.() ?? Date.now());
4152
+ });
4153
+ created.push({ part: row.part, task: row.task, issue });
4154
+ }
4155
+ reply.applied = true;
4156
+ return reply;
4157
+ } finally { this.roadmapPublishes.delete(id); }
4158
+ }
4159
+
3638
4160
  /** Apply one suggestion through R1's own writers. A "new milestone" suggestion creates it first; a retry never creates a second. */
3639
4161
  async roadmapAccept(by: PeerId, rawId: unknown): Promise<{ suggestion: MilestoneSuggestion; milestone: MilestoneView }> {
3640
4162
  const current = this.roadmapWriteAuthority(by);
@@ -3762,6 +4284,7 @@ export class Tasks {
3762
4284
  }
3763
4285
 
3764
4286
  async planBacklog(by: PeerId, input: { id: number; revision: number; fields?: unknown; reason: string }): Promise<Task> {
4287
+ const instructionCheck = this.requestCheck(by);
3765
4288
  this.planningAuthority(by);
3766
4289
  if (!Number.isSafeInteger(input.id) || input.id <= 0 || !Number.isSafeInteger(input.revision) || input.revision < 0) throw new PreEffectToolRefusal("invalid planning identity or revision");
3767
4290
  if (typeof input.reason !== "string" || !input.reason.trim() || input.reason.length > 1000) throw new PreEffectToolRefusal("planning needs a bounded reason");
@@ -3819,6 +4342,7 @@ export class Tasks {
3819
4342
  return task;
3820
4343
  };
3821
4344
  const task = validate(), withheld = await this.withholds("note", input.reason, task);
4345
+ instructionCheck();
3822
4346
  this.planningAuthority(by); // #455: or moved the planner
3823
4347
  const latest = validate(); // a person may have changed planning or frozen a release while the screen ran
3824
4348
  let receipt: Task["sdlc"];
@@ -4209,7 +4733,7 @@ export class Tasks {
4209
4733
  return updated; // a failed readback may follow a durable release write
4210
4734
  }
4211
4735
 
4212
- async propose(by: PeerId, input: { title?: string; detail?: string; class?: string; role?: unknown; refs?: TaskRefs; plan?: TaskPlan; owner?: PeerId; after?: unknown; urgent?: unknown; needs_network?: unknown; needs_worktree?: unknown; backlog?: unknown; draft?: unknown; goal?: unknown }, external?: GitHubSource, created?: () => void, fence?: () => string | undefined, hostCreatedHook?: (task: Task) => void): Promise<Task> {
4736
+ async propose(by: PeerId, input: { title?: string; detail?: string; class?: string; role?: unknown; refs?: TaskRefs; plan?: TaskPlan; owner?: PeerId; after?: unknown; urgent?: unknown; needs_network?: unknown; needs_worktree?: unknown; backlog?: unknown; draft?: unknown; goal?: unknown; [HOST_ROADMAP_DRAFT]?: unknown }, external?: GitHubSource, created?: () => void, fence?: () => string | undefined, hostCreatedHook?: (task: Task) => void): Promise<Task> {
4213
4737
  const requestCheck = this.requestCheck(by, fence);
4214
4738
  const plan = cleanPlan(input.plan, this.d.profileData ?? this.d.profile ?? "dev", (this.d.sdlc?.config().mode ?? "off") !== "off");
4215
4739
  this.validatePlanSources(plan);
@@ -4218,7 +4742,13 @@ export class Tasks {
4218
4742
  if (external && (!this.personOrConductor(by) || input.backlog !== true)) throw new PreEffectToolRefusal("external intake requires person-owned backlog staging");
4219
4743
  if (input.backlog !== undefined && typeof input.backlog !== "boolean") throw new PreEffectToolRefusal("backlog must be a boolean");
4220
4744
  const backlog = input.backlog === true;
4221
- if (input.draft !== undefined && (input.draft !== true || !backlog || by !== USER)) throw new PreEffectToolRefusal("only the person's intake stages a backlog draft");
4745
+ if (input.draft === true && input[HOST_ROADMAP_DRAFT] === true) {
4746
+ // R2 part 2 (#1480): a part the planner or the conductor accepted is held exactly like the person's intake draft. The
4747
+ // capability is a host Symbol, so no tool argument can stage a hidden draft, and the caller is rechecked here as well.
4748
+ if (!backlog) throw new PreEffectToolRefusal("a held roadmap draft is backlog work");
4749
+ if (by !== USER && (!this.d.bus.isRostered(by) || !this.isConfiguredPlanner(by) && !this.configuredManualConductor(by)))
4750
+ throw new PreEffectToolRefusal("a held roadmap draft needs the configured planner or the unique conductor; ask the person to accept the part with ahub roadmap decompose --accept");
4751
+ } else if (input.draft !== undefined && (input.draft !== true || !backlog || by !== USER)) throw new PreEffectToolRefusal("only the person's intake stages a backlog draft");
4222
4752
  const claiming = !backlog && input.owner === by;
4223
4753
  if (claiming) {
4224
4754
  this.acceptanceCapacity({ id: -1, owner: by, state: "proposed" });
@@ -4885,7 +5415,9 @@ export class Tasks {
4885
5415
  }
4886
5416
  const waits = this.waitsFor(task);
4887
5417
  const plannedMove = opts.planner || this.plannerPullRecord(task)?.pull === true && (by === HUB || opts.roster) && (opts.reason !== "manual" || opts.roster);
4888
- const plannerFull = plannedMove ? this.plannerFull(task) : [];
5418
+ // #1626 A: an owner choice the hub makes on its own never offers a peer that must refuse it. A person's or conductor's explicit assignment, a claim and a roster move stay as they were.
5419
+ const hubOffer = !opts.roster && !opts.override && !opts.claim && !opts.namedOwner && !opts.conductorManual && !opts.queueOverride && !opts.plannerPull && this.plannerPullRecord(task)?.pull !== true && opts.reason !== "budget" && opts.reason !== "offline" && (by === HUB || !opts.candidates); // a pause or offline relay moves work that already has an owner, so it is not an offer
5420
+ const plannerFull = plannedMove ? this.plannerFull(task) : hubOffer ? this.hubOfferFull(task) : [];
4889
5421
  const a = assign(opts.plannerPull ? { ...task, state: "proposed" } : task, this.states(), this.d.routing(), { exclude: [...(opts.override ? [] : this.excluded(task)), ...(opts.exclude ?? []), ...(opts.event === "escalated" && task.owner ? [task.owner] : [])], excludeOwners: [...plannerFull, ...this.studyExcludedOwners(task)], ...(opts.candidates ? { candidates: opts.candidates } : {}), waitsFor: waits, ...this.weights(task.class, task), ...(opts.namedOwner ? { namedOwner: opts.namedOwner } : {}), // A self-claim hands over no envelope; reviewer admission remains automatic.
4890
5422
  contextOverride: !!(opts.queueOverride || opts.claim),
4891
5423
  ...(opts.queueOverride || opts.claim ? { queueOverride: opts.queueOverride ?? "owner" as const } : {}) });
@@ -6682,13 +7214,14 @@ export class Tasks {
6682
7214
  * counts) and the staged PR only while the done's effective commit and branch are still the ones it was read for.
6683
7215
  */
6684
7216
  private withLink(task: Task, link: IdentityLink | undefined, refs?: TaskRefs): Task {
6685
- if ((this.d.sdlc?.config().mode ?? "off") === "off" || this.isPii(task)) return task;
7217
+ if (this.isPii(task) || (this.d.sdlc?.config().mode ?? "off") === "off" && link?.managedRevision === undefined) return task;
7218
+ if (link?.managedRevision !== undefined && task.history.length !== link.managedRevision) throw new PreEffectToolRefusal("managed handoff changed; inspect the task and GitHub before retrying");
6686
7219
  const config = this.d.sdlc?.config() ?? sdlcConfig(undefined);
6687
7220
  let issue: { repo: string; issue: number } | undefined;
6688
- if (!task.sdlc?.issue) { try { issue = this.planIssueIdentity(task); } catch { issue = undefined; } }
7221
+ if ((this.d.sdlc?.config().mode ?? "off") !== "off" && !task.sdlc?.issue) { try { issue = this.planIssueIdentity(task); } catch { issue = undefined; } }
6689
7222
  const commit = refs?.commit ?? task.refs.commit, branch = refs?.branch ?? task.refs.branch;
6690
- const repository = task.sdlc?.repo ?? task.refs.repo ?? this.d.repository;
6691
- const pr = link && !task.sdlc?.pr && repository?.toLowerCase() === link.repo.toLowerCase() && link.basis.commit === commit && (commit !== undefined || link.basis.branch === branch) ? link : undefined;
7223
+ const repository = task.sdlc?.repo ?? task.refs.repo ?? this.d.repository ?? (link?.managedRevision !== undefined ? link.repo : undefined);
7224
+ const pr = link && !task.sdlc?.pr && repository?.toLowerCase() === link.repo.toLowerCase() && link.basis.commit === commit && (link.managedRevision !== undefined ? link.basis.branch === branch : commit !== undefined || link.basis.branch === branch) ? link : undefined;
6692
7225
  let next = task.sdlc;
6693
7226
  if (issue) next = linkedReceipt(next, issue, config) ?? next;
6694
7227
  if (pr) next = linkedReceipt(next, { repo: pr.repo, pr: pr.pr }, config) ?? next;
@@ -6808,7 +7341,7 @@ export class Tasks {
6808
7341
  for (const stall of this.stalled()) if (visibleIds.has(stall.task)) byKind[stall.cause.kind] = (byKind[stall.cause.kind] ?? 0) + 1;
6809
7342
  const stalls = { open: Object.values(byKind).reduce((sum, n) => sum + n, 0), byKind, doneWithoutWrites: rows.filter(task => visibleIds.has(task.id) && task.history.findLast(entry => entry.event === "done")?.noWrites).length };
6810
7343
  // #481 S7: the merge-time readback the guarded merge recorded on each merged task's receipt (host-written, never a tool input), and the two series that are not made of tasks.
6811
- const mergedAt: Record<number, number> = {}, ciReruns: Record<number, number | null> = {}, ciRuns: Record<number, number | null> = {}, reviews: Record<number, number | null> = {};
7344
+ const mergedAt: Record<number, number> = {}, ciReruns: Record<number, number | null> = {}, ciRuns: Record<number, number | null> = {}, reviews: Record<number, number | null> = {}, firstPass: Record<number, 0 | 1 | null> = {}, fullGateRuns: Record<number, number | null> = {}, successfulGateRuns: Record<number, number | null> = {}, failedGateRuns: Record<number, number | null> = {}, cancelledGateRuns: Record<number, number | null> = {}, otherGateRuns: Record<number, number | null> = {}, macosShardRuns: Record<number, number | null> = {};
6812
7345
  for (const task of rows) {
6813
7346
  const guarded = task.sdlc?.merge;
6814
7347
  const merge = guarded?.state === "merged" ? guarded : task.sdlc?.mergeReadback;
@@ -6816,9 +7349,9 @@ export class Tasks {
6816
7349
  const cost = cleanMergeCost(merge.cost);
6817
7350
  const at = cost?.mergedAt ?? (merge === guarded && Number.isSafeInteger(merge.at) ? merge.at : null);
6818
7351
  if (at !== null) mergedAt[task.id] = at;
6819
- if (cost) { ciReruns[task.id] = cost.ciReruns; ciRuns[task.id] = cost.ciRuns; reviews[task.id] = cost.reviews; }
7352
+ if (cost) { ciReruns[task.id] = cost.ciReruns; ciRuns[task.id] = cost.ciRuns; reviews[task.id] = cost.reviews; firstPass[task.id] = cost.firstPass ?? null; fullGateRuns[task.id] = cost.fullGateRuns ?? null; successfulGateRuns[task.id] = cost.successfulGateRuns ?? null; failedGateRuns[task.id] = cost.failedGateRuns ?? null; cancelledGateRuns[task.id] = cost.cancelledGateRuns ?? null; otherGateRuns[task.id] = cost.otherGateRuns ?? null; macosShardRuns[task.id] = cost.macosShardRuns ?? null; }
6820
7353
  }
6821
- return { ...sdlcMetrics(tasks, { ...(cutoff !== undefined ? { since: cutoff } : {}), ...(this.d.sdlc?.config().bands ? { bands: this.d.sdlc.config().bands } : {}), stalls, mergedAt, ciReruns, ciRuns, reviews, external: this.externalSeries(), ...(merged ?? {}) }), ...(this.securityScanCounts() ? { securityScan: this.securityScanCounts() } : {}) };
7354
+ return { ...sdlcMetrics(tasks, { ...(cutoff !== undefined ? { since: cutoff } : {}), ...(this.d.sdlc?.config().bands ? { bands: this.d.sdlc.config().bands } : {}), stalls, mergedAt, ciReruns, ciRuns, reviews, firstPass, fullGateRuns, successfulGateRuns, failedGateRuns, cancelledGateRuns, otherGateRuns, macosShardRuns, external: this.externalSeries(), ...(merged ?? {}) }), ...(this.securityScanCounts() ? { securityScan: this.securityScanCounts() } : {}) };
6822
7355
  }
6823
7356
 
6824
7357
  /** Latest configured scan source counts; no repository or alert text is projected. */
@@ -7786,11 +8319,12 @@ export class Tasks {
7786
8319
  current();
7787
8320
  const gates = adoptMergeGates(evidence, head, requiredChecksFor(config, repo));
7788
8321
  if (gates.length) throw new PreEffectToolRefusal(gates.join("; "));
7789
- const costDeadline = performance.now() + MERGE_READBACK_DEADLINE_MS;
8322
+ const costDeadline = performance.now() + INLINE_MERGE_READBACK_DEADLINE_MS;
7790
8323
  const cost = evidence?.costSnapshot ? await readPrCostHistory(repo, pr as number, (args, timeout, cwd, cap) => {
7791
8324
  const remaining = costDeadline - performance.now();
7792
- return remaining > 0 ? run(args, Math.min(timeout ?? remaining, remaining), cwd, cap) : Promise.resolve({ code: 1, stdout: "" });
7793
- }, evidence.costSnapshot, head).then(pr => pr?.complete ? mergeCostFrom(pr) : undefined, () => undefined) : undefined;
8325
+ current();
8326
+ return remaining > 0 ? (this.d.sdlc?.gh ?? sdlcGh)(args, Math.min(timeout ?? remaining, remaining), cwd, cap).then(result => { current(); return result; }) : Promise.resolve({ code: 1, stdout: "" });
8327
+ }, evidence.costSnapshot, head, task.history.find(entry => entry.event === "done")?.requestHead).then(pr => pr?.complete ? mergeCostFrom(pr) : undefined, () => undefined) : undefined;
7794
8328
  const latest = current();
7795
8329
  const merge: ReadbackMergeRecord = { repo, pr: pr as number, head, at: Date.now(), state: "merged", ...(evidence?.mergeCommit ? { mergeCommit: evidence.mergeCommit } : {}), ...(cost ? { cost } : {}) };
7796
8330
  const capacity = this.capacityBefore(latest);
@@ -7840,7 +8374,7 @@ export class Tasks {
7840
8374
  this.mergesInFlight.add(task.id);
7841
8375
  try {
7842
8376
  const links = this.deliveryLinks(config), subject = links.find(link => link.id === task.id)!;
7843
- const outcome = await guardedMerge({ mode, subject, state: task.state, taskState: n => this.d.board.get(n)?.state, config, tasks: links, run: this.d.sdlc?.gh ?? sdlcGh, readableMetadata: this.publicMetadataText,
8377
+ const outcome = await guardedMerge({ mode, subject, state: task.state, taskState: n => this.d.board.get(n)?.state, config, tasks: links, run: this.d.sdlc?.gh ?? sdlcGh, readableMetadata: this.publicMetadataText, firstSubmittedHead: task.history.find(entry => entry.event === "done")?.requestHead,
7844
8378
  recordMerge: record=>this.recordMergeResult(task.id,by,record,artifactCurrent),
7845
8379
  beforeMerge: queue => {
7846
8380
  if (!this.mergeAuthority(by)) return "merge authority changed during the merge check: nothing was run";
@@ -7881,8 +8415,9 @@ export class Tasks {
7881
8415
  async captureExternalMerge(id: number): Promise<"merged" | "closed" | "retry" | "skip"> {
7882
8416
  const task = this.d.board.get(id), config = this.d.sdlc?.config(), receipt = task?.sdlc;
7883
8417
  const repo = receipt?.repo, pr = receipt?.pr, head = task && this.reviewHead(task);
8418
+ const recorded = receipt?.merge?.state === "merged" ? receipt.merge : receipt?.mergeReadback?.state === "merged" ? receipt.mergeReadback : undefined;
7884
8419
  if (!task || task.state !== "approved" || this.isPii(task) || (task.owner && this.d.privateTurn?.(task.owner)) || !config || !repo || !pr || !head || !/^[a-f0-9]{40}$/.test(head)
7885
- || this.repositories.scope(task.refs).key !== this.repositories.scope({ repo }).key || mergeModeFor(config, repo) !== "off" || (receipt?.merge?.state === "merged" || receipt?.mergeReadback?.state === "merged") || this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) return "skip";
8420
+ || this.repositories.scope(task.refs).key !== this.repositories.scope({ repo }).key || (recorded ? recorded.cost?.ciRuns != null || recorded.repo !== repo || recorded.pr !== pr || recorded.head !== head : mergeModeFor(config, repo) !== "off") || this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) return "skip";
7886
8421
  const identity = JSON.stringify([task.history.length, task.updated, task.owner, receipt, config]);
7887
8422
  const current = () => {
7888
8423
  const now = this.d.board.get(id), policy = this.d.sdlc?.config();
@@ -7898,9 +8433,15 @@ export class Tasks {
7898
8433
  if (!current()) return "skip";
7899
8434
  if (evidence?.state === "CLOSED") return "closed";
7900
8435
  if (evidence?.state !== "MERGED" || evidence.head !== head) return "retry";
7901
- const cost = await readPrCostHistory(repo, pr, run, undefined, head).then(value => value?.complete ? mergeCostFrom(value) : undefined, () => undefined);
8436
+ const cost = await readPrCostHistory(repo, pr, run, undefined, head, task.history.find(entry => entry.event === "done")?.requestHead).then(value => value?.complete ? mergeCostFrom(value) : undefined, () => undefined);
7902
8437
  if (!current()) return "skip";
7903
8438
  const now = this.d.board.get(id)!;
8439
+ if (recorded) {
8440
+ if (!cost) return "retry";
8441
+ const key = receipt!.merge === recorded ? "merge" : "mergeReadback";
8442
+ this.d.board.update(id, HUB, "merge cost observed", { sdlc: { ...now.sdlc!, [key]: { ...recorded, cost } } }, undefined, {}, now.history.length);
8443
+ return "merged";
8444
+ }
7904
8445
  const merge: ReadbackMergeRecord = { repo, pr, head, at: Date.now(), state: "merged", ...(evidence.mergeCommit ? { mergeCommit: evidence.mergeCommit } : {}), ...(cost ? { cost } : {}) };
7905
8446
  this.d.board.update(id, HUB, "merge observed", { sdlc: { ...now.sdlc!, mergeReadback: merge } }, undefined, {}, now.history.length);
7906
8447
  return "merged";
@@ -7918,8 +8459,9 @@ export class Tasks {
7918
8459
  const candidates = this.d.board.list().sort((a, b) => (this.mergeReadbackSchedule.get(a.id)?.next ?? -Infinity) - (this.mergeReadbackSchedule.get(b.id)?.next ?? -Infinity) || a.id - b.id);
7919
8460
  for (const task of candidates) {
7920
8461
  if (reads >= 3 || this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) break;
7921
- if (task.state !== "approved" || this.isPii(task) || !task.sdlc?.repo || !task.sdlc.pr || task.sdlc.merge || task.sdlc.mergeReadback) { this.mergeReadbackSchedule.delete(task.id); continue; }
7922
- const approval = task.history.findLastIndex(entry => entry.event === "approved" || entry.event === "done" && entry.by === task.owner);
8462
+ const recorded = task.sdlc?.merge?.state === "merged" ? task.sdlc.merge : task.sdlc?.mergeReadback?.state === "merged" ? task.sdlc.mergeReadback : undefined;
8463
+ if (task.state !== "approved" || this.isPii(task) || !task.sdlc?.repo || !task.sdlc.pr || (recorded ? recorded.cost?.ciRuns != null : !!task.sdlc.merge || !!task.sdlc.mergeReadback)) { this.mergeReadbackSchedule.delete(task.id); continue; }
8464
+ const approval = task.history.findLastIndex(entry => entry.event === "approved" || entry.event === "merged outside the hub" || entry.event === "done" && entry.by === task.owner);
7923
8465
  const at = task.history[approval]?.at;
7924
8466
  if (approval < 0 || at === undefined || now < at || now - at >= 24 * 60 * 60_000) { this.mergeReadbackSchedule.delete(task.id); continue; }
7925
8467
  const previous = this.mergeReadbackSchedule.get(task.id);
@@ -8392,6 +8934,9 @@ export class Tasks {
8392
8934
  } else if (approvalHead && currentHead && currentHead !== approvalHead) throw this.reviewHeadMoveRefusal(task.id, approvalHead, currentHead);
8393
8935
  const integrity = publicTestIntegrity(receipt && evidence && !this.isPii(task) ? await readTestIntegrity(receipt, evidence, read) : this.unknownTestIntegrity(this.isPii(task)), this.publicMetadataText);
8394
8936
  const evalResult = receipt && !this.isPii(task) ? await readEvalFor(config, evidence, receipt.repo, read) : undefined;
8937
+ const draftApproval = transition === "approval" && receipt?.repo && receipt.pr && evidence?.draft === true
8938
+ && evidence.review !== "changes_requested" && approvalHead && evidence.head === approvalHead
8939
+ ? await readReviewReadiness(receipt, approvalHead, read, requiredChecksFor(config, receipt.repo)) : undefined;
8395
8940
  const current = this.need(task.id, false, true);
8396
8941
  if (config.mode === "enforce" && (current.history.length !== task.history.length || current.owner !== task.owner || current.reviewer !== task.reviewer || current.state !== task.state)) throw new PreEffectToolRefusal(`task #${task.id}: changed during lifecycle readback; retry on current work`);
8397
8942
  // Advise may continue on the current task, but evidence from its previous link cannot admit that task's review.
@@ -8402,7 +8947,12 @@ export class Tasks {
8402
8947
  // #481 S5: review entry keeps the eval gate's own blockers (its check, and in enforce its evidence gaps), like the premature-review rule does for the ordinary required checks.
8403
8948
  const evalNames = evalRequiredChecks(config, evidence).filter(name => !config.requiredChecks.includes(name));
8404
8949
  const evalBlocker = (blocker: string) => evalNames.some(name => blocker.startsWith(`required check ${name}:`)) || evalGapBlockers(status.evalGate).includes(blocker);
8405
- const blockers = transition === "review" ? [...new Set([...status.blockers.filter(blocker => ["lifecycle stage definition unknown", "issue identity missing", "PR identity missing", "current PR evidence unknown", "PR is not open", "local gate on current head missing or failed"].includes(blocker) || blocker.startsWith("test integrity:") || evalBlocker(blocker)), ...(status.entry ?? []), ...(status.exit ?? [])])] : status.blockers;
8950
+ const approvalDeferral = draftApproval?.ready === true && draftApproval.draftApprovalEligible === true && evidence?.unresolved === 0;
8951
+ const blockers = transition === "review" ? [...new Set([...status.blockers.filter(blocker => ["lifecycle stage definition unknown", "issue identity missing", "PR identity missing", "current PR evidence unknown", "PR is not open", "local gate on current head missing or failed"].includes(blocker) || blocker.startsWith("test integrity:") || evalBlocker(blocker)), ...(status.entry ?? []), ...(status.exit ?? [])])] : status.blockers.filter(blocker => !approvalDeferral || !(
8952
+ blocker === "required check check (macos-latest): not successful on current head"
8953
+ || blocker === "GitHub review approval missing or changes requested" && evidence?.review !== "changes_requested"
8954
+ || blocker === "review requests pending or unknown" && evidence?.pendingReviews !== null
8955
+ ));
8406
8956
  if (config.mode === "enforce" && blockers.length) throw new PreEffectToolRefusal(`task #${task.id}: SDLC ${transition} blocked: ${blockers.join("; ")}`);
8407
8957
  // #481 S5: the recorded pass rate and suite version ride the approval note; a code-only PR, an unconfigured gate or an unreported value records nothing.
8408
8958
  const gate = status.evalGate;
@@ -8733,10 +9283,63 @@ export class Tasks {
8733
9283
  const task = this.need(id, false, true);
8734
9284
  this.mine(task, by, "owner", true);
8735
9285
  if (this.isPii(task) || !port.describe(by, task.id)) return undefined;
8736
- const result = await port.commitAndPush({ peer: by, task: task.id, title: task.title });
8737
- if (!result.ok) throw new PreEffectToolRefusal(`hub_task_done for task #${task.id}: ${result.reason}`);
9286
+ const requestCheck = this.requestCheck(by), revision = task.history.length;
9287
+ const current = () => {
9288
+ try {
9289
+ requestCheck(); const row = this.d.board.get(task.id);
9290
+ return !!row && row.created === task.created && row.owner === by && row.state === task.state && row.history.length === revision
9291
+ && !this.isPii(row) && !this.d.privateTurn?.(by) && !this.observerExcluded(by) && !this.d.sweepHeld?.() && !this.d.bus.isRecoveryHeld && !this.d.bus.storageError && !!port.describe(by, task.id);
9292
+ } catch { return false; }
9293
+ };
9294
+ if (!current()) throw new PreEffectToolRefusal("managed handoff authority unavailable; inspect the task and retry hub_task_done");
9295
+ const result = await port.commitAndPush({ peer: by, task: task.id, title: task.title, current });
9296
+ if (!result.ok) {
9297
+ const message = `hub_task_done for task #${task.id}: ${result.reason}`;
9298
+ if (result.uncertain) throw new Error(message);
9299
+ throw new PreEffectToolRefusal(message);
9300
+ }
9301
+ const stillCurrent = () => { if (!current()) throw new Error("managed handoff authority changed after the commit; inspect the task and GitHub before retrying"); };
9302
+ stillCurrent();
8738
9303
  if (result.note) this.doneNotes.set(task.id, result.note);
8739
- return { ...cleanRefs(refs), commit: result.commit, branch: result.branch };
9304
+ let repo: string | undefined, pr: number | undefined;
9305
+ if (result.pushed && !task.sdlc?.pr) {
9306
+ repo = githubOriginRepository(this.d.cwd);
9307
+ const named = task.sdlc?.repo ?? task.refs.repo;
9308
+ if (!repo || named && named.toLowerCase() !== repo || this.d.repository && this.d.repository.toLowerCase() !== repo) throw new Error("managed branch was pushed but the project GitHub origin is unavailable or changed; inspect the origin and retry hub_task_done");
9309
+ let issue: { repo: string; issue: number } | undefined;
9310
+ try { issue = this.planIssueIdentity(task); } catch { throw new Error("managed branch was pushed but its issue identity is ambiguous; inspect the task before retrying hub_task_done"); }
9311
+ if (issue && issue.repo.toLowerCase() !== repo) throw new Error("managed branch was pushed but the spec issue belongs to another repository; inspect the task before retrying hub_task_done");
9312
+ if (!this.publicMetadataText(JSON.stringify({ repo, branch: result.branch, ...(issue ? { issue: issue.issue } : {}) }))) throw new Error("managed branch was pushed but PR identity is not public; inspect the task before retrying hub_task_done");
9313
+ const verifiedRepo = repo;
9314
+ const authority = () => { stillCurrent(); if (githubOriginRepository(this.d.cwd) !== verifiedRepo) throw new Error("managed origin changed after the push; inspect GitHub before retrying"); };
9315
+ try { pr = await managedTaskPullRequest({ repo, branch: result.branch, commit: result.commit, task: task.id, ...(this.publicMetadataText(task.title) ? { title: task.title } : {}), ...(issue ? { issue: issue.issue } : {}), current: authority }, this.d.sdlc?.gh ?? sdlcGh); }
9316
+ catch (error) { throw new Error(`managed branch was pushed; ${error instanceof Error && this.publicMetadataText(error.message) ? error.message : "PR outcome is unavailable; inspect GitHub before retrying hub_task_done"}`); }
9317
+ authority();
9318
+ }
9319
+ const handed: ManagedHandoffRefs = { ...cleanRefs(refs), commit: result.commit, branch: result.branch };
9320
+ Object.defineProperty(handed, MANAGED_HANDOFF, { value: { task: task.id, owner: by, revision, commit: result.commit, branch: result.branch, ...(repo && pr ? { repo, pr } : {}) } });
9321
+ return handed;
9322
+ }
9323
+
9324
+ /** Commit the managed owner worktree for a check and bind its exact head through the board. */
9325
+ async worktreeForCheck(by: PeerId, id: number, current: () => boolean): Promise<Task | undefined> {
9326
+ const port = this.d.taskWorktree;
9327
+ if (!port || !port.applies(by) || !port.describe(by, id)) return undefined;
9328
+ const task = this.need(id, false, true);
9329
+ this.mine(task, by, "owner", true);
9330
+ if (task.state !== "in_progress" || this.isPii(task) || !current()) throw new PreEffectToolRefusal("check unavailable");
9331
+ const result = await port.commitAndPush({ peer: by, task: id, title: task.title, current });
9332
+ // A commit or push can have landed even when the request loses authority during an await.
9333
+ if (!result.ok) {
9334
+ const reason = `managed worktree check: ${result.reason.replaceAll("hub_task_done", "hub_check_start")}`;
9335
+ if (result.uncertain) throw new Error(reason);
9336
+ throw new PreEffectToolRefusal(reason);
9337
+ }
9338
+ if (!current()) throw new Error("check unavailable: task authority changed after the worktree commit; read hub_task_show before retrying");
9339
+ const fresh = this.d.board.get(id);
9340
+ if (!fresh || fresh.history.length !== task.history.length) throw new Error("check unavailable: task changed after the worktree commit; read hub_task_show before retrying");
9341
+ if (fresh.refs.commit === result.commit && fresh.refs.branch === result.branch) return fresh;
9342
+ return this.d.board.update(id, HUB, "check worktree committed", { refs: { commit: result.commit, branch: result.branch } }, undefined, {}, fresh.history.length);
8740
9343
  }
8741
9344
 
8742
9345
  /** Decline or cancel: clear the hub-made worktree and its empty branch. Uncommitted work is kept and reported, never force-removed. */
@@ -8760,8 +9363,26 @@ export class Tasks {
8760
9363
  // The owner it is declined for goes on the entry, also when the console declines for it: `excluded()` keeps it out (#207).
8761
9364
  const capacityBefore = this.capacityBefore(task);
8762
9365
  const planned = this.plannerPullRecord(task)?.pull === true;
8763
- const back = this.d.board.update(task.id, by, "declined", { ...(["in_progress", "changes_requested"].includes(task.state) ? { state: "proposed" as const } : {}), ...(planned ? { reserved: null } : {}) }, reason, task.owner ? { from: task.owner, ...(capacity === true ? { capacity: true as const } : {}) } : {});
9366
+ const record = this.plannerPullRecord(task);
9367
+ // #1626 A3: a capacity decline of a pulled card keeps the planner's reservation and returns the card to backlog; any other decline clears it as before.
9368
+ const keep = planned && capacity === true && !!task.owner && ["proposed", "in_progress"].includes(task.state) && !taskHasWorkEvidence(task);
9369
+ // #1626 A2: the decliner is not offered another task by the hub until it next reports idle. A peer already idle gets no back-off: no later idle edge would end it.
9370
+ if (capacity === true && task.owner && this.d.bus.stateOf(task.owner) !== "idle") this.capacityBackoff.add(task.owner);
9371
+ const back = this.d.board.update(task.id, by, "declined", { ...(["in_progress", "changes_requested"].includes(task.state) ? { state: "proposed" as const } : {}), ...(planned && !keep ? { reserved: null } : {}) }, reason, task.owner ? { from: task.owner, ...(capacity === true ? { capacity: true as const } : {}) } : {});
8764
9372
  if (planned) this.offered.delete(task.id);
9373
+ if (keep) {
9374
+ this.d.notify(`task ${this.publicTitle(back)} declined (capacity only) by ${by}${reason && !this.isPii(back) ? `: ${reason}` : ""}; back in backlog with its reservation`);
9375
+ this.releaseHubWorktree(task, task.owner ?? by);
9376
+ try {
9377
+ const returned = this.d.board.update(back.id, HUB, "backlog returned untouched", { state: "backlog", owner: null, reviewer: null, reserved: record?.previous.reserved ?? back.reserved ?? null }, "capacity decline: back in backlog with its reservation", {}, back.history.length);
9378
+ this.cohorts.leave(task.id);
9379
+ this.withdrawRoleRequest(task, returned, "owner");
9380
+ this.incomingBacklog.add(task.id);
9381
+ return returned;
9382
+ } finally {
9383
+ this.writePlannerNotices(this.d.board.get(task.id) ?? back, capacityBefore);
9384
+ }
9385
+ }
8765
9386
  this.d.notify(`task ${this.publicTitle(back)} declined${capacity === true ? " (capacity only)" : ""} by ${by}${reason && !this.isPii(back) ? `: ${reason}` : ""}`);
8766
9387
  this.releaseHubWorktree(task, task.owner ?? by);
8767
9388
  // A capacity decline is not in excluded(), so this move's own reroute leaves the decliner out explicitly.
@@ -8945,6 +9566,14 @@ export class Tasks {
8945
9566
  }
8946
9567
 
8947
9568
  async done(by: PeerId, id: unknown, summary?: string, refs?: TaskRefs, deliverables?: unknown, specAck?: unknown, resolved?: unknown): Promise<Task> {
9569
+ try { return await this.doneWithHandoff(by, id, summary, refs, deliverables, specAck, resolved); }
9570
+ catch (error) {
9571
+ if ((refs as ManagedHandoffRefs | undefined)?.[MANAGED_HANDOFF] && error instanceof PreEffectToolRefusal) throw new Error(`managed worktree was committed before completion was refused: ${error.message}; inspect the task and GitHub before retrying hub_task_done`);
9572
+ throw error;
9573
+ }
9574
+ }
9575
+
9576
+ private async doneWithHandoff(by: PeerId, id: unknown, summary?: string, refs?: TaskRefs, deliverables?: unknown, specAck?: unknown, resolved?: unknown): Promise<Task> {
8948
9577
  const observerExcluded = this.observerExcluded(by);
8949
9578
  const requestCheck = this.requestCheck(by);
8950
9579
  const initial = this.need(id, false, true);
@@ -8989,12 +9618,32 @@ export class Tasks {
8989
9618
  task = valid();
8990
9619
  }
8991
9620
  // #694: stage the identities the hub can verify; the gates read them, and only the admitted done persists them.
8992
- const link = this.d.sdlc && this.d.sdlc.config().mode !== "off" ? await this.identityLink(task, refs) : undefined;
8993
- const current = () => this.stagedSpec(by, this.withLink(valid(), link, refs), specCarry);
9621
+ const handoff = (refs as ManagedHandoffRefs | undefined)?.[MANAGED_HANDOFF];
9622
+ const link: IdentityLink | undefined = handoff?.repo && handoff.pr ? { repo: handoff.repo, pr: handoff.pr, basis: { commit: handoff.commit, branch: handoff.branch }, managedRevision: handoff.revision } : !handoff && this.d.sdlc && this.d.sdlc.config().mode !== "off" ? await this.identityLink(task, refs) : undefined;
9623
+ let managedRevision = handoff?.revision;
9624
+ const stageHandoff = (row: Task) => {
9625
+ let staged = row;
9626
+ if (handoff) {
9627
+ if (handoff.task !== staged.id || handoff.owner !== by || managedRevision !== staged.history.length || handoff.commit !== cleanRefs(refs).commit || handoff.branch !== cleanRefs(refs).branch || this.isPii(staged) || this.d.privateTurn?.(by)) throw new PreEffectToolRefusal("managed handoff changed; inspect the task and GitHub before retrying");
9628
+ if (handoff.repo && handoff.pr && !staged.sdlc?.pr) {
9629
+ const receipt = linkedReceipt(staged.sdlc, { repo: handoff.repo, pr: handoff.pr }, this.d.sdlc?.config() ?? sdlcConfig(undefined));
9630
+ if (!receipt) throw new PreEffectToolRefusal("managed PR repository no longer matches the task; inspect GitHub before retrying");
9631
+ staged = { ...staged, sdlc: receipt };
9632
+ }
9633
+ }
9634
+ return staged;
9635
+ };
9636
+ const ownWrite = (...args: Parameters<Board["update"]>) => {
9637
+ current();
9638
+ const row = write(...args);
9639
+ if (handoff) { managedRevision = row.history.length; if (link) link.managedRevision = managedRevision; }
9640
+ return row;
9641
+ };
9642
+ const current = () => stageHandoff(this.stagedSpec(by, this.withLink(valid(), link, refs), specCarry));
8994
9643
  task = current();
8995
9644
  let reviewEvidence: PrEvidence | undefined;
8996
9645
  if (this.d.sdlc && this.d.sdlc.config().mode !== "off") { reviewEvidence = await this.lifecycleGate(task, "review", undefined, undefined, refileHead); task = current(); }
8997
- const reviewAdmission = task.reviewer || this.d.prepareReviewBrief ? await this.reviewRequestAdmission(task, refs, true, by, reviewEvidence, undefined, staged => this.stagedSpec(by, this.withLink(this.completionDraft(staged, draft), link, refs), specCarry), !task.reviewer, refileHead) : undefined;
9646
+ const reviewAdmission = task.reviewer || this.d.prepareReviewBrief ? await this.reviewRequestAdmission(task, refs, true, by, reviewEvidence, undefined, staged => stageHandoff(this.stagedSpec(by, this.withLink(this.completionDraft(staged, draft), link, refs), specCarry)), !task.reviewer, refileHead) : undefined;
8998
9647
  task = current();
8999
9648
  if (refileHead && (this.d.sdlc?.config().mode ?? "off") === "off") {
9000
9649
  const currentHead = await this.currentPrHeadForReview(task, current);
@@ -9025,8 +9674,8 @@ export class Tasks {
9025
9674
  if (r.action === "request") return write(task.id, HUB, "integration requested", {}, this.integrationRequest(task, r));
9026
9675
  if (r.action === "unresolved") {
9027
9676
  this.d.notify(`task ${this.publicTitle(task)}: turn-free integration unresolved after ${MAX_REQUESTS} requests (${r.why}); its done is recorded, check the overlapping work by hand`);
9028
- task = this.withLink(write(task.id, HUB, "integration unresolved", {}, r.why), link, refs);
9029
- } else if (r.integrated) task = this.withLink(write(task.id, HUB, "integrated", {}, `cohort #${cohort!.id}, revision ${cohort!.revision}`), link, refs);
9677
+ task = this.withLink(ownWrite(task.id, HUB, "integration unresolved", {}, r.why), link, refs);
9678
+ } else if (r.integrated) task = this.withLink(ownWrite(task.id, HUB, "integrated", {}, `cohort #${cohort!.id}, revision ${cohort!.revision}`), link, refs);
9030
9679
  } else if (cohort?.held.size && !this.isPii(task)) {
9031
9680
  // No integration step for this member (silence lifted, a PII task open): the notices the silence held stand in
9032
9681
  // for it (issue #107, AC4).
@@ -9034,7 +9683,7 @@ export class Tasks {
9034
9683
  if (evidence && by === USER) this.d.notify(`task ${this.publicTitle(task)} done by the console; overlapping work finished meanwhile:\n${evidence}`);
9035
9684
  else if (evidence) this.doneNotes.set(task.id, `Overlapping work finished while you worked (no turn-free integration step ran):\n${evidence}`);
9036
9685
  }
9037
- if (task.state === "proposed" || task.state === "changes_requested") task = this.withLink(write(task.id, by, "accepted", { state: "in_progress" }, WITH_DONE), link, refs); // done without a separate accept
9686
+ if (task.state === "proposed" || task.state === "changes_requested") task = this.withLink(ownWrite(task.id, by, "accepted", { state: "in_progress" }, WITH_DONE), link, refs); // done without a separate accept
9038
9687
  const command = this.d.runCheck ? this.d.check?.(task.class, task) : undefined;
9039
9688
  if (!command) return this.complete(task, by, summary, refs, "", withheld, "review", reviewAdmission, link, records, requestCheck, refresh, specInspection, false, resolvedReviewComments, reviewObserverTurn);
9040
9689
  // The tool call returns now; a check can outlast an agent's tool timeout. The result decides what comes next.
@@ -9471,6 +10120,7 @@ export class Tasks {
9471
10120
  const head = admission.head ?? this.reviewHead(task) ?? "unknown head";
9472
10121
  if (admission.ready) {
9473
10122
  const names = admission.checks?.length ? admission.checks.join(", ") : "the required checks";
10123
+ if (admission.deferred?.length) return `Hub-verified at ${head}: required checks ${names} passed at this exact head; ${admission.deferred.join(", ")} deferred on draft; no bot review thread is waiting for a reply. Full CI is still required before merge.\n`;
9474
10124
  return `Hub-verified at ${head}: required checks ${names} passed at this exact head${admission.reusedRun !== undefined ? ` via identical-tree run ${admission.reusedRun}` : ""}; no bot review thread is waiting for a reply.\n`;
9475
10125
  }
9476
10126
  return `Hub-verified at ${head}: not ready: ${admission.blockers.join("; ")}.\n`;
@@ -9507,7 +10157,7 @@ export class Tasks {
9507
10157
  // #824: the hub's own exact-head CI evidence, from the admission this request already carries (no new gh call). Nothing here comes from the builder's summary or a recorded claim.
9508
10158
  const codeScoped = this.d.reviewScope?.(reviewer) === "code";
9509
10159
  const verified = codeScoped ? "" : this.hubVerifiedBlock(task, admission);
9510
- const ciPassed = admission?.ready === true && !this.isPii(task);
10160
+ const ciPassed = admission?.ready === true && !admission.deferred?.length && !this.isPii(task);
9511
10161
  // #852 AC2: a code-scope reviewer's sandbox cannot run tests or read CI, so its Hub-verified and check lines are replaced by one fixed line.
9512
10162
  const checkResult = codeScoped ? CODE_SCOPE_LINE
9513
10163
  : check ? `Check result: ${(check.note ?? "").split("\n")[0]}`