@staix/agent-hub 0.43.0 → 0.45.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 (118) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/README.md +3 -8
  3. package/docs/agent-notes/adapters.md +2 -2
  4. package/docs/agent-notes/daemon.md +4 -4
  5. package/docs/agent-notes/local-worker.md +2 -1
  6. package/docs/agent-notes/security-review.md +1 -1
  7. package/docs/agent-notes/tasks.md +5 -2
  8. package/docs/agent-notes/tests.md +4 -3
  9. package/docs/design/adapters.md +4 -2
  10. package/docs/design/agent-hub-architecture.md +2 -0
  11. package/docs/design/agent-hub.md +1 -1
  12. package/docs/design/roadmap.md +75 -2
  13. package/docs/design/supervision.md +34 -2
  14. package/docs/design/task-board.md +36 -2
  15. package/docs/dogfood.md +20 -5
  16. package/docs/events.md +9 -3
  17. package/docs/influences.md +7 -0
  18. package/docs/memory.md +4 -4
  19. package/docs/operations.md +84 -31
  20. package/docs/quickstart.md +14 -2
  21. package/docs/research.md +18 -0
  22. package/docs/roadmap.json +4 -0
  23. package/docs/roadmap.md +9 -0
  24. package/docs/sdlc.md +19 -4
  25. package/docs/security.md +4 -4
  26. package/docs/verification/2026-11-11-supervision-pilot-1221.md +864 -0
  27. package/docs/verification/2026-11-19-0.44.0.md +60 -0
  28. package/docs/verification/2026-11-19-claude-implementer-2.1.328.md +49 -0
  29. package/docs/verification/2026-11-20-claude-implementer-2.1.329.md +49 -0
  30. package/docs/verification/2026-11-20-sdlc-metrics-diagnosis.md +7 -0
  31. package/docs/verification/2026-11-21-0.45.0.md +69 -0
  32. package/docs/verification/2026-11-22-codex-0171-reviewer-isolation.md +47 -0
  33. package/docs/verified.json +32 -26
  34. package/package.json +2 -2
  35. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  36. package/plugins/agent-hub/kimi-hook.js +585 -264
  37. package/plugins/agent-hub/kimi-review-policy-worker.js +5 -5
  38. package/plugins/agent-hub/server.js +629 -293
  39. package/scripts/check-docs.mjs +9 -1
  40. package/src/adapters/acp.ts +11 -1
  41. package/src/adapters/compat.ts +3 -3
  42. package/src/adapters/definitions/builtin-metadata.ts +2 -2
  43. package/src/adapters/definitions/native-context.ts +10 -0
  44. package/src/adapters/jcode.ts +10 -0
  45. package/src/adapters/local-worker.ts +3 -2
  46. package/src/adapters/pi.ts +15 -4
  47. package/src/cli/console-state.ts +3 -1
  48. package/src/cli/help.ts +3 -1
  49. package/src/cli/identity.ts +2 -1
  50. package/src/cli/main.ts +12 -6
  51. package/src/cli/output.ts +2 -2
  52. package/src/cli/recovery-package.ts +16 -3
  53. package/src/cli/roadmap-write.ts +59 -0
  54. package/src/cli/roadmap.ts +81 -4
  55. package/src/cli/sdlc-output.ts +11 -1
  56. package/src/cli/upgrade-runtime.ts +10 -6
  57. package/src/cli/upgrade.ts +9 -3
  58. package/src/hub/agent-mem-range.ts +43 -0
  59. package/src/hub/board.ts +116 -2
  60. package/src/hub/bus.ts +4 -0
  61. package/src/hub/check-runner.ts +25 -1
  62. package/src/hub/claude-shell-wrapper.ts +2 -1
  63. package/src/hub/config-apply.ts +4 -2
  64. package/src/hub/config-trust.ts +1 -1
  65. package/src/hub/context-window.ts +1 -1
  66. package/src/hub/control-write-trace.ts +39 -2
  67. package/src/hub/cost-governance.ts +11 -7
  68. package/src/hub/daemon.ts +318 -53
  69. package/src/hub/dogfood-read.ts +4 -2
  70. package/src/hub/edit-guard.ts +100 -0
  71. package/src/hub/events.ts +79 -8
  72. package/src/hub/facts.ts +85 -2
  73. package/src/hub/hub-tools.ts +3 -1
  74. package/src/hub/lifecycle.ts +6 -1
  75. package/src/hub/log-rotation.ts +130 -0
  76. package/src/hub/memory-profile.ts +137 -21
  77. package/src/hub/no-writes.ts +1 -0
  78. package/src/hub/operational-authority.ts +3 -2
  79. package/src/hub/operational-settings.ts +2 -2
  80. package/src/hub/quota-events.ts +40 -0
  81. package/src/hub/recovery-store.ts +70 -24
  82. package/src/hub/report.ts +1 -1
  83. package/src/hub/research-experiments.ts +132 -0
  84. package/src/hub/research-quality.ts +13 -3
  85. package/src/hub/research-record.ts +38 -2
  86. package/src/hub/research.ts +128 -28
  87. package/src/hub/restart.ts +49 -2
  88. package/src/hub/roadmap-check.ts +65 -0
  89. package/src/hub/roadmap-decompose.ts +80 -0
  90. package/src/hub/roadmap-export.ts +27 -0
  91. package/src/hub/roadmap-sync.ts +97 -0
  92. package/src/hub/roadmap.ts +40 -0
  93. package/src/hub/runtime-capture-prune.ts +9 -1
  94. package/src/hub/runtime-prune-health.ts +5 -1
  95. package/src/hub/sdlc-branch-ci.ts +128 -0
  96. package/src/hub/sdlc-merge.ts +12 -5
  97. package/src/hub/sdlc-metrics.ts +33 -10
  98. package/src/hub/sdlc.ts +90 -10
  99. package/src/hub/settings.ts +1 -0
  100. package/src/hub/snapshots.ts +56 -1
  101. package/src/hub/startup-event-seeds.ts +21 -15
  102. package/src/hub/startup-timing.ts +3 -1
  103. package/src/hub/supervision-proposals.ts +10 -2
  104. package/src/hub/supervision-rules.ts +27 -4
  105. package/src/hub/supervision.ts +7 -0
  106. package/src/hub/task-pr.ts +47 -0
  107. package/src/hub/task-shell-command.ts +124 -0
  108. package/src/hub/task-worktree.ts +18 -11
  109. package/src/hub/tasks.ts +617 -45
  110. package/src/hub/usage-rollup.ts +35 -20
  111. package/src/hub/worktree-shelf.ts +2 -1
  112. package/src/local/sandbox.ts +2 -1
  113. package/src/local/shell-environment.ts +6 -0
  114. package/src/local/tools.ts +13 -1
  115. package/src/memory/brief.ts +10 -1
  116. package/src/memory/client.ts +3 -2
  117. package/src/pi/extension.ts +15 -3
  118. package/src/pi/tool-receipts.ts +26 -0
package/src/hub/tasks.ts CHANGED
@@ -1,8 +1,14 @@
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 { managedTaskPullRequest } from "./task-pr.ts";
3
+ 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 } from "./roadmap.ts";
3
4
  import { milestoneViews, type MilestoneView, type RoadmapSnapshot } from "./roadmap-view.ts";
5
+ import { readMirrorSnapshot, planRoadmapMirror, recoverMirrorBinding } from "./roadmap-sync.ts";
6
+ import { roadmapExport } from "./roadmap-export.ts";
7
+ import { checkRoadmap, type DriftMilestone, type RoadmapDrift } from "./roadmap-check.ts";
8
+ import type { RoadmapConfig } from "./roadmap.ts";
4
9
  import { computeUnplaced, withTree, type ReadyToClose, type TreeRollup, type UnplacedResult } from "./roadmap-unplaced.ts";
5
10
  import { buildTriagePrompt, parseTriage, TRIAGE_BATCH, type TriageItem } from "./roadmap-triage.ts";
11
+ import { buildDecomposePrompt, parseDecomposition, DECOMPOSE_ITEMS, DECOMPOSE_PATHS, type DecomposeItem } from "./roadmap-decompose.ts";
6
12
  import { pathCandidates } from "@staix/agent-mem";
7
13
  import { renderGuidanceVariantV1 } from "./guidance-variants.ts";
8
14
  import { GuidanceProbeFixtureHost, type GuidanceProbeStore } from "./guidance-probe-store.ts";
@@ -68,7 +74,7 @@ import { folderDetail, MAX_NEW_PER_POLL, scheduleNext, SOURCE_ID, scheduledDetai
68
74
  import { INTAKE_MAX_SOURCES, INTAKE_MAX_TEXT, intakeDetail, intakeSystemPrompt, intakeUserMessage, parseIntakeDetail, parseIntakeSplit, plannerRequestBody } from "./intake.ts";
69
75
  import { DEFAULT_BAND, EPISODE_LOOKBACK, sdlcMetrics, type BandMetric, type BandResult, type MetricTask, type MetricsReport, type SeriesPoint } from "./sdlc-metrics.ts";
70
76
  import { readSecurityScan } from "./security-baseline.ts";
71
- import { cleanMergeCost } from "./cost-governance.ts";
77
+ import { cleanMergeCost, mergeCostFrom } from "./cost-governance.ts";
72
78
  import type { InstancesConfig } from "./instances.ts";
73
79
  import { composeRememberText } from "./memory-fail.ts";
74
80
  import { VERSION } from "../version.ts";
@@ -76,7 +82,7 @@ import { NoWriteTurns } from "./no-writes.ts";
76
82
  import { readGitHubImport, readGitHubIssuePages, readGitHubMilestonePages, type GitHubSource, type GitHubImportSelection } from "./github-import.ts";
77
83
  import { BACKLOG_SPLIT_SCREEN_TIMEOUT_MS, actualTaskDates, planningPatch, type PlanningFields, type Release, type ReleaseState } from "./planning.ts";
78
84
  import { readMergeQueue, type DeliveryTask, type MergeQueue } from "./sdlc-queue.ts";
79
- import { adoptMergeGates, guardedMerge, mergeModeFor, mergeView, readAdoptMergeEvidence, requiredChecksFor, type MergeView } from "./sdlc-merge.ts";
85
+ import { INLINE_MERGE_READBACK_DEADLINE_MS, MERGE_READBACK_DEADLINE_MS, adoptMergeGates, guardedMerge, mergeModeFor, mergeView, readAdoptMergeEvidence, requiredChecksFor, type MergeView } from "./sdlc-merge.ts";
80
86
  import { mirrorVerdict as mirrorToGitHub, type MirrorVerdict } from "./sdlc-mirror.ts";
81
87
  import { CODE_SCOPE_LINE, evidenceOnlyNotice, type ReviewScope } from "./review-scope.ts";
82
88
  import { DEFAULT_MAX_NITS, parseReviewFindings, findingsForHead, findingHead as resolveFindingHead, findingTally, findingFollowUps, positionalFindingId, type ReviewFinding, type ReviewFindingSet } from "./review-findings.ts";
@@ -107,7 +113,7 @@ import { isAbsolute, relative, resolve } from "node:path";
107
113
  import type { Briefs, NativeItem } from "../memory/brief.ts";
108
114
  import type { MemoryClient } from "../memory/client.ts";
109
115
  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";
116
+ 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
117
  import type { Bus } from "./bus.ts";
112
118
  import { HUB, newEnvelope, NOTE_KINDS, noteLine, sanitize, USER, type Envelope, type PeerId, type PeerState } from "./envelope.ts";
113
119
  import type { PiiVerdict, ScreenItem, ScreenRecord } from "./inference.ts";
@@ -115,7 +121,7 @@ import { assign, isRemotePeerId, detectSignals, peerEntry, predictSplit, relayCa
115
121
  import { ExecutionBudget, type ExecutionBudgetConfig, type ExecutionBudgetDecision, type ExecutionBudgetStatus, type ExecutionUnit } from "./execution-budget.ts";
116
122
  import { Cohorts, MAX_REQUESTS, type Cohort, type Completion } from "./cohorts.ts";
117
123
  import { realPath } from "./project.ts";
118
- import { TaskRepositories } from "./task-repository.ts";
124
+ import { TaskRepositories, githubOriginRepository } from "./task-repository.ts";
119
125
  import { mainCheckoutWarning } from "./main-checkout.ts";
120
126
  import { PreEffectToolRefusal } from "./tool-refusal.ts";
121
127
  import type { TaskWorktreePort } from "./task-worktree.ts";
@@ -126,7 +132,7 @@ import { definitionOf as builtinDefinitionOf } from "../adapters/registry.ts";
126
132
  import { ADAPTERS, DEFAULT_REVIEW_POOL, definitionOf, familyOf, type ProjectAdapterCatalog } from "../adapters/registry.ts";
127
133
  import { plannerGrooming, nextSweep, plannedStartPending, taskSweepConfig, taskWait, TASK_WAIT_MAX_MS, TASK_WAIT_REASON_MAX, type TaskSweepConfig, type SweepRecord } from "./task-sweep.ts";
128
134
  import { CiWatchers, pollCi, type CiOutcome, type CiWatch } from "./ci-watch.ts";
129
- import { planningIssueReceipt, linkedReceipt, openPrFor, readPrCostHistory, readReviewReadiness, reviewReadinessFromEvidence, type PrEvidence, type ReviewReadiness, readPlanIssueMetadata, canonicalStage, checklistOf, readSdlcPr, readSdlcPrHead, readSpecEdit, sdlcConfig, sdlcReceipt, sdlcStatus, specState, SPEC_STATE_TEXT, stageDefinition, lifecycleStage, type SdlcConfig, type MergeRecord, type PlanIssueMetadata, sdlcGh, type SdlcGh, type SdlcStatus, type SpecEdit, type SpecState, localSupersedingTask, storedSpecAcceptance, carriedSpecAcceptance } from "./sdlc.ts";
135
+ import { planningIssueReceipt, linkedReceipt, openPrFor, readPrCostHistory, readReviewReadiness, reviewReadinessFromEvidence, type PrEvidence, type ReviewReadiness, readPlanIssueMetadata, canonicalStage, checklistOf, readSdlcPr, readSdlcPrHead, readSpecEdit, sdlcConfig, sdlcReceipt, sdlcStatus, specState, SPEC_STATE_TEXT, stageDefinition, lifecycleStage, type SdlcConfig, type MergeRecord, type ReadbackMergeRecord, type PlanIssueMetadata, sdlcGh, type SdlcGh, type SdlcStatus, type SpecEdit, type SpecState, localSupersedingTask, storedSpecAcceptance, carriedSpecAcceptance } from "./sdlc.ts";
130
136
 
131
137
  /** #1176: refusals for an agent that reaches a person-run card by a path other than the pull gate. */
132
138
  const PERSON_RUN_SPLIT = "a person-run card is the person's to split: its children would be unmarked cards an agent could take (the person's own split marks every child person-run)";
@@ -232,11 +238,14 @@ export interface TasksDeps {
232
238
  /** Explicit, read-only inspection remains available when task notices are disabled. */
233
239
  specsRead?: (action: "check" | "covers", paths: readonly string[]) => SpecsCheckReport | SpecsCoverReport;
234
240
  /** 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 };
241
+ specsList?: () => { specs: { id: string; title: string; status: string | null; type?: string; paths?: string[] }[]; errors: number; truncated: boolean };
236
242
  /** R3 (#1481): the model for triage. Absent, off or failing is no suggestion; it carries no authority and links nothing. */
237
243
  roadmapModel?: (system: string, user: string, allowed: () => boolean) => Promise<string | undefined>;
238
244
  /** R3 (#1481): host-only `gh` runner for the roadmap's read-only issue and milestone reads (tests); production uses `sdlc.gh`. */
239
245
  roadmapGh?: SdlcGh;
246
+ /** Host-only origin proof for tests; production reads the project-local Git origin. */
247
+ roadmapOrigin?: () => string | undefined;
248
+ roadmapConfig?: () => RoadmapConfig;
240
249
  /** Host-verified existing symbols at this task's admitted completion head; never plan guesses. */
241
250
  memorySymbolNodes?: (task: Task) => MemorySymbolNodes | undefined;
242
251
  /** Host-only release report selector; derives its answer from committed policy and the in-memory authorization ledger. */
@@ -245,7 +254,7 @@ export interface TasksDeps {
245
254
  auditSource?: AuditSource;
246
255
  /** #785 P1b: the per-head CI watcher's bounds; tests shorten them, the defaults are `CI_WATCH_*` in `ci-watch.ts`. */
247
256
  ciWatch?: { deadlineMs?: number; pollMs?: number };
248
- /** #785 P1c: `tasks.auto_pull`, read at each capacity release so a reload applies to the next one; absent or false pulls nothing. */
257
+ /** #785 P1c: `tasks.auto_pull`, read for every automatic pull trigger; absent or false pulls nothing. */
249
258
  autoPull?: () => boolean;
250
259
  briefs?: Briefs;
251
260
  /** Screened live fail notes directly intersecting the task plan or refs; read-only advice. */
@@ -409,6 +418,8 @@ QUIET_EVENTS.add("plan observed"); // Host observation does not move the task or
409
418
  QUIET_EVENTS.add("planner changed"); // Planning authority does not move the execution owner or revoke its handoff.
410
419
  QUIET_EVENTS.add("claim verdict"); // #901: a person's bookkeeping on a plan claim moves nothing, so it must not turn a running check into "check finished late".
411
420
  QUIET_EVENTS.add("invocation");
421
+ QUIET_EVENTS.add("check run passed"); // Isolated check bookkeeping does not invalidate an in-flight completion check.
422
+ QUIET_EVENTS.add("check run failed");
412
423
  QUIET_EVENTS.add("wait recorded"); // #1454: a recorded wait moves nothing; it only suspends the idle-owner ladder, so it must not turn a running check into "check finished late".
413
424
  QUIET_EVENTS.add("shell branch bound"); // #880: the hub's host-observed branch binding (#845) is bookkeeping; it neither moves nor settles the task.
414
425
  /** The records of the `done (checking)` entry a passed check now completes: what the owner delivered then (#509a). */
@@ -566,7 +577,9 @@ export interface ExperimentView { attempts: ExperimentAttemptView[]; counts: { a
566
577
  interface ExperimentContext { task: Task; campaign: ResearchCampaignRecord; private: boolean; key: string; fence: ExperimentWriteFence }
567
578
  interface CompletionRefresh { revision: number; commit: string; state: "in_review" | "approved" }
568
579
  interface RefileHeadGuard { recorded?: string }
569
- interface IdentityLink { repo: string; pr: number; basis: { commit?: string; branch?: string } }
580
+ interface IdentityLink { repo: string; pr: number; basis: { commit?: string; branch?: string }; managedRevision?: number }
581
+ const MANAGED_HANDOFF = Symbol("managed worktree handoff");
582
+ type ManagedHandoffRefs = TaskRefs & { [MANAGED_HANDOFF]?: { task: number; owner: PeerId; revision: number; commit: string; branch: string; repo?: string; pr?: number } };
570
583
 
571
584
  /** 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. */
572
585
  export type DeliverableResult = "changed" | "missing" | "unknown" | "unchanged";
@@ -841,6 +854,8 @@ export class Tasks {
841
854
  private readonly planReviewRequests = new Map<number, string>();
842
855
  private readonly repositories: TaskRepositories;
843
856
  private readonly incomingBacklog = new Set<number>();
857
+ /** One accept attempt per (answer, part), so two concurrent accepts of one part make one draft (#1480 R2 part 2). */
858
+ private readonly decompositionAccepts = new Map<string, Promise<unknown>>();
844
859
  private readonly plannerBacklog = new Map<PeerId, Set<number>>();
845
860
  private readonly plannerBlockedQueue = new Map<PeerId, string>();
846
861
  private readonly knownPlanners = new Set<PeerId>();
@@ -860,6 +875,7 @@ export class Tasks {
860
875
  /** #785 P1b: one bounded CI watcher per exact PR head, and the reviews the hub held as premature, by task id. */
861
876
  private readonly ciWatchers: CiWatchers;
862
877
  private readonly heldReviews = new Map<number, { head: string; reviewer: PeerId; revision: number }>();
878
+ private readonly autoPullAttached = new Set<PeerId>();
863
879
 
864
880
  constructor(private readonly d: TasksDeps) {
865
881
  this.ciWatchers = new CiWatchers({
@@ -890,7 +906,15 @@ export class Tasks {
890
906
  });
891
907
  // What the on-prem worker says about a PII task is private on the bus (console tail and log show a stub), so the
892
908
  // board keeps the text: `ahub task show <id>` is where the console user reads it, a refusal included.
909
+ d.bus.onPeerAdded = peer => {
910
+ this.autoPullAttached.delete(peer);
911
+ if (d.bus.stateOf(peer) === "idle") this.autoPullForAttachment(peer);
912
+ };
893
913
  d.bus.tap((e) => {
914
+ if (e.t === "state" && e.state === "offline") this.autoPullAttached.delete(e.peer);
915
+ if (e.t === "state" && e.state === "idle" && !this.autoPullAttached.has(e.peer) && this.d.autoPull?.() === true) {
916
+ this.autoPullForAttachment(e.peer);
917
+ }
894
918
  if (e.t === "overflow" && e.env.from === HUB && e.env.kind === "task" && Array.isArray(e.env.refs?.backlog)) {
895
919
  const ids = e.env.refs.backlog;
896
920
  if (ids.length <= 64 && ids.every(id => Number.isSafeInteger(id) && id > 0)) this.addPlannerBacklog(e.peer, ids);
@@ -908,6 +932,12 @@ export class Tasks {
908
932
  });
909
933
  }
910
934
 
935
+ private autoPullForAttachment(peer: PeerId): void {
936
+ if (this.autoPullAttached.has(peer) || this.d.autoPull?.() !== true) return;
937
+ this.autoPullAttached.add(peer);
938
+ if (this.topReservedReady(peer, undefined, true)) this.queueAutoPulls(new Set([peer]), "peer available");
939
+ }
940
+
911
941
  isPii = (task: Pick<Task, "signals">) => task.signals.includes("pii_path") || (task.signals.includes("pii") && this.d.routing().constraints.pii === "local_only");
912
942
 
913
943
  private signalsFor(task: Pick<Task, "title" | "detail" | "refs"> & { plan?: TaskPlan }, routing = this.d.routing()) {
@@ -3073,9 +3103,13 @@ export class Tasks {
3073
3103
  changes.set(planner, change);
3074
3104
  };
3075
3105
  const released = new Set<PeerId>();
3106
+ const readied = new Set<PeerId>();
3076
3107
  for (const [peer, used] of before) if (this.wip(peer) < used) { released.add(peer); for (const planner of this.taskPlanner(task)) add(planner, peer); }
3077
3108
  if (approved) for (const card of this.d.board.list("backlog")) {
3078
- if (card.deps?.includes(task.id) && !this.waitsFor(card).length && !plannedStartPending(card, now)) for (const planner of this.taskPlanner(card)) add(planner, undefined, card.id);
3109
+ if (card.deps?.includes(task.id) && !this.waitsFor(card).length && !plannedStartPending(card, now)) {
3110
+ for (const planner of this.taskPlanner(card)) add(planner, undefined, card.id);
3111
+ if (card.reserved) readied.add(card.reserved);
3112
+ }
3079
3113
  }
3080
3114
  for (const [planner, change] of changes) this.releaseNotice(`could not notify planner ${planner} about ready work`, () => {
3081
3115
  const pending = this.d.bus.pendingEnvelopes(planner).filter(env => env.from === HUB && env.kind === "task" && env.body.startsWith("Planner work ready:"));
@@ -3100,8 +3134,9 @@ export class Tasks {
3100
3134
  const env = newEnvelope(HUB, sanitize(`Planner work ready:\n${lines.join("\n")}\nRead the current board before planning or pulling work.`), { to: [planner], kind: "task" });
3101
3135
  if (!this.d.bus.publish(env).includes(planner)) throw new Error("the notice was not queued");
3102
3136
  });
3103
- // #785 P1c: only this write's own release, never a merged earlier one, and only when the person turned it on.
3137
+ // Only this write's own release or newly ready dependency, never a merged earlier notice.
3104
3138
  if (this.d.autoPull?.() === true) this.queueAutoPulls(released);
3139
+ if (this.d.autoPull?.() === true) this.queueAutoPulls(new Set([...readied].filter(peer => !released.has(peer))), "backlog ready");
3105
3140
  });
3106
3141
  }
3107
3142
 
@@ -3114,32 +3149,32 @@ export class Tasks {
3114
3149
  }
3115
3150
 
3116
3151
  /**
3117
- * #785 P1c: `tasks.auto_pull`. A slot freed for a peer pulls the one top backlog card explicitly reserved for it, through `pullPlanned` as the hub acting for that card's planner of
3152
+ * #785 P1c: `tasks.auto_pull`. A trigger pulls the one top backlog card explicitly reserved for a peer, through `pullPlanned` as the hub acting for that card's planner of
3118
3153
  * record: revision, dependency, reservation, pinned, frozen-release, P0 order and WIP checks all run there unchanged. One card per release. Never an unreserved card, never PII.
3119
- * Serialized on one chain, so two releases cannot pick the same card; each job re-reads the board, so a card that moved meanwhile is skipped.
3154
+ * Serialized on one chain, so concurrent triggers cannot pick the same card; each job re-reads the board, so a card that moved meanwhile is skipped.
3120
3155
  */
3121
3156
  private autoPulls: Promise<void> = Promise.resolve();
3122
3157
  private autoPullsOpen = 0;
3123
3158
  /** Queued or running auto pulls, so a recovery commit waits for them the way it waits for `checksPending` (#785 P1c): one that is mid-admission would otherwise write after the commit's digest. */
3124
3159
  autoPullsPending = (): number => this.autoPullsOpen;
3125
- private queueAutoPulls(released: ReadonlySet<PeerId>): void {
3160
+ private queueAutoPulls(released: ReadonlySet<PeerId>, cause = "capacity released"): void {
3126
3161
  for (const peer of released) {
3127
3162
  this.autoPullsOpen++;
3128
- this.autoPulls = this.autoPulls.then(() => this.autoPull(peer)).catch(() => { /* autoPull reports its own refusals */ }).finally(() => { this.autoPullsOpen--; });
3163
+ this.autoPulls = this.autoPulls.then(() => this.autoPull(peer, cause)).catch(() => { /* autoPull reports its own refusals */ }).finally(() => { this.autoPullsOpen--; });
3129
3164
  }
3130
3165
  }
3131
3166
  /** Whether the hub may still start work on its own: the setting is on, and no recovery, shutdown or storage hold is active. Read at entry and again right before the assignment write. */
3132
3167
  private autoPullAdmitted(): boolean {
3133
3168
  return this.d.autoPull?.() === true && !this.d.sweepHeld?.() && !this.d.bus.isRecoveryHeld && !this.d.bus.storageError;
3134
3169
  }
3135
- private async autoPull(peer: PeerId): Promise<void> {
3170
+ private async autoPull(peer: PeerId, cause: string): Promise<void> {
3136
3171
  if (!this.autoPullAdmitted()) return;
3137
3172
  const card = this.topReservedReady(peer, undefined, true);
3138
3173
  if (!card) return;
3139
3174
  // 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).
3140
3175
  const planner = this.taskPlanner(card)[0];
3141
3176
  if (!planner || !this.d.bus.isRostered(planner)) return;
3142
- const reason = `auto_pull: capacity released for ${peer}; hub acted for planner ${planner}`;
3177
+ const reason = `auto_pull: ${cause} for ${peer}; hub acted for planner ${planner}`;
3143
3178
  try {
3144
3179
  await this.pullPlanned(HUB, { id: card.id, revision: card.planningRevision ?? 0, reason }, { onBehalfOf: planner, guard: () => {
3145
3180
  if (!this.autoPullAdmitted()) throw new PreEffectToolRefusal("auto pull is no longer admitted: tasks.auto_pull was turned off or a recovery, shutdown or storage hold began");
@@ -3534,6 +3569,227 @@ export class Tasks {
3534
3569
  return row;
3535
3570
  }
3536
3571
 
3572
+ /** Host-sampled GitHub authority is never supplied by a tool argument. */
3573
+ private roadmapRepository(): string {
3574
+ const repo = this.roadmapParsed(() => githubRepo(this.d.repository));
3575
+ let origin: string | undefined;
3576
+ try { origin = this.d.roadmapOrigin ? this.d.roadmapOrigin() : githubOriginRepository(this.d.cwd); } catch { /* unknown is not a trusted origin */ }
3577
+ 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");
3578
+ return repo;
3579
+ }
3580
+ private roadmapApplyAuthority(by: PeerId): void {
3581
+ this.roadmapReadAuthority(by);
3582
+ if (this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) throw new PreEffectToolRefusal("roadmap writes are held; retry after recovery");
3583
+ if (by !== USER && (!(this.d.roadmapConfig?.().github_write === "conductor") || !this.configuredManualConductor(by) || !this.d.bus.isRostered(by)))
3584
+ throw new PreEffectToolRefusal("GitHub roadmap writes require the person or the configured conductor with roadmap.github_write enabled");
3585
+ }
3586
+
3587
+ /** Render only screened views. Issue writes require an exact preview and fresh authority. */
3588
+ async roadmapExport(by: PeerId, input: { issue?: number; apply?: boolean; confirm?: string } = {}): Promise<{ json: string; markdown: string; fingerprint: string; call?: string[]; applied: boolean }> {
3589
+ const check = this.requestCheck(by, () => this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError ? "roadmap is held by recovery or storage" : undefined);
3590
+ check(); this.roadmapReadAuthority(by);
3591
+ 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");
3592
+ if (input.issue !== undefined) this.roadmapParsed(() => milestoneId(input.issue));
3593
+ if (input.apply && input.issue === undefined) throw new PreEffectToolRefusal("roadmap export --apply needs an issue; preview with --issue first");
3594
+ if (input.apply) this.roadmapApplyAuthority(by);
3595
+ const rendered = roadmapExport(this.milestoneList(by));
3596
+ const repo = input.issue === undefined ? undefined : this.roadmapRepository();
3597
+ const call = repo === undefined ? undefined : ["api", `repos/${repo}/issues/${input.issue}`, "--hostname", "github.com", "--method", "PATCH", "-f", `body=${rendered.markdown}`];
3598
+ const fingerprint = createHash("sha256").update(JSON.stringify({ repo: repo ?? null, issue: input.issue ?? null, markdown: rendered.markdown })).digest("hex");
3599
+ if (!input.apply) return { ...rendered, fingerprint, ...(call ? { call } : {}), applied: false };
3600
+ if (input.confirm !== fingerprint) throw new PreEffectToolRefusal(`roadmap export preview changed; run ahub roadmap export --issue ${input.issue} and retry with --confirm ${fingerprint}`);
3601
+ check(); this.roadmapApplyAuthority(by); if (this.roadmapRepository() !== repo) throw new PreEffectToolRefusal("roadmap GitHub origin changed; preview again");
3602
+ let result: Awaited<ReturnType<SdlcGh>>;
3603
+ try { result = await this.roadmapGh()(call!, 10_000, undefined, 64 * 1024); }
3604
+ catch { throw new Error("roadmap issue update outcome is unknown; inspect the issue before retrying"); }
3605
+ if (result.code !== 0) throw new Error("roadmap issue update was not confirmed; inspect the issue before retrying");
3606
+ try { check(); this.roadmapApplyAuthority(by); if (this.roadmapRepository() !== repo || roadmapExport(this.milestoneList(by)).markdown !== rendered.markdown) throw new Error("changed"); }
3607
+ catch { throw new Error("roadmap or authority changed after issue update; inspect the issue and preview again"); }
3608
+ return { ...rendered, fingerprint, call, applied: true };
3609
+ }
3610
+
3611
+ /** Build drift only from the same screened views and host-owned evidence as roadmap reads. */
3612
+ async roadmapCheck(by: PeerId, include?: (finding: RoadmapDrift) => boolean): Promise<ReturnType<typeof checkRoadmap>> {
3613
+ const check = this.requestCheck(by); check(); this.roadmapReadAuthority(by);
3614
+ 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]);
3615
+ const snapshot = (rows: typeof views) => JSON.stringify([rows, rows.flatMap(view => view.tasks.map(member => this.d.board.get(member.id)))]);
3616
+ const evidence = snapshot(views);
3617
+ 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"); };
3618
+ const rendered = roadmapExport(views), exportStates: (boolean | undefined)[] = [];
3619
+ for (const [path, expected] of [["docs/roadmap.json", rendered.json], ["docs/roadmap.md", rendered.markdown]] as const) {
3620
+ try {
3621
+ const file = await readGuardedDeliverable(path, { cwd: this.d.cwd, deny: this.d.deny ?? [], private: name => matchesPolicy(this.d.cwd, name, this.d.piiPaths ?? [], true) });
3622
+ current(); exportStates.push(Buffer.from(file.data).toString("utf8") === expected);
3623
+ } catch (error) { if (error instanceof PreEffectToolRefusal) throw error; exportStates.push(error instanceof DeliverableRefusal && error.message.includes("does not exist") ? false : undefined); }
3624
+ }
3625
+ const exportMatches = exportStates.includes(false) ? false : exportStates.every(value => value === true) ? true : undefined;
3626
+ current();
3627
+ const refs = new Set<string>();
3628
+ for (const view of views) {
3629
+ for (const issue of view.issues) refs.add(issue.ref);
3630
+ for (const member of view.tasks) {
3631
+ const task = this.d.board.get(member.id); if (!task) continue;
3632
+ try { const source = this.planIssueIdentity(task); if (source && this.publicMetadataText(source.repo)) refs.add(`${source.repo.toLowerCase()}#${source.issue}`); } catch { /* ambiguous identity is unknown */ }
3633
+ }
3634
+ }
3635
+ const issueStates = new Map<string, "open" | "closed">(), issueDeadline = performance.now() + 20_000;
3636
+ for (const ref of [...refs].sort().slice(0, 100)) {
3637
+ const match = /^([^#]+)#([1-9][0-9]*)$/.exec(ref); if (!match || issueDeadline <= performance.now()) break;
3638
+ const value = await readPlanIssueMetadata(match[1]!, Number(match[2]), async (args, timeout, cwd, cap) => {
3639
+ current(); const remaining = issueDeadline - performance.now();
3640
+ 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: "" };
3641
+ });
3642
+ current(); if (value) issueStates.set(ref, value.state === "CLOSED" ? "closed" : "open");
3643
+ }
3644
+ let mirror: Awaited<ReturnType<typeof readMirrorSnapshot>> | undefined, repo: string | undefined;
3645
+ if (config.github_mirror) {
3646
+ try { repo = this.roadmapRepository(); mirror = await readMirrorSnapshot(repo, this.roadmapGh()); }
3647
+ catch { /* partial or unavailable evidence stays unknown */ }
3648
+ current();
3649
+ }
3650
+ const milestones: DriftMilestone[] = views.map(view => {
3651
+ const tasks = view.tasks.map(member => {
3652
+ const task = this.d.board.get(member.id)!;
3653
+ let issue: string | null | undefined;
3654
+ try { const source = this.planIssueIdentity(task); issue = source ? `${source.repo.toLowerCase()}#${source.issue}` : null; } catch { issue = undefined; }
3655
+ const issueState: "open" | "closed" | "unknown" = issue ? issueStates.get(issue) ?? "unknown" : "unknown";
3656
+ const merge = task.sdlc?.merge?.state === "merged" ? task.sdlc.merge : task.sdlc?.mergeReadback;
3657
+ const mergedAt = merge?.state === "merged" ? merge.cost?.mergedAt ?? undefined : task.sdlc?.pr && task.state === "approved" ? undefined : null;
3658
+ const report = merge?.state === "merged" ? this.currentSpecReport(task) : undefined;
3659
+ const unchangedSpecs = mergedAt === null ? [] : report?.complete && report.errors === 0 && !report.truncated && report.head === merge?.head ? report.unchanged.map(row => row.id) : undefined;
3660
+ return { id: task.id, state: task.state, issue, issueState, feature: /^feat(?:\([^)]*\))?:/i.test(task.title), specIssue: !!task.sdlc?.issue, mergedAt, unchangedSpecs };
3661
+ });
3662
+ const children = view.children.map(id => views.find(row => row.id === id));
3663
+ 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));
3664
+ const uncertain = !!view.withheld || view.issues.some(row => !issueStates.has(row.ref)) || view.releases.some(row => row.state === "unknown") || children.some(row => !row);
3665
+ 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"; });
3666
+ let mirrorDiff: boolean | undefined;
3667
+ if (mirror && repo && !view.withheld && view.title !== "[withheld]") {
3668
+ try {
3669
+ const marker = `<!-- ahub-roadmap:${this.d.project}:${view.id} -->`, bound = this.d.board.mirrorMilestone(repo, view.id);
3670
+ const recovered = bound === undefined ? recoverMirrorBinding(marker, view.title, mirror.milestones) : undefined;
3671
+ if (recovered?.kind === "ambiguous" || recovered?.titleConflicts.length) mirrorDiff = true;
3672
+ else {
3673
+ const number = bound ?? (recovered?.kind === "bind" ? recovered.number : undefined), remote = number === undefined ? null : mirror.milestones.find(row => row.number === number);
3674
+ 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;
3675
+ }
3676
+ } catch { /* unknown mirror evidence */ }
3677
+ }
3678
+ 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 };
3679
+ });
3680
+ current(); return checkRoadmap({ milestones, now: this.d.now?.() ?? Date.now(), closeLagMs: 24 * 60 * 60_000, mirrorEnabled: config.github_mirror, exportMatches }, include);
3681
+ }
3682
+
3683
+ /** Serialize at the host caller. Persist only admitted ids-only notices, so unavailable feeds can retry. */
3684
+ async roadmapNotify(taskIds: readonly number[], send: (task: number, milestone: number | null, rule: number, marker: string) => boolean): Promise<number> {
3685
+ if (!taskIds.length) return 0;
3686
+ const views = this.milestoneList(HUB);
3687
+ if (!views.some(view => view.tasks.some(task => taskIds.includes(task.id)))) return 0;
3688
+ const select = (finding: RoadmapDrift) => {
3689
+ const referenced = finding.items.filter(item => /^task:[1-9][0-9]*$/.test(item)).map(item => Number(item.slice(5)));
3690
+ const eligible = views.filter(view => finding.milestone === null || view.id === finding.milestone).flatMap(view => view.tasks.map(task => task.id));
3691
+ const marker = createHash("sha256").update(JSON.stringify([finding.rule, finding.milestone, finding.items, finding.cause])).digest("hex");
3692
+ return !this.d.board.hasRoadmapNotice(marker) && taskIds.some(id => eligible.includes(id) && (!referenced.length || referenced.includes(id)));
3693
+ };
3694
+ const checked = await this.roadmapCheck(HUB, select);
3695
+ let sent = 0;
3696
+ for (const finding of checked.findings) {
3697
+ const referenced = finding.items.filter(item => /^task:[1-9][0-9]*$/.test(item)).map(item => Number(item.slice(5)));
3698
+ const eligible = views.filter(view => finding.milestone === null || view.id === finding.milestone).flatMap(view => view.tasks.map(task => task.id));
3699
+ const task = taskIds.find(id => eligible.includes(id) && (!referenced.length || referenced.includes(id)));
3700
+ if (task === undefined) continue;
3701
+ const marker = createHash("sha256").update(JSON.stringify([finding.rule, finding.milestone, finding.items, finding.cause])).digest("hex");
3702
+ if (this.d.board.hasRoadmapNotice(marker)) continue;
3703
+ const latest = this.d.board.get(task);
3704
+ 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;
3705
+ if (send(task, finding.milestone, finding.rule, marker) && this.d.board.recordRoadmapNotice(marker)) sent++;
3706
+ }
3707
+ return sent;
3708
+ }
3709
+
3710
+ /** Preview every fixed GitHub call from a complete inventory; confirmation binds both calls and local bindings. */
3711
+ async roadmapSync(by: PeerId, input: { apply?: boolean; confirm?: string } = {}): Promise<{ repo: string; calls: string[][]; bindings: { milestone: number; number: number }[]; fingerprint: string; applied: boolean }> {
3712
+ this.roadmapReadAuthority(by);
3713
+ 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");
3714
+ if (input.apply) this.roadmapApplyAuthority(by);
3715
+ const config = this.d.roadmapConfig?.() ?? { github_mirror: false, github_write: "off" as const };
3716
+ if (!config.github_mirror) throw new PreEffectToolRefusal("roadmap GitHub mirror is off; enable roadmap.github_mirror in trusted configuration before syncing");
3717
+ const repo = this.roadmapRepository(), views = this.milestoneList(by);
3718
+ if (views.length > 100) throw new PreEffectToolRefusal("roadmap mirror exceeds 100 milestones; narrow the roadmap before syncing");
3719
+ const deadline = performance.now() + 50_000;
3720
+ 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");
3721
+ 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);
3722
+ 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"); };
3723
+ const run = this.roadmapGh();
3724
+ const snapshot = await readMirrorSnapshot(repo, async (...args) => { current(); const result = await run(...args); current(); return result; });
3725
+ current();
3726
+ const bindings: { milestone: number; number: number }[] = [], calls: string[][] = [], createIds: (number | undefined)[] = [], issueOwners = new Set<number>();
3727
+ for (const view of views) for (const issue of view.issues) if (issue.ref.startsWith(`${repo}#`)) {
3728
+ const id = milestoneId(Number(issue.ref.slice(repo.length + 1)));
3729
+ if (issueOwners.has(id)) throw new PreEffectToolRefusal("an issue is linked to multiple roadmap milestones; settle its placement before syncing");
3730
+ issueOwners.add(id);
3731
+ }
3732
+ for (const view of views) {
3733
+ if (view.withheld || view.title === "[withheld]" || view.outcome === "[withheld]") throw new PreEffectToolRefusal("roadmap mirror contains withheld membership or metadata; inspect privacy before syncing");
3734
+ const marker = `<!-- ahub-roadmap:${this.d.project}:${view.id} -->`, bound = this.d.board.mirrorMilestone(repo, view.id);
3735
+ const matching = bound === undefined ? recoverMirrorBinding(marker, view.title, snapshot.milestones) : undefined;
3736
+ if (matching?.kind === "ambiguous" || matching?.titleConflicts.length) throw new PreEffectToolRefusal("roadmap GitHub milestone identity is ambiguous; inspect matching milestones before syncing");
3737
+ const remoteId = bound ?? (matching?.kind === "bind" ? matching.number : undefined);
3738
+ if (bound === undefined && remoteId !== undefined) bindings.push({ milestone: view.id, number: remoteId });
3739
+ const remote = remoteId === undefined ? null : snapshot.milestones.find(row => row.number === remoteId);
3740
+ if (remoteId !== undefined && !remote) throw new PreEffectToolRefusal("recorded GitHub milestone is missing from the complete inventory; inspect the binding");
3741
+ const issues = view.issues.filter(row => row.ref.startsWith(`${repo}#`)).map(row => Number(row.ref.slice(repo.length + 1)));
3742
+ const planned = planRoadmapMirror(repo, { title: view.title, state: view.state === "done" || view.state === "dropped" ? "closed" : "open", issues, marker }, remote ?? null, snapshot.issues);
3743
+ for (const call of planned.calls) {
3744
+ const detached = /^repos\/[^/]+\/[^/]+\/issues\/([1-9][0-9]*)$/.exec(call[1] ?? "");
3745
+ if (detached && call.includes("milestone=null") && issueOwners.has(Number(detached[1]))) continue;
3746
+ calls.push(call); createIds.push(remoteId === undefined ? view.id : undefined);
3747
+ if (calls.length > 200) throw new PreEffectToolRefusal("roadmap mirror exceeds 200 writes; narrow the roadmap before syncing");
3748
+ }
3749
+ }
3750
+ const hiddenIssues = new Set<number>();
3751
+ for (const task of this.d.board.list()) if (this.isPii(task) || task.signals.includes("pii") || task.signals.includes("pii_path")) {
3752
+ try { const issue = this.planIssueIdentity(task); if (issue?.repo.toLowerCase() === repo) hiddenIssues.add(issue.issue); }
3753
+ catch { throw new PreEffectToolRefusal("private issue placement is unknown; inspect privacy before syncing"); }
3754
+ }
3755
+ 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");
3756
+ const fingerprint = createHash("sha256").update(JSON.stringify({ repo, bindings, calls })).digest("hex");
3757
+ if (!input.apply) return { repo, calls, bindings, fingerprint, applied: false };
3758
+ if (input.confirm !== fingerprint) throw new PreEffectToolRefusal(`roadmap sync preview changed; run ahub roadmap sync and retry with --confirm ${fingerprint}`);
3759
+ let effects = false;
3760
+ 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; } };
3761
+ effectCurrent();
3762
+ for (const binding of bindings) {
3763
+ effectCurrent();
3764
+ try { this.d.board.bindMirrorMilestone(repo, binding.milestone, binding.number); effects = true; before = stamp(); }
3765
+ catch (error) { if (effects) throw new Error("roadmap binding changed after effects; inspect the mirror and preview again"); throw error; }
3766
+ }
3767
+ for (let index = 0; index < calls.length; index++) {
3768
+ effectCurrent();
3769
+ let result: Awaited<ReturnType<SdlcGh>>;
3770
+ const remaining = deadline - performance.now();
3771
+ 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"); }
3772
+ effects = true;
3773
+ try { result = await run(calls[index]!, Math.min(10_000, remaining), undefined, 64 * 1024); }
3774
+ catch { throw new Error("roadmap GitHub write outcome is unknown; inspect the mirror and preview again before retrying"); }
3775
+ 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");
3776
+ const local = createIds[index];
3777
+ if (local !== undefined) {
3778
+ let number: number;
3779
+ try {
3780
+ const created = JSON.parse(result.stdout) as Record<string, unknown>, call = calls[index]!;
3781
+ number = milestoneId(created.number);
3782
+ 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");
3783
+ } catch { throw new Error("roadmap milestone creation was not confirmed; preview again to recover its marker"); }
3784
+ effectCurrent();
3785
+ try { this.d.board.bindMirrorMilestone(repo, local, number); before = stamp(); }
3786
+ catch { throw new Error("roadmap milestone was created but its binding is uncertain; preview again to recover its marker"); }
3787
+ }
3788
+ effectCurrent();
3789
+ }
3790
+ return { repo, calls, bindings, fingerprint, applied: true };
3791
+ }
3792
+
3537
3793
  // ---- R3 (#1481): bottom-up placement. Reads are the roadmap read authority; every write below is the R1 writer, never a new one. ----
3538
3794
 
3539
3795
  /** The one repository the roadmap reads from GitHub: the caller's choice, else the project's. Never derived from model text. */
@@ -3613,6 +3869,134 @@ export class Tasks {
3613
3869
  return done(saved, parsed.dropped + parsed.suggestions.length - saved.length, null);
3614
3870
  }
3615
3871
 
3872
+ /**
3873
+ * R2 (#1480) part 1: ask the hub's model how one milestone decomposes. The model sees only the milestone's public text, the
3874
+ * 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
3875
+ * model answer. Nothing is intaken, linked, published or accepted here.
3876
+ */
3877
+ async roadmapDecompose(by: PeerId, rawId: unknown, run?: SdlcGh): Promise<{ milestone: number; parts: DecomposePart[]; dropped: number; saved: MilestoneDecomposition | null; unavailable: string | null }> {
3878
+ const current = this.roadmapWriteAuthority(by);
3879
+ const id = this.roadmapParsed(() => milestoneId(rawId)), view = this.milestoneShow(by, id);
3880
+ current();
3881
+ 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");
3882
+ const done = (parts: DecomposePart[], dropped: number, saved: MilestoneDecomposition | null, unavailable: string | null) => ({ milestone: id, parts, dropped, saved, unavailable });
3883
+ const publicText = (value: string): boolean => { try { return this.publicMetadataText(value); } catch { return false; } };
3884
+ let rows: { id: string; title: string; status: string | null; type?: string; paths?: string[] }[] | undefined;
3885
+ try { const list = this.d.specsList?.(); if (list && !list.truncated && list.errors === 0) rows = list.specs; } catch { rows = undefined; }
3886
+ const linked = new Set(view.specs.map(row => row.id));
3887
+ // Every field that enters the prompt passes the same public screen R3's unplaced list uses; a spec that fails it is not
3888
+ // offered at all, exactly as an unplaced spec is dropped from triage.
3889
+ const summaries = (rows ?? []).filter(row => linked.has(row.id)
3890
+ && [row.id, row.title, ...(row.type ? [row.type] : []), ...(row.status ? [row.status] : []), ...(row.paths ?? []).slice(0, DECOMPOSE_PATHS)].every(publicText));
3891
+ // The milestone's own context is the goal and architecture specs it links; when it links only other types, those are its context.
3892
+ const top = summaries.filter(row => row.type === "goal" || row.type === "architecture");
3893
+ const specs: DecomposeItem[] = (top.length ? top : summaries).map(row => ({ ref: row.id, label: `spec ${row.id}`,
3894
+ text: `${row.title} (${row.type || "spec"}${row.status ? `, ${row.status}` : ""})${row.paths?.length ? ` covers: ${row.paths.slice(0, DECOMPOSE_PATHS).join(", ")}` : ""}` }));
3895
+ // Titles for linked issues come from the same bounded page read R3 uses. A ref outside that repository, an unreadable
3896
+ // 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
3897
+ // links are the only source of refs.
3898
+ const refs = view.issues.map(row => row.ref), first = refs.length ? /^([^#]+)#[1-9][0-9]*$/.exec(refs[0]!)![1]! : undefined;
3899
+ const titles = new Map<string, string>();
3900
+ if (first !== undefined) {
3901
+ 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); }
3902
+ catch { /* unavailable titles are not an empty list: the ref is still offered */ }
3903
+ }
3904
+ const issues: DecomposeItem[] = refs.map(ref => ({ ref, label: `issue ${ref}`, text: titles.get(ref) ?? "" }));
3905
+ if (!specs.length && !issues.length) return done([], 0, null, "the milestone links no spec or issue to decompose from");
3906
+ if (!this.d.roadmapModel) return done([], 0, null, "no hub model is configured for roadmap decompose");
3907
+ const prompt = buildDecomposePrompt({ milestone: { id, title: view.title, outcome: view.outcome }, specs: specs.slice(0, DECOMPOSE_ITEMS), issues: issues.slice(0, DECOMPOSE_ITEMS) });
3908
+ const answer = await this.d.roadmapModel(prompt.system, prompt.user, () => { try { current(); return true; } catch { return false; } });
3909
+ current();
3910
+ if (!answer) return done([], 0, null, "the hub model gave no answer; retry ahub roadmap decompose later");
3911
+ const parsed = parseDecomposition(answer, prompt), kept: DecomposePart[] = [];
3912
+ for (const part of parsed.parts) {
3913
+ // Re-screen at the write, exactly as triage does: what is stored is public planning text only.
3914
+ const text = [part.title, part.detail, ...part.cites].join("\n");
3915
+ if (!this.publicMetadataText(text)) continue;
3916
+ if (this.screenOn() && (await this.screenCall(text)).label !== "clear") continue;
3917
+ current(); kept.push(part);
3918
+ }
3919
+ const dropped = parsed.dropped + parsed.parts.length - kept.length;
3920
+ if (!kept.length) return done([], dropped, null, null);
3921
+ const saved = this.d.board.addDecomposition({ milestone: id, parts: kept }, HUB, this.d.now?.() ?? Date.now());
3922
+ return done(kept, dropped, saved, null);
3923
+ }
3924
+
3925
+ /**
3926
+ * R2 (#1480) part 2: accept one proposed part as a held intake draft. The draft is the existing intake hold (`draft` and
3927
+ * `backlog`): nothing offers, pulls or routes it until the person approves it with `ahub intake approve`, and this path grants
3928
+ * no new release authority. It carries the milestone link and the part's `spec`/`task` kind, each part is accepted on its own,
3929
+ * 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
3930
+ * reads `[withheld]` and no notice repeats the part's words. One accept per part runs at a time: a concurrent caller waits for
3931
+ * the attempt in flight and then reads the accept row, so two accepts of one part cannot make two drafts.
3932
+ */
3933
+ async roadmapDecomposePart(by: PeerId, rawId: unknown, rawPart: unknown): Promise<{ milestone: number; part: number; intake: DecomposeIntake; task: Record<string, unknown>; created: boolean }> {
3934
+ const current = this.roadmapWriteAuthority(by);
3935
+ const id = this.roadmapParsed(() => milestoneId(rawId)), part = this.roadmapParsed(() => milestoneId(rawPart));
3936
+ const view = this.milestoneShow(by, id);
3937
+ current();
3938
+ 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");
3939
+ const pending = this.d.board.pendingDecomposition(id);
3940
+ if (!pending) throw new PreEffectToolRefusal(`milestone ${id} has no pending decomposition; run ahub roadmap decompose ${id} first`);
3941
+ 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`);
3942
+ const chosen = pending.parts[part - 1]!;
3943
+ // A retry reads the draft the first accept made, and records the link again if an interrupted tail lost it.
3944
+ const earlier = this.roadmapAcceptedPart(by, id, pending.id, part);
3945
+ if (earlier) return earlier;
3946
+ const taskClass = CLASSES.includes(chosen.class as TaskClass) ? chosen.class as TaskClass : undefined;
3947
+ if (!taskClass) throw new PreEffectToolRefusal(`part ${part} names no hub task class; run ahub roadmap decompose ${id} to replace the answer`);
3948
+ // A milestone settled while its answer was pending refuses here, before any write. The same check runs again where the link
3949
+ // is written, and there it is best-effort: the draft is durable by then.
3950
+ this.roadmapCurrent(id);
3951
+ current();
3952
+ // One accept per part: a concurrent caller of the same part waits for the attempt in flight and then reads the accept row.
3953
+ const key = `${pending.id}:${part}`, running = this.decompositionAccepts.get(key);
3954
+ if (running) {
3955
+ await running.catch(() => undefined);
3956
+ const after = this.roadmapAcceptedPart(by, id, pending.id, part);
3957
+ if (after) return after;
3958
+ 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`);
3959
+ }
3960
+ const attempt = this.acceptDecompositionPartOnce(by, id, part, pending, chosen, taskClass);
3961
+ this.decompositionAccepts.set(key, attempt);
3962
+ try { return await attempt; } finally { if (this.decompositionAccepts.get(key) === attempt) this.decompositionAccepts.delete(key); }
3963
+ }
3964
+
3965
+ /** The accept row's own draft, while that task exists: the retry's answer, with the milestone link recorded again. */
3966
+ private roadmapAcceptedPart(by: PeerId, id: number, decomposition: number, part: number): { milestone: number; part: number; intake: DecomposeIntake; task: Record<string, unknown>; created: boolean } | undefined {
3967
+ const accepted = this.d.board.decompositionAccept(decomposition, part), earlier = accepted ? this.d.board.get(accepted.task) : undefined;
3968
+ if (!accepted || !earlier) return undefined;
3969
+ // Idempotent, so a missing link heals here; a milestone settled since refuses that as a notice, never as the caller's refusal.
3970
+ this.releaseNotice(`task #${earlier.id}: milestone ${id} part ${part} accepted without its milestone link`, () => {
3971
+ const milestone = this.roadmapCurrent(id);
3972
+ this.d.board.linkMilestone(id, "task", String(earlier.id), by, milestone.revision, this.d.now?.() ?? Date.now());
3973
+ });
3974
+ return { milestone: id, part, intake: accepted.intake, task: this.publicView(earlier), created: false };
3975
+ }
3976
+
3977
+ /** One accept attempt: the durable draft, then a tail that records the hold and never refuses the caller. */
3978
+ 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 }> {
3979
+ 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 });
3980
+ // 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
3981
+ // accept row, the milestone link and the notice are best-effort in that order.
3982
+ this.incomingBacklog.delete(draft.id);
3983
+ this.releaseNotice(`task #${draft.id}: milestone ${id} part ${part} accepted without its accept record`, () => {
3984
+ this.d.board.acceptDecompositionPart({ decomposition: pending.id, milestone: id, part, task: draft.id, intake: chosen.intake }, by, this.d.now?.() ?? Date.now());
3985
+ });
3986
+ this.releaseNotice(`task #${draft.id}: milestone ${id} part ${part} accepted without its milestone link`, () => {
3987
+ const milestone = this.roadmapCurrent(id);
3988
+ this.d.board.linkMilestone(id, "task", String(draft.id), by, milestone.revision, this.d.now?.() ?? Date.now());
3989
+ });
3990
+ this.releaseNotice(`task #${draft.id}: milestone ${id} part ${part} accepted as a held intake draft`);
3991
+ return { milestone: id, part, intake: chosen.intake, task: this.publicView(this.d.board.get(draft.id) ?? draft), created: true };
3992
+ }
3993
+
3994
+ /** The held draft's detail: the part's own words, then the one line a person reads before releasing it. */
3995
+ private decompositionDraftDetail(part: DecomposePart, milestone: number, index: number, total: number): string {
3996
+ const kind = part.intake === "spec" ? "needs its own spec issue before implementation" : "a mechanical chore that goes straight to a task";
3997
+ return [part.detail, `Milestone ${milestone} part ${index} of ${total}: ${kind}. Cites: ${part.cites.join(", ")}.`, `Held until released: ahub intake approve`].join("\n\n");
3998
+ }
3999
+
3616
4000
  /** Apply one suggestion through R1's own writers. A "new milestone" suggestion creates it first; a retry never creates a second. */
3617
4001
  async roadmapAccept(by: PeerId, rawId: unknown): Promise<{ suggestion: MilestoneSuggestion; milestone: MilestoneView }> {
3618
4002
  const current = this.roadmapWriteAuthority(by);
@@ -3804,6 +4188,8 @@ export class Tasks {
3804
4188
  catch (error) { throw new PreEffectToolRefusal((error as Error).message); }
3805
4189
  const updated = this.d.board.plan(task.id, by, patch, input.revision, input.reason.trim(), withheld, receipt);
3806
4190
  this.planningRecorded({ by, task: task.id, fields: Object.keys(patch), revision: updated.planningRevision! });
4191
+ if (updated.state === "backlog" && updated.reserved && ["reserved", "pinned", "deps", "plannedStart", "release", "needsPerson"].some(key => Object.hasOwn(patch, key)) && this.d.autoPull?.() === true)
4192
+ this.queueAutoPulls(new Set([updated.reserved]), "backlog planned");
3807
4193
  return updated; // persistence/readback failures must never claim no effect
3808
4194
  }
3809
4195
 
@@ -4185,7 +4571,7 @@ export class Tasks {
4185
4571
  return updated; // a failed readback may follow a durable release write
4186
4572
  }
4187
4573
 
4188
- 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> {
4574
+ 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> {
4189
4575
  const requestCheck = this.requestCheck(by, fence);
4190
4576
  const plan = cleanPlan(input.plan, this.d.profileData ?? this.d.profile ?? "dev", (this.d.sdlc?.config().mode ?? "off") !== "off");
4191
4577
  this.validatePlanSources(plan);
@@ -4194,7 +4580,13 @@ export class Tasks {
4194
4580
  if (external && (!this.personOrConductor(by) || input.backlog !== true)) throw new PreEffectToolRefusal("external intake requires person-owned backlog staging");
4195
4581
  if (input.backlog !== undefined && typeof input.backlog !== "boolean") throw new PreEffectToolRefusal("backlog must be a boolean");
4196
4582
  const backlog = input.backlog === true;
4197
- if (input.draft !== undefined && (input.draft !== true || !backlog || by !== USER)) throw new PreEffectToolRefusal("only the person's intake stages a backlog draft");
4583
+ if (input.draft === true && input[HOST_ROADMAP_DRAFT] === true) {
4584
+ // R2 part 2 (#1480): a part the planner or the conductor accepted is held exactly like the person's intake draft. The
4585
+ // capability is a host Symbol, so no tool argument can stage a hidden draft, and the caller is rechecked here as well.
4586
+ if (!backlog) throw new PreEffectToolRefusal("a held roadmap draft is backlog work");
4587
+ if (by !== USER && (!this.d.bus.isRostered(by) || !this.isConfiguredPlanner(by) && !this.configuredManualConductor(by)))
4588
+ 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");
4589
+ } else if (input.draft !== undefined && (input.draft !== true || !backlog || by !== USER)) throw new PreEffectToolRefusal("only the person's intake stages a backlog draft");
4198
4590
  const claiming = !backlog && input.owner === by;
4199
4591
  if (claiming) {
4200
4592
  this.acceptanceCapacity({ id: -1, owner: by, state: "proposed" });
@@ -6658,13 +7050,14 @@ export class Tasks {
6658
7050
  * counts) and the staged PR only while the done's effective commit and branch are still the ones it was read for.
6659
7051
  */
6660
7052
  private withLink(task: Task, link: IdentityLink | undefined, refs?: TaskRefs): Task {
6661
- if ((this.d.sdlc?.config().mode ?? "off") === "off" || this.isPii(task)) return task;
7053
+ if (this.isPii(task) || (this.d.sdlc?.config().mode ?? "off") === "off" && link?.managedRevision === undefined) return task;
7054
+ if (link?.managedRevision !== undefined && task.history.length !== link.managedRevision) throw new PreEffectToolRefusal("managed handoff changed; inspect the task and GitHub before retrying");
6662
7055
  const config = this.d.sdlc?.config() ?? sdlcConfig(undefined);
6663
7056
  let issue: { repo: string; issue: number } | undefined;
6664
- if (!task.sdlc?.issue) { try { issue = this.planIssueIdentity(task); } catch { issue = undefined; } }
7057
+ if ((this.d.sdlc?.config().mode ?? "off") !== "off" && !task.sdlc?.issue) { try { issue = this.planIssueIdentity(task); } catch { issue = undefined; } }
6665
7058
  const commit = refs?.commit ?? task.refs.commit, branch = refs?.branch ?? task.refs.branch;
6666
- const repository = task.sdlc?.repo ?? task.refs.repo ?? this.d.repository;
6667
- const pr = link && !task.sdlc?.pr && repository?.toLowerCase() === link.repo.toLowerCase() && link.basis.commit === commit && (commit !== undefined || link.basis.branch === branch) ? link : undefined;
7059
+ const repository = task.sdlc?.repo ?? task.refs.repo ?? this.d.repository ?? (link?.managedRevision !== undefined ? link.repo : undefined);
7060
+ 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;
6668
7061
  let next = task.sdlc;
6669
7062
  if (issue) next = linkedReceipt(next, issue, config) ?? next;
6670
7063
  if (pr) next = linkedReceipt(next, { repo: pr.repo, pr: pr.pr }, config) ?? next;
@@ -6778,22 +7171,30 @@ export class Tasks {
6778
7171
  }
6779
7172
  const rows = this.d.board.list();
6780
7173
  const tasks: MetricTask[] = rows.map(task => ({ id: task.id, private: this.isPii(task), history: task.history.map(entry => ({ at: entry.at, event: entry.event,
6781
- ...(entry.event === "done" && (entry.requestHead ?? entry.reviewCost?.head ?? entry.specReport?.head) ? { requestHead: entry.requestHead ?? entry.reviewCost?.head ?? entry.specReport?.head } : {}), ...(entry.reviewFindings?.head ? { verdictHead: entry.reviewFindings.head } : {}), ...(entry.evidenceOnly ? { evidenceOnly: true as const } : {}) })) }));
7174
+ ...(["check run passed", "check run failed"].includes(entry.event) && entry.requestHead ? { requestHead: entry.requestHead } : {}), ...(entry.event === "done" && (entry.requestHead ?? entry.reviewCost?.head ?? entry.specReport?.head) ? { requestHead: entry.requestHead ?? entry.reviewCost?.head ?? entry.specReport?.head } : {}), ...(entry.reviewFindings?.head ? { verdictHead: entry.reviewFindings.head } : {}), ...(entry.evidenceOnly ? { evidenceOnly: true as const } : {}) })) }));
6782
7175
  const visibleIds = new Set(rows.filter(task => !this.isPii(task)).map(task => task.id));
6783
7176
  const byKind: Record<string, number> = {};
6784
7177
  for (const stall of this.stalled()) if (visibleIds.has(stall.task)) byKind[stall.cause.kind] = (byKind[stall.cause.kind] ?? 0) + 1;
6785
7178
  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 };
6786
7179
  // #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.
6787
- const mergedAt: Record<number, number> = {}, ciReruns: Record<number, number | null> = {}, ciRuns: Record<number, number | null> = {}, reviews: Record<number, number | null> = {};
7180
+ 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> = {};
6788
7181
  for (const task of rows) {
6789
- const merge = task.sdlc?.merge;
7182
+ const guarded = task.sdlc?.merge;
7183
+ const merge = guarded?.state === "merged" ? guarded : task.sdlc?.mergeReadback;
6790
7184
  if (!visibleIds.has(task.id) || merge?.state !== "merged") continue;
6791
7185
  const cost = cleanMergeCost(merge.cost);
6792
- const at = cost?.mergedAt ?? (Number.isSafeInteger(merge.at) ? merge.at : null);
7186
+ const at = cost?.mergedAt ?? (merge === guarded && Number.isSafeInteger(merge.at) ? merge.at : null);
6793
7187
  if (at !== null) mergedAt[task.id] = at;
6794
- if (cost) { ciReruns[task.id] = cost.ciReruns; ciRuns[task.id] = cost.ciRuns; reviews[task.id] = cost.reviews; }
7188
+ 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; }
6795
7189
  }
6796
- 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 ?? {}) });
7190
+ 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() } : {}) };
7191
+ }
7192
+
7193
+ /** Latest configured scan source counts; no repository or alert text is projected. */
7194
+ securityScanCounts(): Record<string, number | null> | undefined {
7195
+ const scan = this.d.sdlc?.config().securityScan, repo = scan?.repo ?? this.d.repository;
7196
+ if (!scan || typeof repo !== "string" || !this.nameable(repo)) return undefined;
7197
+ return this.d.board.latestSecurityScanCounts(repo, scan.sources.join(","));
6797
7198
  }
6798
7199
 
6799
7200
  /** #481 S7: one point per shipped release (1 for a hotfix, 0 otherwise; a release with no recorded train is skipped, never a 0) and one per recorded security scan whose total is known. */
@@ -7751,12 +8152,20 @@ export class Tasks {
7751
8152
  return result;
7752
8153
  };
7753
8154
  const evidence = await readAdoptMergeEvidence(receipt, run);
7754
- const now = current();
8155
+ current();
7755
8156
  const gates = adoptMergeGates(evidence, head, requiredChecksFor(config, repo));
7756
8157
  if (gates.length) throw new PreEffectToolRefusal(gates.join("; "));
7757
- const capacity = this.capacityBefore(now);
8158
+ const costDeadline = performance.now() + INLINE_MERGE_READBACK_DEADLINE_MS;
8159
+ const cost = evidence?.costSnapshot ? await readPrCostHistory(repo, pr as number, (args, timeout, cwd, cap) => {
8160
+ const remaining = costDeadline - performance.now();
8161
+ current();
8162
+ 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: "" });
8163
+ }, evidence.costSnapshot, head, task.history.find(entry => entry.event === "done")?.requestHead).then(pr => pr?.complete ? mergeCostFrom(pr) : undefined, () => undefined) : undefined;
8164
+ const latest = current();
8165
+ const merge: ReadbackMergeRecord = { repo, pr: pr as number, head, at: Date.now(), state: "merged", ...(evidence?.mergeCommit ? { mergeCommit: evidence.mergeCommit } : {}), ...(cost ? { cost } : {}) };
8166
+ const capacity = this.capacityBefore(latest);
7758
8167
  current(); // No await between the last authority/privacy/flow check and the sole approval write.
7759
- const next = this.d.board.adoptMerge(now.id, by, receipt, head, now.history.length, HOST_MERGE_ADOPTION);
8168
+ const next = this.d.board.adoptMerge(latest.id, by, { ...receipt, mergeReadback: merge }, head, latest.history.length, HOST_MERGE_ADOPTION);
7760
8169
  this.cohorts.closed(next.id);
7761
8170
  this.ciWatchers.cancel(next.id); this.heldReviews.delete(next.id);
7762
8171
  this.writePlannerNotices(next, capacity, true);
@@ -7801,7 +8210,7 @@ export class Tasks {
7801
8210
  this.mergesInFlight.add(task.id);
7802
8211
  try {
7803
8212
  const links = this.deliveryLinks(config), subject = links.find(link => link.id === task.id)!;
7804
- 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,
8213
+ 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,
7805
8214
  recordMerge: record=>this.recordMergeResult(task.id,by,record,artifactCurrent),
7806
8215
  beforeMerge: queue => {
7807
8216
  if (!this.mergeAuthority(by)) return "merge authority changed during the merge check: nothing was run";
@@ -7838,6 +8247,69 @@ export class Tasks {
7838
8247
  if(!current.history.some(h=>h.by===HUB && h.event==="merge refused" && h.note===note))
7839
8248
  this.d.board.update(id,HUB,"merge refused",{},note,{...(this.isPii(current)||this.d.privateTurn?.(by)?{withheld:true}:{})});
7840
8249
  }
8250
+ /** Observe one eligible externally merged approved PR without mutating GitHub. */
8251
+ async captureExternalMerge(id: number): Promise<"merged" | "closed" | "retry" | "skip"> {
8252
+ const task = this.d.board.get(id), config = this.d.sdlc?.config(), receipt = task?.sdlc;
8253
+ const repo = receipt?.repo, pr = receipt?.pr, head = task && this.reviewHead(task);
8254
+ const recorded = receipt?.merge?.state === "merged" ? receipt.merge : receipt?.mergeReadback?.state === "merged" ? receipt.mergeReadback : undefined;
8255
+ 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)
8256
+ || 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";
8257
+ const identity = JSON.stringify([task.history.length, task.updated, task.owner, receipt, config]);
8258
+ const current = () => {
8259
+ const now = this.d.board.get(id), policy = this.d.sdlc?.config();
8260
+ return !!now && !this.isPii(now) && !(now.owner && this.d.privateTurn?.(now.owner)) && !this.d.sweepHeld?.() && !this.d.bus.isRecoveryHeld && !this.d.bus.storageError
8261
+ && JSON.stringify([now.history.length, now.updated, now.owner, now.sdlc, policy]) === identity;
8262
+ };
8263
+ const deadline = performance.now() + MERGE_READBACK_DEADLINE_MS;
8264
+ const run: SdlcGh = (args, timeout, cwd, cap) => {
8265
+ const remaining = deadline - performance.now();
8266
+ return current() && remaining > 0 ? (this.d.sdlc?.gh ?? sdlcGh)(args, Math.min(timeout ?? remaining, remaining), cwd, cap) : Promise.resolve({ code: 1, stdout: "" });
8267
+ };
8268
+ const evidence = await readSdlcPr(receipt!, run).catch(() => undefined);
8269
+ if (!current()) return "skip";
8270
+ if (evidence?.state === "CLOSED") return "closed";
8271
+ if (evidence?.state !== "MERGED" || evidence.head !== head) return "retry";
8272
+ 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);
8273
+ if (!current()) return "skip";
8274
+ const now = this.d.board.get(id)!;
8275
+ if (recorded) {
8276
+ if (!cost) return "retry";
8277
+ const key = receipt!.merge === recorded ? "merge" : "mergeReadback";
8278
+ this.d.board.update(id, HUB, "merge cost observed", { sdlc: { ...now.sdlc!, [key]: { ...recorded, cost } } }, undefined, {}, now.history.length);
8279
+ return "merged";
8280
+ }
8281
+ const merge: ReadbackMergeRecord = { repo, pr, head, at: Date.now(), state: "merged", ...(evidence.mergeCommit ? { mergeCommit: evidence.mergeCommit } : {}), ...(cost ? { cost } : {}) };
8282
+ this.d.board.update(id, HUB, "merge observed", { sdlc: { ...now.sdlc!, mergeReadback: merge } }, undefined, {}, now.history.length);
8283
+ return "merged";
8284
+ }
8285
+
8286
+ // ponytail: this in-memory schedule is lost on restart; only approvals still within 24 hours are retried.
8287
+ private readonly mergeReadbackSchedule = new Map<number, { approval: number; next: number; closed: boolean }>();
8288
+ private mergeReadbackRunning = false;
8289
+ async settleMergeReadbacks(now = Date.now()): Promise<void> {
8290
+ if (this.mergeReadbackRunning || this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) return;
8291
+ this.mergeReadbackRunning = true;
8292
+ try {
8293
+ let reads = 0;
8294
+ // Unseen work goes first, then the least recently scheduled read, so a busy backlog cannot starve later tasks.
8295
+ 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);
8296
+ for (const task of candidates) {
8297
+ if (reads >= 3 || this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) break;
8298
+ const recorded = task.sdlc?.merge?.state === "merged" ? task.sdlc.merge : task.sdlc?.mergeReadback?.state === "merged" ? task.sdlc.mergeReadback : undefined;
8299
+ 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; }
8300
+ const approval = task.history.findLastIndex(entry => entry.event === "approved" || entry.event === "merged outside the hub" || entry.event === "done" && entry.by === task.owner);
8301
+ const at = task.history[approval]?.at;
8302
+ if (approval < 0 || at === undefined || now < at || now - at >= 24 * 60 * 60_000) { this.mergeReadbackSchedule.delete(task.id); continue; }
8303
+ const previous = this.mergeReadbackSchedule.get(task.id);
8304
+ if (previous?.approval === approval && (previous.closed || now < previous.next)) continue;
8305
+ this.mergeReadbackSchedule.set(task.id, { approval, next: now + 10 * 60_000, closed: false });
8306
+ reads++;
8307
+ const outcome = await this.captureExternalMerge(task.id).catch(() => "retry" as const);
8308
+ if (outcome === "closed") this.mergeReadbackSchedule.set(task.id, { approval, next: now + 10 * 60_000, closed: true });
8309
+ }
8310
+ } finally { this.mergeReadbackRunning = false; }
8311
+ }
8312
+
7841
8313
  private mergeRecordCurrent(id:number,by:PeerId,record:MergeRecord,artifactCurrent:()=>boolean):Task|undefined {
7842
8314
  const now=this.d.board.get(id);
7843
8315
  return artifactCurrent() && now && now.sdlc?.repo===record.repo && now.sdlc.pr===record.pr && now.sdlc.reviewedHead===record.head
@@ -8298,6 +8770,9 @@ export class Tasks {
8298
8770
  } else if (approvalHead && currentHead && currentHead !== approvalHead) throw this.reviewHeadMoveRefusal(task.id, approvalHead, currentHead);
8299
8771
  const integrity = publicTestIntegrity(receipt && evidence && !this.isPii(task) ? await readTestIntegrity(receipt, evidence, read) : this.unknownTestIntegrity(this.isPii(task)), this.publicMetadataText);
8300
8772
  const evalResult = receipt && !this.isPii(task) ? await readEvalFor(config, evidence, receipt.repo, read) : undefined;
8773
+ const draftApproval = transition === "approval" && receipt?.repo && receipt.pr && evidence?.draft === true
8774
+ && evidence.review !== "changes_requested" && approvalHead && evidence.head === approvalHead
8775
+ ? await readReviewReadiness(receipt, approvalHead, read, requiredChecksFor(config, receipt.repo)) : undefined;
8301
8776
  const current = this.need(task.id, false, true);
8302
8777
  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`);
8303
8778
  // Advise may continue on the current task, but evidence from its previous link cannot admit that task's review.
@@ -8308,7 +8783,12 @@ export class Tasks {
8308
8783
  // #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.
8309
8784
  const evalNames = evalRequiredChecks(config, evidence).filter(name => !config.requiredChecks.includes(name));
8310
8785
  const evalBlocker = (blocker: string) => evalNames.some(name => blocker.startsWith(`required check ${name}:`)) || evalGapBlockers(status.evalGate).includes(blocker);
8311
- 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;
8786
+ const approvalDeferral = draftApproval?.ready === true && draftApproval.draftApprovalEligible === true && evidence?.unresolved === 0;
8787
+ 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 || !(
8788
+ blocker === "required check check (macos-latest): not successful on current head"
8789
+ || blocker === "GitHub review approval missing or changes requested" && evidence?.review !== "changes_requested"
8790
+ || blocker === "review requests pending or unknown" && evidence?.pendingReviews !== null
8791
+ ));
8312
8792
  if (config.mode === "enforce" && blockers.length) throw new PreEffectToolRefusal(`task #${task.id}: SDLC ${transition} blocked: ${blockers.join("; ")}`);
8313
8793
  // #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.
8314
8794
  const gate = status.evalGate;
@@ -8325,7 +8805,7 @@ export class Tasks {
8325
8805
  if (!Number.isInteger(n)) throw new (preEffect ? PreEffectToolRefusal : Error)(`id must be a task number, not ${(typeof id === "number" ? String(id) : JSON.stringify(id ?? null)).slice(0, 60)}`);
8326
8806
  const task = this.d.board.get(n);
8327
8807
  if (!task) throw new (preEffect ? PreEffectToolRefusal : Error)(`no task #${n}`);
8328
- if (task.state === "backlog" && !allowBacklog) throw new (preEffect ? PreEffectToolRefusal : Error)(`task #${n} is backlog: pull it into To Do first`);
8808
+ if (task.state === "backlog" && !allowBacklog) throw new (preEffect ? PreEffectToolRefusal : Error)(`task #${n} is in backlog: a planner or person must pull it into To Do first (hub_backlog_pull)`);
8329
8809
  // Handing a task to someone else only makes sense while there is work left on it.
8330
8810
  if (open && !OPEN.includes(task.state)) throw new (preEffect ? PreEffectToolRefusal : Error)(`task #${task.id} is ${task.state}: it can no longer change hands`);
8331
8811
  return task;
@@ -8639,10 +9119,63 @@ export class Tasks {
8639
9119
  const task = this.need(id, false, true);
8640
9120
  this.mine(task, by, "owner", true);
8641
9121
  if (this.isPii(task) || !port.describe(by, task.id)) return undefined;
8642
- const result = await port.commitAndPush({ peer: by, task: task.id, title: task.title });
8643
- if (!result.ok) throw new PreEffectToolRefusal(`hub_task_done for task #${task.id}: ${result.reason}`);
9122
+ const requestCheck = this.requestCheck(by), revision = task.history.length;
9123
+ const current = () => {
9124
+ try {
9125
+ requestCheck(); const row = this.d.board.get(task.id);
9126
+ return !!row && row.created === task.created && row.owner === by && row.state === task.state && row.history.length === revision
9127
+ && !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);
9128
+ } catch { return false; }
9129
+ };
9130
+ if (!current()) throw new PreEffectToolRefusal("managed handoff authority unavailable; inspect the task and retry hub_task_done");
9131
+ const result = await port.commitAndPush({ peer: by, task: task.id, title: task.title, current });
9132
+ if (!result.ok) {
9133
+ const message = `hub_task_done for task #${task.id}: ${result.reason}`;
9134
+ if (result.uncertain) throw new Error(message);
9135
+ throw new PreEffectToolRefusal(message);
9136
+ }
9137
+ const stillCurrent = () => { if (!current()) throw new Error("managed handoff authority changed after the commit; inspect the task and GitHub before retrying"); };
9138
+ stillCurrent();
8644
9139
  if (result.note) this.doneNotes.set(task.id, result.note);
8645
- return { ...cleanRefs(refs), commit: result.commit, branch: result.branch };
9140
+ let repo: string | undefined, pr: number | undefined;
9141
+ if (result.pushed && !task.sdlc?.pr) {
9142
+ repo = githubOriginRepository(this.d.cwd);
9143
+ const named = task.sdlc?.repo ?? task.refs.repo;
9144
+ 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");
9145
+ let issue: { repo: string; issue: number } | undefined;
9146
+ 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"); }
9147
+ 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");
9148
+ 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");
9149
+ const verifiedRepo = repo;
9150
+ const authority = () => { stillCurrent(); if (githubOriginRepository(this.d.cwd) !== verifiedRepo) throw new Error("managed origin changed after the push; inspect GitHub before retrying"); };
9151
+ 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); }
9152
+ 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"}`); }
9153
+ authority();
9154
+ }
9155
+ const handed: ManagedHandoffRefs = { ...cleanRefs(refs), commit: result.commit, branch: result.branch };
9156
+ Object.defineProperty(handed, MANAGED_HANDOFF, { value: { task: task.id, owner: by, revision, commit: result.commit, branch: result.branch, ...(repo && pr ? { repo, pr } : {}) } });
9157
+ return handed;
9158
+ }
9159
+
9160
+ /** Commit the managed owner worktree for a check and bind its exact head through the board. */
9161
+ async worktreeForCheck(by: PeerId, id: number, current: () => boolean): Promise<Task | undefined> {
9162
+ const port = this.d.taskWorktree;
9163
+ if (!port || !port.applies(by) || !port.describe(by, id)) return undefined;
9164
+ const task = this.need(id, false, true);
9165
+ this.mine(task, by, "owner", true);
9166
+ if (task.state !== "in_progress" || this.isPii(task) || !current()) throw new PreEffectToolRefusal("check unavailable");
9167
+ const result = await port.commitAndPush({ peer: by, task: id, title: task.title, current });
9168
+ // A commit or push can have landed even when the request loses authority during an await.
9169
+ if (!result.ok) {
9170
+ const reason = `managed worktree check: ${result.reason.replaceAll("hub_task_done", "hub_check_start")}`;
9171
+ if (result.uncertain) throw new Error(reason);
9172
+ throw new PreEffectToolRefusal(reason);
9173
+ }
9174
+ if (!current()) throw new Error("check unavailable: task authority changed after the worktree commit; read hub_task_show before retrying");
9175
+ const fresh = this.d.board.get(id);
9176
+ 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");
9177
+ if (fresh.refs.commit === result.commit && fresh.refs.branch === result.branch) return fresh;
9178
+ return this.d.board.update(id, HUB, "check worktree committed", { refs: { commit: result.commit, branch: result.branch } }, undefined, {}, fresh.history.length);
8646
9179
  }
8647
9180
 
8648
9181
  /** Decline or cancel: clear the hub-made worktree and its empty branch. Uncommitted work is kept and reported, never force-removed. */
@@ -8805,6 +9338,7 @@ export class Tasks {
8805
9338
  if (sdlc.reviewedHead !== refresh.commit) delete sdlc.reviewedHead;
8806
9339
  if (sdlc.localHead !== refresh.commit) { delete sdlc.localHead; delete sdlc.localResult; }
8807
9340
  delete sdlc.merge;
9341
+ delete sdlc.mergeReadback;
8808
9342
  return { ...task, sdlc };
8809
9343
  }
8810
9344
 
@@ -8850,6 +9384,14 @@ export class Tasks {
8850
9384
  }
8851
9385
 
8852
9386
  async done(by: PeerId, id: unknown, summary?: string, refs?: TaskRefs, deliverables?: unknown, specAck?: unknown, resolved?: unknown): Promise<Task> {
9387
+ try { return await this.doneWithHandoff(by, id, summary, refs, deliverables, specAck, resolved); }
9388
+ catch (error) {
9389
+ 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`);
9390
+ throw error;
9391
+ }
9392
+ }
9393
+
9394
+ private async doneWithHandoff(by: PeerId, id: unknown, summary?: string, refs?: TaskRefs, deliverables?: unknown, specAck?: unknown, resolved?: unknown): Promise<Task> {
8853
9395
  const observerExcluded = this.observerExcluded(by);
8854
9396
  const requestCheck = this.requestCheck(by);
8855
9397
  const initial = this.need(id, false, true);
@@ -8894,12 +9436,32 @@ export class Tasks {
8894
9436
  task = valid();
8895
9437
  }
8896
9438
  // #694: stage the identities the hub can verify; the gates read them, and only the admitted done persists them.
8897
- const link = this.d.sdlc && this.d.sdlc.config().mode !== "off" ? await this.identityLink(task, refs) : undefined;
8898
- const current = () => this.stagedSpec(by, this.withLink(valid(), link, refs), specCarry);
9439
+ const handoff = (refs as ManagedHandoffRefs | undefined)?.[MANAGED_HANDOFF];
9440
+ 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;
9441
+ let managedRevision = handoff?.revision;
9442
+ const stageHandoff = (row: Task) => {
9443
+ let staged = row;
9444
+ if (handoff) {
9445
+ 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");
9446
+ if (handoff.repo && handoff.pr && !staged.sdlc?.pr) {
9447
+ const receipt = linkedReceipt(staged.sdlc, { repo: handoff.repo, pr: handoff.pr }, this.d.sdlc?.config() ?? sdlcConfig(undefined));
9448
+ if (!receipt) throw new PreEffectToolRefusal("managed PR repository no longer matches the task; inspect GitHub before retrying");
9449
+ staged = { ...staged, sdlc: receipt };
9450
+ }
9451
+ }
9452
+ return staged;
9453
+ };
9454
+ const ownWrite = (...args: Parameters<Board["update"]>) => {
9455
+ current();
9456
+ const row = write(...args);
9457
+ if (handoff) { managedRevision = row.history.length; if (link) link.managedRevision = managedRevision; }
9458
+ return row;
9459
+ };
9460
+ const current = () => stageHandoff(this.stagedSpec(by, this.withLink(valid(), link, refs), specCarry));
8899
9461
  task = current();
8900
9462
  let reviewEvidence: PrEvidence | undefined;
8901
9463
  if (this.d.sdlc && this.d.sdlc.config().mode !== "off") { reviewEvidence = await this.lifecycleGate(task, "review", undefined, undefined, refileHead); task = current(); }
8902
- 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;
9464
+ 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;
8903
9465
  task = current();
8904
9466
  if (refileHead && (this.d.sdlc?.config().mode ?? "off") === "off") {
8905
9467
  const currentHead = await this.currentPrHeadForReview(task, current);
@@ -8930,8 +9492,8 @@ export class Tasks {
8930
9492
  if (r.action === "request") return write(task.id, HUB, "integration requested", {}, this.integrationRequest(task, r));
8931
9493
  if (r.action === "unresolved") {
8932
9494
  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`);
8933
- task = this.withLink(write(task.id, HUB, "integration unresolved", {}, r.why), link, refs);
8934
- } else if (r.integrated) task = this.withLink(write(task.id, HUB, "integrated", {}, `cohort #${cohort!.id}, revision ${cohort!.revision}`), link, refs);
9495
+ task = this.withLink(ownWrite(task.id, HUB, "integration unresolved", {}, r.why), link, refs);
9496
+ } else if (r.integrated) task = this.withLink(ownWrite(task.id, HUB, "integrated", {}, `cohort #${cohort!.id}, revision ${cohort!.revision}`), link, refs);
8935
9497
  } else if (cohort?.held.size && !this.isPii(task)) {
8936
9498
  // No integration step for this member (silence lifted, a PII task open): the notices the silence held stand in
8937
9499
  // for it (issue #107, AC4).
@@ -8939,7 +9501,7 @@ export class Tasks {
8939
9501
  if (evidence && by === USER) this.d.notify(`task ${this.publicTitle(task)} done by the console; overlapping work finished meanwhile:\n${evidence}`);
8940
9502
  else if (evidence) this.doneNotes.set(task.id, `Overlapping work finished while you worked (no turn-free integration step ran):\n${evidence}`);
8941
9503
  }
8942
- 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
9504
+ 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
8943
9505
  const command = this.d.runCheck ? this.d.check?.(task.class, task) : undefined;
8944
9506
  if (!command) return this.complete(task, by, summary, refs, "", withheld, "review", reviewAdmission, link, records, requestCheck, refresh, specInspection, false, resolvedReviewComments, reviewObserverTurn);
8945
9507
  // The tool call returns now; a check can outlast an agent's tool timeout. The result decides what comes next.
@@ -9047,6 +9609,15 @@ export class Tasks {
9047
9609
  return [head, "The done counts once the files did not change between two calls and the others have stopped.", ...lines, facts?.text ?? ""].filter(Boolean).join("\n");
9048
9610
  }
9049
9611
 
9612
+ /** Record an already-admitted isolated run without retaining its output. */
9613
+ recordCheckResult(receipt: import("./check-runner.ts").RunReceipt): void {
9614
+ const task = this.d.board.get(receipt.task);
9615
+ if (!task || task.state !== "in_progress" || task.owner !== receipt.owner) return;
9616
+ const passed = receipt.exit === 0 && !receipt.timed_out && !receipt.cancelled && !receipt.interrupted;
9617
+ this.d.board.update(task.id, HUB, passed ? "check run passed" : "check run failed", {}, undefined,
9618
+ { checkKey: receipt.check, requestHead: receipt.sha }, task.history.length);
9619
+ }
9620
+
9050
9621
  /**
9051
9622
  * #901: which check key produced this result, and how many citation keys the example citation check said were unresolved. The key is the hub's own selection (`Deps.checkKey`, the lookup
9052
9623
  * `Deps.check` makes), never read from output; without that dependency it is not recorded. The count is read only from the example check's own last line (`citations: N declared keys, M missing`, scripts/check-citations.ts);
@@ -9367,6 +9938,7 @@ export class Tasks {
9367
9938
  const head = admission.head ?? this.reviewHead(task) ?? "unknown head";
9368
9939
  if (admission.ready) {
9369
9940
  const names = admission.checks?.length ? admission.checks.join(", ") : "the required checks";
9941
+ 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`;
9370
9942
  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`;
9371
9943
  }
9372
9944
  return `Hub-verified at ${head}: not ready: ${admission.blockers.join("; ")}.\n`;
@@ -9403,7 +9975,7 @@ export class Tasks {
9403
9975
  // #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.
9404
9976
  const codeScoped = this.d.reviewScope?.(reviewer) === "code";
9405
9977
  const verified = codeScoped ? "" : this.hubVerifiedBlock(task, admission);
9406
- const ciPassed = admission?.ready === true && !this.isPii(task);
9978
+ const ciPassed = admission?.ready === true && !admission.deferred?.length && !this.isPii(task);
9407
9979
  // #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.
9408
9980
  const checkResult = codeScoped ? CODE_SCOPE_LINE
9409
9981
  : check ? `Check result: ${(check.note ?? "").split("\n")[0]}`